]> Untitled Git - lemmy.git/blob - ui/src/components/community.tsx
Fixing select alignment.
[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.selects()}
140         {this.state.loading ? (
141           <h5>
142             <svg class="icon icon-spinner spin">
143               <use xlinkHref="#icon-spinner"></use>
144             </svg>
145           </h5>
146         ) : (
147           <div class="row">
148             <div class="col-12 col-md-8">
149               <h5>
150                 {this.state.community.title}
151                 {this.state.community.removed && (
152                   <small className="ml-2 text-muted font-italic">
153                     {i18n.t('removed')}
154                   </small>
155                 )}
156                 {this.state.community.nsfw && (
157                   <small className="ml-2 text-muted font-italic">
158                     {i18n.t('nsfw')}
159                   </small>
160                 )}
161               </h5>
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
182         posts={this.state.posts}
183         removeDuplicates
184         sort={this.state.sort}
185       />
186     ) : (
187       <CommentNodes
188         nodes={commentsToFlatNodes(this.state.comments)}
189         noIndent
190         sortType={this.state.sort}
191       />
192     );
193   }
194
195   selects() {
196     return (
197       <div class="mb-3">
198         <span class="mr-3">
199           <DataTypeSelect
200             type_={this.state.dataType}
201             onChange={this.handleDataTypeChange}
202           />
203         </span>
204         <span class="mr-2">
205           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
206         </span>
207         <a
208           href={`/feeds/c/${this.state.communityName}.xml?sort=${
209             SortType[this.state.sort]
210           }`}
211           target="_blank"
212           title="RSS"
213         >
214           <svg class="icon text-muted small">
215             <use xlinkHref="#icon-rss">#</use>
216           </svg>
217         </a>
218       </div>
219     );
220   }
221
222   paginator() {
223     return (
224       <div class="my-2">
225         {this.state.page > 1 && (
226           <button
227             class="btn btn-sm btn-secondary mr-1"
228             onClick={linkEvent(this, this.prevPage)}
229           >
230             {i18n.t('prev')}
231           </button>
232         )}
233         {this.state.posts.length == fetchLimit && (
234           <button
235             class="btn btn-sm btn-secondary"
236             onClick={linkEvent(this, this.nextPage)}
237           >
238             {i18n.t('next')}
239           </button>
240         )}
241       </div>
242     );
243   }
244
245   nextPage(i: Community) {
246     i.state.page++;
247     i.setState(i.state);
248     i.updateUrl();
249     i.fetchData();
250     window.scrollTo(0, 0);
251   }
252
253   prevPage(i: Community) {
254     i.state.page--;
255     i.setState(i.state);
256     i.updateUrl();
257     i.fetchData();
258     window.scrollTo(0, 0);
259   }
260
261   handleSortChange(val: SortType) {
262     this.state.sort = 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   handleDataTypeChange(val: DataType) {
272     this.state.dataType = val;
273     this.state.page = 1;
274     this.state.loading = true;
275     this.setState(this.state);
276     this.updateUrl();
277     this.fetchData();
278     window.scrollTo(0, 0);
279   }
280
281   updateUrl() {
282     let dataTypeStr = DataType[this.state.dataType].toLowerCase();
283     let sortStr = SortType[this.state.sort].toLowerCase();
284     this.props.history.push(
285       `/c/${this.state.community.name}/data_type/${dataTypeStr}/sort/${sortStr}/page/${this.state.page}`
286     );
287   }
288
289   fetchData() {
290     if (this.state.dataType == DataType.Post) {
291       let getPostsForm: GetPostsForm = {
292         page: this.state.page,
293         limit: fetchLimit,
294         sort: SortType[this.state.sort],
295         type_: ListingType[ListingType.Community],
296         community_id: this.state.community.id,
297       };
298       WebSocketService.Instance.getPosts(getPostsForm);
299     } else {
300       let getCommentsForm: GetCommentsForm = {
301         page: this.state.page,
302         limit: fetchLimit,
303         sort: SortType[this.state.sort],
304         type_: ListingType[ListingType.Community],
305         community_id: this.state.community.id,
306       };
307       WebSocketService.Instance.getComments(getCommentsForm);
308     }
309   }
310
311   parseMessage(msg: WebSocketJsonResponse) {
312     console.log(msg);
313     let res = wsJsonToRes(msg);
314     if (msg.error) {
315       toast(i18n.t(msg.error), 'danger');
316       this.context.router.history.push('/');
317       return;
318     } else if (msg.reconnect) {
319       this.fetchData();
320     } else if (res.op == UserOperation.GetCommunity) {
321       let data = res.data as GetCommunityResponse;
322       this.state.community = data.community;
323       this.state.moderators = data.moderators;
324       this.state.admins = data.admins;
325       this.state.online = data.online;
326       document.title = `/c/${this.state.community.name} - ${WebSocketService.Instance.site.name}`;
327       this.setState(this.state);
328       this.fetchData();
329     } else if (res.op == UserOperation.EditCommunity) {
330       let data = res.data as CommunityResponse;
331       this.state.community = data.community;
332       this.setState(this.state);
333     } else if (res.op == UserOperation.FollowCommunity) {
334       let data = res.data as CommunityResponse;
335       this.state.community.subscribed = data.community.subscribed;
336       this.state.community.number_of_subscribers =
337         data.community.number_of_subscribers;
338       this.setState(this.state);
339     } else if (res.op == UserOperation.GetPosts) {
340       let data = res.data as GetPostsResponse;
341       this.state.posts = data.posts;
342       this.state.loading = false;
343       this.setState(this.state);
344     } else if (res.op == UserOperation.EditPost) {
345       let data = res.data as PostResponse;
346       editPostFindRes(data, this.state.posts);
347       this.setState(this.state);
348     } else if (res.op == UserOperation.CreatePost) {
349       let data = res.data as PostResponse;
350       this.state.posts.unshift(data.post);
351       this.setState(this.state);
352     } else if (res.op == UserOperation.CreatePostLike) {
353       let data = res.data as PostResponse;
354       createPostLikeFindRes(data, this.state.posts);
355       this.setState(this.state);
356     } else if (res.op == UserOperation.AddModToCommunity) {
357       let data = res.data as AddModToCommunityResponse;
358       this.state.moderators = data.moderators;
359       this.setState(this.state);
360     } else if (res.op == UserOperation.BanFromCommunity) {
361       let data = res.data as BanFromCommunityResponse;
362
363       this.state.posts
364         .filter(p => p.creator_id == data.user.id)
365         .forEach(p => (p.banned = data.banned));
366
367       this.setState(this.state);
368     } else if (res.op == UserOperation.GetComments) {
369       let data = res.data as GetCommentsResponse;
370       this.state.comments = data.comments;
371       this.state.loading = false;
372       this.setState(this.state);
373     } else if (res.op == UserOperation.EditComment) {
374       let data = res.data as CommentResponse;
375       editCommentRes(data, this.state.comments);
376       this.setState(this.state);
377     } else if (res.op == UserOperation.CreateComment) {
378       let data = res.data as CommentResponse;
379
380       // Necessary since it might be a user reply
381       if (data.recipient_ids.length == 0) {
382         this.state.comments.unshift(data.comment);
383         this.setState(this.state);
384       }
385     } else if (res.op == UserOperation.SaveComment) {
386       let data = res.data as CommentResponse;
387       saveCommentRes(data, this.state.comments);
388       this.setState(this.state);
389     } else if (res.op == UserOperation.CreateCommentLike) {
390       let data = res.data as CommentResponse;
391       createCommentLikeRes(data, this.state.comments);
392       this.setState(this.state);
393     }
394   }
395 }