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