1 import { None, Option, Some } from "@sniptt/monads";
2 import { Component, linkEvent } from "inferno";
3 import { T } from "inferno-i18next-dess";
4 import { Link } from "inferno-router";
19 ListCommunitiesResponse,
30 } from "lemmy-js-client";
31 import { Subscription } from "rxjs";
32 import { i18n } from "../../i18next";
33 import { DataType, InitialFetchRequest } from "../../interfaces";
34 import { UserService, WebSocketService } from "../../services";
39 createPostLikeFindRes,
46 getListingTypeFromProps,
52 restoreScrollPosition,
64 import { CommentNodes } from "../comment/comment-nodes";
65 import { DataTypeSelect } from "../common/data-type-select";
66 import { HtmlTags } from "../common/html-tags";
67 import { Icon, Spinner } from "../common/icon";
68 import { ListingTypeSelect } from "../common/listing-type-select";
69 import { Paginator } from "../common/paginator";
70 import { SortSelect } from "../common/sort-select";
71 import { CommunityLink } from "../community/community-link";
72 import { PostListings } from "../post/post-listings";
73 import { SiteSidebar } from "./site-sidebar";
76 trendingCommunities: CommunityView[];
77 siteRes: GetSiteResponse;
79 comments: CommentView[];
80 listingType: ListingType;
84 showSubscribedMobile: boolean;
85 showTrendingMobile: boolean;
86 showSidebarMobile: boolean;
87 subscribedCollapsed: boolean;
92 listingType: ListingType;
99 listingType?: ListingType;
105 export class Home extends Component<any, HomeState> {
106 private isoData = setIsoData(
110 ListCommunitiesResponse
112 private subscription: Subscription;
113 private emptyState: HomeState = {
114 trendingCommunities: [],
115 siteRes: this.isoData.site_res,
116 showSubscribedMobile: false,
117 showTrendingMobile: false,
118 showSidebarMobile: false,
119 subscribedCollapsed: false,
123 listingType: getListingTypeFromProps(
126 this.isoData.site_res.site_view.match({
127 some: type_ => type_.site.default_post_listing_type,
128 none: ListingType.Local,
132 dataType: getDataTypeFromProps(this.props),
133 sort: getSortTypeFromProps(this.props),
134 page: getPageFromProps(this.props),
137 constructor(props: any, context: any) {
138 super(props, context);
140 this.state = this.emptyState;
141 this.handleSortChange = this.handleSortChange.bind(this);
142 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
143 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
144 this.handlePageChange = this.handlePageChange.bind(this);
146 this.parseMessage = this.parseMessage.bind(this);
147 this.subscription = wsSubscribe(this.parseMessage);
149 // Only fetch the data if coming from another route
150 if (this.isoData.path == this.context.router.route.match.url) {
151 let postsRes = Some(this.isoData.routeData[0] as GetPostsResponse);
152 let commentsRes = Some(this.isoData.routeData[1] as GetCommentsResponse);
153 let trendingRes = this.isoData.routeData[2] as ListCommunitiesResponse;
156 some: pvs => (this.state.posts = pvs.posts),
160 some: cvs => (this.state.comments = cvs.comments),
163 this.state.trendingCommunities = trendingRes.communities;
166 WebSocketService.Instance.send(
167 wsClient.communityJoin({ community_id: 0 })
170 this.state.loading = false;
172 this.fetchTrendingCommunities();
177 fetchTrendingCommunities() {
178 let listCommunitiesForm = new ListCommunities({
179 type_: Some(ListingType.Local),
180 sort: Some(SortType.Hot),
181 limit: Some(trendingFetchLimit),
183 auth: auth(false).ok(),
185 WebSocketService.Instance.send(
186 wsClient.listCommunities(listCommunitiesForm)
190 componentDidMount() {
191 // This means it hasn't been set up yet
192 if (this.state.siteRes.site_view.isNone()) {
193 this.context.router.history.push("/setup");
198 componentWillUnmount() {
199 saveScrollPosition(this.context);
200 this.subscription.unsubscribe();
203 static getDerivedStateFromProps(props: any): HomeProps {
205 listingType: getListingTypeFromProps(props, ListingType.Local),
206 dataType: getDataTypeFromProps(props),
207 sort: getSortTypeFromProps(props),
208 page: getPageFromProps(props),
212 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
213 let pathSplit = req.path.split("/");
214 let dataType: DataType = pathSplit[3]
215 ? DataType[pathSplit[3]]
218 // TODO figure out auth default_listingType, default_sort_type
219 let type_: Option<ListingType> = Some(
221 ? ListingType[pathSplit[5]]
222 : UserService.Instance.myUserInfo.match({
224 Object.values(ListingType)[
225 mui.local_user_view.local_user.default_listing_type
227 none: ListingType.Local,
230 let sort: Option<SortType> = Some(
232 ? SortType[pathSplit[7]]
233 : UserService.Instance.myUserInfo.match({
235 Object.values(SortType)[
236 mui.local_user_view.local_user.default_sort_type
238 none: SortType.Active,
242 let page = Some(pathSplit[9] ? Number(pathSplit[9]) : 1);
244 let promises: Promise<any>[] = [];
246 if (dataType == DataType.Post) {
247 let getPostsForm = new GetPosts({
249 community_name: None,
252 limit: Some(fetchLimit),
254 saved_only: Some(false),
258 promises.push(req.client.getPosts(getPostsForm));
259 promises.push(Promise.resolve());
261 let getCommentsForm = new GetComments({
263 community_name: None,
265 limit: Some(fetchLimit),
268 saved_only: Some(false),
271 promises.push(Promise.resolve());
272 promises.push(req.client.getComments(getCommentsForm));
275 let trendingCommunitiesForm = new ListCommunities({
276 type_: Some(ListingType.Local),
277 sort: Some(SortType.Hot),
278 limit: Some(trendingFetchLimit),
282 promises.push(req.client.listCommunities(trendingCommunitiesForm));
287 componentDidUpdate(_: any, lastState: HomeState) {
289 lastState.listingType !== this.state.listingType ||
290 lastState.dataType !== this.state.dataType ||
291 lastState.sort !== this.state.sort ||
292 lastState.page !== this.state.page
294 this.setState({ loading: true });
299 get documentTitle(): string {
300 return this.state.siteRes.site_view.match({
302 siteView.site.description.match({
303 some: desc => `${siteView.site.name} - ${desc}`,
304 none: siteView.site.name,
312 <div class="container">
314 title={this.documentTitle}
315 path={this.context.router.route.match.url}
319 {this.state.siteRes.site_view.isSome() && (
321 <main role="main" class="col-12 col-md-8">
322 <div class="d-block d-md-none">{this.mobileView()}</div>
325 <aside class="d-none d-md-block col-md-4">{this.mySidebar()}</aside>
332 get hasFollows(): boolean {
333 return UserService.Instance.myUserInfo.match({
334 some: mui => mui.follows.length > 0,
340 let siteRes = this.state.siteRes;
344 {this.hasFollows && (
346 class="btn btn-secondary d-inline-block mb-2 mr-3"
347 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
349 {i18n.t("subscribed")}{" "}
352 this.state.showSubscribedMobile
356 classes="icon-inline"
361 class="btn btn-secondary d-inline-block mb-2 mr-3"
362 onClick={linkEvent(this, this.handleShowTrendingMobile)}
364 {i18n.t("trending")}{" "}
367 this.state.showTrendingMobile ? `minus-square` : `plus-square`
369 classes="icon-inline"
373 class="btn btn-secondary d-inline-block mb-2 mr-3"
374 onClick={linkEvent(this, this.handleShowSidebarMobile)}
376 {i18n.t("sidebar")}{" "}
379 this.state.showSidebarMobile ? `minus-square` : `plus-square`
381 classes="icon-inline"
384 {this.state.showSidebarMobile &&
385 siteRes.site_view.match({
389 admins={Some(siteRes.admins)}
390 counts={Some(siteView.counts)}
391 online={Some(siteRes.online)}
392 showLocal={showLocal(this.isoData)}
397 {this.state.showTrendingMobile && (
398 <div class="col-12 card border-secondary mb-3">
399 <div class="card-body">{this.trendingCommunities()}</div>
402 {this.state.showSubscribedMobile && (
403 <div class="col-12 card border-secondary mb-3">
404 <div class="card-body">{this.subscribedCommunities()}</div>
413 let siteRes = this.state.siteRes;
416 {!this.state.loading && (
418 <div class="card border-secondary mb-3">
419 <div class="card-body">
420 {this.trendingCommunities()}
421 {this.createCommunityButton()}
422 {this.exploreCommunitiesButton()}
425 {siteRes.site_view.match({
429 admins={Some(siteRes.admins)}
430 counts={Some(siteView.counts)}
431 online={Some(siteRes.online)}
432 showLocal={showLocal(this.isoData)}
437 {this.hasFollows && (
438 <div class="card border-secondary mb-3">
439 <div class="card-body">{this.subscribedCommunities()}</div>
448 createCommunityButton() {
450 <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
451 {i18n.t("create_a_community")}
456 exploreCommunitiesButton() {
458 <Link className="btn btn-secondary btn-block" to="/communities">
459 {i18n.t("explore_communities")}
464 trendingCommunities() {
468 <T i18nKey="trending_communities">
470 <Link className="text-body" to="/communities">
475 <ul class="list-inline mb-0">
476 {this.state.trendingCommunities.map(cv => (
477 <li class="list-inline-item d-inline-block">
478 <CommunityLink community={cv.community} />
486 subscribedCommunities() {
490 <T class="d-inline" i18nKey="subscribed_to_communities">
492 <Link className="text-body" to="/communities">
497 class="btn btn-sm text-muted"
498 onClick={linkEvent(this, this.handleCollapseSubscribe)}
499 aria-label={i18n.t("collapse")}
500 data-tippy-content={i18n.t("collapse")}
502 {this.state.subscribedCollapsed ? (
503 <Icon icon="plus-square" classes="icon-inline" />
505 <Icon icon="minus-square" classes="icon-inline" />
509 {!this.state.subscribedCollapsed && (
510 <ul class="list-inline mb-0">
511 {UserService.Instance.myUserInfo
515 <li class="list-inline-item d-inline-block">
516 <CommunityLink community={cfv.community} />
525 updateUrl(paramUpdates: UrlParams) {
526 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
527 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
528 const sortStr = paramUpdates.sort || this.state.sort;
529 const page = paramUpdates.page || this.state.page;
530 this.props.history.push(
531 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
537 <div class="main-content-wrapper">
538 {this.state.loading ? (
547 page={this.state.page}
548 onChange={this.handlePageChange}
557 return this.state.dataType == DataType.Post ? (
559 posts={this.state.posts}
562 enableDownvotes={enableDownvotes(this.state.siteRes)}
563 enableNsfw={enableNsfw(this.state.siteRes)}
567 nodes={commentsToFlatNodes(this.state.comments)}
570 maxCommentsShown={None}
574 enableDownvotes={enableDownvotes(this.state.siteRes)}
580 let allRss = `/feeds/all.xml?sort=${this.state.sort}`;
581 let localRss = `/feeds/local.xml?sort=${this.state.sort}`;
582 let frontRss = auth(false)
584 .map(auth => `/feeds/front/${auth}.xml?sort=${this.state.sort}`);
587 <div className="mb-3">
590 type_={this.state.dataType}
591 onChange={this.handleDataTypeChange}
596 type_={this.state.listingType}
597 showLocal={showLocal(this.isoData)}
599 onChange={this.handleListingTypeChange}
603 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
605 {this.state.listingType == ListingType.All && (
607 <a href={allRss} rel={relTags} title="RSS">
608 <Icon icon="rss" classes="text-muted small" />
610 <link rel="alternate" type="application/atom+xml" href={allRss} />
613 {this.state.listingType == ListingType.Local && (
615 <a href={localRss} rel={relTags} title="RSS">
616 <Icon icon="rss" classes="text-muted small" />
618 <link rel="alternate" type="application/atom+xml" href={localRss} />
621 {this.state.listingType == ListingType.Subscribed &&
625 <a href={rss} title="RSS" rel={relTags}>
626 <Icon icon="rss" classes="text-muted small" />
628 <link rel="alternate" type="application/atom+xml" href={rss} />
637 handleShowSubscribedMobile(i: Home) {
638 i.state.showSubscribedMobile = !i.state.showSubscribedMobile;
642 handleShowTrendingMobile(i: Home) {
643 i.state.showTrendingMobile = !i.state.showTrendingMobile;
647 handleShowSidebarMobile(i: Home) {
648 i.state.showSidebarMobile = !i.state.showSidebarMobile;
652 handleCollapseSubscribe(i: Home) {
653 i.state.subscribedCollapsed = !i.state.subscribedCollapsed;
657 handlePageChange(page: number) {
658 this.updateUrl({ page });
659 window.scrollTo(0, 0);
662 handleSortChange(val: SortType) {
663 this.updateUrl({ sort: val, page: 1 });
664 window.scrollTo(0, 0);
667 handleListingTypeChange(val: ListingType) {
668 this.updateUrl({ listingType: val, page: 1 });
669 window.scrollTo(0, 0);
672 handleDataTypeChange(val: DataType) {
673 this.updateUrl({ dataType: DataType[val], page: 1 });
674 window.scrollTo(0, 0);
678 if (this.state.dataType == DataType.Post) {
679 let getPostsForm = new GetPosts({
681 community_name: None,
682 page: Some(this.state.page),
683 limit: Some(fetchLimit),
684 sort: Some(this.state.sort),
685 saved_only: Some(false),
686 auth: auth(false).ok(),
687 type_: Some(this.state.listingType),
690 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
692 let getCommentsForm = new GetComments({
694 community_name: None,
695 page: Some(this.state.page),
696 limit: Some(fetchLimit),
697 sort: Some(this.state.sort),
698 saved_only: Some(false),
699 auth: auth(false).ok(),
700 type_: Some(this.state.listingType),
702 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
706 parseMessage(msg: any) {
707 let op = wsUserOp(msg);
710 toast(i18n.t(msg.error), "danger");
712 } else if (msg.reconnect) {
713 WebSocketService.Instance.send(
714 wsClient.communityJoin({ community_id: 0 })
717 } else if (op == UserOperation.ListCommunities) {
718 let data = wsJsonToRes<ListCommunitiesResponse>(
720 ListCommunitiesResponse
722 this.state.trendingCommunities = data.communities;
723 this.setState(this.state);
724 } else if (op == UserOperation.EditSite) {
725 let data = wsJsonToRes<SiteResponse>(msg, SiteResponse);
726 this.state.siteRes.site_view = Some(data.site_view);
727 this.setState(this.state);
728 toast(i18n.t("site_saved"));
729 } else if (op == UserOperation.GetPosts) {
730 let data = wsJsonToRes<GetPostsResponse>(msg, GetPostsResponse);
731 this.state.posts = data.posts;
732 this.state.loading = false;
733 this.setState(this.state);
734 WebSocketService.Instance.send(
735 wsClient.communityJoin({ community_id: 0 })
737 restoreScrollPosition(this.context);
739 } else if (op == UserOperation.CreatePost) {
740 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
742 let nsfw = data.post_view.post.nsfw || data.post_view.community.nsfw;
746 UserService.Instance.myUserInfo
747 .map(m => m.local_user_view.local_user.show_nsfw)
750 let showPostNotifs = UserService.Instance.myUserInfo
751 .map(m => m.local_user_view.local_user.show_new_post_notifs)
754 // Only push these if you're on the first page, and you pass the nsfw check
755 if (this.state.page == 1 && nsfwCheck) {
756 // If you're on subscribed, only push it if you're subscribed.
757 if (this.state.listingType == ListingType.Subscribed) {
759 UserService.Instance.myUserInfo
762 .map(c => c.community.id)
763 .includes(data.post_view.community.id)
765 this.state.posts.unshift(data.post_view);
766 if (showPostNotifs) {
767 notifyPost(data.post_view, this.context.router);
770 } else if (this.state.listingType == ListingType.Local) {
771 // If you're on the local view, only push it if its local
772 if (data.post_view.post.local) {
773 this.state.posts.unshift(data.post_view);
774 if (showPostNotifs) {
775 notifyPost(data.post_view, this.context.router);
779 this.state.posts.unshift(data.post_view);
780 if (showPostNotifs) {
781 notifyPost(data.post_view, this.context.router);
784 this.setState(this.state);
787 op == UserOperation.EditPost ||
788 op == UserOperation.DeletePost ||
789 op == UserOperation.RemovePost ||
790 op == UserOperation.LockPost ||
791 op == UserOperation.StickyPost ||
792 op == UserOperation.SavePost
794 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
795 editPostFindRes(data.post_view, this.state.posts);
796 this.setState(this.state);
797 } else if (op == UserOperation.CreatePostLike) {
798 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
799 createPostLikeFindRes(data.post_view, this.state.posts);
800 this.setState(this.state);
801 } else if (op == UserOperation.AddAdmin) {
802 let data = wsJsonToRes<AddAdminResponse>(msg, AddAdminResponse);
803 this.state.siteRes.admins = data.admins;
804 this.setState(this.state);
805 } else if (op == UserOperation.BanPerson) {
806 let data = wsJsonToRes<BanPersonResponse>(msg, BanPersonResponse);
808 .filter(p => p.creator.id == data.person_view.person.id)
809 .forEach(p => (p.creator.banned = data.banned));
811 this.setState(this.state);
812 } else if (op == UserOperation.GetComments) {
813 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
814 this.state.comments = data.comments;
815 this.state.loading = false;
816 this.setState(this.state);
818 op == UserOperation.EditComment ||
819 op == UserOperation.DeleteComment ||
820 op == UserOperation.RemoveComment
822 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
823 editCommentRes(data.comment_view, this.state.comments);
824 this.setState(this.state);
825 } else if (op == UserOperation.CreateComment) {
826 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
828 // Necessary since it might be a user reply
830 // If you're on subscribed, only push it if you're subscribed.
831 if (this.state.listingType == ListingType.Subscribed) {
833 UserService.Instance.myUserInfo
836 .map(c => c.community.id)
837 .includes(data.comment_view.community.id)
839 this.state.comments.unshift(data.comment_view);
842 this.state.comments.unshift(data.comment_view);
844 this.setState(this.state);
846 } else if (op == UserOperation.SaveComment) {
847 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
848 saveCommentRes(data.comment_view, this.state.comments);
849 this.setState(this.state);
850 } else if (op == UserOperation.CreateCommentLike) {
851 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
852 createCommentLikeRes(data.comment_view, this.state.comments);
853 this.setState(this.state);
854 } else if (op == UserOperation.BlockPerson) {
855 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
856 updatePersonBlock(data);
857 } else if (op == UserOperation.CreatePostReport) {
858 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
860 toast(i18n.t("report_created"));
862 } else if (op == UserOperation.CreateCommentReport) {
863 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
865 toast(i18n.t("report_created"));
868 op == UserOperation.PurgePerson ||
869 op == UserOperation.PurgePost ||
870 op == UserOperation.PurgeComment ||
871 op == UserOperation.PurgeCommunity
873 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
875 toast(i18n.t("purge_success"));
876 this.context.router.history.push(`/`);