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