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()}
376 {this.exploreCommunitiesButton()}
380 {UserService.Instance.localUserView &&
381 this.state.subscribedCommunities.length > 0 && (
382 <div class="card border-secondary mb-3">
383 <div class="card-body">{this.subscribedCommunities()}</div>
387 <div class="card border-secondary mb-3">
388 <div class="card-body">{this.sidebar()}</div>
396 createCommunityButton() {
398 <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
399 {i18n.t("create_a_community")}
404 exploreCommunitiesButton() {
406 <Link className="btn btn-secondary btn-block" to="/communities">
407 {i18n.t("explore_communities")}
412 trendingCommunities() {
416 <T i18nKey="trending_communities">
418 <Link className="text-body" to="/communities">
423 <ul class="list-inline mb-0">
424 {this.state.trendingCommunities.map(cv => (
425 <li class="list-inline-item d-inline-block">
426 <CommunityLink community={cv.community} />
434 subscribedCommunities() {
438 <T i18nKey="subscribed_to_communities">
440 <Link className="text-body" to="/communities">
445 <ul class="list-inline mb-0">
446 {this.state.subscribedCommunities.map(cfv => (
447 <li class="list-inline-item d-inline-block">
448 <CommunityLink community={cfv.community} />
457 let site = this.state.siteRes.site_view.site;
460 {!this.state.showEditSite ? (
464 {this.adminButtons()}
466 <BannerIconHeader banner={site.banner} />
470 <SiteForm site={site} onCancel={this.handleEditCancel} />
476 updateUrl(paramUpdates: UrlParams) {
477 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
478 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
479 const sortStr = paramUpdates.sort || this.state.sort;
480 const page = paramUpdates.page || this.state.page;
481 this.props.history.push(
482 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
487 let site = this.state.siteRes.site_view.site;
490 {site.description && <h6>{site.description}</h6>}
491 {site.sidebar && this.siteSidebar()}
499 let site = this.state.siteRes.site_view.site;
500 return site.name && <h5 class="mb-0">{site.name}</h5>;
505 <ul class="mt-1 list-inline small mb-0">
506 <li class="list-inline-item">{i18n.t("admins")}:</li>
507 {this.state.siteRes.admins.map(av => (
508 <li class="list-inline-item">
509 <PersonListing person={av.person} />
517 let counts = this.state.siteRes.site_view.counts;
519 <ul class="my-2 list-inline">
520 <li className="list-inline-item badge badge-secondary">
521 {i18n.t("number_online", { count: this.state.siteRes.online })}
524 className="list-inline-item badge badge-secondary pointer"
525 data-tippy-content={`${i18n.t("number_of_users", {
526 count: counts.users_active_day,
527 })} ${i18n.t("active_in_the_last")} ${i18n.t("day")}`}
529 {i18n.t("number_of_users", {
530 count: counts.users_active_day,
535 className="list-inline-item badge badge-secondary pointer"
536 data-tippy-content={`${i18n.t("number_of_users", {
537 count: counts.users_active_week,
538 })} ${i18n.t("active_in_the_last")} ${i18n.t("week")}`}
540 {i18n.t("number_of_users", {
541 count: counts.users_active_week,
546 className="list-inline-item badge badge-secondary pointer"
547 data-tippy-content={`${i18n.t("number_of_users", {
548 count: counts.users_active_month,
549 })} ${i18n.t("active_in_the_last")} ${i18n.t("month")}`}
551 {i18n.t("number_of_users", {
552 count: counts.users_active_month,
557 className="list-inline-item badge badge-secondary pointer"
558 data-tippy-content={`${i18n.t("number_of_users", {
559 count: counts.users_active_half_year,
560 })} ${i18n.t("active_in_the_last")} ${i18n.t("number_of_months", {
564 {i18n.t("number_of_users", {
565 count: counts.users_active_half_year,
567 / {i18n.t("number_of_months", { count: 6 })}
569 <li className="list-inline-item badge badge-secondary">
570 {i18n.t("number_of_users", {
574 <li className="list-inline-item badge badge-secondary">
575 {i18n.t("number_of_communities", {
576 count: counts.communities,
579 <li className="list-inline-item badge badge-secondary">
580 {i18n.t("number_of_posts", {
584 <li className="list-inline-item badge badge-secondary">
585 {i18n.t("number_of_comments", {
586 count: counts.comments,
589 <li className="list-inline-item">
590 <Link className="badge badge-secondary" to="/modlog">
601 <ul class="list-inline mb-1 text-muted font-weight-bold">
602 <li className="list-inline-item-action">
604 class="btn btn-link d-inline-block text-muted"
605 onClick={linkEvent(this, this.handleEditClick)}
606 aria-label={i18n.t("edit")}
607 data-tippy-content={i18n.t("edit")}
609 <Icon icon="edit" classes="icon-inline" />
621 dangerouslySetInnerHTML={mdToHtml(
622 this.state.siteRes.site_view.site.sidebar
630 <div class="main-content-wrapper">
631 {this.state.loading ? (
640 page={this.state.page}
641 onChange={this.handlePageChange}
650 let site = this.state.siteRes.site_view.site;
651 return this.state.dataType == DataType.Post ? (
653 posts={this.state.posts}
656 enableDownvotes={site.enable_downvotes}
657 enableNsfw={site.enable_nsfw}
661 nodes={commentsToFlatNodes(this.state.comments)}
665 enableDownvotes={site.enable_downvotes}
672 <div className="mb-3">
675 type_={this.state.dataType}
676 onChange={this.handleDataTypeChange}
681 type_={this.state.listingType}
682 showLocal={showLocal(this.isoData)}
683 onChange={this.handleListingTypeChange}
687 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
689 {this.state.listingType == ListingType.All && (
691 href={`/feeds/all.xml?sort=${this.state.sort}`}
695 <Icon icon="rss" classes="text-muted small" />
698 {this.state.listingType == ListingType.Local && (
700 href={`/feeds/local.xml?sort=${this.state.sort}`}
704 <Icon icon="rss" classes="text-muted small" />
707 {UserService.Instance.localUserView &&
708 this.state.listingType == ListingType.Subscribed && (
710 href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${this.state.sort}`}
714 <Icon icon="rss" classes="text-muted small" />
721 get canAdmin(): boolean {
723 UserService.Instance.localUserView &&
724 this.state.siteRes.admins
725 .map(a => a.person.id)
726 .includes(UserService.Instance.localUserView.person.id)
730 handleEditClick(i: Home) {
731 i.state.showEditSite = true;
736 this.state.showEditSite = false;
737 this.setState(this.state);
740 handleShowSubscribedMobile(i: Home) {
741 i.state.showSubscribedMobile = !i.state.showSubscribedMobile;
745 handleShowTrendingMobile(i: Home) {
746 i.state.showTrendingMobile = !i.state.showTrendingMobile;
750 handleShowSidebarMobile(i: Home) {
751 i.state.showSidebarMobile = !i.state.showSidebarMobile;
755 handlePageChange(page: number) {
756 this.updateUrl({ page });
757 window.scrollTo(0, 0);
760 handleSortChange(val: SortType) {
761 this.updateUrl({ sort: val, page: 1 });
762 window.scrollTo(0, 0);
765 handleListingTypeChange(val: ListingType) {
766 this.updateUrl({ listingType: val, page: 1 });
767 window.scrollTo(0, 0);
770 handleDataTypeChange(val: DataType) {
771 this.updateUrl({ dataType: DataType[val], page: 1 });
772 window.scrollTo(0, 0);
776 if (this.state.dataType == DataType.Post) {
777 let getPostsForm: GetPosts = {
778 page: this.state.page,
780 sort: this.state.sort,
781 type_: this.state.listingType,
783 auth: authField(false),
785 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
787 let getCommentsForm: GetComments = {
788 page: this.state.page,
790 sort: this.state.sort,
791 type_: this.state.listingType,
793 auth: authField(false),
795 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
799 parseMessage(msg: any) {
800 let op = wsUserOp(msg);
803 toast(i18n.t(msg.error), "danger");
805 } else if (msg.reconnect) {
806 WebSocketService.Instance.send(
807 wsClient.communityJoin({ community_id: 0 })
810 } else if (op == UserOperation.GetFollowedCommunities) {
811 let data = wsJsonToRes<GetFollowedCommunitiesResponse>(msg).data;
812 this.state.subscribedCommunities = data.communities;
813 this.setState(this.state);
814 } else if (op == UserOperation.ListCommunities) {
815 let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
816 this.state.trendingCommunities = data.communities;
817 this.setState(this.state);
818 } else if (op == UserOperation.EditSite) {
819 let data = wsJsonToRes<SiteResponse>(msg).data;
820 this.state.siteRes.site_view = data.site_view;
821 this.state.showEditSite = false;
822 this.setState(this.state);
823 toast(i18n.t("site_saved"));
824 } else if (op == UserOperation.GetPosts) {
825 let data = wsJsonToRes<GetPostsResponse>(msg).data;
826 this.state.posts = data.posts;
827 this.state.loading = false;
828 this.setState(this.state);
829 restoreScrollPosition(this.context);
831 } else if (op == UserOperation.CreatePost) {
832 let data = wsJsonToRes<PostResponse>(msg).data;
835 let nsfw = data.post_view.post.nsfw || data.post_view.community.nsfw;
839 UserService.Instance.localUserView &&
840 UserService.Instance.localUserView.local_user.show_nsfw);
842 // Only push these if you're on the first page, and you pass the nsfw check
843 if (this.state.page == 1 && nsfwCheck) {
844 // If you're on subscribed, only push it if you're subscribed.
845 if (this.state.listingType == ListingType.Subscribed) {
847 this.state.subscribedCommunities
848 .map(c => c.community.id)
849 .includes(data.post_view.community.id)
851 this.state.posts.unshift(data.post_view);
852 notifyPost(data.post_view, this.context.router);
854 } else if (this.state.listingType == ListingType.Local) {
855 // If you're on the local view, only push it if its local
856 if (data.post_view.post.local) {
857 this.state.posts.unshift(data.post_view);
858 notifyPost(data.post_view, this.context.router);
861 this.state.posts.unshift(data.post_view);
862 notifyPost(data.post_view, this.context.router);
864 this.setState(this.state);
867 op == UserOperation.EditPost ||
868 op == UserOperation.DeletePost ||
869 op == UserOperation.RemovePost ||
870 op == UserOperation.LockPost ||
871 op == UserOperation.StickyPost ||
872 op == UserOperation.SavePost
874 let data = wsJsonToRes<PostResponse>(msg).data;
875 editPostFindRes(data.post_view, this.state.posts);
876 this.setState(this.state);
877 } else if (op == UserOperation.CreatePostLike) {
878 let data = wsJsonToRes<PostResponse>(msg).data;
879 createPostLikeFindRes(data.post_view, this.state.posts);
880 this.setState(this.state);
881 } else if (op == UserOperation.AddAdmin) {
882 let data = wsJsonToRes<AddAdminResponse>(msg).data;
883 this.state.siteRes.admins = data.admins;
884 this.setState(this.state);
885 } else if (op == UserOperation.BanPerson) {
886 let data = wsJsonToRes<BanPersonResponse>(msg).data;
887 let found = this.state.siteRes.banned.find(
888 p => (p.person.id = data.person_view.person.id)
891 // Remove the banned if its found in the list, and the action is an unban
892 if (found && !data.banned) {
893 this.state.siteRes.banned = this.state.siteRes.banned.filter(
894 i => i.person.id !== data.person_view.person.id
897 this.state.siteRes.banned.push(data.person_view);
901 .filter(p => p.creator.id == data.person_view.person.id)
902 .forEach(p => (p.creator.banned = data.banned));
904 this.setState(this.state);
905 } else if (op == UserOperation.GetComments) {
906 let data = wsJsonToRes<GetCommentsResponse>(msg).data;
907 this.state.comments = data.comments;
908 this.state.loading = false;
909 this.setState(this.state);
911 op == UserOperation.EditComment ||
912 op == UserOperation.DeleteComment ||
913 op == UserOperation.RemoveComment
915 let data = wsJsonToRes<CommentResponse>(msg).data;
916 editCommentRes(data.comment_view, this.state.comments);
917 this.setState(this.state);
918 } else if (op == UserOperation.CreateComment) {
919 let data = wsJsonToRes<CommentResponse>(msg).data;
921 // Necessary since it might be a user reply
923 // If you're on subscribed, only push it if you're subscribed.
924 if (this.state.listingType == ListingType.Subscribed) {
926 this.state.subscribedCommunities
927 .map(c => c.community.id)
928 .includes(data.comment_view.community.id)
930 this.state.comments.unshift(data.comment_view);
933 this.state.comments.unshift(data.comment_view);
935 this.setState(this.state);
937 } else if (op == UserOperation.SaveComment) {
938 let data = wsJsonToRes<CommentResponse>(msg).data;
939 saveCommentRes(data.comment_view, this.state.comments);
940 this.setState(this.state);
941 } else if (op == UserOperation.CreateCommentLike) {
942 let data = wsJsonToRes<CommentResponse>(msg).data;
943 createCommentLikeRes(data.comment_view, this.state.comments);
944 this.setState(this.state);