]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Merge remote-tracking branch 'origin/drone-ci' into drone-ci-dess
[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   SiteView,
13 } from 'lemmy-js-client';
14 import { WebSocketService } from '../services';
15 import {
16   wsJsonToRes,
17   toast,
18   getPageFromProps,
19   isBrowser,
20   setIsoData,
21   wsSubscribe,
22   wsUserOp,
23   wsClient,
24   authField,
25   setOptionalAuth,
26 } from '../utils';
27 import { CommunityLink } from './community-link';
28 import { i18n } from '../i18next';
29 import { InitialFetchRequest } from 'shared/interfaces';
30
31 const communityLimit = 100;
32
33 interface CommunitiesState {
34   communities: CommunityView[];
35   page: number;
36   loading: boolean;
37   site_view: SiteView;
38 }
39
40 interface CommunitiesProps {
41   page: number;
42 }
43
44 export class Communities extends Component<any, CommunitiesState> {
45   private subscription: Subscription;
46   private isoData = setIsoData(this.context);
47   private emptyState: CommunitiesState = {
48     communities: [],
49     loading: true,
50     page: getPageFromProps(this.props),
51     site_view: this.isoData.site_res.site_view,
52   };
53
54   constructor(props: any, context: any) {
55     super(props, context);
56     this.state = this.emptyState;
57
58     this.parseMessage = this.parseMessage.bind(this);
59     this.subscription = wsSubscribe(this.parseMessage);
60
61     // Only fetch the data if coming from another route
62     if (this.isoData.path == this.context.router.route.match.url) {
63       this.state.communities = this.isoData.routeData[0].communities;
64       this.state.communities.sort(
65         (a, b) => b.counts.subscribers - a.counts.subscribers
66       );
67       this.state.loading = false;
68     } else {
69       this.refetch();
70     }
71   }
72
73   componentWillUnmount() {
74     if (isBrowser()) {
75       this.subscription.unsubscribe();
76     }
77   }
78
79   static getDerivedStateFromProps(props: any): CommunitiesProps {
80     return {
81       page: getPageFromProps(props),
82     };
83   }
84
85   componentDidUpdate(_: any, lastState: CommunitiesState) {
86     if (lastState.page !== this.state.page) {
87       this.setState({ loading: true });
88       this.refetch();
89     }
90   }
91
92   get documentTitle(): string {
93     return `${i18n.t('communities')} - ${this.state.site_view.site.name}`;
94   }
95
96   render() {
97     return (
98       <div class="container">
99         <HtmlTags
100           title={this.documentTitle}
101           path={this.context.router.route.match.url}
102         />
103         {this.state.loading ? (
104           <h5 class="">
105             <svg class="icon icon-spinner spin">
106               <use xlinkHref="#icon-spinner"></use>
107             </svg>
108           </h5>
109         ) : (
110           <div>
111             <h5>{i18n.t('list_of_communities')}</h5>
112             <div class="table-responsive">
113               <table id="community_table" class="table table-sm table-hover">
114                 <thead class="pointer">
115                   <tr>
116                     <th>{i18n.t('name')}</th>
117                     <th>{i18n.t('category')}</th>
118                     <th class="text-right">{i18n.t('subscribers')}</th>
119                     <th class="text-right d-none d-lg-table-cell">
120                       {i18n.t('posts')}
121                     </th>
122                     <th class="text-right d-none d-lg-table-cell">
123                       {i18n.t('comments')}
124                     </th>
125                     <th></th>
126                   </tr>
127                 </thead>
128                 <tbody>
129                   {this.state.communities.map(cv => (
130                     <tr>
131                       <td>
132                         <CommunityLink community={cv.community} />
133                       </td>
134                       <td>{cv.category.name}</td>
135                       <td class="text-right">{cv.counts.subscribers}</td>
136                       <td class="text-right d-none d-lg-table-cell">
137                         {cv.counts.posts}
138                       </td>
139                       <td class="text-right d-none d-lg-table-cell">
140                         {cv.counts.comments}
141                       </td>
142                       <td class="text-right">
143                         {cv.subscribed ? (
144                           <span
145                             class="pointer btn-link"
146                             onClick={linkEvent(
147                               cv.community.id,
148                               this.handleUnsubscribe
149                             )}
150                           >
151                             {i18n.t('unsubscribe')}
152                           </span>
153                         ) : (
154                           <span
155                             class="pointer btn-link"
156                             onClick={linkEvent(
157                               cv.community.id,
158                               this.handleSubscribe
159                             )}
160                           >
161                             {i18n.t('subscribe')}
162                           </span>
163                         )}
164                       </td>
165                     </tr>
166                   ))}
167                 </tbody>
168               </table>
169             </div>
170             {this.paginator()}
171           </div>
172         )}
173       </div>
174     );
175   }
176
177   paginator() {
178     return (
179       <div class="mt-2">
180         {this.state.page > 1 && (
181           <button
182             class="btn btn-secondary mr-1"
183             onClick={linkEvent(this, this.prevPage)}
184           >
185             {i18n.t('prev')}
186           </button>
187         )}
188
189         {this.state.communities.length > 0 && (
190           <button
191             class="btn btn-secondary"
192             onClick={linkEvent(this, this.nextPage)}
193           >
194             {i18n.t('next')}
195           </button>
196         )}
197       </div>
198     );
199   }
200
201   updateUrl(paramUpdates: CommunitiesProps) {
202     const page = paramUpdates.page || this.state.page;
203     this.props.history.push(`/communities/page/${page}`);
204   }
205
206   nextPage(i: Communities) {
207     i.updateUrl({ page: i.state.page + 1 });
208   }
209
210   prevPage(i: Communities) {
211     i.updateUrl({ page: i.state.page - 1 });
212   }
213
214   handleUnsubscribe(communityId: number) {
215     let form: FollowCommunity = {
216       community_id: communityId,
217       follow: false,
218       auth: authField(),
219     };
220     WebSocketService.Instance.send(wsClient.followCommunity(form));
221   }
222
223   handleSubscribe(communityId: number) {
224     let form: FollowCommunity = {
225       community_id: communityId,
226       follow: true,
227       auth: authField(),
228     };
229     WebSocketService.Instance.send(wsClient.followCommunity(form));
230   }
231
232   refetch() {
233     let listCommunitiesForm: ListCommunities = {
234       sort: SortType.TopAll,
235       limit: communityLimit,
236       page: this.state.page,
237       auth: authField(false),
238     };
239
240     WebSocketService.Instance.send(
241       wsClient.listCommunities(listCommunitiesForm)
242     );
243   }
244
245   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
246     let pathSplit = req.path.split('/');
247     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
248     let listCommunitiesForm: ListCommunities = {
249       sort: SortType.TopAll,
250       limit: communityLimit,
251       page,
252     };
253     setOptionalAuth(listCommunitiesForm, req.auth);
254
255     return [req.client.listCommunities(listCommunitiesForm)];
256   }
257
258   parseMessage(msg: any) {
259     let op = wsUserOp(msg);
260     if (msg.error) {
261       toast(i18n.t(msg.error), 'danger');
262       return;
263     } else if (op == UserOperation.ListCommunities) {
264       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
265       this.state.communities = data.communities;
266       this.state.communities.sort(
267         (a, b) => b.counts.subscribers - a.counts.subscribers
268       );
269       this.state.loading = false;
270       window.scrollTo(0, 0);
271       this.setState(this.state);
272     } else if (op == UserOperation.FollowCommunity) {
273       let data = wsJsonToRes<CommunityResponse>(msg).data;
274       let found = this.state.communities.find(
275         c => c.community.id == data.community_view.community.id
276       );
277       found.subscribed = data.community_view.subscribed;
278       found.counts.subscribers = data.community_view.counts.subscribers;
279       this.setState(this.state);
280     }
281   }
282 }