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