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