]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Running newer prettier.
[lemmy-ui.git] / src / shared / components / communities.tsx
1 import { Component, linkEvent } from "inferno";
2 import { HtmlTags } from "./html-tags";
3 import { Subscription } from "rxjs";
4 import {
5   UserOperation,
6   CommunityView,
7   ListCommunitiesResponse,
8   CommunityResponse,
9   FollowCommunity,
10   ListCommunities,
11   SortType,
12   ListingType,
13   SiteView,
14 } from "lemmy-js-client";
15 import { WebSocketService } from "../services";
16 import {
17   wsJsonToRes,
18   toast,
19   getPageFromProps,
20   isBrowser,
21   setIsoData,
22   wsSubscribe,
23   wsUserOp,
24   wsClient,
25   authField,
26   setOptionalAuth,
27 } from "../utils";
28 import { CommunityLink } from "./community-link";
29 import { Spinner } from "./icon";
30 import { i18n } from "../i18next";
31 import { InitialFetchRequest } from "shared/interfaces";
32
33 const communityLimit = 100;
34
35 interface CommunitiesState {
36   communities: CommunityView[];
37   page: number;
38   loading: boolean;
39   site_view: SiteView;
40   searchText: string;
41 }
42
43 interface CommunitiesProps {
44   page: number;
45 }
46
47 export class Communities extends Component<any, CommunitiesState> {
48   private subscription: Subscription;
49   private isoData = setIsoData(this.context);
50   private emptyState: CommunitiesState = {
51     communities: [],
52     loading: true,
53     page: getPageFromProps(this.props),
54     site_view: this.isoData.site_res.site_view,
55     searchText: "",
56   };
57
58   constructor(props: any, context: any) {
59     super(props, context);
60     this.state = this.emptyState;
61
62     this.parseMessage = this.parseMessage.bind(this);
63     this.subscription = wsSubscribe(this.parseMessage);
64
65     // Only fetch the data if coming from another route
66     if (this.isoData.path == this.context.router.route.match.url) {
67       this.state.communities = this.isoData.routeData[0].communities;
68       this.state.communities.sort(
69         (a, b) => b.counts.subscribers - a.counts.subscribers
70       );
71       this.state.loading = false;
72     } else {
73       this.refetch();
74     }
75   }
76
77   componentWillUnmount() {
78     if (isBrowser()) {
79       this.subscription.unsubscribe();
80     }
81   }
82
83   static getDerivedStateFromProps(props: any): CommunitiesProps {
84     return {
85       page: getPageFromProps(props),
86     };
87   }
88
89   componentDidUpdate(_: any, lastState: CommunitiesState) {
90     if (lastState.page !== this.state.page) {
91       this.setState({ loading: true });
92       this.refetch();
93     }
94   }
95
96   get documentTitle(): string {
97     return `${i18n.t("communities")} - ${this.state.site_view.site.name}`;
98   }
99
100   render() {
101     return (
102       <div class="container">
103         <HtmlTags
104           title={this.documentTitle}
105           path={this.context.router.route.match.url}
106         />
107         {this.state.loading ? (
108           <h5>
109             <Spinner />
110           </h5>
111         ) : (
112           <div>
113             <div class="row">
114               <div class="col-md-6">
115                 <h4>{i18n.t("list_of_communities")}</h4>
116               </div>
117               <div class="col-md-6">
118                 <div class="float-md-right">{this.searchForm()}</div>
119               </div>
120             </div>
121
122             <div class="table-responsive">
123               <table id="community_table" class="table table-sm table-hover">
124                 <thead class="pointer">
125                   <tr>
126                     <th>{i18n.t("name")}</th>
127                     <th>{i18n.t("category")}</th>
128                     <th class="text-right">{i18n.t("subscribers")}</th>
129                     <th class="text-right">
130                       {i18n.t("users")} / {i18n.t("month")}
131                     </th>
132                     <th class="text-right d-none d-lg-table-cell">
133                       {i18n.t("posts")}
134                     </th>
135                     <th class="text-right d-none d-lg-table-cell">
136                       {i18n.t("comments")}
137                     </th>
138                     <th></th>
139                   </tr>
140                 </thead>
141                 <tbody>
142                   {this.state.communities.map(cv => (
143                     <tr>
144                       <td>
145                         <CommunityLink community={cv.community} />
146                       </td>
147                       <td>{cv.category.name}</td>
148                       <td class="text-right">{cv.counts.subscribers}</td>
149                       <td class="text-right">{cv.counts.users_active_month}</td>
150                       <td class="text-right d-none d-lg-table-cell">
151                         {cv.counts.posts}
152                       </td>
153                       <td class="text-right d-none d-lg-table-cell">
154                         {cv.counts.comments}
155                       </td>
156                       <td class="text-right">
157                         {cv.subscribed ? (
158                           <span
159                             class="pointer btn-link"
160                             role="button"
161                             onClick={linkEvent(
162                               cv.community.id,
163                               this.handleUnsubscribe
164                             )}
165                           >
166                             {i18n.t("unsubscribe")}
167                           </span>
168                         ) : (
169                           <span
170                             class="pointer btn-link"
171                             role="button"
172                             onClick={linkEvent(
173                               cv.community.id,
174                               this.handleSubscribe
175                             )}
176                           >
177                             {i18n.t("subscribe")}
178                           </span>
179                         )}
180                       </td>
181                     </tr>
182                   ))}
183                 </tbody>
184               </table>
185             </div>
186             {this.paginator()}
187           </div>
188         )}
189       </div>
190     );
191   }
192
193   searchForm() {
194     return (
195       <form
196         class="form-inline"
197         onSubmit={linkEvent(this, this.handleSearchSubmit)}
198       >
199         <input
200           type="text"
201           id="communities-search"
202           class="form-control mr-2 mb-2"
203           value={this.state.searchText}
204           placeholder={`${i18n.t("search")}...`}
205           onInput={linkEvent(this, this.handleSearchChange)}
206           required
207           minLength={3}
208         />
209         <label class="sr-only" htmlFor="communities-search">
210           {i18n.t("search")}
211         </label>
212         <button type="submit" class="btn btn-secondary mr-2 mb-2">
213           <span>{i18n.t("search")}</span>
214         </button>
215       </form>
216     );
217   }
218
219   paginator() {
220     return (
221       <div class="mt-2">
222         {this.state.page > 1 && (
223           <button
224             class="btn btn-secondary mr-1"
225             onClick={linkEvent(this, this.prevPage)}
226           >
227             {i18n.t("prev")}
228           </button>
229         )}
230
231         {this.state.communities.length > 0 && (
232           <button
233             class="btn btn-secondary"
234             onClick={linkEvent(this, this.nextPage)}
235           >
236             {i18n.t("next")}
237           </button>
238         )}
239       </div>
240     );
241   }
242
243   updateUrl(paramUpdates: CommunitiesProps) {
244     const page = paramUpdates.page || this.state.page;
245     this.props.history.push(`/communities/page/${page}`);
246   }
247
248   nextPage(i: Communities) {
249     i.updateUrl({ page: i.state.page + 1 });
250   }
251
252   prevPage(i: Communities) {
253     i.updateUrl({ page: i.state.page - 1 });
254   }
255
256   handleUnsubscribe(communityId: number) {
257     let form: FollowCommunity = {
258       community_id: communityId,
259       follow: false,
260       auth: authField(),
261     };
262     WebSocketService.Instance.send(wsClient.followCommunity(form));
263   }
264
265   handleSubscribe(communityId: number) {
266     let form: FollowCommunity = {
267       community_id: communityId,
268       follow: true,
269       auth: authField(),
270     };
271     WebSocketService.Instance.send(wsClient.followCommunity(form));
272   }
273
274   handleSearchChange(i: Communities, event: any) {
275     i.setState({ searchText: event.target.value });
276   }
277
278   handleSearchSubmit(i: Communities) {
279     const searchParamEncoded = encodeURIComponent(i.state.searchText);
280     i.context.router.history.push(
281       `/search/q/${searchParamEncoded}/type/Communities/sort/TopAll/page/1`
282     );
283   }
284
285   refetch() {
286     let listCommunitiesForm: ListCommunities = {
287       type_: ListingType.All,
288       sort: SortType.TopAll,
289       limit: communityLimit,
290       page: this.state.page,
291       auth: authField(false),
292     };
293
294     WebSocketService.Instance.send(
295       wsClient.listCommunities(listCommunitiesForm)
296     );
297   }
298
299   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
300     let pathSplit = req.path.split("/");
301     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
302     let listCommunitiesForm: ListCommunities = {
303       type_: ListingType.All,
304       sort: SortType.TopAll,
305       limit: communityLimit,
306       page,
307     };
308     setOptionalAuth(listCommunitiesForm, req.auth);
309
310     return [req.client.listCommunities(listCommunitiesForm)];
311   }
312
313   parseMessage(msg: any) {
314     let op = wsUserOp(msg);
315     if (msg.error) {
316       toast(i18n.t(msg.error), "danger");
317       return;
318     } else if (op == UserOperation.ListCommunities) {
319       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
320       this.state.communities = data.communities;
321       this.state.communities.sort(
322         (a, b) => b.counts.subscribers - a.counts.subscribers
323       );
324       this.state.loading = false;
325       window.scrollTo(0, 0);
326       this.setState(this.state);
327     } else if (op == UserOperation.FollowCommunity) {
328       let data = wsJsonToRes<CommunityResponse>(msg).data;
329       let found = this.state.communities.find(
330         c => c.community.id == data.community_view.community.id
331       );
332       found.subscribed = data.community_view.subscribed;
333       found.counts.subscribers = data.community_view.counts.subscribers;
334       this.setState(this.state);
335     }
336   }
337 }