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