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