]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Adding some active users aggregate fields. (#148)
[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 { i18n } from '../i18next';
30 import { InitialFetchRequest } from 'shared/interfaces';
31
32 const communityLimit = 100;
33
34 interface CommunitiesState {
35   communities: CommunityView[];
36   page: number;
37   loading: boolean;
38   site_view: SiteView;
39   searchText: string;
40 }
41
42 interface CommunitiesProps {
43   page: number;
44 }
45
46 export class Communities extends Component<any, CommunitiesState> {
47   private subscription: Subscription;
48   private isoData = setIsoData(this.context);
49   private emptyState: CommunitiesState = {
50     communities: [],
51     loading: true,
52     page: getPageFromProps(this.props),
53     site_view: this.isoData.site_res.site_view,
54     searchText: '',
55   };
56
57   constructor(props: any, context: any) {
58     super(props, context);
59     this.state = this.emptyState;
60
61     this.parseMessage = this.parseMessage.bind(this);
62     this.subscription = wsSubscribe(this.parseMessage);
63
64     // Only fetch the data if coming from another route
65     if (this.isoData.path == this.context.router.route.match.url) {
66       this.state.communities = this.isoData.routeData[0].communities;
67       this.state.communities.sort(
68         (a, b) => b.counts.subscribers - a.counts.subscribers
69       );
70       this.state.loading = false;
71     } else {
72       this.refetch();
73     }
74   }
75
76   componentWillUnmount() {
77     if (isBrowser()) {
78       this.subscription.unsubscribe();
79     }
80   }
81
82   static getDerivedStateFromProps(props: any): CommunitiesProps {
83     return {
84       page: getPageFromProps(props),
85     };
86   }
87
88   componentDidUpdate(_: any, lastState: CommunitiesState) {
89     if (lastState.page !== this.state.page) {
90       this.setState({ loading: true });
91       this.refetch();
92     }
93   }
94
95   get documentTitle(): string {
96     return `${i18n.t('communities')} - ${this.state.site_view.site.name}`;
97   }
98
99   render() {
100     return (
101       <div class="container">
102         <HtmlTags
103           title={this.documentTitle}
104           path={this.context.router.route.match.url}
105         />
106         {this.state.loading ? (
107           <h5 class="">
108             <svg class="icon icon-spinner spin">
109               <use xlinkHref="#icon-spinner"></use>
110             </svg>
111           </h5>
112         ) : (
113           <div>
114             <div class="row">
115               <div class="col-md-6">
116                 <h4>{i18n.t('list_of_communities')}</h4>
117               </div>
118               <div class="col-md-6">
119                 <div class="float-md-right">{this.searchForm()}</div>
120               </div>
121             </div>
122
123             <div class="table-responsive">
124               <table id="community_table" class="table table-sm table-hover">
125                 <thead class="pointer">
126                   <tr>
127                     <th>{i18n.t('name')}</th>
128                     <th>{i18n.t('category')}</th>
129                     <th class="text-right">{i18n.t('subscribers')}</th>
130                     <th class="text-right">
131                       {i18n.t('users')} / {i18n.t('month')}
132                     </th>
133                     <th class="text-right d-none d-lg-table-cell">
134                       {i18n.t('posts')}
135                     </th>
136                     <th class="text-right d-none d-lg-table-cell">
137                       {i18n.t('comments')}
138                     </th>
139                     <th></th>
140                   </tr>
141                 </thead>
142                 <tbody>
143                   {this.state.communities.map(cv => (
144                     <tr>
145                       <td>
146                         <CommunityLink community={cv.community} />
147                       </td>
148                       <td>{cv.category.name}</td>
149                       <td class="text-right">{cv.counts.subscribers}</td>
150                       <td class="text-right">{cv.counts.users_active_month}</td>
151                       <td class="text-right d-none d-lg-table-cell">
152                         {cv.counts.posts}
153                       </td>
154                       <td class="text-right d-none d-lg-table-cell">
155                         {cv.counts.comments}
156                       </td>
157                       <td class="text-right">
158                         {cv.subscribed ? (
159                           <span
160                             class="pointer btn-link"
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                             onClick={linkEvent(
172                               cv.community.id,
173                               this.handleSubscribe
174                             )}
175                           >
176                             {i18n.t('subscribe')}
177                           </span>
178                         )}
179                       </td>
180                     </tr>
181                   ))}
182                 </tbody>
183               </table>
184             </div>
185             {this.paginator()}
186           </div>
187         )}
188       </div>
189     );
190   }
191
192   searchForm() {
193     return (
194       <form
195         class="form-inline"
196         onSubmit={linkEvent(this, this.handleSearchSubmit)}
197       >
198         <input
199           type="text"
200           class="form-control mr-2 mb-2"
201           value={this.state.searchText}
202           placeholder={`${i18n.t('search')}...`}
203           onInput={linkEvent(this, this.handleSearchChange)}
204           required
205           minLength={3}
206         />
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.TopAll,
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.TopAll,
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     if (msg.error) {
311       toast(i18n.t(msg.error), 'danger');
312       return;
313     } else if (op == UserOperation.ListCommunities) {
314       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
315       this.state.communities = data.communities;
316       this.state.communities.sort(
317         (a, b) => b.counts.subscribers - a.counts.subscribers
318       );
319       this.state.loading = false;
320       window.scrollTo(0, 0);
321       this.setState(this.state);
322     } else if (op == UserOperation.FollowCommunity) {
323       let data = wsJsonToRes<CommunityResponse>(msg).data;
324       let found = this.state.communities.find(
325         c => c.community.id == data.community_view.community.id
326       );
327       found.subscribed = data.community_view.subscribed;
328       found.counts.subscribers = data.community_view.counts.subscribers;
329       this.setState(this.state);
330     }
331   }
332 }