]> Untitled Git - lemmy.git/blob - ui/src/components/main.tsx
Merge branch 'master' into federation
[lemmy.git] / ui / src / components / main.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Link } from 'inferno-router';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import {
6   UserOperation,
7   CommunityUser,
8   GetFollowedCommunitiesResponse,
9   ListCommunitiesForm,
10   ListCommunitiesResponse,
11   Community,
12   SortType,
13   GetSiteResponse,
14   ListingType,
15   DataType,
16   SiteResponse,
17   GetPostsResponse,
18   PostResponse,
19   Post,
20   GetPostsForm,
21   Comment,
22   GetCommentsForm,
23   GetCommentsResponse,
24   CommentResponse,
25   AddAdminResponse,
26   BanUserResponse,
27   WebSocketJsonResponse,
28 } from '../interfaces';
29 import { WebSocketService, UserService } from '../services';
30 import { PostListings } from './post-listings';
31 import { CommentNodes } from './comment-nodes';
32 import { SortSelect } from './sort-select';
33 import { ListingTypeSelect } from './listing-type-select';
34 import { DataTypeSelect } from './data-type-select';
35 import { SiteForm } from './site-form';
36 import {
37   wsJsonToRes,
38   repoUrl,
39   mdToHtml,
40   fetchLimit,
41   pictshareAvatarThumbnail,
42   showAvatars,
43   toast,
44   getListingTypeFromProps,
45   getPageFromProps,
46   getSortTypeFromProps,
47   getDataTypeFromProps,
48   editCommentRes,
49   saveCommentRes,
50   createCommentLikeRes,
51   createPostLikeFindRes,
52   editPostFindRes,
53   commentsToFlatNodes,
54   commentSortSortType,
55 } from '../utils';
56 import { i18n } from '../i18next';
57 import { T } from 'inferno-i18next';
58
59 interface MainState {
60   subscribedCommunities: Array<CommunityUser>;
61   trendingCommunities: Array<Community>;
62   siteRes: GetSiteResponse;
63   showEditSite: boolean;
64   loading: boolean;
65   posts: Array<Post>;
66   comments: Array<Comment>;
67   listingType: ListingType;
68   dataType: DataType;
69   sort: SortType;
70   page: number;
71 }
72
73 export class Main extends Component<any, MainState> {
74   private subscription: Subscription;
75   private emptyState: MainState = {
76     subscribedCommunities: [],
77     trendingCommunities: [],
78     siteRes: {
79       site: {
80         id: null,
81         name: null,
82         creator_id: null,
83         creator_name: null,
84         published: null,
85         number_of_users: null,
86         number_of_posts: null,
87         number_of_comments: null,
88         number_of_communities: null,
89         enable_downvotes: null,
90         open_registration: null,
91         enable_nsfw: null,
92       },
93       admins: [],
94       banned: [],
95       online: null,
96     },
97     showEditSite: false,
98     loading: true,
99     posts: [],
100     comments: [],
101     listingType: getListingTypeFromProps(this.props),
102     dataType: getDataTypeFromProps(this.props),
103     sort: getSortTypeFromProps(this.props),
104     page: getPageFromProps(this.props),
105   };
106
107   constructor(props: any, context: any) {
108     super(props, context);
109
110     this.state = this.emptyState;
111     this.handleEditCancel = this.handleEditCancel.bind(this);
112     this.handleSortChange = this.handleSortChange.bind(this);
113     this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
114     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
115
116     this.subscription = WebSocketService.Instance.subject
117       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
118       .subscribe(
119         msg => this.parseMessage(msg),
120         err => console.error(err),
121         () => console.log('complete')
122       );
123
124     WebSocketService.Instance.getSite();
125
126     if (UserService.Instance.user) {
127       WebSocketService.Instance.getFollowedCommunities();
128     }
129
130     let listCommunitiesForm: ListCommunitiesForm = {
131       sort: SortType[SortType.Hot],
132       limit: 6,
133     };
134
135     WebSocketService.Instance.listCommunities(listCommunitiesForm);
136
137     this.fetchData();
138   }
139
140   componentWillUnmount() {
141     this.subscription.unsubscribe();
142   }
143
144   // Necessary for back button for some reason
145   componentWillReceiveProps(nextProps: any) {
146     if (
147       nextProps.history.action == 'POP' ||
148       nextProps.history.action == 'PUSH'
149     ) {
150       this.state.listingType = getListingTypeFromProps(nextProps);
151       this.state.dataType = getDataTypeFromProps(nextProps);
152       this.state.sort = getSortTypeFromProps(nextProps);
153       this.state.page = getPageFromProps(nextProps);
154       this.setState(this.state);
155       this.fetchData();
156     }
157   }
158
159   render() {
160     return (
161       <div class="container">
162         <div class="row">
163           <main role="main" class="col-12 col-md-8">
164             {this.posts()}
165           </main>
166           <aside class="col-12 col-md-4">{this.my_sidebar()}</aside>
167         </div>
168       </div>
169     );
170   }
171
172   my_sidebar() {
173     return (
174       <div>
175         {!this.state.loading && (
176           <div>
177             <div class="card border-secondary mb-3">
178               <div class="card-body">
179                 {this.trendingCommunities()}
180                 {UserService.Instance.user &&
181                   this.state.subscribedCommunities.length > 0 && (
182                     <div>
183                       <h5>
184                         <T i18nKey="subscribed_to_communities">
185                           #
186                           <Link class="text-white" to="/communities">
187                             #
188                           </Link>
189                         </T>
190                       </h5>
191                       <ul class="list-inline">
192                         {this.state.subscribedCommunities.map(community => (
193                           <li class="list-inline-item">
194                             <Link to={`/c/${community.community_name}`}>
195                               {community.community_name}
196                             </Link>
197                           </li>
198                         ))}
199                       </ul>
200                     </div>
201                   )}
202                 <Link
203                   class="btn btn-sm btn-secondary btn-block"
204                   to="/create_community"
205                 >
206                   {i18n.t('create_a_community')}
207                 </Link>
208               </div>
209             </div>
210             {this.sidebar()}
211             {this.landing()}
212           </div>
213         )}
214       </div>
215     );
216   }
217
218   trendingCommunities() {
219     return (
220       <div>
221         <h5>
222           <T i18nKey="trending_communities">
223             #
224             <Link class="text-white" to="/communities">
225               #
226             </Link>
227           </T>
228         </h5>
229         <ul class="list-inline">
230           {this.state.trendingCommunities.map(community => (
231             <li class="list-inline-item">
232               <Link to={`/c/${community.name}`}>{community.name}</Link>
233             </li>
234           ))}
235         </ul>
236       </div>
237     );
238   }
239
240   sidebar() {
241     return (
242       <div>
243         {!this.state.showEditSite ? (
244           this.siteInfo()
245         ) : (
246           <SiteForm
247             site={this.state.siteRes.site}
248             onCancel={this.handleEditCancel}
249           />
250         )}
251       </div>
252     );
253   }
254
255   updateUrl() {
256     let listingTypeStr = ListingType[this.state.listingType].toLowerCase();
257     let dataTypeStr = DataType[this.state.dataType].toLowerCase();
258     let sortStr = SortType[this.state.sort].toLowerCase();
259     this.props.history.push(
260       `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${this.state.page}`
261     );
262   }
263
264   siteInfo() {
265     return (
266       <div>
267         <div class="card border-secondary mb-3">
268           <div class="card-body">
269             <h5 class="mb-0">{`${this.state.siteRes.site.name}`}</h5>
270             {this.canAdmin && (
271               <ul class="list-inline mb-1 text-muted small font-weight-bold">
272                 <li className="list-inline-item">
273                   <span
274                     class="pointer"
275                     onClick={linkEvent(this, this.handleEditClick)}
276                   >
277                     {i18n.t('edit')}
278                   </span>
279                 </li>
280               </ul>
281             )}
282             <ul class="my-2 list-inline">
283               <li className="list-inline-item badge badge-secondary">
284                 {i18n.t('number_online', { count: this.state.siteRes.online })}
285               </li>
286               <li className="list-inline-item badge badge-secondary">
287                 {i18n.t('number_of_users', {
288                   count: this.state.siteRes.site.number_of_users,
289                 })}
290               </li>
291               <li className="list-inline-item badge badge-secondary">
292                 {i18n.t('number_of_communities', {
293                   count: this.state.siteRes.site.number_of_communities,
294                 })}
295               </li>
296               <li className="list-inline-item badge badge-secondary">
297                 {i18n.t('number_of_posts', {
298                   count: this.state.siteRes.site.number_of_posts,
299                 })}
300               </li>
301               <li className="list-inline-item badge badge-secondary">
302                 {i18n.t('number_of_comments', {
303                   count: this.state.siteRes.site.number_of_comments,
304                 })}
305               </li>
306               <li className="list-inline-item">
307                 <Link className="badge badge-secondary" to="/modlog">
308                   {i18n.t('modlog')}
309                 </Link>
310               </li>
311             </ul>
312             <ul class="mt-1 list-inline small mb-0">
313               <li class="list-inline-item">{i18n.t('admins')}:</li>
314               {this.state.siteRes.admins.map(admin => (
315                 <li class="list-inline-item">
316                   <Link class="text-info" to={`/u/${admin.name}`}>
317                     {admin.avatar && showAvatars() && (
318                       <img
319                         height="32"
320                         width="32"
321                         src={pictshareAvatarThumbnail(admin.avatar)}
322                         class="rounded-circle mr-1"
323                       />
324                     )}
325                     <span>{admin.name}</span>
326                   </Link>
327                 </li>
328               ))}
329             </ul>
330           </div>
331         </div>
332         {this.state.siteRes.site.description && (
333           <div class="card border-secondary mb-3">
334             <div class="card-body">
335               <div
336                 className="md-div"
337                 dangerouslySetInnerHTML={mdToHtml(
338                   this.state.siteRes.site.description
339                 )}
340               />
341             </div>
342           </div>
343         )}
344       </div>
345     );
346   }
347
348   landing() {
349     return (
350       <div class="card border-secondary">
351         <div class="card-body">
352           <h5>
353             {i18n.t('powered_by')}
354             <svg class="icon mx-2">
355               <use xlinkHref="#icon-mouse">#</use>
356             </svg>
357             <a href={repoUrl}>
358               Lemmy<sup>beta</sup>
359             </a>
360           </h5>
361           <p class="mb-0">
362             <T i18nKey="landing_0">
363               #
364               <a href="https://en.wikipedia.org/wiki/Social_network_aggregation">
365                 #
366               </a>
367               <a href="https://en.wikipedia.org/wiki/Fediverse">#</a>
368               <br></br>
369               <code>#</code>
370               <br></br>
371               <b>#</b>
372               <br></br>
373               <a href={repoUrl}>#</a>
374               <br></br>
375               <a href="https://www.rust-lang.org">#</a>
376               <a href="https://actix.rs/">#</a>
377               <a href="https://infernojs.org">#</a>
378               <a href="https://www.typescriptlang.org/">#</a>
379             </T>
380           </p>
381         </div>
382       </div>
383     );
384   }
385
386   posts() {
387     return (
388       <div class="main-content-wrapper">
389         {this.selects()}
390         {this.state.loading ? (
391           <h5>
392             <svg class="icon icon-spinner spin">
393               <use xlinkHref="#icon-spinner"></use>
394             </svg>
395           </h5>
396         ) : (
397           <div>
398             {this.listings()}
399             {this.paginator()}
400           </div>
401         )}
402       </div>
403     );
404   }
405
406   listings() {
407     return this.state.dataType == DataType.Post ? (
408       <PostListings
409         posts={this.state.posts}
410         showCommunity
411         removeDuplicates
412         sort={this.state.sort}
413       />
414     ) : (
415       <CommentNodes
416         nodes={commentsToFlatNodes(this.state.comments)}
417         noIndent
418         showCommunity
419         sortType={this.state.sort}
420       />
421     );
422   }
423
424   selects() {
425     return (
426       <div className="mb-3">
427         <DataTypeSelect
428           type_={this.state.dataType}
429           onChange={this.handleDataTypeChange}
430         />
431         <span class="mx-3">
432           <ListingTypeSelect
433             type_={this.state.listingType}
434             onChange={this.handleListingTypeChange}
435           />
436         </span>
437         <span class="mr-2">
438           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
439         </span>
440         {this.state.listingType == ListingType.All && (
441           <a
442             href={`/feeds/all.xml?sort=${SortType[this.state.sort]}`}
443             target="_blank"
444           >
445             <svg class="icon mx-1 text-muted small">
446               <use xlinkHref="#icon-rss">#</use>
447             </svg>
448           </a>
449         )}
450         {UserService.Instance.user &&
451           this.state.listingType == ListingType.Subscribed && (
452             <a
453               href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${
454                 SortType[this.state.sort]
455               }`}
456               target="_blank"
457             >
458               <svg class="icon mx-1 text-muted small">
459                 <use xlinkHref="#icon-rss">#</use>
460               </svg>
461             </a>
462           )}
463       </div>
464     );
465   }
466
467   paginator() {
468     return (
469       <div class="my-2">
470         {this.state.page > 1 && (
471           <button
472             class="btn btn-sm btn-secondary mr-1"
473             onClick={linkEvent(this, this.prevPage)}
474           >
475             {i18n.t('prev')}
476           </button>
477         )}
478         {this.state.posts.length == fetchLimit && (
479           <button
480             class="btn btn-sm btn-secondary"
481             onClick={linkEvent(this, this.nextPage)}
482           >
483             {i18n.t('next')}
484           </button>
485         )}
486       </div>
487     );
488   }
489
490   get canAdmin(): boolean {
491     return (
492       UserService.Instance.user &&
493       this.state.siteRes.admins
494         .map(a => a.id)
495         .includes(UserService.Instance.user.id)
496     );
497   }
498
499   handleEditClick(i: Main) {
500     i.state.showEditSite = true;
501     i.setState(i.state);
502   }
503
504   handleEditCancel() {
505     this.state.showEditSite = false;
506     this.setState(this.state);
507   }
508
509   nextPage(i: Main) {
510     i.state.page++;
511     i.state.loading = true;
512     i.setState(i.state);
513     i.updateUrl();
514     i.fetchData();
515     window.scrollTo(0, 0);
516   }
517
518   prevPage(i: Main) {
519     i.state.page--;
520     i.state.loading = true;
521     i.setState(i.state);
522     i.updateUrl();
523     i.fetchData();
524     window.scrollTo(0, 0);
525   }
526
527   handleSortChange(val: SortType) {
528     this.state.sort = val;
529     this.state.page = 1;
530     this.state.loading = true;
531     this.setState(this.state);
532     this.updateUrl();
533     this.fetchData();
534     window.scrollTo(0, 0);
535   }
536
537   handleListingTypeChange(val: ListingType) {
538     this.state.listingType = val;
539     this.state.page = 1;
540     this.state.loading = true;
541     this.setState(this.state);
542     this.updateUrl();
543     this.fetchData();
544     window.scrollTo(0, 0);
545   }
546
547   handleDataTypeChange(val: DataType) {
548     this.state.dataType = val;
549     this.state.page = 1;
550     this.state.loading = true;
551     this.setState(this.state);
552     this.updateUrl();
553     this.fetchData();
554     window.scrollTo(0, 0);
555   }
556
557   fetchData() {
558     if (this.state.dataType == DataType.Post) {
559       let getPostsForm: GetPostsForm = {
560         page: this.state.page,
561         limit: fetchLimit,
562         sort: SortType[this.state.sort],
563         type_: ListingType[this.state.listingType],
564       };
565       WebSocketService.Instance.getPosts(getPostsForm);
566     } else {
567       let getCommentsForm: GetCommentsForm = {
568         page: this.state.page,
569         limit: fetchLimit,
570         sort: SortType[this.state.sort],
571         type_: ListingType[this.state.listingType],
572       };
573       WebSocketService.Instance.getComments(getCommentsForm);
574     }
575   }
576
577   parseMessage(msg: WebSocketJsonResponse) {
578     console.log(msg);
579     let res = wsJsonToRes(msg);
580     if (msg.error) {
581       toast(i18n.t(msg.error), 'danger');
582       return;
583     } else if (msg.reconnect) {
584       this.fetchData();
585     } else if (res.op == UserOperation.GetFollowedCommunities) {
586       let data = res.data as GetFollowedCommunitiesResponse;
587       this.state.subscribedCommunities = data.communities;
588       this.setState(this.state);
589     } else if (res.op == UserOperation.ListCommunities) {
590       let data = res.data as ListCommunitiesResponse;
591       this.state.trendingCommunities = data.communities;
592       this.setState(this.state);
593     } else if (res.op == UserOperation.GetSite) {
594       let data = res.data as GetSiteResponse;
595
596       // This means it hasn't been set up yet
597       if (!data.site) {
598         this.context.router.history.push('/setup');
599       }
600       this.state.siteRes.admins = data.admins;
601       this.state.siteRes.site = data.site;
602       this.state.siteRes.banned = data.banned;
603       this.state.siteRes.online = data.online;
604       this.setState(this.state);
605       document.title = `${WebSocketService.Instance.site.name}`;
606     } else if (res.op == UserOperation.EditSite) {
607       let data = res.data as SiteResponse;
608       this.state.siteRes.site = data.site;
609       this.state.showEditSite = false;
610       this.setState(this.state);
611     } else if (res.op == UserOperation.GetPosts) {
612       let data = res.data as GetPostsResponse;
613       this.state.posts = data.posts;
614       this.state.loading = false;
615       this.setState(this.state);
616     } else if (res.op == UserOperation.CreatePost) {
617       let data = res.data as PostResponse;
618
619       // If you're on subscribed, only push it if you're subscribed.
620       if (this.state.listingType == ListingType.Subscribed) {
621         if (
622           this.state.subscribedCommunities
623             .map(c => c.community_id)
624             .includes(data.post.community_id)
625         ) {
626           this.state.posts.unshift(data.post);
627         }
628       } else {
629         this.state.posts.unshift(data.post);
630       }
631
632       this.setState(this.state);
633     } else if (res.op == UserOperation.EditPost) {
634       let data = res.data as PostResponse;
635       editPostFindRes(data, this.state.posts);
636       this.setState(this.state);
637     } else if (res.op == UserOperation.CreatePostLike) {
638       let data = res.data as PostResponse;
639       createPostLikeFindRes(data, this.state.posts);
640       this.setState(this.state);
641     } else if (res.op == UserOperation.AddAdmin) {
642       let data = res.data as AddAdminResponse;
643       this.state.siteRes.admins = data.admins;
644       this.setState(this.state);
645     } else if (res.op == UserOperation.BanUser) {
646       let data = res.data as BanUserResponse;
647       let found = this.state.siteRes.banned.find(u => (u.id = data.user.id));
648
649       // Remove the banned if its found in the list, and the action is an unban
650       if (found && !data.banned) {
651         this.state.siteRes.banned = this.state.siteRes.banned.filter(
652           i => i.id !== data.user.id
653         );
654       } else {
655         this.state.siteRes.banned.push(data.user);
656       }
657
658       this.state.posts
659         .filter(p => p.creator_id == data.user.id)
660         .forEach(p => (p.banned = data.banned));
661
662       this.setState(this.state);
663     } else if (res.op == UserOperation.GetComments) {
664       let data = res.data as GetCommentsResponse;
665       this.state.comments = data.comments;
666       this.state.loading = false;
667       this.setState(this.state);
668     } else if (res.op == UserOperation.EditComment) {
669       let data = res.data as CommentResponse;
670       editCommentRes(data, this.state.comments);
671       this.setState(this.state);
672     } else if (res.op == UserOperation.CreateComment) {
673       let data = res.data as CommentResponse;
674
675       // Necessary since it might be a user reply
676       if (data.recipient_ids.length == 0) {
677         // If you're on subscribed, only push it if you're subscribed.
678         if (this.state.listingType == ListingType.Subscribed) {
679           if (
680             this.state.subscribedCommunities
681               .map(c => c.community_id)
682               .includes(data.comment.community_id)
683           ) {
684             this.state.comments.unshift(data.comment);
685           }
686         } else {
687           this.state.comments.unshift(data.comment);
688         }
689         this.setState(this.state);
690       }
691     } else if (res.op == UserOperation.SaveComment) {
692       let data = res.data as CommentResponse;
693       saveCommentRes(data, this.state.comments);
694       this.setState(this.state);
695     } else if (res.op == UserOperation.CreateCommentLike) {
696       let data = res.data as CommentResponse;
697       createCommentLikeRes(data, this.state.comments);
698       this.setState(this.state);
699     }
700   }
701 }