1 import { Component, linkEvent } from "inferno";
2 import { T } from "inferno-i18next";
3 import { Link } from "inferno-router";
13 GetFollowedCommunitiesResponse,
18 ListCommunitiesResponse,
25 } from "lemmy-js-client";
26 import { Subscription } from "rxjs";
27 import { i18n } from "../../i18next";
28 import { DataType, InitialFetchRequest } from "../../interfaces";
29 import { UserService, WebSocketService } from "../../services";
34 createPostLikeFindRes,
39 getListingTypeFromProps,
44 restoreScrollPosition,
57 import { CommentNodes } from "../comment/comment-nodes";
58 import { BannerIconHeader } from "../common/banner-icon-header";
59 import { DataTypeSelect } from "../common/data-type-select";
60 import { HtmlTags } from "../common/html-tags";
61 import { Icon, Spinner } from "../common/icon";
62 import { ListingTypeSelect } from "../common/listing-type-select";
63 import { Paginator } from "../common/paginator";
64 import { SortSelect } from "../common/sort-select";
65 import { CommunityLink } from "../community/community-link";
66 import { PersonListing } from "../person/person-listing";
67 import { PostListings } from "../post/post-listings";
68 import { SiteForm } from "./site-form";
71 subscribedCommunities: CommunityFollowerView[];
72 trendingCommunities: CommunityView[];
73 siteRes: GetSiteResponse;
74 showEditSite: boolean;
75 showSubscribedMobile: boolean;
76 showTrendingMobile: boolean;
77 showSidebarMobile: boolean;
80 comments: CommentView[];
81 listingType: ListingType;
88 listingType: ListingType;
95 listingType?: ListingType;
101 export class Home extends Component<any, HomeState> {
102 private isoData = setIsoData(this.context);
103 private subscription: Subscription;
104 private emptyState: HomeState = {
105 subscribedCommunities: [],
106 trendingCommunities: [],
107 siteRes: this.isoData.site_res,
109 showSubscribedMobile: false,
110 showTrendingMobile: false,
111 showSidebarMobile: false,
115 listingType: getListingTypeFromProps(this.props),
116 dataType: getDataTypeFromProps(this.props),
117 sort: getSortTypeFromProps(this.props),
118 page: getPageFromProps(this.props),
121 constructor(props: any, context: any) {
122 super(props, context);
124 this.state = this.emptyState;
125 this.handleEditCancel = this.handleEditCancel.bind(this);
126 this.handleSortChange = this.handleSortChange.bind(this);
127 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
128 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
129 this.handlePageChange = this.handlePageChange.bind(this);
131 this.parseMessage = this.parseMessage.bind(this);
132 this.subscription = wsSubscribe(this.parseMessage);
134 // Only fetch the data if coming from another route
135 if (this.isoData.path == this.context.router.route.match.url) {
136 if (this.state.dataType == DataType.Post) {
137 this.state.posts = this.isoData.routeData[0].posts;
139 this.state.comments = this.isoData.routeData[0].comments;
141 this.state.trendingCommunities = this.isoData.routeData[1].communities;
142 if (UserService.Instance.localUserView) {
143 this.state.subscribedCommunities =
144 this.isoData.routeData[2].communities;
146 this.state.loading = false;
148 this.fetchTrendingCommunities();
150 if (UserService.Instance.localUserView) {
151 WebSocketService.Instance.send(
152 wsClient.getFollowedCommunities({
162 fetchTrendingCommunities() {
163 let listCommunitiesForm: ListCommunities = {
164 type_: ListingType.Local,
167 auth: authField(false),
169 WebSocketService.Instance.send(
170 wsClient.listCommunities(listCommunitiesForm)
174 componentDidMount() {
175 // This means it hasn't been set up yet
176 if (!this.state.siteRes.site_view) {
177 this.context.router.history.push("/setup");
180 WebSocketService.Instance.send(wsClient.communityJoin({ community_id: 0 }));
183 componentWillUnmount() {
184 saveScrollPosition(this.context);
185 this.subscription.unsubscribe();
186 window.isoData.path = undefined;
189 static getDerivedStateFromProps(props: any): HomeProps {
191 listingType: getListingTypeFromProps(props),
192 dataType: getDataTypeFromProps(props),
193 sort: getSortTypeFromProps(props),
194 page: getPageFromProps(props),
198 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
199 let pathSplit = req.path.split("/");
200 let dataType: DataType = pathSplit[3]
201 ? DataType[pathSplit[3]]
204 // TODO figure out auth default_listingType, default_sort_type
205 let type_: ListingType = pathSplit[5]
206 ? ListingType[pathSplit[5]]
207 : UserService.Instance.localUserView
208 ? Object.values(ListingType)[
209 UserService.Instance.localUserView.local_user.default_listing_type
212 let sort: SortType = pathSplit[7]
213 ? SortType[pathSplit[7]]
214 : UserService.Instance.localUserView
215 ? Object.values(SortType)[
216 UserService.Instance.localUserView.local_user.default_sort_type
220 let page = pathSplit[9] ? Number(pathSplit[9]) : 1;
222 let promises: Promise<any>[] = [];
224 if (dataType == DataType.Post) {
225 let getPostsForm: GetPosts = {
232 setOptionalAuth(getPostsForm, req.auth);
233 promises.push(req.client.getPosts(getPostsForm));
235 let getCommentsForm: GetComments = {
242 setOptionalAuth(getCommentsForm, req.auth);
243 promises.push(req.client.getComments(getCommentsForm));
246 let trendingCommunitiesForm: ListCommunities = {
247 type_: ListingType.Local,
251 promises.push(req.client.listCommunities(trendingCommunitiesForm));
254 promises.push(req.client.getFollowedCommunities({ auth: req.auth }));
260 componentDidUpdate(_: any, lastState: HomeState) {
262 lastState.listingType !== this.state.listingType ||
263 lastState.dataType !== this.state.dataType ||
264 lastState.sort !== this.state.sort ||
265 lastState.page !== this.state.page
267 this.setState({ loading: true });
272 get documentTitle(): string {
274 this.state.siteRes.site_view
275 ? this.state.siteRes.site_view.site.description
276 ? `${this.state.siteRes.site_view.site.name} - ${this.state.siteRes.site_view.site.description}`
277 : this.state.siteRes.site_view.site.name
284 <div class="container">
286 title={this.documentTitle}
287 path={this.context.router.route.match.url}
289 {this.state.siteRes.site_view?.site && (
291 <main role="main" class="col-12 col-md-8">
292 <div class="d-block d-md-none">{this.mobileView()}</div>
295 <aside class="d-none d-md-block col-md-4">{this.mySidebar()}</aside>
306 {UserService.Instance.localUserView &&
307 this.state.subscribedCommunities.length > 0 && (
309 class="btn btn-secondary d-inline-block mb-2 mr-3"
310 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
312 {i18n.t("subscribed")}{" "}
315 this.state.showSubscribedMobile
319 classes="icon-inline"
324 class="btn btn-secondary d-inline-block mb-2 mr-3"
325 onClick={linkEvent(this, this.handleShowTrendingMobile)}
327 {i18n.t("trending")}{" "}
330 this.state.showTrendingMobile ? `minus-square` : `plus-square`
332 classes="icon-inline"
336 class="btn btn-secondary d-inline-block mb-2 mr-3"
337 onClick={linkEvent(this, this.handleShowSidebarMobile)}
339 {i18n.t("sidebar")}{" "}
342 this.state.showSidebarMobile ? `minus-square` : `plus-square`
344 classes="icon-inline"
347 {this.state.showSubscribedMobile && (
348 <div class="col-12 card border-secondary mb-3">
349 <div class="card-body">{this.subscribedCommunities()}</div>
352 {this.state.showTrendingMobile && (
353 <div class="col-12 card border-secondary mb-3">
354 <div class="card-body">{this.trendingCommunities()}</div>
357 {this.state.showSidebarMobile && (
358 <div class="col-12 card border-secondary mb-3">
359 <div class="card-body">{this.sidebar()}</div>
370 {!this.state.loading && (
372 <div class="card border-secondary mb-3">
373 <div class="card-body">
374 {this.trendingCommunities()}
375 {this.createCommunityButton()}
379 {UserService.Instance.localUserView &&
380 this.state.subscribedCommunities.length > 0 && (
381 <div class="card border-secondary mb-3">
382 <div class="card-body">{this.subscribedCommunities()}</div>
386 <div class="card border-secondary mb-3">
387 <div class="card-body">{this.sidebar()}</div>
395 createCommunityButton() {
397 <Link className="btn btn-secondary btn-block" to="/create_community">
398 {i18n.t("create_a_community")}
403 trendingCommunities() {
407 <T i18nKey="trending_communities">
409 <Link className="text-body" to="/communities">
414 <ul class="list-inline">
415 {this.state.trendingCommunities.map(cv => (
416 <li class="list-inline-item d-inline-block">
417 <CommunityLink community={cv.community} />
425 subscribedCommunities() {
429 <T i18nKey="subscribed_to_communities">
431 <Link className="text-body" to="/communities">
436 <ul class="list-inline mb-0">
437 {this.state.subscribedCommunities.map(cfv => (
438 <li class="list-inline-item d-inline-block">
439 <CommunityLink community={cfv.community} />
448 let site = this.state.siteRes.site_view.site;
451 {!this.state.showEditSite ? (
455 {this.adminButtons()}
457 <BannerIconHeader banner={site.banner} />
461 <SiteForm site={site} onCancel={this.handleEditCancel} />
467 updateUrl(paramUpdates: UrlParams) {
468 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
469 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
470 const sortStr = paramUpdates.sort || this.state.sort;
471 const page = paramUpdates.page || this.state.page;
472 this.props.history.push(
473 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
478 let site = this.state.siteRes.site_view.site;
481 {site.description && <h6>{site.description}</h6>}
482 {site.sidebar && this.siteSidebar()}
490 let site = this.state.siteRes.site_view.site;
491 return site.name && <h5 class="mb-0">{site.name}</h5>;
496 <ul class="mt-1 list-inline small mb-0">
497 <li class="list-inline-item">{i18n.t("admins")}:</li>
498 {this.state.siteRes.admins.map(av => (
499 <li class="list-inline-item">
500 <PersonListing person={av.person} />
508 let counts = this.state.siteRes.site_view.counts;
510 <ul class="my-2 list-inline">
511 <li className="list-inline-item badge badge-secondary">
512 {i18n.t("number_online", { count: this.state.siteRes.online })}
515 className="list-inline-item badge badge-secondary pointer"
516 data-tippy-content={`${i18n.t("number_of_users", {
517 count: counts.users_active_day,
518 })} ${i18n.t("active_in_the_last")} ${i18n.t("day")}`}
520 {i18n.t("number_of_users", {
521 count: counts.users_active_day,
526 className="list-inline-item badge badge-secondary pointer"
527 data-tippy-content={`${i18n.t("number_of_users", {
528 count: counts.users_active_week,
529 })} ${i18n.t("active_in_the_last")} ${i18n.t("week")}`}
531 {i18n.t("number_of_users", {
532 count: counts.users_active_week,
537 className="list-inline-item badge badge-secondary pointer"
538 data-tippy-content={`${i18n.t("number_of_users", {
539 count: counts.users_active_month,
540 })} ${i18n.t("active_in_the_last")} ${i18n.t("month")}`}
542 {i18n.t("number_of_users", {
543 count: counts.users_active_month,
548 className="list-inline-item badge badge-secondary pointer"
549 data-tippy-content={`${i18n.t("number_of_users", {
550 count: counts.users_active_half_year,
551 })} ${i18n.t("active_in_the_last")} ${i18n.t("number_of_months", {
555 {i18n.t("number_of_users", {
556 count: counts.users_active_half_year,
558 / {i18n.t("number_of_months", { count: 6 })}
560 <li className="list-inline-item badge badge-secondary">
561 {i18n.t("number_of_users", {
565 <li className="list-inline-item badge badge-secondary">
566 {i18n.t("number_of_communities", {
567 count: counts.communities,
570 <li className="list-inline-item badge badge-secondary">
571 {i18n.t("number_of_posts", {
575 <li className="list-inline-item badge badge-secondary">
576 {i18n.t("number_of_comments", {
577 count: counts.comments,
580 <li className="list-inline-item">
581 <Link className="badge badge-secondary" to="/modlog">
592 <ul class="list-inline mb-1 text-muted font-weight-bold">
593 <li className="list-inline-item-action">
595 class="btn btn-link d-inline-block text-muted"
596 onClick={linkEvent(this, this.handleEditClick)}
597 aria-label={i18n.t("edit")}
598 data-tippy-content={i18n.t("edit")}
600 <Icon icon="edit" classes="icon-inline" />
612 dangerouslySetInnerHTML={mdToHtml(
613 this.state.siteRes.site_view.site.sidebar
621 <div class="main-content-wrapper">
622 {this.state.loading ? (
631 page={this.state.page}
632 onChange={this.handlePageChange}
641 let site = this.state.siteRes.site_view.site;
642 return this.state.dataType == DataType.Post ? (
644 posts={this.state.posts}
647 enableDownvotes={site.enable_downvotes}
648 enableNsfw={site.enable_nsfw}
652 nodes={commentsToFlatNodes(this.state.comments)}
656 enableDownvotes={site.enable_downvotes}
663 <div className="mb-3">
666 type_={this.state.dataType}
667 onChange={this.handleDataTypeChange}
672 type_={this.state.listingType}
673 showLocal={showLocal(this.isoData)}
674 onChange={this.handleListingTypeChange}
678 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
680 {this.state.listingType == ListingType.All && (
682 href={`/feeds/all.xml?sort=${this.state.sort}`}
686 <Icon icon="rss" classes="text-muted small" />
689 {this.state.listingType == ListingType.Local && (
691 href={`/feeds/local.xml?sort=${this.state.sort}`}
695 <Icon icon="rss" classes="text-muted small" />
698 {UserService.Instance.localUserView &&
699 this.state.listingType == ListingType.Subscribed && (
701 href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${this.state.sort}`}
705 <Icon icon="rss" classes="text-muted small" />
712 get canAdmin(): boolean {
714 UserService.Instance.localUserView &&
715 this.state.siteRes.admins
716 .map(a => a.person.id)
717 .includes(UserService.Instance.localUserView.person.id)
721 handleEditClick(i: Home) {
722 i.state.showEditSite = true;
727 this.state.showEditSite = false;
728 this.setState(this.state);
731 handleShowSubscribedMobile(i: Home) {
732 i.state.showSubscribedMobile = !i.state.showSubscribedMobile;
736 handleShowTrendingMobile(i: Home) {
737 i.state.showTrendingMobile = !i.state.showTrendingMobile;
741 handleShowSidebarMobile(i: Home) {
742 i.state.showSidebarMobile = !i.state.showSidebarMobile;
746 handlePageChange(page: number) {
747 this.updateUrl({ page });
748 window.scrollTo(0, 0);
751 handleSortChange(val: SortType) {
752 this.updateUrl({ sort: val, page: 1 });
753 window.scrollTo(0, 0);
756 handleListingTypeChange(val: ListingType) {
757 this.updateUrl({ listingType: val, page: 1 });
758 window.scrollTo(0, 0);
761 handleDataTypeChange(val: DataType) {
762 this.updateUrl({ dataType: DataType[val], page: 1 });
763 window.scrollTo(0, 0);
767 if (this.state.dataType == DataType.Post) {
768 let getPostsForm: GetPosts = {
769 page: this.state.page,
771 sort: this.state.sort,
772 type_: this.state.listingType,
774 auth: authField(false),
776 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
778 let getCommentsForm: GetComments = {
779 page: this.state.page,
781 sort: this.state.sort,
782 type_: this.state.listingType,
784 auth: authField(false),
786 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
790 parseMessage(msg: any) {
791 let op = wsUserOp(msg);
794 toast(i18n.t(msg.error), "danger");
796 } else if (msg.reconnect) {
797 WebSocketService.Instance.send(
798 wsClient.communityJoin({ community_id: 0 })
801 } else if (op == UserOperation.GetFollowedCommunities) {
802 let data = wsJsonToRes<GetFollowedCommunitiesResponse>(msg).data;
803 this.state.subscribedCommunities = data.communities;
804 this.setState(this.state);
805 } else if (op == UserOperation.ListCommunities) {
806 let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
807 this.state.trendingCommunities = data.communities;
808 this.setState(this.state);
809 } else if (op == UserOperation.EditSite) {
810 let data = wsJsonToRes<SiteResponse>(msg).data;
811 this.state.siteRes.site_view = data.site_view;
812 this.state.showEditSite = false;
813 this.setState(this.state);
814 toast(i18n.t("site_saved"));
815 } else if (op == UserOperation.GetPosts) {
816 let data = wsJsonToRes<GetPostsResponse>(msg).data;
817 this.state.posts = data.posts;
818 this.state.loading = false;
819 this.setState(this.state);
820 restoreScrollPosition(this.context);
822 } else if (op == UserOperation.CreatePost) {
823 let data = wsJsonToRes<PostResponse>(msg).data;
826 let nsfw = data.post_view.post.nsfw || data.post_view.community.nsfw;
830 UserService.Instance.localUserView &&
831 UserService.Instance.localUserView.local_user.show_nsfw);
833 // Only push these if you're on the first page, and you pass the nsfw check
834 if (this.state.page == 1 && nsfwCheck) {
835 // If you're on subscribed, only push it if you're subscribed.
836 if (this.state.listingType == ListingType.Subscribed) {
838 this.state.subscribedCommunities
839 .map(c => c.community.id)
840 .includes(data.post_view.community.id)
842 this.state.posts.unshift(data.post_view);
843 notifyPost(data.post_view, this.context.router);
845 } else if (this.state.listingType == ListingType.Local) {
846 // If you're on the local view, only push it if its local
847 if (data.post_view.post.local) {
848 this.state.posts.unshift(data.post_view);
849 notifyPost(data.post_view, this.context.router);
852 this.state.posts.unshift(data.post_view);
853 notifyPost(data.post_view, this.context.router);
855 this.setState(this.state);
858 op == UserOperation.EditPost ||
859 op == UserOperation.DeletePost ||
860 op == UserOperation.RemovePost ||
861 op == UserOperation.LockPost ||
862 op == UserOperation.StickyPost ||
863 op == UserOperation.SavePost
865 let data = wsJsonToRes<PostResponse>(msg).data;
866 editPostFindRes(data.post_view, this.state.posts);
867 this.setState(this.state);
868 } else if (op == UserOperation.CreatePostLike) {
869 let data = wsJsonToRes<PostResponse>(msg).data;
870 createPostLikeFindRes(data.post_view, this.state.posts);
871 this.setState(this.state);
872 } else if (op == UserOperation.AddAdmin) {
873 let data = wsJsonToRes<AddAdminResponse>(msg).data;
874 this.state.siteRes.admins = data.admins;
875 this.setState(this.state);
876 } else if (op == UserOperation.BanPerson) {
877 let data = wsJsonToRes<BanPersonResponse>(msg).data;
878 let found = this.state.siteRes.banned.find(
879 p => (p.person.id = data.person_view.person.id)
882 // Remove the banned if its found in the list, and the action is an unban
883 if (found && !data.banned) {
884 this.state.siteRes.banned = this.state.siteRes.banned.filter(
885 i => i.person.id !== data.person_view.person.id
888 this.state.siteRes.banned.push(data.person_view);
892 .filter(p => p.creator.id == data.person_view.person.id)
893 .forEach(p => (p.creator.banned = data.banned));
895 this.setState(this.state);
896 } else if (op == UserOperation.GetComments) {
897 let data = wsJsonToRes<GetCommentsResponse>(msg).data;
898 this.state.comments = data.comments;
899 this.state.loading = false;
900 this.setState(this.state);
902 op == UserOperation.EditComment ||
903 op == UserOperation.DeleteComment ||
904 op == UserOperation.RemoveComment
906 let data = wsJsonToRes<CommentResponse>(msg).data;
907 editCommentRes(data.comment_view, this.state.comments);
908 this.setState(this.state);
909 } else if (op == UserOperation.CreateComment) {
910 let data = wsJsonToRes<CommentResponse>(msg).data;
912 // Necessary since it might be a user reply
914 // If you're on subscribed, only push it if you're subscribed.
915 if (this.state.listingType == ListingType.Subscribed) {
917 this.state.subscribedCommunities
918 .map(c => c.community.id)
919 .includes(data.comment_view.community.id)
921 this.state.comments.unshift(data.comment_view);
924 this.state.comments.unshift(data.comment_view);
926 this.setState(this.state);
928 } else if (op == UserOperation.SaveComment) {
929 let data = wsJsonToRes<CommentResponse>(msg).data;
930 saveCommentRes(data.comment_view, this.state.comments);
931 this.setState(this.state);
932 } else if (op == UserOperation.CreateCommentLike) {
933 let data = wsJsonToRes<CommentResponse>(msg).data;
934 createCommentLikeRes(data.comment_view, this.state.comments);
935 this.setState(this.state);