]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
First pass at v2_api
[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 { UserService, WebSocketService } from '../services';
15 import {
16   wsJsonToRes,
17   toast,
18   getPageFromProps,
19   isBrowser,
20   setIsoData,
21   wsSubscribe,
22   wsUserOp,
23 } from '../utils';
24 import { CommunityLink } from './community-link';
25 import { i18n } from '../i18next';
26 import { InitialFetchRequest } from 'shared/interfaces';
27
28 const communityLimit = 100;
29
30 interface CommunitiesState {
31   communities: CommunityView[];
32   page: number;
33   loading: boolean;
34   site_view: SiteView;
35 }
36
37 interface CommunitiesProps {
38   page: number;
39 }
40
41 export class Communities extends Component<any, CommunitiesState> {
42   private subscription: Subscription;
43   private isoData = setIsoData(this.context);
44   private emptyState: CommunitiesState = {
45     communities: [],
46     loading: true,
47     page: getPageFromProps(this.props),
48     site_view: this.isoData.site_res.site_view,
49   };
50
51   constructor(props: any, context: any) {
52     super(props, context);
53     this.state = this.emptyState;
54
55     this.parseMessage = this.parseMessage.bind(this);
56     this.subscription = wsSubscribe(this.parseMessage);
57
58     // Only fetch the data if coming from another route
59     if (this.isoData.path == this.context.router.route.match.url) {
60       this.state.communities = this.isoData.routeData[0].communities;
61       this.state.communities.sort(
62         (a, b) => b.counts.subscribers - a.counts.subscribers
63       );
64       this.state.loading = false;
65     } else {
66       this.refetch();
67     }
68   }
69
70   componentWillUnmount() {
71     if (isBrowser()) {
72       this.subscription.unsubscribe();
73     }
74   }
75
76   static getDerivedStateFromProps(props: any): CommunitiesProps {
77     return {
78       page: getPageFromProps(props),
79     };
80   }
81
82   componentDidUpdate(_: any, lastState: CommunitiesState) {
83     if (lastState.page !== this.state.page) {
84       this.setState({ loading: true });
85       this.refetch();
86     }
87   }
88
89   get documentTitle(): string {
90     return `${i18n.t('communities')} - ${this.state.site_view.site.name}`;
91   }
92
93   render() {
94     return (
95       <div class="container">
96         <HtmlTags
97           title={this.documentTitle}
98           path={this.context.router.route.match.url}
99         />
100         {this.state.loading ? (
101           <h5 class="">
102             <svg class="icon icon-spinner spin">
103               <use xlinkHref="#icon-spinner"></use>
104             </svg>
105           </h5>
106         ) : (
107           <div>
108             <h5>{i18n.t('list_of_communities')}</h5>
109             <div class="table-responsive">
110               <table id="community_table" class="table table-sm table-hover">
111                 <thead class="pointer">
112                   <tr>
113                     <th>{i18n.t('name')}</th>
114                     <th>{i18n.t('category')}</th>
115                     <th class="text-right">{i18n.t('subscribers')}</th>
116                     <th class="text-right d-none d-lg-table-cell">
117                       {i18n.t('posts')}
118                     </th>
119                     <th class="text-right d-none d-lg-table-cell">
120                       {i18n.t('comments')}
121                     </th>
122                     <th></th>
123                   </tr>
124                 </thead>
125                 <tbody>
126                   {this.state.communities.map(cv => (
127                     <tr>
128                       <td>
129                         <CommunityLink community={cv.community} />
130                       </td>
131                       <td>{cv.category.name}</td>
132                       <td class="text-right">{cv.counts.subscribers}</td>
133                       <td class="text-right d-none d-lg-table-cell">
134                         {cv.counts.posts}
135                       </td>
136                       <td class="text-right d-none d-lg-table-cell">
137                         {cv.counts.comments}
138                       </td>
139                       <td class="text-right">
140                         {cv.subscribed ? (
141                           <span
142                             class="pointer btn-link"
143                             onClick={linkEvent(
144                               cv.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                               cv.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: FollowCommunity = {
213       community_id: communityId,
214       follow: false,
215       auth: UserService.Instance.authField(),
216     };
217     WebSocketService.Instance.client.followCommunity(form);
218   }
219
220   handleSubscribe(communityId: number) {
221     let form: FollowCommunity = {
222       community_id: communityId,
223       follow: true,
224       auth: UserService.Instance.authField(),
225     };
226     WebSocketService.Instance.client.followCommunity(form);
227   }
228
229   refetch() {
230     let listCommunitiesForm: ListCommunities = {
231       sort: SortType.TopAll,
232       limit: communityLimit,
233       page: this.state.page,
234       auth: UserService.Instance.authField(false),
235     };
236
237     WebSocketService.Instance.client.listCommunities(listCommunitiesForm);
238   }
239
240   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
241     let pathSplit = req.path.split('/');
242     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
243     let listCommunitiesForm: ListCommunities = {
244       sort: SortType.TopAll,
245       limit: communityLimit,
246       page,
247       auth: req.auth,
248     };
249
250     return [req.client.listCommunities(listCommunitiesForm)];
251   }
252
253   parseMessage(msg: any) {
254     let op = wsUserOp(msg);
255     if (msg.error) {
256       toast(i18n.t(msg.error), 'danger');
257       return;
258     } else if (op == UserOperation.ListCommunities) {
259       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
260       this.state.communities = data.communities;
261       this.state.communities.sort(
262         (a, b) => b.counts.subscribers - a.counts.subscribers
263       );
264       this.state.loading = false;
265       window.scrollTo(0, 0);
266       this.setState(this.state);
267     } else if (op == UserOperation.FollowCommunity) {
268       let data = wsJsonToRes<CommunityResponse>(msg).data;
269       let found = this.state.communities.find(
270         c => c.community.id == data.community_view.community.id
271       );
272       found.subscribed = data.community_view.subscribed;
273       found.counts.subscribers = data.community_view.counts.subscribers;
274       this.setState(this.state);
275     }
276   }
277 }