1 import { Component, linkEvent } from 'inferno';
2 import { Link } from 'inferno-router';
3 import { Subscription } from 'rxjs';
7 GetFollowedCommunitiesResponse,
9 ListCommunitiesResponse,
25 } from 'lemmy-js-client';
26 import { DataType, InitialFetchRequest } from '../interfaces';
27 import { WebSocketService, UserService } from '../services';
28 import { PostListings } from './post-listings';
29 import { CommentNodes } from './comment-nodes';
30 import { SortSelect } from './sort-select';
31 import { ListingTypeSelect } from './listing-type-select';
32 import { DataTypeSelect } from './data-type-select';
33 import { SiteForm } from './site-form';
34 import { UserListing } from './user-listing';
35 import { CommunityLink } from './community-link';
36 import { BannerIconHeader } from './banner-icon-header';
42 getListingTypeFromProps,
49 createPostLikeFindRes,
62 import { i18n } from '../i18next';
63 import { T } from 'inferno-i18next';
64 import { HtmlTags } from './html-tags';
67 subscribedCommunities: CommunityFollowerView[];
68 trendingCommunities: CommunityView[];
69 siteRes: GetSiteResponse;
70 showEditSite: boolean;
73 comments: CommentView[];
74 listingType: ListingType;
81 listingType: ListingType;
88 listingType?: ListingType;
94 export class Main extends Component<any, MainState> {
95 private isoData = setIsoData(this.context);
96 private subscription: Subscription;
97 private emptyState: MainState = {
98 subscribedCommunities: [],
99 trendingCommunities: [],
100 siteRes: this.isoData.site_res,
105 listingType: getListingTypeFromProps(this.props),
106 dataType: getDataTypeFromProps(this.props),
107 sort: getSortTypeFromProps(this.props),
108 page: getPageFromProps(this.props),
111 constructor(props: any, context: any) {
112 super(props, context);
114 this.state = this.emptyState;
115 this.handleEditCancel = this.handleEditCancel.bind(this);
116 this.handleSortChange = this.handleSortChange.bind(this);
117 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
118 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
120 this.parseMessage = this.parseMessage.bind(this);
121 this.subscription = wsSubscribe(this.parseMessage);
123 // Only fetch the data if coming from another route
124 if (this.isoData.path == this.context.router.route.match.url) {
125 if (this.state.dataType == DataType.Post) {
126 this.state.posts = this.isoData.routeData[0].posts;
128 this.state.comments = this.isoData.routeData[0].comments;
130 this.state.trendingCommunities = this.isoData.routeData[1].communities;
131 if (UserService.Instance.user) {
132 this.state.subscribedCommunities = this.isoData.routeData[2].communities;
134 this.state.loading = false;
136 this.fetchTrendingCommunities();
138 if (UserService.Instance.user) {
139 WebSocketService.Instance.send(
140 wsClient.getFollowedCommunities({
150 fetchTrendingCommunities() {
151 let listCommunitiesForm: ListCommunities = {
154 auth: authField(false),
156 WebSocketService.Instance.send(
157 wsClient.listCommunities(listCommunitiesForm)
161 componentDidMount() {
162 // This means it hasn't been set up yet
163 if (!this.state.siteRes.site_view) {
164 this.context.router.history.push('/setup');
167 WebSocketService.Instance.send(wsClient.communityJoin({ community_id: 0 }));
170 componentWillUnmount() {
172 this.subscription.unsubscribe();
173 window.isoData.path = undefined;
177 static getDerivedStateFromProps(props: any): MainProps {
179 listingType: getListingTypeFromProps(props),
180 dataType: getDataTypeFromProps(props),
181 sort: getSortTypeFromProps(props),
182 page: getPageFromProps(props),
186 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
187 let pathSplit = req.path.split('/');
188 let dataType: DataType = pathSplit[3]
189 ? DataType[pathSplit[3]]
192 // TODO figure out auth default_listingType, default_sort_type
193 let type_: ListingType = pathSplit[5]
194 ? ListingType[pathSplit[5]]
195 : UserService.Instance.user
196 ? Object.values(ListingType)[
197 UserService.Instance.user.default_listing_type
200 let sort: SortType = pathSplit[7]
201 ? SortType[pathSplit[7]]
202 : UserService.Instance.user
203 ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
206 let page = pathSplit[9] ? Number(pathSplit[9]) : 1;
208 let promises: Promise<any>[] = [];
210 if (dataType == DataType.Post) {
211 let getPostsForm: GetPosts = {
217 setOptionalAuth(getPostsForm, req.auth);
218 promises.push(req.client.getPosts(getPostsForm));
220 let getCommentsForm: GetComments = {
226 setOptionalAuth(getCommentsForm, req.auth);
227 promises.push(req.client.getComments(getCommentsForm));
230 let trendingCommunitiesForm: ListCommunities = {
234 promises.push(req.client.listCommunities(trendingCommunitiesForm));
237 promises.push(req.client.getFollowedCommunities({ auth: req.auth }));
243 componentDidUpdate(_: any, lastState: MainState) {
245 lastState.listingType !== this.state.listingType ||
246 lastState.dataType !== this.state.dataType ||
247 lastState.sort !== this.state.sort ||
248 lastState.page !== this.state.page
250 this.setState({ loading: true });
255 get documentTitle(): string {
257 this.state.siteRes.site_view
258 ? this.state.siteRes.site_view.site.name
265 <div class="container">
267 title={this.documentTitle}
268 path={this.context.router.route.match.url}
270 {this.state.siteRes.site_view.site && (
272 <main role="main" class="col-12 col-md-8">
275 <aside class="col-12 col-md-4">{this.mySidebar()}</aside>
285 {!this.state.loading && (
287 <div class="card border-secondary mb-3">
288 <div class="card-body">
289 {this.trendingCommunities()}
290 {this.createCommunityButton()}
294 {UserService.Instance.user &&
295 this.state.subscribedCommunities.length > 0 && (
296 <div class="card border-secondary mb-3">
297 <div class="card-body">{this.subscribedCommunities()}</div>
301 <div class="card border-secondary mb-3">
302 <div class="card-body">{this.sidebar()}</div>
310 createCommunityButton() {
312 <Link className="btn btn-secondary btn-block" to="/create_community">
313 {i18n.t('create_a_community')}
318 trendingCommunities() {
322 <T i18nKey="trending_communities">
324 <Link className="text-body" to="/communities">
329 <ul class="list-inline">
330 {this.state.trendingCommunities.map(cv => (
331 <li class="list-inline-item d-inline">
332 <CommunityLink community={cv.community} />
340 subscribedCommunities() {
344 <T i18nKey="subscribed_to_communities">
346 <Link className="text-body" to="/communities">
351 <ul class="list-inline mb-0">
352 {this.state.subscribedCommunities.map(cfv => (
353 <li class="list-inline-item d-inline">
354 <CommunityLink community={cfv.community} />
363 let site = this.state.siteRes.site_view.site;
366 {!this.state.showEditSite ? (
370 {this.adminButtons()}
372 <BannerIconHeader banner={site.banner} />
376 <SiteForm site={site} onCancel={this.handleEditCancel} />
382 updateUrl(paramUpdates: UrlParams) {
383 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
384 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
385 const sortStr = paramUpdates.sort || this.state.sort;
386 const page = paramUpdates.page || this.state.page;
387 this.props.history.push(
388 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
395 {this.state.siteRes.site_view.site.description &&
396 this.siteDescription()}
404 return <h5 class="mb-0">{`${this.documentTitle}`}</h5>;
409 <ul class="mt-1 list-inline small mb-0">
410 <li class="list-inline-item">{i18n.t('admins')}:</li>
411 {this.state.siteRes.admins.map(av => (
412 <li class="list-inline-item">
413 <UserListing user={av.user} />
421 let site_view = this.state.siteRes.site_view;
423 <ul class="my-2 list-inline">
424 <li className="list-inline-item badge badge-secondary">
425 {i18n.t('number_online', { count: this.state.siteRes.online })}
427 <li className="list-inline-item badge badge-secondary">
428 {i18n.t('number_of_users', {
429 count: site_view.counts.users,
432 <li className="list-inline-item badge badge-secondary">
433 {i18n.t('number_of_communities', {
434 count: site_view.counts.communities,
437 <li className="list-inline-item badge badge-secondary">
438 {i18n.t('number_of_posts', {
439 count: site_view.counts.posts,
442 <li className="list-inline-item badge badge-secondary">
443 {i18n.t('number_of_comments', {
444 count: site_view.counts.comments,
447 <li className="list-inline-item">
448 <Link className="badge badge-secondary" to="/modlog">
459 <ul class="list-inline mb-1 text-muted font-weight-bold">
460 <li className="list-inline-item-action">
463 onClick={linkEvent(this, this.handleEditClick)}
464 data-tippy-content={i18n.t('edit')}
466 <svg class="icon icon-inline">
467 <use xlinkHref="#icon-edit"></use>
480 dangerouslySetInnerHTML={mdToHtml(
481 this.state.siteRes.site_view.site.description
489 <div class="main-content-wrapper">
490 {this.state.loading ? (
492 <svg class="icon icon-spinner spin">
493 <use xlinkHref="#icon-spinner"></use>
508 let site = this.state.siteRes.site_view.site;
509 return this.state.dataType == DataType.Post ? (
511 posts={this.state.posts}
514 sort={this.state.sort}
515 enableDownvotes={site.enable_downvotes}
516 enableNsfw={site.enable_nsfw}
520 nodes={commentsToFlatNodes(this.state.comments)}
523 sortType={this.state.sort}
525 enableDownvotes={site.enable_downvotes}
532 <div className="mb-3">
535 type_={this.state.dataType}
536 onChange={this.handleDataTypeChange}
541 type_={this.state.listingType}
542 showLocal={this.showLocal}
543 onChange={this.handleListingTypeChange}
547 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
549 {this.state.listingType == ListingType.All && (
551 href={`/feeds/all.xml?sort=${this.state.sort}`}
556 <svg class="icon text-muted small">
557 <use xlinkHref="#icon-rss">#</use>
561 {this.state.listingType == ListingType.Local && (
563 href={`/feeds/local.xml?sort=${this.state.sort}`}
568 <svg class="icon text-muted small">
569 <use xlinkHref="#icon-rss">#</use>
573 {UserService.Instance.user &&
574 this.state.listingType == ListingType.Subscribed && (
576 href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${this.state.sort}`}
581 <svg class="icon text-muted small">
582 <use xlinkHref="#icon-rss">#</use>
593 {this.state.page > 1 && (
595 class="btn btn-secondary mr-1"
596 onClick={linkEvent(this, this.prevPage)}
601 {this.state.posts.length > 0 && (
603 class="btn btn-secondary"
604 onClick={linkEvent(this, this.nextPage)}
613 get showLocal(): boolean {
615 this.isoData.site_res.federated_instances !== null &&
616 this.isoData.site_res.federated_instances.length > 0
620 get canAdmin(): boolean {
622 UserService.Instance.user &&
623 this.state.siteRes.admins
625 .includes(UserService.Instance.user.id)
629 handleEditClick(i: Main) {
630 i.state.showEditSite = true;
635 this.state.showEditSite = false;
636 this.setState(this.state);
640 i.updateUrl({ page: i.state.page + 1 });
641 window.scrollTo(0, 0);
645 i.updateUrl({ page: i.state.page - 1 });
646 window.scrollTo(0, 0);
649 handleSortChange(val: SortType) {
650 this.updateUrl({ sort: val, page: 1 });
651 window.scrollTo(0, 0);
654 handleListingTypeChange(val: ListingType) {
655 this.updateUrl({ listingType: val, page: 1 });
656 window.scrollTo(0, 0);
659 handleDataTypeChange(val: DataType) {
660 this.updateUrl({ dataType: DataType[val], page: 1 });
661 window.scrollTo(0, 0);
665 if (this.state.dataType == DataType.Post) {
666 let getPostsForm: GetPosts = {
667 page: this.state.page,
669 sort: this.state.sort,
670 type_: this.state.listingType,
671 auth: authField(false),
673 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
675 let getCommentsForm: GetComments = {
676 page: this.state.page,
678 sort: this.state.sort,
679 type_: this.state.listingType,
680 auth: authField(false),
682 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
686 parseMessage(msg: any) {
687 let op = wsUserOp(msg);
689 toast(i18n.t(msg.error), 'danger');
691 } else if (msg.reconnect) {
692 WebSocketService.Instance.send(
693 wsClient.communityJoin({ community_id: 0 })
696 } else if (op == UserOperation.GetFollowedCommunities) {
697 let data = wsJsonToRes<GetFollowedCommunitiesResponse>(msg).data;
698 this.state.subscribedCommunities = data.communities;
699 this.setState(this.state);
700 } else if (op == UserOperation.ListCommunities) {
701 let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
702 this.state.trendingCommunities = data.communities;
703 this.setState(this.state);
704 } else if (op == UserOperation.EditSite) {
705 let data = wsJsonToRes<SiteResponse>(msg).data;
706 this.state.siteRes.site_view = data.site_view;
707 this.state.showEditSite = false;
708 this.setState(this.state);
709 toast(i18n.t('site_saved'));
710 } else if (op == UserOperation.GetPosts) {
711 let data = wsJsonToRes<GetPostsResponse>(msg).data;
712 this.state.posts = data.posts;
713 this.state.loading = false;
714 this.setState(this.state);
716 } else if (op == UserOperation.CreatePost) {
717 let data = wsJsonToRes<PostResponse>(msg).data;
719 // If you're on subscribed, only push it if you're subscribed.
720 if (this.state.listingType == ListingType.Subscribed) {
722 this.state.subscribedCommunities
723 .map(c => c.community.id)
724 .includes(data.post_view.community.id)
726 this.state.posts.unshift(data.post_view);
727 notifyPost(data.post_view, this.context.router);
731 let nsfw = data.post_view.post.nsfw || data.post_view.community.nsfw;
733 // Don't push the post if its nsfw, and don't have that setting on
737 UserService.Instance.user &&
738 UserService.Instance.user.show_nsfw)
740 this.state.posts.unshift(data.post_view);
741 notifyPost(data.post_view, this.context.router);
744 this.setState(this.state);
746 op == UserOperation.EditPost ||
747 op == UserOperation.DeletePost ||
748 op == UserOperation.RemovePost ||
749 op == UserOperation.LockPost ||
750 op == UserOperation.StickyPost ||
751 op == UserOperation.SavePost
753 let data = wsJsonToRes<PostResponse>(msg).data;
754 editPostFindRes(data.post_view, this.state.posts);
755 this.setState(this.state);
756 } else if (op == UserOperation.CreatePostLike) {
757 let data = wsJsonToRes<PostResponse>(msg).data;
758 createPostLikeFindRes(data.post_view, this.state.posts);
759 this.setState(this.state);
760 } else if (op == UserOperation.AddAdmin) {
761 let data = wsJsonToRes<AddAdminResponse>(msg).data;
762 this.state.siteRes.admins = data.admins;
763 this.setState(this.state);
764 } else if (op == UserOperation.BanUser) {
765 let data = wsJsonToRes<BanUserResponse>(msg).data;
766 let found = this.state.siteRes.banned.find(
767 u => (u.user.id = data.user_view.user.id)
770 // Remove the banned if its found in the list, and the action is an unban
771 if (found && !data.banned) {
772 this.state.siteRes.banned = this.state.siteRes.banned.filter(
773 i => i.user.id !== data.user_view.user.id
776 this.state.siteRes.banned.push(data.user_view);
780 .filter(p => p.creator.id == data.user_view.user.id)
781 .forEach(p => (p.creator.banned = data.banned));
783 this.setState(this.state);
784 } else if (op == UserOperation.GetComments) {
785 let data = wsJsonToRes<GetCommentsResponse>(msg).data;
786 this.state.comments = data.comments;
787 this.state.loading = false;
788 this.setState(this.state);
790 op == UserOperation.EditComment ||
791 op == UserOperation.DeleteComment ||
792 op == UserOperation.RemoveComment
794 let data = wsJsonToRes<CommentResponse>(msg).data;
795 editCommentRes(data.comment_view, this.state.comments);
796 this.setState(this.state);
797 } else if (op == UserOperation.CreateComment) {
798 let data = wsJsonToRes<CommentResponse>(msg).data;
800 // Necessary since it might be a user reply
801 if (data.recipient_ids.length == 0) {
802 // If you're on subscribed, only push it if you're subscribed.
803 if (this.state.listingType == ListingType.Subscribed) {
805 this.state.subscribedCommunities
806 .map(c => c.community.id)
807 .includes(data.comment_view.community.id)
809 this.state.comments.unshift(data.comment_view);
812 this.state.comments.unshift(data.comment_view);
814 this.setState(this.state);
816 } else if (op == UserOperation.SaveComment) {
817 let data = wsJsonToRes<CommentResponse>(msg).data;
818 saveCommentRes(data.comment_view, this.state.comments);
819 this.setState(this.state);
820 } else if (op == UserOperation.CreateCommentLike) {
821 let data = wsJsonToRes<CommentResponse>(msg).data;
822 createCommentLikeRes(data.comment_view, this.state.comments);
823 this.setState(this.state);