]> Untitled Git - lemmy.git/blob - ui/src/components/main.tsx
Front end federation names and links for users, posts, and communities.
[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 { UserListing } from './user-listing';
37 import { CommunityLink } from './community-link';
38 import {
39   wsJsonToRes,
40   repoUrl,
41   mdToHtml,
42   fetchLimit,
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                             <CommunityLink
195                               community={{
196                                 name: community.community_name,
197                                 id: community.community_id,
198                                 local: community.community_local,
199                                 actor_id: community.community_actor_id,
200                               }}
201                             />
202                           </li>
203                         ))}
204                       </ul>
205                     </div>
206                   )}
207                 <Link
208                   class="btn btn-sm btn-secondary btn-block"
209                   to="/create_community"
210                 >
211                   {i18n.t('create_a_community')}
212                 </Link>
213               </div>
214             </div>
215             {this.sidebar()}
216             {this.landing()}
217           </div>
218         )}
219       </div>
220     );
221   }
222
223   trendingCommunities() {
224     return (
225       <div>
226         <h5>
227           <T i18nKey="trending_communities">
228             #
229             <Link class="text-body" to="/communities">
230               #
231             </Link>
232           </T>
233         </h5>
234         <ul class="list-inline">
235           {this.state.trendingCommunities.map(community => (
236             <li class="list-inline-item">
237               <CommunityLink community={community} />
238             </li>
239           ))}
240         </ul>
241       </div>
242     );
243   }
244
245   sidebar() {
246     return (
247       <div>
248         {!this.state.showEditSite ? (
249           this.siteInfo()
250         ) : (
251           <SiteForm
252             site={this.state.siteRes.site}
253             onCancel={this.handleEditCancel}
254           />
255         )}
256       </div>
257     );
258   }
259
260   updateUrl() {
261     let listingTypeStr = ListingType[this.state.listingType].toLowerCase();
262     let dataTypeStr = DataType[this.state.dataType].toLowerCase();
263     let sortStr = SortType[this.state.sort].toLowerCase();
264     this.props.history.push(
265       `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${this.state.page}`
266     );
267   }
268
269   siteInfo() {
270     return (
271       <div>
272         <div class="card border-secondary mb-3">
273           <div class="card-body">
274             <h5 class="mb-0">{`${this.state.siteRes.site.name}`}</h5>
275             {this.canAdmin && (
276               <ul class="list-inline mb-1 text-muted font-weight-bold">
277                 <li className="list-inline-item-action">
278                   <span
279                     class="pointer"
280                     onClick={linkEvent(this, this.handleEditClick)}
281                     data-tippy-content={i18n.t('edit')}
282                   >
283                     <svg class="icon icon-inline">
284                       <use xlinkHref="#icon-edit"></use>
285                     </svg>
286                   </span>
287                 </li>
288               </ul>
289             )}
290             <ul class="my-2 list-inline">
291               <li className="list-inline-item badge badge-secondary">
292                 {i18n.t('number_online', { count: this.state.siteRes.online })}
293               </li>
294               <li className="list-inline-item badge badge-secondary">
295                 {i18n.t('number_of_users', {
296                   count: this.state.siteRes.site.number_of_users,
297                 })}
298               </li>
299               <li className="list-inline-item badge badge-secondary">
300                 {i18n.t('number_of_communities', {
301                   count: this.state.siteRes.site.number_of_communities,
302                 })}
303               </li>
304               <li className="list-inline-item badge badge-secondary">
305                 {i18n.t('number_of_posts', {
306                   count: this.state.siteRes.site.number_of_posts,
307                 })}
308               </li>
309               <li className="list-inline-item badge badge-secondary">
310                 {i18n.t('number_of_comments', {
311                   count: this.state.siteRes.site.number_of_comments,
312                 })}
313               </li>
314               <li className="list-inline-item">
315                 <Link className="badge badge-secondary" to="/modlog">
316                   {i18n.t('modlog')}
317                 </Link>
318               </li>
319             </ul>
320             <ul class="mt-1 list-inline small mb-0">
321               <li class="list-inline-item">{i18n.t('admins')}:</li>
322               {this.state.siteRes.admins.map(admin => (
323                 <li class="list-inline-item">
324                   <UserListing
325                     user={{
326                       name: admin.name,
327                       avatar: admin.avatar,
328                       local: admin.local,
329                       actor_id: admin.actor_id,
330                       id: admin.id,
331                     }}
332                   />
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         showContext
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       toast(i18n.t('site_saved'));
623     } else if (res.op == UserOperation.GetPosts) {
624       let data = res.data as GetPostsResponse;
625       this.state.posts = data.posts;
626       this.state.loading = false;
627       this.setState(this.state);
628       setupTippy();
629     } else if (res.op == UserOperation.CreatePost) {
630       let data = res.data as PostResponse;
631
632       // If you're on subscribed, only push it if you're subscribed.
633       if (this.state.listingType == ListingType.Subscribed) {
634         if (
635           this.state.subscribedCommunities
636             .map(c => c.community_id)
637             .includes(data.post.community_id)
638         ) {
639           this.state.posts.unshift(data.post);
640         }
641       } else {
642         // NSFW posts
643         let nsfw = data.post.nsfw || data.post.community_nsfw;
644
645         // Don't push the post if its nsfw, and don't have that setting on
646         if (
647           !nsfw ||
648           (nsfw &&
649             UserService.Instance.user &&
650             UserService.Instance.user.show_nsfw)
651         ) {
652           this.state.posts.unshift(data.post);
653         }
654       }
655       this.setState(this.state);
656     } else if (res.op == UserOperation.EditPost) {
657       let data = res.data as PostResponse;
658       editPostFindRes(data, this.state.posts);
659       this.setState(this.state);
660     } else if (res.op == UserOperation.CreatePostLike) {
661       let data = res.data as PostResponse;
662       createPostLikeFindRes(data, this.state.posts);
663       this.setState(this.state);
664     } else if (res.op == UserOperation.AddAdmin) {
665       let data = res.data as AddAdminResponse;
666       this.state.siteRes.admins = data.admins;
667       this.setState(this.state);
668     } else if (res.op == UserOperation.BanUser) {
669       let data = res.data as BanUserResponse;
670       let found = this.state.siteRes.banned.find(u => (u.id = data.user.id));
671
672       // Remove the banned if its found in the list, and the action is an unban
673       if (found && !data.banned) {
674         this.state.siteRes.banned = this.state.siteRes.banned.filter(
675           i => i.id !== data.user.id
676         );
677       } else {
678         this.state.siteRes.banned.push(data.user);
679       }
680
681       this.state.posts
682         .filter(p => p.creator_id == data.user.id)
683         .forEach(p => (p.banned = data.banned));
684
685       this.setState(this.state);
686     } else if (res.op == UserOperation.GetComments) {
687       let data = res.data as GetCommentsResponse;
688       this.state.comments = data.comments;
689       this.state.loading = false;
690       this.setState(this.state);
691     } else if (res.op == UserOperation.EditComment) {
692       let data = res.data as CommentResponse;
693       editCommentRes(data, this.state.comments);
694       this.setState(this.state);
695     } else if (res.op == UserOperation.CreateComment) {
696       let data = res.data as CommentResponse;
697
698       // Necessary since it might be a user reply
699       if (data.recipient_ids.length == 0) {
700         // If you're on subscribed, only push it if you're subscribed.
701         if (this.state.listingType == ListingType.Subscribed) {
702           if (
703             this.state.subscribedCommunities
704               .map(c => c.community_id)
705               .includes(data.comment.community_id)
706           ) {
707             this.state.comments.unshift(data.comment);
708           }
709         } else {
710           this.state.comments.unshift(data.comment);
711         }
712         this.setState(this.state);
713       }
714     } else if (res.op == UserOperation.SaveComment) {
715       let data = res.data as CommentResponse;
716       saveCommentRes(data, this.state.comments);
717       this.setState(this.state);
718     } else if (res.op == UserOperation.CreateCommentLike) {
719       let data = res.data as CommentResponse;
720       createCommentLikeRes(data, this.state.comments);
721       this.setState(this.state);
722     }
723   }
724 }