]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/communities.tsx
Merge branch 'browser_popup'
[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 this.state.siteRes.site_view.match({
113       some: siteView => `${i18n.t("communities")} - ${siteView.site.name}`,
114       none: "",
115     });
116   }
117
118   render() {
119     return (
120       <div className="container-lg">
121         <HtmlTags
122           title={this.documentTitle}
123           path={this.context.router.route.match.url}
124           description={None}
125           image={None}
126         />
127         {this.state.loading ? (
128           <h5>
129             <Spinner large />
130           </h5>
131         ) : (
132           <div>
133             <div className="row">
134               <div className="col-md-6">
135                 <h4>{i18n.t("list_of_communities")}</h4>
136                 <span className="mb-2">
137                   <ListingTypeSelect
138                     type_={this.state.listingType}
139                     showLocal={showLocal(this.isoData)}
140                     showSubscribed
141                     onChange={this.handleListingTypeChange}
142                   />
143                 </span>
144               </div>
145               <div className="col-md-6">
146                 <div className="float-md-right">{this.searchForm()}</div>
147               </div>
148             </div>
149
150             <div className="table-responsive">
151               <table
152                 id="community_table"
153                 className="table table-sm table-hover"
154               >
155                 <thead className="pointer">
156                   <tr>
157                     <th>{i18n.t("name")}</th>
158                     <th className="text-right">{i18n.t("subscribers")}</th>
159                     <th className="text-right">
160                       {i18n.t("users")} / {i18n.t("month")}
161                     </th>
162                     <th className="text-right d-none d-lg-table-cell">
163                       {i18n.t("posts")}
164                     </th>
165                     <th className="text-right d-none d-lg-table-cell">
166                       {i18n.t("comments")}
167                     </th>
168                     <th></th>
169                   </tr>
170                 </thead>
171                 <tbody>
172                   {this.state.listCommunitiesResponse
173                     .map(l => l.communities)
174                     .unwrapOr([])
175                     .map(cv => (
176                       <tr key={cv.community.id}>
177                         <td>
178                           <CommunityLink community={cv.community} />
179                         </td>
180                         <td className="text-right">
181                           {numToSI(cv.counts.subscribers)}
182                         </td>
183                         <td className="text-right">
184                           {numToSI(cv.counts.users_active_month)}
185                         </td>
186                         <td className="text-right d-none d-lg-table-cell">
187                           {numToSI(cv.counts.posts)}
188                         </td>
189                         <td className="text-right d-none d-lg-table-cell">
190                           {numToSI(cv.counts.comments)}
191                         </td>
192                         <td className="text-right">
193                           {cv.subscribed == SubscribedType.Subscribed && (
194                             <button
195                               className="btn btn-link d-inline-block"
196                               onClick={linkEvent(
197                                 cv.community.id,
198                                 this.handleUnsubscribe
199                               )}
200                             >
201                               {i18n.t("unsubscribe")}
202                             </button>
203                           )}
204                           {cv.subscribed == SubscribedType.NotSubscribed && (
205                             <button
206                               className="btn btn-link d-inline-block"
207                               onClick={linkEvent(
208                                 cv.community.id,
209                                 this.handleSubscribe
210                               )}
211                             >
212                               {i18n.t("subscribe")}
213                             </button>
214                           )}
215                           {cv.subscribed == SubscribedType.Pending && (
216                             <div className="text-warning d-inline-block">
217                               {i18n.t("subscribe_pending")}
218                             </div>
219                           )}
220                         </td>
221                       </tr>
222                     ))}
223                 </tbody>
224               </table>
225             </div>
226             <Paginator
227               page={this.state.page}
228               onChange={this.handlePageChange}
229             />
230           </div>
231         )}
232       </div>
233     );
234   }
235
236   searchForm() {
237     return (
238       <form
239         className="form-inline"
240         onSubmit={linkEvent(this, this.handleSearchSubmit)}
241       >
242         <input
243           type="text"
244           id="communities-search"
245           className="form-control mr-2 mb-2"
246           value={this.state.searchText}
247           placeholder={`${i18n.t("search")}...`}
248           onInput={linkEvent(this, this.handleSearchChange)}
249           required
250           minLength={3}
251         />
252         <label className="sr-only" htmlFor="communities-search">
253           {i18n.t("search")}
254         </label>
255         <button type="submit" className="btn btn-secondary mr-2 mb-2">
256           <span>{i18n.t("search")}</span>
257         </button>
258       </form>
259     );
260   }
261
262   updateUrl(paramUpdates: CommunitiesProps) {
263     const page = paramUpdates.page || this.state.page;
264     const listingTypeStr = paramUpdates.listingType || this.state.listingType;
265     this.props.history.push(
266       `/communities/listing_type/${listingTypeStr}/page/${page}`
267     );
268   }
269
270   handlePageChange(page: number) {
271     this.updateUrl({ page });
272   }
273
274   handleListingTypeChange(val: ListingType) {
275     this.updateUrl({
276       listingType: val,
277       page: 1,
278     });
279   }
280
281   handleUnsubscribe(communityId: number) {
282     let form = new FollowCommunity({
283       community_id: communityId,
284       follow: false,
285       auth: auth().unwrap(),
286     });
287     WebSocketService.Instance.send(wsClient.followCommunity(form));
288   }
289
290   handleSubscribe(communityId: number) {
291     let form = new FollowCommunity({
292       community_id: communityId,
293       follow: true,
294       auth: auth().unwrap(),
295     });
296     WebSocketService.Instance.send(wsClient.followCommunity(form));
297   }
298
299   handleSearchChange(i: Communities, event: any) {
300     i.setState({ searchText: event.target.value });
301   }
302
303   handleSearchSubmit(i: Communities) {
304     const searchParamEncoded = encodeURIComponent(i.state.searchText);
305     i.context.router.history.push(
306       `/search/q/${searchParamEncoded}/type/Communities/sort/TopAll/listing_type/All/community_id/0/creator_id/0/page/1`
307     );
308   }
309
310   refetch() {
311     let listCommunitiesForm = new ListCommunities({
312       type_: Some(this.state.listingType),
313       sort: Some(SortType.TopMonth),
314       limit: Some(communityLimit),
315       page: Some(this.state.page),
316       auth: auth(false).ok(),
317     });
318
319     WebSocketService.Instance.send(
320       wsClient.listCommunities(listCommunitiesForm)
321     );
322   }
323
324   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
325     let pathSplit = req.path.split("/");
326     let type_: Option<ListingType> = Some(
327       pathSplit[3] ? ListingType[pathSplit[3]] : ListingType.Local
328     );
329     let page = Some(pathSplit[5] ? Number(pathSplit[5]) : 1);
330     let listCommunitiesForm = new ListCommunities({
331       type_,
332       sort: Some(SortType.TopMonth),
333       limit: Some(communityLimit),
334       page,
335       auth: req.auth,
336     });
337
338     return [req.client.listCommunities(listCommunitiesForm)];
339   }
340
341   parseMessage(msg: any) {
342     let op = wsUserOp(msg);
343     console.log(msg);
344     if (msg.error) {
345       toast(i18n.t(msg.error), "danger");
346       return;
347     } else if (op == UserOperation.ListCommunities) {
348       let data = wsJsonToRes<ListCommunitiesResponse>(
349         msg,
350         ListCommunitiesResponse
351       );
352       this.setState({ listCommunitiesResponse: Some(data), loading: false });
353       window.scrollTo(0, 0);
354     } else if (op == UserOperation.FollowCommunity) {
355       let data = wsJsonToRes<CommunityResponse>(msg, CommunityResponse);
356       this.state.listCommunitiesResponse.match({
357         some: res => {
358           let found = res.communities.find(
359             c => c.community.id == data.community_view.community.id
360           );
361           found.subscribed = data.community_view.subscribed;
362           found.counts.subscribers = data.community_view.counts.subscribers;
363         },
364         none: void 0,
365       });
366       this.setState(this.state);
367     }
368   }
369 }