]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Create community, Create post, and instances pages 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
56     this.parseMessage = this.parseMessage.bind(this);
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.communities.sort(
63         (a, b) => b.number_of_subscribers - a.number_of_subscribers
64       );
65       this.state.loading = false;
66     } else {
67       this.refetch();
68     }
69   }
70
71   componentWillUnmount() {
72     if (isBrowser()) {
73       this.subscription.unsubscribe();
74     }
75   }
76
77   static getDerivedStateFromProps(props: any): CommunitiesProps {
78     return {
79       page: getPageFromProps(props),
80     };
81   }
82
83   componentDidUpdate(_: any, lastState: CommunitiesState) {
84     if (lastState.page !== this.state.page) {
85       this.setState({ loading: true });
86       this.refetch();
87     }
88   }
89
90   get documentTitle(): string {
91     return `${i18n.t('communities')} - ${this.state.site.name}`;
92   }
93
94   render() {
95     return (
96       <div class="container">
97         <Helmet title={this.documentTitle} />
98         {this.state.loading ? (
99           <h5 class="">
100             <svg class="icon icon-spinner spin">
101               <use xlinkHref="#icon-spinner"></use>
102             </svg>
103           </h5>
104         ) : (
105           <div>
106             <h5>{i18n.t('list_of_communities')}</h5>
107             <div class="table-responsive">
108               <table id="community_table" class="table table-sm table-hover">
109                 <thead class="pointer">
110                   <tr>
111                     <th>{i18n.t('name')}</th>
112                     <th>{i18n.t('category')}</th>
113                     <th class="text-right">{i18n.t('subscribers')}</th>
114                     <th class="text-right d-none d-lg-table-cell">
115                       {i18n.t('posts')}
116                     </th>
117                     <th class="text-right d-none d-lg-table-cell">
118                       {i18n.t('comments')}
119                     </th>
120                     <th></th>
121                   </tr>
122                 </thead>
123                 <tbody>
124                   {this.state.communities.map(community => (
125                     <tr>
126                       <td>
127                         <CommunityLink community={community} />
128                       </td>
129                       <td>{community.category_name}</td>
130                       <td class="text-right">
131                         {community.number_of_subscribers}
132                       </td>
133                       <td class="text-right d-none d-lg-table-cell">
134                         {community.number_of_posts}
135                       </td>
136                       <td class="text-right d-none d-lg-table-cell">
137                         {community.number_of_comments}
138                       </td>
139                       <td class="text-right">
140                         {community.subscribed ? (
141                           <span
142                             class="pointer btn-link"
143                             onClick={linkEvent(
144                               community.id,
145                               this.handleUnsubscribe
146                             )}
147                           >
148                             {i18n.t('unsubscribe')}
149                           </span>
150                         ) : (
151                           <span
152                             class="pointer btn-link"
153                             onClick={linkEvent(
154                               community.id,
155                               this.handleSubscribe
156                             )}
157                           >
158                             {i18n.t('subscribe')}
159                           </span>
160                         )}
161                       </td>
162                     </tr>
163                   ))}
164                 </tbody>
165               </table>
166             </div>
167             {this.paginator()}
168           </div>
169         )}
170       </div>
171     );
172   }
173
174   paginator() {
175     return (
176       <div class="mt-2">
177         {this.state.page > 1 && (
178           <button
179             class="btn btn-secondary mr-1"
180             onClick={linkEvent(this, this.prevPage)}
181           >
182             {i18n.t('prev')}
183           </button>
184         )}
185
186         {this.state.communities.length > 0 && (
187           <button
188             class="btn btn-secondary"
189             onClick={linkEvent(this, this.nextPage)}
190           >
191             {i18n.t('next')}
192           </button>
193         )}
194       </div>
195     );
196   }
197
198   updateUrl(paramUpdates: CommunitiesProps) {
199     const page = paramUpdates.page || this.state.page;
200     this.props.history.push(`/communities/page/${page}`);
201   }
202
203   nextPage(i: Communities) {
204     i.updateUrl({ page: i.state.page + 1 });
205   }
206
207   prevPage(i: Communities) {
208     i.updateUrl({ page: i.state.page - 1 });
209   }
210
211   handleUnsubscribe(communityId: number) {
212     let form: FollowCommunityForm = {
213       community_id: communityId,
214       follow: false,
215     };
216     WebSocketService.Instance.followCommunity(form);
217   }
218
219   handleSubscribe(communityId: number) {
220     let form: FollowCommunityForm = {
221       community_id: communityId,
222       follow: true,
223     };
224     WebSocketService.Instance.followCommunity(form);
225   }
226
227   refetch() {
228     let listCommunitiesForm: ListCommunitiesForm = {
229       sort: SortType.TopAll,
230       limit: communityLimit,
231       page: this.state.page,
232     };
233
234     WebSocketService.Instance.listCommunities(listCommunitiesForm);
235   }
236
237   static fetchInitialData(auth: string, path: string): Promise<any>[] {
238     let pathSplit = path.split('/');
239     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
240     let listCommunitiesForm: ListCommunitiesForm = {
241       sort: SortType.TopAll,
242       limit: communityLimit,
243       page,
244     };
245     setAuth(listCommunitiesForm, auth);
246
247     return [lemmyHttp.listCommunities(listCommunitiesForm)];
248   }
249
250   parseMessage(msg: WebSocketJsonResponse) {
251     console.log(msg);
252     let res = wsJsonToRes(msg);
253     if (msg.error) {
254       toast(i18n.t(msg.error), 'danger');
255       return;
256     } else if (res.op == UserOperation.ListCommunities) {
257       let data = res.data as ListCommunitiesResponse;
258       this.state.communities = data.communities;
259       this.state.communities.sort(
260         (a, b) => b.number_of_subscribers - a.number_of_subscribers
261       );
262       this.state.loading = false;
263       window.scrollTo(0, 0);
264       this.setState(this.state);
265     } else if (res.op == UserOperation.FollowCommunity) {
266       let data = res.data as CommunityResponse;
267       let found = this.state.communities.find(c => c.id == data.community.id);
268       found.subscribed = data.community.subscribed;
269       found.number_of_subscribers = data.community.number_of_subscribers;
270       this.setState(this.state);
271     }
272   }
273 }