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