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";
37 } from "../../interfaces";
38 import { UserService, WebSocketService } from "../../services";
44 createPostLikeFindRes,
51 getListingTypeFromProps,
58 postToCommentSortType,
60 restoreScrollPosition,
72 import { CommentNodes } from "../comment/comment-nodes";
73 import { DataTypeSelect } from "../common/data-type-select";
74 import { HtmlTags } from "../common/html-tags";
75 import { Icon, Spinner } from "../common/icon";
76 import { ListingTypeSelect } from "../common/listing-type-select";
77 import { Paginator } from "../common/paginator";
78 import { SortSelect } from "../common/sort-select";
79 import { CommunityLink } from "../community/community-link";
80 import { PostListings } from "../post/post-listings";
81 import { SiteSidebar } from "./site-sidebar";
84 trendingCommunities: CommunityView[];
85 siteRes: GetSiteResponse;
87 comments: CommentView[];
88 listingType: ListingType;
92 showSubscribedMobile: boolean;
93 showTrendingMobile: boolean;
94 showSidebarMobile: boolean;
95 subscribedCollapsed: boolean;
100 listingType: ListingType;
106 interface UrlParams {
107 listingType?: ListingType;
113 export class Home extends Component<any, HomeState> {
114 private isoData = setIsoData(
118 ListCommunitiesResponse
120 private subscription: Subscription;
121 private emptyState: HomeState = {
122 trendingCommunities: [],
123 siteRes: this.isoData.site_res,
124 showSubscribedMobile: false,
125 showTrendingMobile: false,
126 showSidebarMobile: false,
127 subscribedCollapsed: false,
131 listingType: getListingTypeFromProps(
134 this.isoData.site_res.site_view.local_site.default_post_listing_type
137 dataType: getDataTypeFromProps(this.props),
138 sort: getSortTypeFromProps(this.props),
139 page: getPageFromProps(this.props),
142 constructor(props: any, context: any) {
143 super(props, context);
145 this.state = this.emptyState;
146 this.handleSortChange = this.handleSortChange.bind(this);
147 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
148 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
149 this.handlePageChange = this.handlePageChange.bind(this);
151 this.parseMessage = this.parseMessage.bind(this);
152 this.subscription = wsSubscribe(this.parseMessage);
154 // Only fetch the data if coming from another route
155 if (this.isoData.path == this.context.router.route.match.url) {
156 let postsRes = Some(this.isoData.routeData[0] as GetPostsResponse);
157 let commentsRes = Some(this.isoData.routeData[1] as GetCommentsResponse);
158 let trendingRes = this.isoData.routeData[2] as ListCommunitiesResponse;
160 if (postsRes.isSome()) {
161 this.state = { ...this.state, posts: postsRes.unwrap().posts };
164 if (commentsRes.isSome()) {
165 this.state = { ...this.state, comments: commentsRes.unwrap().comments };
169 WebSocketService.Instance.send(
170 wsClient.communityJoin({ community_id: 0 })
175 trendingCommunities: trendingRes.communities,
179 this.fetchTrendingCommunities();
184 fetchTrendingCommunities() {
185 let listCommunitiesForm = new ListCommunities({
186 type_: Some(ListingType.Local),
187 sort: Some(SortType.Hot),
188 limit: Some(trendingFetchLimit),
190 auth: auth(false).ok(),
192 WebSocketService.Instance.send(
193 wsClient.listCommunities(listCommunitiesForm)
197 componentDidMount() {
198 // This means it hasn't been set up yet
199 if (!this.state.siteRes.site_view.local_site.site_setup) {
200 this.context.router.history.push("/setup");
205 componentWillUnmount() {
206 saveScrollPosition(this.context);
207 this.subscription.unsubscribe();
210 static getDerivedStateFromProps(
215 listingType: getListingTypeFromProps(props, state.listingType),
216 dataType: getDataTypeFromProps(props),
217 sort: getSortTypeFromProps(props),
218 page: getPageFromProps(props),
222 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
223 let pathSplit = req.path.split("/");
224 let dataType: DataType = pathSplit[3]
225 ? DataType[pathSplit[3]]
228 // TODO figure out auth default_listingType, default_sort_type
229 let type_: Option<ListingType> = Some(
231 ? ListingType[pathSplit[5]]
232 : UserService.Instance.myUserInfo.match({
234 Object.values(ListingType)[
235 mui.local_user_view.local_user.default_listing_type
237 none: ListingType.Local,
240 let sort: Option<SortType> = Some(
242 ? SortType[pathSplit[7]]
243 : UserService.Instance.myUserInfo.match({
245 Object.values(SortType)[
246 mui.local_user_view.local_user.default_sort_type
248 none: SortType.Active,
252 let page = Some(pathSplit[9] ? Number(pathSplit[9]) : 1);
254 let promises: Promise<any>[] = [];
256 if (dataType == DataType.Post) {
257 let getPostsForm = new GetPosts({
259 community_name: None,
262 limit: Some(fetchLimit),
264 saved_only: Some(false),
268 promises.push(req.client.getPosts(getPostsForm));
269 promises.push(Promise.resolve());
271 let getCommentsForm = new GetComments({
273 community_name: None,
275 limit: Some(fetchLimit),
277 sort: sort.map(postToCommentSortType),
279 saved_only: Some(false),
284 promises.push(Promise.resolve());
285 promises.push(req.client.getComments(getCommentsForm));
288 let trendingCommunitiesForm = new ListCommunities({
289 type_: Some(ListingType.Local),
290 sort: Some(SortType.Hot),
291 limit: Some(trendingFetchLimit),
295 promises.push(req.client.listCommunities(trendingCommunitiesForm));
300 componentDidUpdate(_: any, lastState: HomeState) {
302 lastState.listingType !== this.state.listingType ||
303 lastState.dataType !== this.state.dataType ||
304 lastState.sort !== this.state.sort ||
305 lastState.page !== this.state.page
307 this.setState({ loading: true });
312 get documentTitle(): string {
313 let siteView = this.state.siteRes.site_view;
314 return this.state.siteRes.site_view.site.description.match({
315 some: desc => `${siteView.site.name} - ${desc}`,
316 none: siteView.site.name,
322 <div className="container-lg">
324 title={this.documentTitle}
325 path={this.context.router.route.match.url}
329 {this.state.siteRes.site_view.local_site.site_setup && (
330 <div className="row">
331 <main role="main" className="col-12 col-md-8">
332 <div className="d-block d-md-none">{this.mobileView()}</div>
335 <aside className="d-none d-md-block col-md-4">
344 get hasFollows(): boolean {
345 return UserService.Instance.myUserInfo.match({
346 some: mui => mui.follows.length > 0,
352 let siteRes = this.state.siteRes;
353 let siteView = siteRes.site_view;
355 <div className="row">
356 <div className="col-12">
357 {this.hasFollows && (
359 className="btn btn-secondary d-inline-block mb-2 mr-3"
360 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
362 {i18n.t("subscribed")}{" "}
365 this.state.showSubscribedMobile
369 classes="icon-inline"
374 className="btn btn-secondary d-inline-block mb-2 mr-3"
375 onClick={linkEvent(this, this.handleShowTrendingMobile)}
377 {i18n.t("trending")}{" "}
380 this.state.showTrendingMobile ? `minus-square` : `plus-square`
382 classes="icon-inline"
386 className="btn btn-secondary d-inline-block mb-2 mr-3"
387 onClick={linkEvent(this, this.handleShowSidebarMobile)}
389 {i18n.t("sidebar")}{" "}
392 this.state.showSidebarMobile ? `minus-square` : `plus-square`
394 classes="icon-inline"
397 {this.state.showSidebarMobile && (
400 admins={Some(siteRes.admins)}
401 counts={Some(siteView.counts)}
402 online={Some(siteRes.online)}
403 showLocal={showLocal(this.isoData)}
406 {this.state.showTrendingMobile && (
407 <div className="col-12 card border-secondary mb-3">
408 <div className="card-body">{this.trendingCommunities()}</div>
411 {this.state.showSubscribedMobile && (
412 <div className="col-12 card border-secondary mb-3">
413 <div className="card-body">{this.subscribedCommunities()}</div>
422 let siteRes = this.state.siteRes;
423 let siteView = siteRes.site_view;
426 {!this.state.loading && (
428 <div className="card border-secondary mb-3">
429 <div className="card-body">
430 {this.trendingCommunities()}
431 {canCreateCommunity(this.state.siteRes) &&
432 this.createCommunityButton()}
433 {this.exploreCommunitiesButton()}
438 admins={Some(siteRes.admins)}
439 counts={Some(siteView.counts)}
440 online={Some(siteRes.online)}
441 showLocal={showLocal(this.isoData)}
443 {this.hasFollows && (
444 <div className="card border-secondary mb-3">
445 <div className="card-body">{this.subscribedCommunities()}</div>
454 createCommunityButton() {
456 <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
457 {i18n.t("create_a_community")}
462 exploreCommunitiesButton() {
464 <Link className="btn btn-secondary btn-block" to="/communities">
465 {i18n.t("explore_communities")}
470 trendingCommunities() {
474 <T i18nKey="trending_communities">
476 <Link className="text-body" to="/communities">
481 <ul className="list-inline mb-0">
482 {this.state.trendingCommunities.map(cv => (
484 key={cv.community.id}
485 className="list-inline-item d-inline-block"
487 <CommunityLink community={cv.community} />
495 subscribedCommunities() {
499 <T class="d-inline" i18nKey="subscribed_to_communities">
501 <Link className="text-body" to="/communities">
506 className="btn btn-sm text-muted"
507 onClick={linkEvent(this, this.handleCollapseSubscribe)}
508 aria-label={i18n.t("collapse")}
509 data-tippy-content={i18n.t("collapse")}
511 {this.state.subscribedCollapsed ? (
512 <Icon icon="plus-square" classes="icon-inline" />
514 <Icon icon="minus-square" classes="icon-inline" />
518 {!this.state.subscribedCollapsed && (
519 <ul className="list-inline mb-0">
520 {UserService.Instance.myUserInfo
525 key={cfv.community.id}
526 className="list-inline-item d-inline-block"
528 <CommunityLink community={cfv.community} />
537 updateUrl(paramUpdates: UrlParams) {
538 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
539 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
540 const sortStr = paramUpdates.sort || this.state.sort;
541 const page = paramUpdates.page || this.state.page;
542 this.props.history.push(
543 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
549 <div className="main-content-wrapper">
550 {this.state.loading ? (
559 page={this.state.page}
560 onChange={this.handlePageChange}
569 return this.state.dataType == DataType.Post ? (
571 posts={this.state.posts}
574 enableDownvotes={enableDownvotes(this.state.siteRes)}
575 enableNsfw={enableNsfw(this.state.siteRes)}
576 allLanguages={this.state.siteRes.all_languages}
580 nodes={commentsToFlatNodes(this.state.comments)}
581 viewType={CommentViewType.Flat}
584 maxCommentsShown={None}
588 enableDownvotes={enableDownvotes(this.state.siteRes)}
589 allLanguages={this.state.siteRes.all_languages}
595 let allRss = `/feeds/all.xml?sort=${this.state.sort}`;
596 let localRss = `/feeds/local.xml?sort=${this.state.sort}`;
597 let frontRss = auth(false)
599 .map(auth => `/feeds/front/${auth}.xml?sort=${this.state.sort}`);
602 <div className="mb-3">
603 <span className="mr-3">
605 type_={this.state.dataType}
606 onChange={this.handleDataTypeChange}
609 <span className="mr-3">
611 type_={this.state.listingType}
612 showLocal={showLocal(this.isoData)}
614 onChange={this.handleListingTypeChange}
617 <span className="mr-2">
618 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
620 {this.state.listingType == ListingType.All && (
622 <a href={allRss} rel={relTags} title="RSS">
623 <Icon icon="rss" classes="text-muted small" />
625 <link rel="alternate" type="application/atom+xml" href={allRss} />
628 {this.state.listingType == ListingType.Local && (
630 <a href={localRss} rel={relTags} title="RSS">
631 <Icon icon="rss" classes="text-muted small" />
633 <link rel="alternate" type="application/atom+xml" href={localRss} />
636 {this.state.listingType == ListingType.Subscribed &&
640 <a href={rss} title="RSS" rel={relTags}>
641 <Icon icon="rss" classes="text-muted small" />
643 <link rel="alternate" type="application/atom+xml" href={rss} />
652 handleShowSubscribedMobile(i: Home) {
653 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
656 handleShowTrendingMobile(i: Home) {
657 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
660 handleShowSidebarMobile(i: Home) {
661 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
664 handleCollapseSubscribe(i: Home) {
665 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
668 handlePageChange(page: number) {
669 this.updateUrl({ page });
670 window.scrollTo(0, 0);
673 handleSortChange(val: SortType) {
674 this.updateUrl({ sort: val, page: 1 });
675 window.scrollTo(0, 0);
678 handleListingTypeChange(val: ListingType) {
679 this.updateUrl({ listingType: val, page: 1 });
680 window.scrollTo(0, 0);
683 handleDataTypeChange(val: DataType) {
684 this.updateUrl({ dataType: DataType[val], page: 1 });
685 window.scrollTo(0, 0);
689 if (this.state.dataType == DataType.Post) {
690 let getPostsForm = new GetPosts({
692 community_name: None,
693 page: Some(this.state.page),
694 limit: Some(fetchLimit),
695 sort: Some(this.state.sort),
696 saved_only: Some(false),
697 auth: auth(false).ok(),
698 type_: Some(this.state.listingType),
701 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
703 let getCommentsForm = new GetComments({
705 community_name: None,
706 page: Some(this.state.page),
707 limit: Some(fetchLimit),
709 sort: Some(postToCommentSortType(this.state.sort)),
710 saved_only: Some(false),
713 auth: auth(false).ok(),
714 type_: Some(this.state.listingType),
716 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
720 parseMessage(msg: any) {
721 let op = wsUserOp(msg);
724 toast(i18n.t(msg.error), "danger");
726 } else if (msg.reconnect) {
727 WebSocketService.Instance.send(
728 wsClient.communityJoin({ community_id: 0 })
731 } else if (op == UserOperation.ListCommunities) {
732 let data = wsJsonToRes<ListCommunitiesResponse>(
734 ListCommunitiesResponse
736 this.setState({ trendingCommunities: data.communities });
737 } else if (op == UserOperation.EditSite) {
738 let data = wsJsonToRes<SiteResponse>(msg, SiteResponse);
739 this.setState(s => ((s.siteRes.site_view = data.site_view), s));
740 toast(i18n.t("site_saved"));
741 } else if (op == UserOperation.GetPosts) {
742 let data = wsJsonToRes<GetPostsResponse>(msg, GetPostsResponse);
743 this.setState({ posts: data.posts, loading: false });
744 WebSocketService.Instance.send(
745 wsClient.communityJoin({ community_id: 0 })
747 restoreScrollPosition(this.context);
749 } else if (op == UserOperation.CreatePost) {
750 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
752 let showPostNotifs = UserService.Instance.myUserInfo
753 .map(m => m.local_user_view.local_user.show_new_post_notifs)
756 // Only push these if you're on the first page, you pass the nsfw check, and it isn't blocked
758 this.state.page == 1 &&
759 nsfwCheck(data.post_view) &&
760 !isPostBlocked(data.post_view)
762 // If you're on subscribed, only push it if you're subscribed.
763 if (this.state.listingType == ListingType.Subscribed) {
765 UserService.Instance.myUserInfo
768 .map(c => c.community.id)
769 .includes(data.post_view.community.id)
771 this.state.posts.unshift(data.post_view);
772 if (showPostNotifs) {
773 notifyPost(data.post_view, this.context.router);
776 } else if (this.state.listingType == ListingType.Local) {
777 // If you're on the local view, only push it if its local
778 if (data.post_view.post.local) {
779 this.state.posts.unshift(data.post_view);
780 if (showPostNotifs) {
781 notifyPost(data.post_view, this.context.router);
785 this.state.posts.unshift(data.post_view);
786 if (showPostNotifs) {
787 notifyPost(data.post_view, this.context.router);
790 this.setState(this.state);
793 op == UserOperation.EditPost ||
794 op == UserOperation.DeletePost ||
795 op == UserOperation.RemovePost ||
796 op == UserOperation.LockPost ||
797 op == UserOperation.StickyPost ||
798 op == UserOperation.SavePost
800 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
801 editPostFindRes(data.post_view, this.state.posts);
802 this.setState(this.state);
803 } else if (op == UserOperation.CreatePostLike) {
804 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
805 createPostLikeFindRes(data.post_view, this.state.posts);
806 this.setState(this.state);
807 } else if (op == UserOperation.AddAdmin) {
808 let data = wsJsonToRes<AddAdminResponse>(msg, AddAdminResponse);
809 this.setState(s => ((s.siteRes.admins = data.admins), s));
810 } else if (op == UserOperation.BanPerson) {
811 let data = wsJsonToRes<BanPersonResponse>(msg, BanPersonResponse);
813 .filter(p => p.creator.id == data.person_view.person.id)
814 .forEach(p => (p.creator.banned = data.banned));
816 this.setState(this.state);
817 } else if (op == UserOperation.GetComments) {
818 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
819 this.setState({ comments: data.comments, loading: false });
821 op == UserOperation.EditComment ||
822 op == UserOperation.DeleteComment ||
823 op == UserOperation.RemoveComment
825 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
826 editCommentRes(data.comment_view, this.state.comments);
827 this.setState(this.state);
828 } else if (op == UserOperation.CreateComment) {
829 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
831 // Necessary since it might be a user reply
833 // If you're on subscribed, only push it if you're subscribed.
834 if (this.state.listingType == ListingType.Subscribed) {
836 UserService.Instance.myUserInfo
839 .map(c => c.community.id)
840 .includes(data.comment_view.community.id)
842 this.state.comments.unshift(data.comment_view);
845 this.state.comments.unshift(data.comment_view);
847 this.setState(this.state);
849 } else if (op == UserOperation.SaveComment) {
850 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
851 saveCommentRes(data.comment_view, this.state.comments);
852 this.setState(this.state);
853 } else if (op == UserOperation.CreateCommentLike) {
854 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
855 createCommentLikeRes(data.comment_view, this.state.comments);
856 this.setState(this.state);
857 } else if (op == UserOperation.BlockPerson) {
858 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
859 updatePersonBlock(data);
860 } else if (op == UserOperation.CreatePostReport) {
861 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
863 toast(i18n.t("report_created"));
865 } else if (op == UserOperation.CreateCommentReport) {
866 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
868 toast(i18n.t("report_created"));
871 op == UserOperation.PurgePerson ||
872 op == UserOperation.PurgePost ||
873 op == UserOperation.PurgeComment ||
874 op == UserOperation.PurgeCommunity
876 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
878 toast(i18n.t("purge_success"));
879 this.context.router.history.push(`/`);