]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/communities.tsx
Merge pull request #344 from LemmyNet/fix/add_communities_listing_type_filter
[lemmy-ui.git] / src / shared / components / community / communities.tsx
1 import { Component, linkEvent } from "inferno";
2 import {
3   CommunityResponse,
4   CommunityView,
5   FollowCommunity,
6   ListCommunities,
7   ListCommunitiesResponse,
8   ListingType,
9   SiteView,
10   SortType,
11   UserOperation,
12 } from "lemmy-js-client";
13 import { Subscription } from "rxjs";
14 import { InitialFetchRequest } from "shared/interfaces";
15 import { i18n } from "../../i18next";
16 import { WebSocketService } from "../../services";
17 import {
18   authField,
19   getListingTypeFromPropsNoDefault,
20   getPageFromProps,
21   isBrowser,
22   setIsoData,
23   setOptionalAuth,
24   showLocal,
25   toast,
26   wsClient,
27   wsJsonToRes,
28   wsSubscribe,
29   wsUserOp,
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   communities: CommunityView[];
41   page: number;
42   loading: boolean;
43   site_view: SiteView;
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);
56   private emptyState: CommunitiesState = {
57     communities: [],
58     loading: true,
59     page: getPageFromProps(this.props),
60     listingType: getListingTypeFromPropsNoDefault(this.props),
61     site_view: this.isoData.site_res.site_view,
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       this.state.communities = this.isoData.routeData[0].communities;
77       this.state.loading = false;
78     } else {
79       this.refetch();
80     }
81   }
82
83   componentWillUnmount() {
84     if (isBrowser()) {
85       this.subscription.unsubscribe();
86     }
87   }
88
89   static getDerivedStateFromProps(props: any): CommunitiesProps {
90     return {
91       listingType: getListingTypeFromPropsNoDefault(props),
92       page: getPageFromProps(props),
93     };
94   }
95
96   componentDidUpdate(_: any, lastState: CommunitiesState) {
97     if (
98       lastState.page !== this.state.page ||
99       lastState.listingType !== this.state.listingType
100     ) {
101       this.setState({ loading: true });
102       this.refetch();
103     }
104   }
105
106   get documentTitle(): string {
107     return `${i18n.t("communities")} - ${this.state.site_view.site.name}`;
108   }
109
110   render() {
111     return (
112       <div class="container">
113         <HtmlTags
114           title={this.documentTitle}
115           path={this.context.router.route.match.url}
116         />
117         {this.state.loading ? (
118           <h5>
119             <Spinner large />
120           </h5>
121         ) : (
122           <div>
123             <div class="row">
124               <div class="col-md-6">
125                 <h4>{i18n.t("list_of_communities")}</h4>
126                 <span class="mb-2">
127                   <ListingTypeSelect
128                     type_={this.state.listingType}
129                     showLocal={showLocal(this.isoData)}
130                     onChange={this.handleListingTypeChange}
131                   />
132                 </span>
133               </div>
134               <div class="col-md-6">
135                 <div class="float-md-right">{this.searchForm()}</div>
136               </div>
137             </div>
138
139             <div class="table-responsive">
140               <table id="community_table" class="table table-sm table-hover">
141                 <thead class="pointer">
142                   <tr>
143                     <th>{i18n.t("name")}</th>
144                     <th class="text-right">{i18n.t("subscribers")}</th>
145                     <th class="text-right">
146                       {i18n.t("users")} / {i18n.t("month")}
147                     </th>
148                     <th class="text-right d-none d-lg-table-cell">
149                       {i18n.t("posts")}
150                     </th>
151                     <th class="text-right d-none d-lg-table-cell">
152                       {i18n.t("comments")}
153                     </th>
154                     <th></th>
155                   </tr>
156                 </thead>
157                 <tbody>
158                   {this.state.communities.map(cv => (
159                     <tr>
160                       <td>
161                         <CommunityLink community={cv.community} />
162                       </td>
163                       <td class="text-right">{cv.counts.subscribers}</td>
164                       <td class="text-right">{cv.counts.users_active_month}</td>
165                       <td class="text-right d-none d-lg-table-cell">
166                         {cv.counts.posts}
167                       </td>
168                       <td class="text-right d-none d-lg-table-cell">
169                         {cv.counts.comments}
170                       </td>
171                       <td class="text-right">
172                         {cv.subscribed ? (
173                           <button
174                             class="btn btn-link d-inline-block"
175                             onClick={linkEvent(
176                               cv.community.id,
177                               this.handleUnsubscribe
178                             )}
179                           >
180                             {i18n.t("unsubscribe")}
181                           </button>
182                         ) : (
183                           <button
184                             class="btn btn-link d-inline-block"
185                             onClick={linkEvent(
186                               cv.community.id,
187                               this.handleSubscribe
188                             )}
189                           >
190                             {i18n.t("subscribe")}
191                           </button>
192                         )}
193                       </td>
194                     </tr>
195                   ))}
196                 </tbody>
197               </table>
198             </div>
199             <Paginator
200               page={this.state.page}
201               onChange={this.handlePageChange}
202             />
203           </div>
204         )}
205       </div>
206     );
207   }
208
209   searchForm() {
210     return (
211       <form
212         class="form-inline"
213         onSubmit={linkEvent(this, this.handleSearchSubmit)}
214       >
215         <input
216           type="text"
217           id="communities-search"
218           class="form-control mr-2 mb-2"
219           value={this.state.searchText}
220           placeholder={`${i18n.t("search")}...`}
221           onInput={linkEvent(this, this.handleSearchChange)}
222           required
223           minLength={3}
224         />
225         <label class="sr-only" htmlFor="communities-search">
226           {i18n.t("search")}
227         </label>
228         <button type="submit" class="btn btn-secondary mr-2 mb-2">
229           <span>{i18n.t("search")}</span>
230         </button>
231       </form>
232     );
233   }
234
235   updateUrl(paramUpdates: CommunitiesProps) {
236     const page = paramUpdates.page || this.state.page;
237     const listingTypeStr = paramUpdates.listingType || this.state.listingType;
238     this.props.history.push(
239       `/communities/listing_type/${listingTypeStr}/page/${page}`
240     );
241   }
242
243   handlePageChange(page: number) {
244     this.updateUrl({ page });
245   }
246
247   handleListingTypeChange(val: ListingType) {
248     this.updateUrl({
249       listingType: val,
250       page: 1,
251     });
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/listing_type/All/community_id/0/creator_id/0/page/1`
280     );
281   }
282
283   refetch() {
284     let listCommunitiesForm: ListCommunities = {
285       type_: this.state.listingType,
286       sort: SortType.TopMonth,
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 type_: ListingType = pathSplit[3]
300       ? ListingType[pathSplit[3]]
301       : ListingType.Local;
302     let page = pathSplit[5] ? Number(pathSplit[5]) : 1;
303     let listCommunitiesForm: ListCommunities = {
304       type_,
305       sort: SortType.TopMonth,
306       limit: communityLimit,
307       page,
308     };
309     setOptionalAuth(listCommunitiesForm, req.auth);
310
311     return [req.client.listCommunities(listCommunitiesForm)];
312   }
313
314   parseMessage(msg: any) {
315     let op = wsUserOp(msg);
316     console.log(msg);
317     if (msg.error) {
318       toast(i18n.t(msg.error), "danger");
319       return;
320     } else if (op == UserOperation.ListCommunities) {
321       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
322       this.state.communities = data.communities;
323       this.state.loading = false;
324       window.scrollTo(0, 0);
325       this.setState(this.state);
326     } else if (op == UserOperation.FollowCommunity) {
327       let data = wsJsonToRes<CommunityResponse>(msg).data;
328       let found = this.state.communities.find(
329         c => c.community.id == data.community_view.community.id
330       );
331       found.subscribed = data.community_view.subscribed;
332       found.counts.subscribers = data.community_view.counts.subscribers;
333       this.setState(this.state);
334     }
335   }
336 }