]> Untitled Git - lemmy.git/blob - ui/src/components/community.tsx
Front end federation names and links for users, posts, and communities.
[lemmy.git] / ui / src / components / community.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Subscription } from 'rxjs';
3 import { retryWhen, delay, take } from 'rxjs/operators';
4 import {
5   UserOperation,
6   Community as CommunityI,
7   GetCommunityResponse,
8   CommunityResponse,
9   CommunityUser,
10   UserView,
11   SortType,
12   Post,
13   GetPostsForm,
14   GetCommunityForm,
15   ListingType,
16   DataType,
17   GetPostsResponse,
18   PostResponse,
19   AddModToCommunityResponse,
20   BanFromCommunityResponse,
21   Comment,
22   GetCommentsForm,
23   GetCommentsResponse,
24   CommentResponse,
25   WebSocketJsonResponse,
26 } from '../interfaces';
27 import { WebSocketService } from '../services';
28 import { PostListings } from './post-listings';
29 import { CommentNodes } from './comment-nodes';
30 import { SortSelect } from './sort-select';
31 import { DataTypeSelect } from './data-type-select';
32 import { Sidebar } from './sidebar';
33 import {
34   wsJsonToRes,
35   fetchLimit,
36   toast,
37   getPageFromProps,
38   getSortTypeFromProps,
39   getDataTypeFromProps,
40   editCommentRes,
41   saveCommentRes,
42   createCommentLikeRes,
43   createPostLikeFindRes,
44   editPostFindRes,
45   commentsToFlatNodes,
46   setupTippy,
47 } from '../utils';
48 import { i18n } from '../i18next';
49
50 interface State {
51   community: CommunityI;
52   communityId: number;
53   communityName: string;
54   moderators: Array<CommunityUser>;
55   admins: Array<UserView>;
56   online: number;
57   loading: boolean;
58   posts: Array<Post>;
59   comments: Array<Comment>;
60   dataType: DataType;
61   sort: SortType;
62   page: number;
63 }
64
65 export class Community extends Component<any, State> {
66   private subscription: Subscription;
67   private emptyState: State = {
68     community: {
69       id: null,
70       name: null,
71       title: null,
72       category_id: null,
73       category_name: null,
74       creator_id: null,
75       creator_name: null,
76       number_of_subscribers: null,
77       number_of_posts: null,
78       number_of_comments: null,
79       published: null,
80       removed: null,
81       nsfw: false,
82       deleted: null,
83       local: null,
84       actor_id: null,
85       last_refreshed_at: null,
86       creator_actor_id: null,
87       creator_local: null,
88     },
89     moderators: [],
90     admins: [],
91     communityId: Number(this.props.match.params.id),
92     communityName: this.props.match.params.name,
93     online: null,
94     loading: true,
95     posts: [],
96     comments: [],
97     dataType: getDataTypeFromProps(this.props),
98     sort: getSortTypeFromProps(this.props),
99     page: getPageFromProps(this.props),
100   };
101
102   constructor(props: any, context: any) {
103     super(props, context);
104
105     this.state = this.emptyState;
106     this.handleSortChange = this.handleSortChange.bind(this);
107     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
108
109     this.subscription = WebSocketService.Instance.subject
110       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
111       .subscribe(
112         msg => this.parseMessage(msg),
113         err => console.error(err),
114         () => console.log('complete')
115       );
116
117     let form: GetCommunityForm = {
118       id: this.state.communityId ? this.state.communityId : null,
119       name: this.state.communityName ? this.state.communityName : null,
120     };
121     WebSocketService.Instance.getCommunity(form);
122   }
123
124   componentWillUnmount() {
125     this.subscription.unsubscribe();
126   }
127
128   // Necessary for back button for some reason
129   componentWillReceiveProps(nextProps: any) {
130     if (
131       nextProps.history.action == 'POP' ||
132       nextProps.history.action == 'PUSH'
133     ) {
134       this.state.dataType = getDataTypeFromProps(nextProps);
135       this.state.sort = getSortTypeFromProps(nextProps);
136       this.state.page = getPageFromProps(nextProps);
137       this.setState(this.state);
138       this.fetchData();
139     }
140   }
141
142   render() {
143     return (
144       <div class="container">
145         {this.selects()}
146         {this.state.loading ? (
147           <h5>
148             <svg class="icon icon-spinner spin">
149               <use xlinkHref="#icon-spinner"></use>
150             </svg>
151           </h5>
152         ) : (
153           <div class="row">
154             <div class="col-12 col-md-8">
155               <h5>
156                 {this.state.community.title}
157                 {this.state.community.removed && (
158                   <small className="ml-2 text-muted font-italic">
159                     {i18n.t('removed')}
160                   </small>
161                 )}
162                 {this.state.community.nsfw && (
163                   <small className="ml-2 text-muted font-italic">
164                     {i18n.t('nsfw')}
165                   </small>
166                 )}
167               </h5>
168               {this.listings()}
169               {this.paginator()}
170             </div>
171             <div class="col-12 col-md-4">
172               <Sidebar
173                 community={this.state.community}
174                 moderators={this.state.moderators}
175                 admins={this.state.admins}
176                 online={this.state.online}
177               />
178             </div>
179           </div>
180         )}
181       </div>
182     );
183   }
184
185   listings() {
186     return this.state.dataType == DataType.Post ? (
187       <PostListings
188         posts={this.state.posts}
189         removeDuplicates
190         sort={this.state.sort}
191       />
192     ) : (
193       <CommentNodes
194         nodes={commentsToFlatNodes(this.state.comments)}
195         noIndent
196         sortType={this.state.sort}
197         showContext
198       />
199     );
200   }
201
202   selects() {
203     return (
204       <div class="mb-3">
205         <span class="mr-3">
206           <DataTypeSelect
207             type_={this.state.dataType}
208             onChange={this.handleDataTypeChange}
209           />
210         </span>
211         <span class="mr-2">
212           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
213         </span>
214         <a
215           href={`/feeds/c/${this.state.communityName}.xml?sort=${
216             SortType[this.state.sort]
217           }`}
218           target="_blank"
219           title="RSS"
220         >
221           <svg class="icon text-muted small">
222             <use xlinkHref="#icon-rss">#</use>
223           </svg>
224         </a>
225       </div>
226     );
227   }
228
229   paginator() {
230     return (
231       <div class="my-2">
232         {this.state.page > 1 && (
233           <button
234             class="btn btn-sm btn-secondary mr-1"
235             onClick={linkEvent(this, this.prevPage)}
236           >
237             {i18n.t('prev')}
238           </button>
239         )}
240         {this.state.posts.length == fetchLimit && (
241           <button
242             class="btn btn-sm btn-secondary"
243             onClick={linkEvent(this, this.nextPage)}
244           >
245             {i18n.t('next')}
246           </button>
247         )}
248       </div>
249     );
250   }
251
252   nextPage(i: Community) {
253     i.state.page++;
254     i.setState(i.state);
255     i.updateUrl();
256     i.fetchData();
257     window.scrollTo(0, 0);
258   }
259
260   prevPage(i: Community) {
261     i.state.page--;
262     i.setState(i.state);
263     i.updateUrl();
264     i.fetchData();
265     window.scrollTo(0, 0);
266   }
267
268   handleSortChange(val: SortType) {
269     this.state.sort = val;
270     this.state.page = 1;
271     this.state.loading = true;
272     this.setState(this.state);
273     this.updateUrl();
274     this.fetchData();
275     window.scrollTo(0, 0);
276   }
277
278   handleDataTypeChange(val: DataType) {
279     this.state.dataType = val;
280     this.state.page = 1;
281     this.state.loading = true;
282     this.setState(this.state);
283     this.updateUrl();
284     this.fetchData();
285     window.scrollTo(0, 0);
286   }
287
288   updateUrl() {
289     let dataTypeStr = DataType[this.state.dataType].toLowerCase();
290     let sortStr = SortType[this.state.sort].toLowerCase();
291     this.props.history.push(
292       `/c/${this.state.community.name}/data_type/${dataTypeStr}/sort/${sortStr}/page/${this.state.page}`
293     );
294   }
295
296   fetchData() {
297     if (this.state.dataType == DataType.Post) {
298       let getPostsForm: GetPostsForm = {
299         page: this.state.page,
300         limit: fetchLimit,
301         sort: SortType[this.state.sort],
302         type_: ListingType[ListingType.Community],
303         community_id: this.state.community.id,
304       };
305       WebSocketService.Instance.getPosts(getPostsForm);
306     } else {
307       let getCommentsForm: GetCommentsForm = {
308         page: this.state.page,
309         limit: fetchLimit,
310         sort: SortType[this.state.sort],
311         type_: ListingType[ListingType.Community],
312         community_id: this.state.community.id,
313       };
314       WebSocketService.Instance.getComments(getCommentsForm);
315     }
316   }
317
318   parseMessage(msg: WebSocketJsonResponse) {
319     console.log(msg);
320     let res = wsJsonToRes(msg);
321     if (msg.error) {
322       toast(i18n.t(msg.error), 'danger');
323       this.context.router.history.push('/');
324       return;
325     } else if (msg.reconnect) {
326       this.fetchData();
327     } else if (res.op == UserOperation.GetCommunity) {
328       let data = res.data as GetCommunityResponse;
329       this.state.community = data.community;
330       this.state.moderators = data.moderators;
331       this.state.admins = data.admins;
332       this.state.online = data.online;
333       document.title = `/c/${this.state.community.name} - ${WebSocketService.Instance.site.name}`;
334       this.setState(this.state);
335       this.fetchData();
336     } else if (res.op == UserOperation.EditCommunity) {
337       let data = res.data as CommunityResponse;
338       this.state.community = data.community;
339       this.setState(this.state);
340     } else if (res.op == UserOperation.FollowCommunity) {
341       let data = res.data as CommunityResponse;
342       this.state.community.subscribed = data.community.subscribed;
343       this.state.community.number_of_subscribers =
344         data.community.number_of_subscribers;
345       this.setState(this.state);
346     } else if (res.op == UserOperation.GetPosts) {
347       let data = res.data as GetPostsResponse;
348       this.state.posts = data.posts;
349       this.state.loading = false;
350       this.setState(this.state);
351       setupTippy();
352     } else if (res.op == UserOperation.EditPost) {
353       let data = res.data as PostResponse;
354       editPostFindRes(data, this.state.posts);
355       this.setState(this.state);
356     } else if (res.op == UserOperation.CreatePost) {
357       let data = res.data as PostResponse;
358       this.state.posts.unshift(data.post);
359       this.setState(this.state);
360     } else if (res.op == UserOperation.CreatePostLike) {
361       let data = res.data as PostResponse;
362       createPostLikeFindRes(data, this.state.posts);
363       this.setState(this.state);
364     } else if (res.op == UserOperation.AddModToCommunity) {
365       let data = res.data as AddModToCommunityResponse;
366       this.state.moderators = data.moderators;
367       this.setState(this.state);
368     } else if (res.op == UserOperation.BanFromCommunity) {
369       let data = res.data as BanFromCommunityResponse;
370
371       this.state.posts
372         .filter(p => p.creator_id == data.user.id)
373         .forEach(p => (p.banned = data.banned));
374
375       this.setState(this.state);
376     } else if (res.op == UserOperation.GetComments) {
377       let data = res.data as GetCommentsResponse;
378       this.state.comments = data.comments;
379       this.state.loading = false;
380       this.setState(this.state);
381     } else if (res.op == UserOperation.EditComment) {
382       let data = res.data as CommentResponse;
383       editCommentRes(data, this.state.comments);
384       this.setState(this.state);
385     } else if (res.op == UserOperation.CreateComment) {
386       let data = res.data as CommentResponse;
387
388       // Necessary since it might be a user reply
389       if (data.recipient_ids.length == 0) {
390         this.state.comments.unshift(data.comment);
391         this.setState(this.state);
392       }
393     } else if (res.op == UserOperation.SaveComment) {
394       let data = res.data as CommentResponse;
395       saveCommentRes(data, this.state.comments);
396       this.setState(this.state);
397     } else if (res.op == UserOperation.CreateCommentLike) {
398       let data = res.data as CommentResponse;
399       createCommentLikeRes(data, this.state.comments);
400       this.setState(this.state);
401     }
402   }
403 }