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