]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Merge pull request #178 from LemmyNet/icon_component
[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.communities.sort(
69         (a, b) => b.counts.subscribers - a.counts.subscribers
70       );
71       this.state.loading = false;
72     } else {
73       this.refetch();
74     }
75   }
76
77   componentWillUnmount() {
78     if (isBrowser()) {
79       this.subscription.unsubscribe();
80     }
81   }
82
83   static getDerivedStateFromProps(props: any): CommunitiesProps {
84     return {
85       page: getPageFromProps(props),
86     };
87   }
88
89   componentDidUpdate(_: any, lastState: CommunitiesState) {
90     if (lastState.page !== this.state.page) {
91       this.setState({ loading: true });
92       this.refetch();
93     }
94   }
95
96   get documentTitle(): string {
97     return `${i18n.t('communities')} - ${this.state.site_view.site.name}`;
98   }
99
100   render() {
101     return (
102       <div class="container">
103         <HtmlTags
104           title={this.documentTitle}
105           path={this.context.router.route.match.url}
106         />
107         {this.state.loading ? (
108           <h5>
109             <Spinner />
110           </h5>
111         ) : (
112           <div>
113             <div class="row">
114               <div class="col-md-6">
115                 <h4>{i18n.t('list_of_communities')}</h4>
116               </div>
117               <div class="col-md-6">
118                 <div class="float-md-right">{this.searchForm()}</div>
119               </div>
120             </div>
121
122             <div class="table-responsive">
123               <table id="community_table" class="table table-sm table-hover">
124                 <thead class="pointer">
125                   <tr>
126                     <th>{i18n.t('name')}</th>
127                     <th>{i18n.t('category')}</th>
128                     <th class="text-right">{i18n.t('subscribers')}</th>
129                     <th class="text-right">
130                       {i18n.t('users')} / {i18n.t('month')}
131                     </th>
132                     <th class="text-right d-none d-lg-table-cell">
133                       {i18n.t('posts')}
134                     </th>
135                     <th class="text-right d-none d-lg-table-cell">
136                       {i18n.t('comments')}
137                     </th>
138                     <th></th>
139                   </tr>
140                 </thead>
141                 <tbody>
142                   {this.state.communities.map(cv => (
143                     <tr>
144                       <td>
145                         <CommunityLink community={cv.community} />
146                       </td>
147                       <td>{cv.category.name}</td>
148                       <td class="text-right">{cv.counts.subscribers}</td>
149                       <td class="text-right">{cv.counts.users_active_month}</td>
150                       <td class="text-right d-none d-lg-table-cell">
151                         {cv.counts.posts}
152                       </td>
153                       <td class="text-right d-none d-lg-table-cell">
154                         {cv.counts.comments}
155                       </td>
156                       <td class="text-right">
157                         {cv.subscribed ? (
158                           <span
159                             class="pointer btn-link"
160                             role="button"
161                             onClick={linkEvent(
162                               cv.community.id,
163                               this.handleUnsubscribe
164                             )}
165                           >
166                             {i18n.t('unsubscribe')}
167                           </span>
168                         ) : (
169                           <span
170                             class="pointer btn-link"
171                             role="button"
172                             onClick={linkEvent(
173                               cv.community.id,
174                               this.handleSubscribe
175                             )}
176                           >
177                             {i18n.t('subscribe')}
178                           </span>
179                         )}
180                       </td>
181                     </tr>
182                   ))}
183                 </tbody>
184               </table>
185             </div>
186             {this.paginator()}
187           </div>
188         )}
189       </div>
190     );
191   }
192
193   searchForm() {
194     return (
195       <form
196         class="form-inline"
197         onSubmit={linkEvent(this, this.handleSearchSubmit)}
198       >
199         <input
200           type="text"
201           class="form-control mr-2 mb-2"
202           value={this.state.searchText}
203           placeholder={`${i18n.t('search')}...`}
204           onInput={linkEvent(this, this.handleSearchChange)}
205           required
206           minLength={3}
207         />
208         <button type="submit" class="btn btn-secondary mr-2 mb-2">
209           <span>{i18n.t('search')}</span>
210         </button>
211       </form>
212     );
213   }
214
215   paginator() {
216     return (
217       <div class="mt-2">
218         {this.state.page > 1 && (
219           <button
220             class="btn btn-secondary mr-1"
221             onClick={linkEvent(this, this.prevPage)}
222           >
223             {i18n.t('prev')}
224           </button>
225         )}
226
227         {this.state.communities.length > 0 && (
228           <button
229             class="btn btn-secondary"
230             onClick={linkEvent(this, this.nextPage)}
231           >
232             {i18n.t('next')}
233           </button>
234         )}
235       </div>
236     );
237   }
238
239   updateUrl(paramUpdates: CommunitiesProps) {
240     const page = paramUpdates.page || this.state.page;
241     this.props.history.push(`/communities/page/${page}`);
242   }
243
244   nextPage(i: Communities) {
245     i.updateUrl({ page: i.state.page + 1 });
246   }
247
248   prevPage(i: Communities) {
249     i.updateUrl({ page: i.state.page - 1 });
250   }
251
252   handleUnsubscribe(communityId: number) {
253     let form: FollowCommunity = {
254       community_id: communityId,
255       follow: false,
256       auth: authField(),
257     };
258     WebSocketService.Instance.send(wsClient.followCommunity(form));
259   }
260
261   handleSubscribe(communityId: number) {
262     let form: FollowCommunity = {
263       community_id: communityId,
264       follow: true,
265       auth: authField(),
266     };
267     WebSocketService.Instance.send(wsClient.followCommunity(form));
268   }
269
270   handleSearchChange(i: Communities, event: any) {
271     i.setState({ searchText: event.target.value });
272   }
273
274   handleSearchSubmit(i: Communities) {
275     const searchParamEncoded = encodeURIComponent(i.state.searchText);
276     i.context.router.history.push(
277       `/search/q/${searchParamEncoded}/type/Communities/sort/TopAll/page/1`
278     );
279   }
280
281   refetch() {
282     let listCommunitiesForm: ListCommunities = {
283       type_: ListingType.All,
284       sort: SortType.TopAll,
285       limit: communityLimit,
286       page: this.state.page,
287       auth: authField(false),
288     };
289
290     WebSocketService.Instance.send(
291       wsClient.listCommunities(listCommunitiesForm)
292     );
293   }
294
295   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
296     let pathSplit = req.path.split('/');
297     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
298     let listCommunitiesForm: ListCommunities = {
299       type_: ListingType.All,
300       sort: SortType.TopAll,
301       limit: communityLimit,
302       page,
303     };
304     setOptionalAuth(listCommunitiesForm, req.auth);
305
306     return [req.client.listCommunities(listCommunitiesForm)];
307   }
308
309   parseMessage(msg: any) {
310     let op = wsUserOp(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.communities.sort(
318         (a, b) => b.counts.subscribers - a.counts.subscribers
319       );
320       this.state.loading = false;
321       window.scrollTo(0, 0);
322       this.setState(this.state);
323     } else if (op == UserOperation.FollowCommunity) {
324       let data = wsJsonToRes<CommunityResponse>(msg).data;
325       let found = this.state.communities.find(
326         c => c.community.id == data.community_view.community.id
327       );
328       found.subscribed = data.community_view.subscribed;
329       found.counts.subscribers = data.community_view.counts.subscribers;
330       this.setState(this.state);
331     }
332   }
333 }