]> Untitled Git - lemmy-ui.git/blob - src/shared/components/communities.tsx
Add aria attributes where possible (#156)
[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">
131                       {i18n.t('users')} / {i18n.t('month')}
132                     </th>
133                     <th class="text-right d-none d-lg-table-cell">
134                       {i18n.t('posts')}
135                     </th>
136                     <th class="text-right d-none d-lg-table-cell">
137                       {i18n.t('comments')}
138                     </th>
139                     <th></th>
140                   </tr>
141                 </thead>
142                 <tbody>
143                   {this.state.communities.map(cv => (
144                     <tr>
145                       <td>
146                         <CommunityLink community={cv.community} />
147                       </td>
148                       <td>{cv.category.name}</td>
149                       <td class="text-right">{cv.counts.subscribers}</td>
150                       <td class="text-right">{cv.counts.users_active_month}</td>
151                       <td class="text-right d-none d-lg-table-cell">
152                         {cv.counts.posts}
153                       </td>
154                       <td class="text-right d-none d-lg-table-cell">
155                         {cv.counts.comments}
156                       </td>
157                       <td class="text-right">
158                         {cv.subscribed ? (
159                           <span
160                             class="pointer btn-link"
161                             role="button"
162                             onClick={linkEvent(
163                               cv.community.id,
164                               this.handleUnsubscribe
165                             )}
166                           >
167                             {i18n.t('unsubscribe')}
168                           </span>
169                         ) : (
170                           <span
171                             class="pointer btn-link"
172                             role="button"
173                             onClick={linkEvent(
174                               cv.community.id,
175                               this.handleSubscribe
176                             )}
177                           >
178                             {i18n.t('subscribe')}
179                           </span>
180                         )}
181                       </td>
182                     </tr>
183                   ))}
184                 </tbody>
185               </table>
186             </div>
187             {this.paginator()}
188           </div>
189         )}
190       </div>
191     );
192   }
193
194   searchForm() {
195     return (
196       <form
197         class="form-inline"
198         onSubmit={linkEvent(this, this.handleSearchSubmit)}
199       >
200         <input
201           type="text"
202           class="form-control mr-2 mb-2"
203           value={this.state.searchText}
204           placeholder={`${i18n.t('search')}...`}
205           onInput={linkEvent(this, this.handleSearchChange)}
206           required
207           minLength={3}
208         />
209         <button type="submit" class="btn btn-secondary mr-2 mb-2">
210           <span>{i18n.t('search')}</span>
211         </button>
212       </form>
213     );
214   }
215
216   paginator() {
217     return (
218       <div class="mt-2">
219         {this.state.page > 1 && (
220           <button
221             class="btn btn-secondary mr-1"
222             onClick={linkEvent(this, this.prevPage)}
223           >
224             {i18n.t('prev')}
225           </button>
226         )}
227
228         {this.state.communities.length > 0 && (
229           <button
230             class="btn btn-secondary"
231             onClick={linkEvent(this, this.nextPage)}
232           >
233             {i18n.t('next')}
234           </button>
235         )}
236       </div>
237     );
238   }
239
240   updateUrl(paramUpdates: CommunitiesProps) {
241     const page = paramUpdates.page || this.state.page;
242     this.props.history.push(`/communities/page/${page}`);
243   }
244
245   nextPage(i: Communities) {
246     i.updateUrl({ page: i.state.page + 1 });
247   }
248
249   prevPage(i: Communities) {
250     i.updateUrl({ page: i.state.page - 1 });
251   }
252
253   handleUnsubscribe(communityId: number) {
254     let form: FollowCommunity = {
255       community_id: communityId,
256       follow: false,
257       auth: authField(),
258     };
259     WebSocketService.Instance.send(wsClient.followCommunity(form));
260   }
261
262   handleSubscribe(communityId: number) {
263     let form: FollowCommunity = {
264       community_id: communityId,
265       follow: true,
266       auth: authField(),
267     };
268     WebSocketService.Instance.send(wsClient.followCommunity(form));
269   }
270
271   handleSearchChange(i: Communities, event: any) {
272     i.setState({ searchText: event.target.value });
273   }
274
275   handleSearchSubmit(i: Communities) {
276     const searchParamEncoded = encodeURIComponent(i.state.searchText);
277     i.context.router.history.push(
278       `/search/q/${searchParamEncoded}/type/Communities/sort/TopAll/page/1`
279     );
280   }
281
282   refetch() {
283     let listCommunitiesForm: ListCommunities = {
284       type_: ListingType.All,
285       sort: SortType.TopAll,
286       limit: communityLimit,
287       page: this.state.page,
288       auth: authField(false),
289     };
290
291     WebSocketService.Instance.send(
292       wsClient.listCommunities(listCommunitiesForm)
293     );
294   }
295
296   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
297     let pathSplit = req.path.split('/');
298     let page = pathSplit[3] ? Number(pathSplit[3]) : 1;
299     let listCommunitiesForm: ListCommunities = {
300       type_: ListingType.All,
301       sort: SortType.TopAll,
302       limit: communityLimit,
303       page,
304     };
305     setOptionalAuth(listCommunitiesForm, req.auth);
306
307     return [req.client.listCommunities(listCommunitiesForm)];
308   }
309
310   parseMessage(msg: any) {
311     let op = wsUserOp(msg);
312     if (msg.error) {
313       toast(i18n.t(msg.error), 'danger');
314       return;
315     } else if (op == UserOperation.ListCommunities) {
316       let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
317       this.state.communities = data.communities;
318       this.state.communities.sort(
319         (a, b) => b.counts.subscribers - a.counts.subscribers
320       );
321       this.state.loading = false;
322       window.scrollTo(0, 0);
323       this.setState(this.state);
324     } else if (op == UserOperation.FollowCommunity) {
325       let data = wsJsonToRes<CommunityResponse>(msg).data;
326       let found = this.state.communities.find(
327         c => c.community.id == data.community_view.community.id
328       );
329       found.subscribed = data.community_view.subscribed;
330       found.counts.subscribers = data.community_view.counts.subscribers;
331       this.setState(this.state);
332     }
333   }
334 }