]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Adding opengraph tags. Fixes #5
[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   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         <HtmlTags
98           title={this.documentTitle}
99           path={this.context.router.route.match.url}
100         />
101         {this.state.loading ? (
102           <h5 class="">
103             <svg class="icon icon-spinner spin">
104               <use xlinkHref="#icon-spinner"></use>
105             </svg>
106           </h5>
107         ) : (
108           <div>
109             <h5>{i18n.t('list_of_communities')}</h5>
110             <div class="table-responsive">
111               <table id="community_table" class="table table-sm table-hover">
112                 <thead class="pointer">
113                   <tr>
114                     <th>{i18n.t('name')}</th>
115                     <th>{i18n.t('category')}</th>
116                     <th class="text-right">{i18n.t('subscribers')}</th>
117                     <th class="text-right d-none d-lg-table-cell">
118                       {i18n.t('posts')}
119                     </th>
120                     <th class="text-right d-none d-lg-table-cell">
121                       {i18n.t('comments')}
122                     </th>
123                     <th></th>
124                   </tr>
125                 </thead>
126                 <tbody>
127                   {this.state.communities.map(community => (
128                     <tr>
129                       <td>
130                         <CommunityLink community={community} />
131                       </td>
132                       <td>{community.category_name}</td>
133                       <td class="text-right">
134                         {community.number_of_subscribers}
135                       </td>
136                       <td class="text-right d-none d-lg-table-cell">
137                         {community.number_of_posts}
138                       </td>
139                       <td class="text-right d-none d-lg-table-cell">
140                         {community.number_of_comments}
141                       </td>
142                       <td class="text-right">
143                         {community.subscribed ? (
144                           <span
145                             class="pointer btn-link"
146                             onClick={linkEvent(
147                               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                               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: FollowCommunityForm = {
216       community_id: communityId,
217       follow: false,
218     };
219     WebSocketService.Instance.followCommunity(form);
220   }
221
222   handleSubscribe(communityId: number) {
223     let form: FollowCommunityForm = {
224       community_id: communityId,
225       follow: true,
226     };
227     WebSocketService.Instance.followCommunity(form);
228   }
229
230   refetch() {
231     let listCommunitiesForm: ListCommunitiesForm = {
232       sort: SortType.TopAll,
233       limit: communityLimit,
234       page: this.state.page,
235     };
236
237     WebSocketService.Instance.listCommunities(listCommunitiesForm);
238   }
239
240   static fetchInitialData(auth: string, path: string): Promise<any>[] {
241     let pathSplit = path.split('/');
242     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
243     let listCommunitiesForm: ListCommunitiesForm = {
244       sort: SortType.TopAll,
245       limit: communityLimit,
246       page,
247     };
248     setAuth(listCommunitiesForm, auth);
249
250     return [lemmyHttp.listCommunities(listCommunitiesForm)];
251   }
252
253   parseMessage(msg: WebSocketJsonResponse) {
254     console.log(msg);
255     let res = wsJsonToRes(msg);
256     if (msg.error) {
257       toast(i18n.t(msg.error), 'danger');
258       return;
259     } else if (res.op == UserOperation.ListCommunities) {
260       let data = res.data as ListCommunitiesResponse;
261       this.state.communities = data.communities;
262       this.state.communities.sort(
263         (a, b) => b.number_of_subscribers - a.number_of_subscribers
264       );
265       this.state.loading = false;
266       window.scrollTo(0, 0);
267       this.setState(this.state);
268     } else if (res.op == UserOperation.FollowCommunity) {
269       let data = res.data as CommunityResponse;
270       let found = this.state.communities.find(c => c.id == data.community.id);
271       found.subscribed = data.community.subscribed;
272       found.number_of_subscribers = data.community.number_of_subscribers;
273       this.setState(this.state);
274     }
275   }
276 }