]> Untitled Git - lemmy.git/blob - ui/src/components/main.tsx
Merge branch 'nutomic-federation' 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   setupTippy,
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-body" 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-body" 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 font-weight-bold">
272                 <li className="list-inline-item-action">
273                   <span
274                     class="pointer"
275                     onClick={linkEvent(this, this.handleEditClick)}
276                     data-tippy-content={i18n.t('edit')}
277                   >
278                     <svg class="icon icon-inline">
279                       <use xlinkHref="#icon-edit"></use>
280                     </svg>
281                   </span>
282                 </li>
283               </ul>
284             )}
285             <ul class="my-2 list-inline">
286               <li className="list-inline-item badge badge-secondary">
287                 {i18n.t('number_online', { count: this.state.siteRes.online })}
288               </li>
289               <li className="list-inline-item badge badge-secondary">
290                 {i18n.t('number_of_users', {
291                   count: this.state.siteRes.site.number_of_users,
292                 })}
293               </li>
294               <li className="list-inline-item badge badge-secondary">
295                 {i18n.t('number_of_communities', {
296                   count: this.state.siteRes.site.number_of_communities,
297                 })}
298               </li>
299               <li className="list-inline-item badge badge-secondary">
300                 {i18n.t('number_of_posts', {
301                   count: this.state.siteRes.site.number_of_posts,
302                 })}
303               </li>
304               <li className="list-inline-item badge badge-secondary">
305                 {i18n.t('number_of_comments', {
306                   count: this.state.siteRes.site.number_of_comments,
307                 })}
308               </li>
309               <li className="list-inline-item">
310                 <Link className="badge badge-secondary" to="/modlog">
311                   {i18n.t('modlog')}
312                 </Link>
313               </li>
314             </ul>
315             <ul class="mt-1 list-inline small mb-0">
316               <li class="list-inline-item">{i18n.t('admins')}:</li>
317               {this.state.siteRes.admins.map(admin => (
318                 <li class="list-inline-item">
319                   <Link
320                     class="text-body font-weight-bold"
321                     to={`/u/${admin.name}`}
322                   >
323                     {admin.avatar && showAvatars() && (
324                       <img
325                         height="32"
326                         width="32"
327                         src={pictshareAvatarThumbnail(admin.avatar)}
328                         class="rounded-circle mr-1"
329                       />
330                     )}
331                     <span>{admin.name}</span>
332                   </Link>
333                 </li>
334               ))}
335             </ul>
336           </div>
337         </div>
338         {this.state.siteRes.site.description && (
339           <div class="card border-secondary mb-3">
340             <div class="card-body">
341               <div
342                 className="md-div"
343                 dangerouslySetInnerHTML={mdToHtml(
344                   this.state.siteRes.site.description
345                 )}
346               />
347             </div>
348           </div>
349         )}
350       </div>
351     );
352   }
353
354   landing() {
355     return (
356       <div class="card border-secondary">
357         <div class="card-body">
358           <h5>
359             {i18n.t('powered_by')}
360             <svg class="icon mx-2">
361               <use xlinkHref="#icon-mouse">#</use>
362             </svg>
363             <a href={repoUrl}>
364               Lemmy<sup>beta</sup>
365             </a>
366           </h5>
367           <p class="mb-0">
368             <T i18nKey="landing_0">
369               #
370               <a href="https://en.wikipedia.org/wiki/Social_network_aggregation">
371                 #
372               </a>
373               <a href="https://en.wikipedia.org/wiki/Fediverse">#</a>
374               <br></br>
375               <code>#</code>
376               <br></br>
377               <b>#</b>
378               <br></br>
379               <a href={repoUrl}>#</a>
380               <br></br>
381               <a href="https://www.rust-lang.org">#</a>
382               <a href="https://actix.rs/">#</a>
383               <a href="https://infernojs.org">#</a>
384               <a href="https://www.typescriptlang.org/">#</a>
385             </T>
386           </p>
387         </div>
388       </div>
389     );
390   }
391
392   posts() {
393     return (
394       <div class="main-content-wrapper">
395         {this.selects()}
396         {this.state.loading ? (
397           <h5>
398             <svg class="icon icon-spinner spin">
399               <use xlinkHref="#icon-spinner"></use>
400             </svg>
401           </h5>
402         ) : (
403           <div>
404             {this.listings()}
405             {this.paginator()}
406           </div>
407         )}
408       </div>
409     );
410   }
411
412   listings() {
413     return this.state.dataType == DataType.Post ? (
414       <PostListings
415         posts={this.state.posts}
416         showCommunity
417         removeDuplicates
418         sort={this.state.sort}
419       />
420     ) : (
421       <CommentNodes
422         nodes={commentsToFlatNodes(this.state.comments)}
423         noIndent
424         showCommunity
425         sortType={this.state.sort}
426       />
427     );
428   }
429
430   selects() {
431     return (
432       <div className="mb-3">
433         <span class="mr-3">
434           <DataTypeSelect
435             type_={this.state.dataType}
436             onChange={this.handleDataTypeChange}
437           />
438         </span>
439         <span class="mr-3">
440           <ListingTypeSelect
441             type_={this.state.listingType}
442             onChange={this.handleListingTypeChange}
443           />
444         </span>
445         <span class="mr-2">
446           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
447         </span>
448         {this.state.listingType == ListingType.All && (
449           <a
450             href={`/feeds/all.xml?sort=${SortType[this.state.sort]}`}
451             target="_blank"
452             title="RSS"
453           >
454             <svg class="icon text-muted small">
455               <use xlinkHref="#icon-rss">#</use>
456             </svg>
457           </a>
458         )}
459         {UserService.Instance.user &&
460           this.state.listingType == ListingType.Subscribed && (
461             <a
462               href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${
463                 SortType[this.state.sort]
464               }`}
465               target="_blank"
466               title="RSS"
467             >
468               <svg class="icon text-muted small">
469                 <use xlinkHref="#icon-rss">#</use>
470               </svg>
471             </a>
472           )}
473       </div>
474     );
475   }
476
477   paginator() {
478     return (
479       <div class="my-2">
480         {this.state.page > 1 && (
481           <button
482             class="btn btn-sm btn-secondary mr-1"
483             onClick={linkEvent(this, this.prevPage)}
484           >
485             {i18n.t('prev')}
486           </button>
487         )}
488         {this.state.posts.length == fetchLimit && (
489           <button
490             class="btn btn-sm btn-secondary"
491             onClick={linkEvent(this, this.nextPage)}
492           >
493             {i18n.t('next')}
494           </button>
495         )}
496       </div>
497     );
498   }
499
500   get canAdmin(): boolean {
501     return (
502       UserService.Instance.user &&
503       this.state.siteRes.admins
504         .map(a => a.id)
505         .includes(UserService.Instance.user.id)
506     );
507   }
508
509   handleEditClick(i: Main) {
510     i.state.showEditSite = true;
511     i.setState(i.state);
512   }
513
514   handleEditCancel() {
515     this.state.showEditSite = false;
516     this.setState(this.state);
517   }
518
519   nextPage(i: Main) {
520     i.state.page++;
521     i.state.loading = true;
522     i.setState(i.state);
523     i.updateUrl();
524     i.fetchData();
525     window.scrollTo(0, 0);
526   }
527
528   prevPage(i: Main) {
529     i.state.page--;
530     i.state.loading = true;
531     i.setState(i.state);
532     i.updateUrl();
533     i.fetchData();
534     window.scrollTo(0, 0);
535   }
536
537   handleSortChange(val: SortType) {
538     this.state.sort = 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   handleListingTypeChange(val: ListingType) {
548     this.state.listingType = 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   handleDataTypeChange(val: DataType) {
558     this.state.dataType = val;
559     this.state.page = 1;
560     this.state.loading = true;
561     this.setState(this.state);
562     this.updateUrl();
563     this.fetchData();
564     window.scrollTo(0, 0);
565   }
566
567   fetchData() {
568     if (this.state.dataType == DataType.Post) {
569       let getPostsForm: GetPostsForm = {
570         page: this.state.page,
571         limit: fetchLimit,
572         sort: SortType[this.state.sort],
573         type_: ListingType[this.state.listingType],
574       };
575       WebSocketService.Instance.getPosts(getPostsForm);
576     } else {
577       let getCommentsForm: GetCommentsForm = {
578         page: this.state.page,
579         limit: fetchLimit,
580         sort: SortType[this.state.sort],
581         type_: ListingType[this.state.listingType],
582       };
583       WebSocketService.Instance.getComments(getCommentsForm);
584     }
585   }
586
587   parseMessage(msg: WebSocketJsonResponse) {
588     console.log(msg);
589     let res = wsJsonToRes(msg);
590     if (msg.error) {
591       toast(i18n.t(msg.error), 'danger');
592       return;
593     } else if (msg.reconnect) {
594       this.fetchData();
595     } else if (res.op == UserOperation.GetFollowedCommunities) {
596       let data = res.data as GetFollowedCommunitiesResponse;
597       this.state.subscribedCommunities = data.communities;
598       this.setState(this.state);
599     } else if (res.op == UserOperation.ListCommunities) {
600       let data = res.data as ListCommunitiesResponse;
601       this.state.trendingCommunities = data.communities;
602       this.setState(this.state);
603     } else if (res.op == UserOperation.GetSite) {
604       let data = res.data as GetSiteResponse;
605
606       // This means it hasn't been set up yet
607       if (!data.site) {
608         this.context.router.history.push('/setup');
609       }
610       this.state.siteRes.admins = data.admins;
611       this.state.siteRes.site = data.site;
612       this.state.siteRes.banned = data.banned;
613       this.state.siteRes.online = data.online;
614       this.setState(this.state);
615       document.title = `${WebSocketService.Instance.site.name}`;
616     } else if (res.op == UserOperation.EditSite) {
617       let data = res.data as SiteResponse;
618       this.state.siteRes.site = data.site;
619       this.state.showEditSite = false;
620       this.setState(this.state);
621     } else if (res.op == UserOperation.GetPosts) {
622       let data = res.data as GetPostsResponse;
623       this.state.posts = data.posts;
624       this.state.loading = false;
625       this.setState(this.state);
626       setupTippy();
627     } else if (res.op == UserOperation.CreatePost) {
628       let data = res.data as PostResponse;
629
630       // If you're on subscribed, only push it if you're subscribed.
631       if (this.state.listingType == ListingType.Subscribed) {
632         if (
633           this.state.subscribedCommunities
634             .map(c => c.community_id)
635             .includes(data.post.community_id)
636         ) {
637           this.state.posts.unshift(data.post);
638         }
639       } else {
640         // NSFW posts
641         let nsfw = data.post.nsfw || data.post.community_nsfw;
642
643         // Don't push the post if its nsfw, and don't have that setting on
644         if (
645           !nsfw ||
646           (nsfw &&
647             UserService.Instance.user &&
648             UserService.Instance.user.show_nsfw)
649         ) {
650           this.state.posts.unshift(data.post);
651         }
652       }
653       this.setState(this.state);
654     } else if (res.op == UserOperation.EditPost) {
655       let data = res.data as PostResponse;
656       editPostFindRes(data, this.state.posts);
657       this.setState(this.state);
658     } else if (res.op == UserOperation.CreatePostLike) {
659       let data = res.data as PostResponse;
660       createPostLikeFindRes(data, this.state.posts);
661       this.setState(this.state);
662     } else if (res.op == UserOperation.AddAdmin) {
663       let data = res.data as AddAdminResponse;
664       this.state.siteRes.admins = data.admins;
665       this.setState(this.state);
666     } else if (res.op == UserOperation.BanUser) {
667       let data = res.data as BanUserResponse;
668       let found = this.state.siteRes.banned.find(u => (u.id = data.user.id));
669
670       // Remove the banned if its found in the list, and the action is an unban
671       if (found && !data.banned) {
672         this.state.siteRes.banned = this.state.siteRes.banned.filter(
673           i => i.id !== data.user.id
674         );
675       } else {
676         this.state.siteRes.banned.push(data.user);
677       }
678
679       this.state.posts
680         .filter(p => p.creator_id == data.user.id)
681         .forEach(p => (p.banned = data.banned));
682
683       this.setState(this.state);
684     } else if (res.op == UserOperation.GetComments) {
685       let data = res.data as GetCommentsResponse;
686       this.state.comments = data.comments;
687       this.state.loading = false;
688       this.setState(this.state);
689     } else if (res.op == UserOperation.EditComment) {
690       let data = res.data as CommentResponse;
691       editCommentRes(data, this.state.comments);
692       this.setState(this.state);
693     } else if (res.op == UserOperation.CreateComment) {
694       let data = res.data as CommentResponse;
695
696       // Necessary since it might be a user reply
697       if (data.recipient_ids.length == 0) {
698         // If you're on subscribed, only push it if you're subscribed.
699         if (this.state.listingType == ListingType.Subscribed) {
700           if (
701             this.state.subscribedCommunities
702               .map(c => c.community_id)
703               .includes(data.comment.community_id)
704           ) {
705             this.state.comments.unshift(data.comment);
706           }
707         } else {
708           this.state.comments.unshift(data.comment);
709         }
710         this.setState(this.state);
711       }
712     } else if (res.op == UserOperation.SaveComment) {
713       let data = res.data as CommentResponse;
714       saveCommentRes(data, this.state.comments);
715       this.setState(this.state);
716     } else if (res.op == UserOperation.CreateCommentLike) {
717       let data = res.data as CommentResponse;
718       createCommentLikeRes(data, this.state.comments);
719       this.setState(this.state);
720     }
721   }
722 }