1 import { Component, linkEvent } from "inferno";
2 import { T } from "inferno-i18next-dess";
3 import { Link } from "inferno-router";
17 ListCommunitiesResponse,
24 } from "lemmy-js-client";
25 import { Subscription } from "rxjs";
26 import { i18n } from "../../i18next";
27 import { DataType, InitialFetchRequest } from "../../interfaces";
28 import { UserService, WebSocketService } from "../../services";
33 createPostLikeFindRes,
38 getListingTypeFromProps,
44 restoreScrollPosition,
58 import { CommentNodes } from "../comment/comment-nodes";
59 import { BannerIconHeader } from "../common/banner-icon-header";
60 import { DataTypeSelect } from "../common/data-type-select";
61 import { HtmlTags } from "../common/html-tags";
62 import { Icon, Spinner } from "../common/icon";
63 import { ListingTypeSelect } from "../common/listing-type-select";
64 import { Paginator } from "../common/paginator";
65 import { SortSelect } from "../common/sort-select";
66 import { CommunityLink } from "../community/community-link";
67 import { PersonListing } from "../person/person-listing";
68 import { PostListings } from "../post/post-listings";
69 import { SiteForm } from "./site-form";
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 trendingCommunities: [],
106 siteRes: this.isoData.site_res,
108 showSubscribedMobile: false,
109 showTrendingMobile: false,
110 showSidebarMobile: false,
114 listingType: getListingTypeFromProps(this.props),
115 dataType: getDataTypeFromProps(this.props),
116 sort: getSortTypeFromProps(this.props),
117 page: getPageFromProps(this.props),
120 constructor(props: any, context: any) {
121 super(props, context);
123 this.state = this.emptyState;
124 this.handleEditCancel = this.handleEditCancel.bind(this);
125 this.handleSortChange = this.handleSortChange.bind(this);
126 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
127 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
128 this.handlePageChange = this.handlePageChange.bind(this);
130 this.parseMessage = this.parseMessage.bind(this);
131 this.subscription = wsSubscribe(this.parseMessage);
133 // Only fetch the data if coming from another route
134 if (this.isoData.path == this.context.router.route.match.url) {
135 if (this.state.dataType == DataType.Post) {
136 this.state.posts = this.isoData.routeData[0].posts;
138 this.state.comments = this.isoData.routeData[0].comments;
140 this.state.trendingCommunities = this.isoData.routeData[1].communities;
141 this.state.loading = false;
143 this.fetchTrendingCommunities();
150 fetchTrendingCommunities() {
151 let listCommunitiesForm: ListCommunities = {
152 type_: ListingType.Local,
155 auth: authField(false),
157 WebSocketService.Instance.send(
158 wsClient.listCommunities(listCommunitiesForm)
162 componentDidMount() {
163 // This means it hasn't been set up yet
164 if (!this.state.siteRes.site_view) {
165 this.context.router.history.push("/setup");
168 WebSocketService.Instance.send(wsClient.communityJoin({ community_id: 0 }));
171 componentWillUnmount() {
172 saveScrollPosition(this.context);
173 this.subscription.unsubscribe();
174 window.isoData.path = undefined;
177 static getDerivedStateFromProps(props: any): HomeProps {
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.myUserInfo
196 ? Object.values(ListingType)[
197 UserService.Instance.myUserInfo.local_user_view.local_user
198 .default_listing_type
201 let sort: SortType = pathSplit[7]
202 ? SortType[pathSplit[7]]
203 : UserService.Instance.myUserInfo
204 ? Object.values(SortType)[
205 UserService.Instance.myUserInfo.local_user_view.local_user
210 let page = pathSplit[9] ? Number(pathSplit[9]) : 1;
212 let promises: Promise<any>[] = [];
214 if (dataType == DataType.Post) {
215 let getPostsForm: GetPosts = {
222 setOptionalAuth(getPostsForm, req.auth);
223 promises.push(req.client.getPosts(getPostsForm));
225 let getCommentsForm: GetComments = {
232 setOptionalAuth(getCommentsForm, req.auth);
233 promises.push(req.client.getComments(getCommentsForm));
236 let trendingCommunitiesForm: ListCommunities = {
237 type_: ListingType.Local,
241 promises.push(req.client.listCommunities(trendingCommunitiesForm));
246 componentDidUpdate(_: any, lastState: HomeState) {
248 lastState.listingType !== this.state.listingType ||
249 lastState.dataType !== this.state.dataType ||
250 lastState.sort !== this.state.sort ||
251 lastState.page !== this.state.page
253 this.setState({ loading: true });
258 get documentTitle(): string {
260 this.state.siteRes.site_view
261 ? this.state.siteRes.site_view.site.description
262 ? `${this.state.siteRes.site_view.site.name} - ${this.state.siteRes.site_view.site.description}`
263 : this.state.siteRes.site_view.site.name
270 <div class="container">
272 title={this.documentTitle}
273 path={this.context.router.route.match.url}
275 {this.state.siteRes.site_view?.site && (
277 <main role="main" class="col-12 col-md-8">
278 <div class="d-block d-md-none">{this.mobileView()}</div>
281 <aside class="d-none d-md-block col-md-4">{this.mySidebar()}</aside>
292 {UserService.Instance.myUserInfo &&
293 UserService.Instance.myUserInfo.follows.length > 0 && (
295 class="btn btn-secondary d-inline-block mb-2 mr-3"
296 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
298 {i18n.t("subscribed")}{" "}
301 this.state.showSubscribedMobile
305 classes="icon-inline"
310 class="btn btn-secondary d-inline-block mb-2 mr-3"
311 onClick={linkEvent(this, this.handleShowTrendingMobile)}
313 {i18n.t("trending")}{" "}
316 this.state.showTrendingMobile ? `minus-square` : `plus-square`
318 classes="icon-inline"
322 class="btn btn-secondary d-inline-block mb-2 mr-3"
323 onClick={linkEvent(this, this.handleShowSidebarMobile)}
325 {i18n.t("sidebar")}{" "}
328 this.state.showSidebarMobile ? `minus-square` : `plus-square`
330 classes="icon-inline"
333 {this.state.showSubscribedMobile && (
334 <div class="col-12 card border-secondary mb-3">
335 <div class="card-body">{this.subscribedCommunities()}</div>
338 {this.state.showTrendingMobile && (
339 <div class="col-12 card border-secondary mb-3">
340 <div class="card-body">{this.trendingCommunities()}</div>
343 {this.state.showSidebarMobile && (
344 <div class="col-12 card border-secondary mb-3">
345 <div class="card-body">{this.sidebar()}</div>
356 {!this.state.loading && (
358 <div class="card border-secondary mb-3">
359 <div class="card-body">
360 {this.trendingCommunities()}
361 {this.createCommunityButton()}
362 {this.exploreCommunitiesButton()}
366 {UserService.Instance.myUserInfo &&
367 UserService.Instance.myUserInfo.follows.length > 0 && (
368 <div class="card border-secondary mb-3">
369 <div class="card-body">{this.subscribedCommunities()}</div>
373 <div class="card border-secondary mb-3">
374 <div class="card-body">{this.sidebar()}</div>
382 createCommunityButton() {
384 <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
385 {i18n.t("create_a_community")}
390 exploreCommunitiesButton() {
392 <Link className="btn btn-secondary btn-block" to="/communities">
393 {i18n.t("explore_communities")}
398 trendingCommunities() {
402 <T i18nKey="trending_communities">
404 <Link className="text-body" to="/communities">
409 <ul class="list-inline mb-0">
410 {this.state.trendingCommunities.map(cv => (
411 <li class="list-inline-item d-inline-block">
412 <CommunityLink community={cv.community} />
420 subscribedCommunities() {
424 <T i18nKey="subscribed_to_communities">
426 <Link className="text-body" to="/communities">
431 <ul class="list-inline mb-0">
432 {UserService.Instance.myUserInfo.follows.map(cfv => (
433 <li class="list-inline-item d-inline-block">
434 <CommunityLink community={cfv.community} />
443 let site = this.state.siteRes.site_view.site;
446 {!this.state.showEditSite ? (
450 {this.adminButtons()}
452 <BannerIconHeader banner={site.banner} />
456 <SiteForm site={site} onCancel={this.handleEditCancel} />
462 updateUrl(paramUpdates: UrlParams) {
463 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
464 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
465 const sortStr = paramUpdates.sort || this.state.sort;
466 const page = paramUpdates.page || this.state.page;
467 this.props.history.push(
468 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
473 let site = this.state.siteRes.site_view.site;
476 {site.description && <h6>{site.description}</h6>}
477 {site.sidebar && this.siteSidebar()}
485 let site = this.state.siteRes.site_view.site;
486 return site.name && <h5 class="mb-0">{site.name}</h5>;
491 <ul class="mt-1 list-inline small mb-0">
492 <li class="list-inline-item">{i18n.t("admins")}:</li>
493 {this.state.siteRes.admins.map(av => (
494 <li class="list-inline-item">
495 <PersonListing person={av.person} />
503 let counts = this.state.siteRes.site_view.counts;
505 <ul class="my-2 list-inline">
506 <li className="list-inline-item badge badge-secondary">
507 {i18n.t("number_online", {
508 count: this.state.siteRes.online,
509 formattedCount: numToSI(this.state.siteRes.online),
513 className="list-inline-item badge badge-secondary pointer"
514 data-tippy-content={`${i18n.t("number_of_users", {
515 count: counts.users_active_day,
516 formattedCount: counts.users_active_day,
517 })} ${i18n.t("active_in_the_last")} ${i18n.t("day")}`}
519 {i18n.t("number_of_users", {
520 count: counts.users_active_day,
521 formattedCount: numToSI(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 formattedCount: counts.users_active_week,
530 })} ${i18n.t("active_in_the_last")} ${i18n.t("week")}`}
532 {i18n.t("number_of_users", {
533 count: counts.users_active_week,
534 formattedCount: numToSI(counts.users_active_week),
539 className="list-inline-item badge badge-secondary pointer"
540 data-tippy-content={`${i18n.t("number_of_users", {
541 count: counts.users_active_month,
542 formattedCount: counts.users_active_month,
543 })} ${i18n.t("active_in_the_last")} ${i18n.t("month")}`}
545 {i18n.t("number_of_users", {
546 count: counts.users_active_month,
547 formattedCount: numToSI(counts.users_active_month),
552 className="list-inline-item badge badge-secondary pointer"
553 data-tippy-content={`${i18n.t("number_of_users", {
554 count: counts.users_active_half_year,
555 formattedCount: counts.users_active_half_year,
556 })} ${i18n.t("active_in_the_last")} ${i18n.t("number_of_months", {
561 {i18n.t("number_of_users", {
562 count: counts.users_active_half_year,
563 formattedCount: numToSI(counts.users_active_half_year),
565 / {i18n.t("number_of_months", { count: 6, formattedCount: 6 })}
567 <li className="list-inline-item badge badge-secondary">
568 {i18n.t("number_of_users", {
570 formattedCount: numToSI(counts.users),
573 <li className="list-inline-item badge badge-secondary">
574 {i18n.t("number_of_communities", {
575 count: counts.communities,
576 formattedCount: numToSI(counts.communities),
579 <li className="list-inline-item badge badge-secondary">
580 {i18n.t("number_of_posts", {
582 formattedCount: numToSI(counts.posts),
585 <li className="list-inline-item badge badge-secondary">
586 {i18n.t("number_of_comments", {
587 count: counts.comments,
588 formattedCount: numToSI(counts.comments),
591 <li className="list-inline-item">
592 <Link className="badge badge-secondary" to="/modlog">
603 <ul class="list-inline mb-1 text-muted font-weight-bold">
604 <li className="list-inline-item-action">
606 class="btn btn-link d-inline-block text-muted"
607 onClick={linkEvent(this, this.handleEditClick)}
608 aria-label={i18n.t("edit")}
609 data-tippy-content={i18n.t("edit")}
611 <Icon icon="edit" classes="icon-inline" />
623 dangerouslySetInnerHTML={mdToHtml(
624 this.state.siteRes.site_view.site.sidebar
632 <div class="main-content-wrapper">
633 {this.state.loading ? (
642 page={this.state.page}
643 onChange={this.handlePageChange}
652 let site = this.state.siteRes.site_view.site;
653 return this.state.dataType == DataType.Post ? (
655 posts={this.state.posts}
658 enableDownvotes={site.enable_downvotes}
659 enableNsfw={site.enable_nsfw}
663 nodes={commentsToFlatNodes(this.state.comments)}
667 enableDownvotes={site.enable_downvotes}
674 <div className="mb-3">
677 type_={this.state.dataType}
678 onChange={this.handleDataTypeChange}
683 type_={this.state.listingType}
684 showLocal={showLocal(this.isoData)}
685 onChange={this.handleListingTypeChange}
689 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
691 {this.state.listingType == ListingType.All && (
693 href={`/feeds/all.xml?sort=${this.state.sort}`}
697 <Icon icon="rss" classes="text-muted small" />
700 {this.state.listingType == ListingType.Local && (
702 href={`/feeds/local.xml?sort=${this.state.sort}`}
706 <Icon icon="rss" classes="text-muted small" />
709 {UserService.Instance.myUserInfo &&
710 this.state.listingType == ListingType.Subscribed && (
712 href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${this.state.sort}`}
716 <Icon icon="rss" classes="text-muted small" />
723 get canAdmin(): boolean {
725 UserService.Instance.myUserInfo &&
726 this.state.siteRes.admins
727 .map(a => a.person.id)
728 .includes(UserService.Instance.myUserInfo.local_user_view.person.id)
732 handleEditClick(i: Home) {
733 i.state.showEditSite = true;
738 this.state.showEditSite = false;
739 this.setState(this.state);
742 handleShowSubscribedMobile(i: Home) {
743 i.state.showSubscribedMobile = !i.state.showSubscribedMobile;
747 handleShowTrendingMobile(i: Home) {
748 i.state.showTrendingMobile = !i.state.showTrendingMobile;
752 handleShowSidebarMobile(i: Home) {
753 i.state.showSidebarMobile = !i.state.showSidebarMobile;
757 handlePageChange(page: number) {
758 this.updateUrl({ page });
759 window.scrollTo(0, 0);
762 handleSortChange(val: SortType) {
763 this.updateUrl({ sort: val, page: 1 });
764 window.scrollTo(0, 0);
767 handleListingTypeChange(val: ListingType) {
768 this.updateUrl({ listingType: val, page: 1 });
769 window.scrollTo(0, 0);
772 handleDataTypeChange(val: DataType) {
773 this.updateUrl({ dataType: DataType[val], page: 1 });
774 window.scrollTo(0, 0);
778 if (this.state.dataType == DataType.Post) {
779 let getPostsForm: GetPosts = {
780 page: this.state.page,
782 sort: this.state.sort,
783 type_: this.state.listingType,
785 auth: authField(false),
787 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
789 let getCommentsForm: GetComments = {
790 page: this.state.page,
792 sort: this.state.sort,
793 type_: this.state.listingType,
795 auth: authField(false),
797 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
801 parseMessage(msg: any) {
802 let op = wsUserOp(msg);
805 toast(i18n.t(msg.error), "danger");
807 } else if (msg.reconnect) {
808 WebSocketService.Instance.send(
809 wsClient.communityJoin({ community_id: 0 })
812 } else if (op == UserOperation.ListCommunities) {
813 let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
814 this.state.trendingCommunities = data.communities;
815 this.setState(this.state);
816 } else if (op == UserOperation.EditSite) {
817 let data = wsJsonToRes<SiteResponse>(msg).data;
818 this.state.siteRes.site_view = data.site_view;
819 this.state.showEditSite = false;
820 this.setState(this.state);
821 toast(i18n.t("site_saved"));
822 } else if (op == UserOperation.GetPosts) {
823 let data = wsJsonToRes<GetPostsResponse>(msg).data;
824 this.state.posts = data.posts;
825 this.state.loading = false;
826 this.setState(this.state);
827 restoreScrollPosition(this.context);
829 } else if (op == UserOperation.CreatePost) {
830 let data = wsJsonToRes<PostResponse>(msg).data;
833 let nsfw = data.post_view.post.nsfw || data.post_view.community.nsfw;
837 UserService.Instance.myUserInfo &&
838 UserService.Instance.myUserInfo.local_user_view.local_user.show_nsfw);
840 // Only push these if you're on the first page, and you pass the nsfw check
841 if (this.state.page == 1 && nsfwCheck) {
842 // If you're on subscribed, only push it if you're subscribed.
843 if (this.state.listingType == ListingType.Subscribed) {
845 UserService.Instance.myUserInfo.follows
846 .map(c => c.community.id)
847 .includes(data.post_view.community.id)
849 this.state.posts.unshift(data.post_view);
851 UserService.Instance.myUserInfo?.local_user_view.local_user
852 .show_new_post_notifs
854 notifyPost(data.post_view, this.context.router);
857 } else if (this.state.listingType == ListingType.Local) {
858 // If you're on the local view, only push it if its local
859 if (data.post_view.post.local) {
860 this.state.posts.unshift(data.post_view);
862 UserService.Instance.myUserInfo?.local_user_view.local_user
863 .show_new_post_notifs
865 notifyPost(data.post_view, this.context.router);
869 this.state.posts.unshift(data.post_view);
871 UserService.Instance.myUserInfo?.local_user_view.local_user
872 .show_new_post_notifs
874 notifyPost(data.post_view, this.context.router);
877 this.setState(this.state);
880 op == UserOperation.EditPost ||
881 op == UserOperation.DeletePost ||
882 op == UserOperation.RemovePost ||
883 op == UserOperation.LockPost ||
884 op == UserOperation.StickyPost ||
885 op == UserOperation.SavePost
887 let data = wsJsonToRes<PostResponse>(msg).data;
888 editPostFindRes(data.post_view, this.state.posts);
889 this.setState(this.state);
890 } else if (op == UserOperation.CreatePostLike) {
891 let data = wsJsonToRes<PostResponse>(msg).data;
892 createPostLikeFindRes(data.post_view, this.state.posts);
893 this.setState(this.state);
894 } else if (op == UserOperation.AddAdmin) {
895 let data = wsJsonToRes<AddAdminResponse>(msg).data;
896 this.state.siteRes.admins = data.admins;
897 this.setState(this.state);
898 } else if (op == UserOperation.BanPerson) {
899 let data = wsJsonToRes<BanPersonResponse>(msg).data;
900 let found = this.state.siteRes.banned.find(
901 p => (p.person.id = data.person_view.person.id)
904 // Remove the banned if its found in the list, and the action is an unban
905 if (found && !data.banned) {
906 this.state.siteRes.banned = this.state.siteRes.banned.filter(
907 i => i.person.id !== data.person_view.person.id
910 this.state.siteRes.banned.push(data.person_view);
914 .filter(p => p.creator.id == data.person_view.person.id)
915 .forEach(p => (p.creator.banned = data.banned));
917 this.setState(this.state);
918 } else if (op == UserOperation.GetComments) {
919 let data = wsJsonToRes<GetCommentsResponse>(msg).data;
920 this.state.comments = data.comments;
921 this.state.loading = false;
922 this.setState(this.state);
924 op == UserOperation.EditComment ||
925 op == UserOperation.DeleteComment ||
926 op == UserOperation.RemoveComment
928 let data = wsJsonToRes<CommentResponse>(msg).data;
929 editCommentRes(data.comment_view, this.state.comments);
930 this.setState(this.state);
931 } else if (op == UserOperation.CreateComment) {
932 let data = wsJsonToRes<CommentResponse>(msg).data;
934 // Necessary since it might be a user reply
936 // If you're on subscribed, only push it if you're subscribed.
937 if (this.state.listingType == ListingType.Subscribed) {
939 UserService.Instance.myUserInfo.follows
940 .map(c => c.community.id)
941 .includes(data.comment_view.community.id)
943 this.state.comments.unshift(data.comment_view);
946 this.state.comments.unshift(data.comment_view);
948 this.setState(this.state);
950 } else if (op == UserOperation.SaveComment) {
951 let data = wsJsonToRes<CommentResponse>(msg).data;
952 saveCommentRes(data.comment_view, this.state.comments);
953 this.setState(this.state);
954 } else if (op == UserOperation.CreateCommentLike) {
955 let data = wsJsonToRes<CommentResponse>(msg).data;
956 createCommentLikeRes(data.comment_view, this.state.comments);
957 this.setState(this.state);
958 } else if (op == UserOperation.BlockPerson) {
959 let data = wsJsonToRes<BlockPersonResponse>(msg).data;
960 updatePersonBlock(data);