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