]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Remove categories
[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 class="text-right">{i18n.t("subscribers")}</th>
128                     <th class="text-right">
129                       {i18n.t("users")} / {i18n.t("month")}
130                     </th>
131                     <th class="text-right d-none d-lg-table-cell">
132                       {i18n.t("posts")}
133                     </th>
134                     <th class="text-right d-none d-lg-table-cell">
135                       {i18n.t("comments")}
136                     </th>
137                     <th></th>
138                   </tr>
139                 </thead>
140                 <tbody>
141                   {this.state.communities.map(cv => (
142                     <tr>
143                       <td>
144                         <CommunityLink community={cv.community} />
145                       </td>
146                       <td class="text-right">{cv.counts.subscribers}</td>
147                       <td class="text-right">{cv.counts.users_active_month}</td>
148                       <td class="text-right d-none d-lg-table-cell">
149                         {cv.counts.posts}
150                       </td>
151                       <td class="text-right d-none d-lg-table-cell">
152                         {cv.counts.comments}
153                       </td>
154                       <td class="text-right">
155                         {cv.subscribed ? (
156                           <span
157                             class="pointer btn-link"
158                             role="button"
159                             onClick={linkEvent(
160                               cv.community.id,
161                               this.handleUnsubscribe
162                             )}
163                           >
164                             {i18n.t("unsubscribe")}
165                           </span>
166                         ) : (
167                           <span
168                             class="pointer btn-link"
169                             role="button"
170                             onClick={linkEvent(
171                               cv.community.id,
172                               this.handleSubscribe
173                             )}
174                           >
175                             {i18n.t("subscribe")}
176                           </span>
177                         )}
178                       </td>
179                     </tr>
180                   ))}
181                 </tbody>
182               </table>
183             </div>
184             {this.paginator()}
185           </div>
186         )}
187       </div>
188     );
189   }
190
191   searchForm() {
192     return (
193       <form
194         class="form-inline"
195         onSubmit={linkEvent(this, this.handleSearchSubmit)}
196       >
197         <input
198           type="text"
199           id="communities-search"
200           class="form-control mr-2 mb-2"
201           value={this.state.searchText}
202           placeholder={`${i18n.t("search")}...`}
203           onInput={linkEvent(this, this.handleSearchChange)}
204           required
205           minLength={3}
206         />
207         <label class="sr-only" htmlFor="communities-search">
208           {i18n.t("search")}
209         </label>
210         <button type="submit" class="btn btn-secondary mr-2 mb-2">
211           <span>{i18n.t("search")}</span>
212         </button>
213       </form>
214     );
215   }
216
217   paginator() {
218     return (
219       <div class="mt-2">
220         {this.state.page > 1 && (
221           <button
222             class="btn btn-secondary mr-1"
223             onClick={linkEvent(this, this.prevPage)}
224           >
225             {i18n.t("prev")}
226           </button>
227         )}
228
229         {this.state.communities.length > 0 && (
230           <button
231             class="btn btn-secondary"
232             onClick={linkEvent(this, this.nextPage)}
233           >
234             {i18n.t("next")}
235           </button>
236         )}
237       </div>
238     );
239   }
240
241   updateUrl(paramUpdates: CommunitiesProps) {
242     const page = paramUpdates.page || this.state.page;
243     this.props.history.push(`/communities/page/${page}`);
244   }
245
246   nextPage(i: Communities) {
247     i.updateUrl({ page: i.state.page + 1 });
248   }
249
250   prevPage(i: Communities) {
251     i.updateUrl({ page: i.state.page - 1 });
252   }
253
254   handleUnsubscribe(communityId: number) {
255     let form: FollowCommunity = {
256       community_id: communityId,
257       follow: false,
258       auth: authField(),
259     };
260     WebSocketService.Instance.send(wsClient.followCommunity(form));
261   }
262
263   handleSubscribe(communityId: number) {
264     let form: FollowCommunity = {
265       community_id: communityId,
266       follow: true,
267       auth: authField(),
268     };
269     WebSocketService.Instance.send(wsClient.followCommunity(form));
270   }
271
272   handleSearchChange(i: Communities, event: any) {
273     i.setState({ searchText: event.target.value });
274   }
275
276   handleSearchSubmit(i: Communities) {
277     const searchParamEncoded = encodeURIComponent(i.state.searchText);
278     i.context.router.history.push(
279       `/search/q/${searchParamEncoded}/type/Communities/sort/TopAll/page/1`
280     );
281   }
282
283   refetch() {
284     let listCommunitiesForm: ListCommunities = {
285       type_: ListingType.All,
286       sort: SortType.TopAll,
287       limit: communityLimit,
288       page: this.state.page,
289       auth: authField(false),
290     };
291
292     WebSocketService.Instance.send(
293       wsClient.listCommunities(listCommunitiesForm)
294     );
295   }
296
297   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
298     let pathSplit = req.path.split("/");
299     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
300     let listCommunitiesForm: ListCommunities = {
301       type_: ListingType.All,
302       sort: SortType.TopAll,
303       limit: communityLimit,
304       page,
305     };
306     setOptionalAuth(listCommunitiesForm, req.auth);
307
308     return [req.client.listCommunities(listCommunitiesForm)];
309   }
310
311   parseMessage(msg: any) {
312     let op = wsUserOp(msg);
313     if (msg.error) {
314       toast(i18n.t(msg.error), "danger");
315       return;
316     } else if (op == UserOperation.ListCommunities) {
317       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
318       this.state.communities = data.communities;
319       this.state.communities.sort(
320         (a, b) => b.counts.subscribers - a.counts.subscribers
321       );
322       this.state.loading = false;
323       window.scrollTo(0, 0);
324       this.setState(this.state);
325     } else if (op == UserOperation.FollowCommunity) {
326       let data = wsJsonToRes<CommunityResponse>(msg).data;
327       let found = this.state.communities.find(
328         c => c.community.id == data.community_view.community.id
329       );
330       found.subscribed = data.community_view.subscribed;
331       found.counts.subscribers = data.community_view.counts.subscribers;
332       this.setState(this.state);
333     }
334   }
335 }