]> Untitled Git - lemmy.git/blob - ui/src/components/community.tsx
A first pass at adding icons, and tippy tooltips.
[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-2">
198         <DataTypeSelect
199           type_={this.state.dataType}
200           onChange={this.handleDataTypeChange}
201         />
202
203         <span class="mx-3">
204           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
205         </span>
206         <a
207           href={`/feeds/c/${this.state.communityName}.xml?sort=${
208             SortType[this.state.sort]
209           }`}
210           target="_blank"
211           title="RSS"
212         >
213           <svg class="icon text-muted small">
214             <use xlinkHref="#icon-rss">#</use>
215           </svg>
216         </a>
217       </div>
218     );
219   }
220
221   paginator() {
222     return (
223       <div class="my-2">
224         {this.state.page > 1 && (
225           <button
226             class="btn btn-sm btn-secondary mr-1"
227             onClick={linkEvent(this, this.prevPage)}
228           >
229             {i18n.t('prev')}
230           </button>
231         )}
232         {this.state.posts.length == fetchLimit && (
233           <button
234             class="btn btn-sm btn-secondary"
235             onClick={linkEvent(this, this.nextPage)}
236           >
237             {i18n.t('next')}
238           </button>
239         )}
240       </div>
241     );
242   }
243
244   nextPage(i: Community) {
245     i.state.page++;
246     i.setState(i.state);
247     i.updateUrl();
248     i.fetchData();
249     window.scrollTo(0, 0);
250   }
251
252   prevPage(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   handleSortChange(val: SortType) {
261     this.state.sort = val;
262     this.state.page = 1;
263     this.state.loading = true;
264     this.setState(this.state);
265     this.updateUrl();
266     this.fetchData();
267     window.scrollTo(0, 0);
268   }
269
270   handleDataTypeChange(val: DataType) {
271     this.state.dataType = val;
272     this.state.page = 1;
273     this.state.loading = true;
274     this.setState(this.state);
275     this.updateUrl();
276     this.fetchData();
277     window.scrollTo(0, 0);
278   }
279
280   updateUrl() {
281     let dataTypeStr = DataType[this.state.dataType].toLowerCase();
282     let sortStr = SortType[this.state.sort].toLowerCase();
283     this.props.history.push(
284       `/c/${this.state.community.name}/data_type/${dataTypeStr}/sort/${sortStr}/page/${this.state.page}`
285     );
286   }
287
288   fetchData() {
289     if (this.state.dataType == DataType.Post) {
290       let getPostsForm: GetPostsForm = {
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.getPosts(getPostsForm);
298     } else {
299       let getCommentsForm: GetCommentsForm = {
300         page: this.state.page,
301         limit: fetchLimit,
302         sort: SortType[this.state.sort],
303         type_: ListingType[ListingType.Community],
304         community_id: this.state.community.id,
305       };
306       WebSocketService.Instance.getComments(getCommentsForm);
307     }
308   }
309
310   parseMessage(msg: WebSocketJsonResponse) {
311     console.log(msg);
312     let res = wsJsonToRes(msg);
313     if (msg.error) {
314       toast(i18n.t(msg.error), 'danger');
315       this.context.router.history.push('/');
316       return;
317     } else if (msg.reconnect) {
318       this.fetchData();
319     } else if (res.op == UserOperation.GetCommunity) {
320       let data = res.data as GetCommunityResponse;
321       this.state.community = data.community;
322       this.state.moderators = data.moderators;
323       this.state.admins = data.admins;
324       this.state.online = data.online;
325       document.title = `/c/${this.state.community.name} - ${WebSocketService.Instance.site.name}`;
326       this.setState(this.state);
327       this.fetchData();
328     } else if (res.op == UserOperation.EditCommunity) {
329       let data = res.data as CommunityResponse;
330       this.state.community = data.community;
331       this.setState(this.state);
332     } else if (res.op == UserOperation.FollowCommunity) {
333       let data = res.data as CommunityResponse;
334       this.state.community.subscribed = data.community.subscribed;
335       this.state.community.number_of_subscribers =
336         data.community.number_of_subscribers;
337       this.setState(this.state);
338     } else if (res.op == UserOperation.GetPosts) {
339       let data = res.data as GetPostsResponse;
340       this.state.posts = data.posts;
341       this.state.loading = false;
342       this.setState(this.state);
343     } else if (res.op == UserOperation.EditPost) {
344       let data = res.data as PostResponse;
345       editPostFindRes(data, this.state.posts);
346       this.setState(this.state);
347     } else if (res.op == UserOperation.CreatePost) {
348       let data = res.data as PostResponse;
349       this.state.posts.unshift(data.post);
350       this.setState(this.state);
351     } else if (res.op == UserOperation.CreatePostLike) {
352       let data = res.data as PostResponse;
353       createPostLikeFindRes(data, this.state.posts);
354       this.setState(this.state);
355     } else if (res.op == UserOperation.AddModToCommunity) {
356       let data = res.data as AddModToCommunityResponse;
357       this.state.moderators = data.moderators;
358       this.setState(this.state);
359     } else if (res.op == UserOperation.BanFromCommunity) {
360       let data = res.data as BanFromCommunityResponse;
361
362       this.state.posts
363         .filter(p => p.creator_id == data.user.id)
364         .forEach(p => (p.banned = data.banned));
365
366       this.setState(this.state);
367     } else if (res.op == UserOperation.GetComments) {
368       let data = res.data as GetCommentsResponse;
369       this.state.comments = data.comments;
370       this.state.loading = false;
371       this.setState(this.state);
372     } else if (res.op == UserOperation.EditComment) {
373       let data = res.data as CommentResponse;
374       editCommentRes(data, this.state.comments);
375       this.setState(this.state);
376     } else if (res.op == UserOperation.CreateComment) {
377       let data = res.data as CommentResponse;
378
379       // Necessary since it might be a user reply
380       if (data.recipient_ids.length == 0) {
381         this.state.comments.unshift(data.comment);
382         this.setState(this.state);
383       }
384     } else if (res.op == UserOperation.SaveComment) {
385       let data = res.data as CommentResponse;
386       saveCommentRes(data, this.state.comments);
387       this.setState(this.state);
388     } else if (res.op == UserOperation.CreateCommentLike) {
389       let data = res.data as CommentResponse;
390       createCommentLikeRes(data, this.state.comments);
391       this.setState(this.state);
392     }
393   }
394 }