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