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,
60 postToCommentSortType,
62 restoreScrollPosition,
74 import { CommentNodes } from "../comment/comment-nodes";
75 import { DataTypeSelect } from "../common/data-type-select";
76 import { HtmlTags } from "../common/html-tags";
77 import { Icon, Spinner } from "../common/icon";
78 import { ListingTypeSelect } from "../common/listing-type-select";
79 import { Paginator } from "../common/paginator";
80 import { SortSelect } from "../common/sort-select";
81 import { CommunityLink } from "../community/community-link";
82 import { PostListings } from "../post/post-listings";
83 import { SiteSidebar } from "./site-sidebar";
86 trendingCommunities: CommunityView[];
87 siteRes: GetSiteResponse;
89 comments: CommentView[];
90 listingType: ListingType;
94 showSubscribedMobile: boolean;
95 showTrendingMobile: boolean;
96 showSidebarMobile: boolean;
97 subscribedCollapsed: boolean;
99 tagline: Option<string>;
102 interface HomeProps {
103 listingType: ListingType;
109 interface UrlParams {
110 listingType?: ListingType;
116 export class Home extends Component<any, HomeState> {
117 private isoData = setIsoData(
121 ListCommunitiesResponse
123 private subscription: Subscription;
124 private emptyState: HomeState = {
125 trendingCommunities: [],
126 siteRes: this.isoData.site_res,
127 showSubscribedMobile: false,
128 showTrendingMobile: false,
129 showSidebarMobile: false,
130 subscribedCollapsed: false,
134 listingType: getListingTypeFromProps(
137 this.isoData.site_res.site_view.local_site.default_post_listing_type
140 dataType: getDataTypeFromProps(this.props),
141 sort: getSortTypeFromProps(this.props),
142 page: getPageFromProps(this.props),
146 constructor(props: any, context: any) {
147 super(props, context);
149 this.state = this.emptyState;
150 this.handleSortChange = this.handleSortChange.bind(this);
151 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
152 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
153 this.handlePageChange = this.handlePageChange.bind(this);
155 this.parseMessage = this.parseMessage.bind(this);
156 this.subscription = wsSubscribe(this.parseMessage);
158 // Only fetch the data if coming from another route
159 if (this.isoData.path == this.context.router.route.match.url) {
160 let postsRes = Some(this.isoData.routeData[0] as GetPostsResponse);
161 let commentsRes = Some(this.isoData.routeData[1] as GetCommentsResponse);
162 let trendingRes = this.isoData.routeData[2] as ListCommunitiesResponse;
164 if (postsRes.isSome()) {
165 this.state = { ...this.state, posts: postsRes.unwrap().posts };
168 if (commentsRes.isSome()) {
169 this.state = { ...this.state, comments: commentsRes.unwrap().comments };
173 WebSocketService.Instance.send(
174 wsClient.communityJoin({ community_id: 0 })
177 const taglines = this.state.siteRes.taglines;
180 trendingCommunities: trendingRes.communities,
182 tagline: taglines.map(tls => getRandomFromList(tls).content),
185 this.fetchTrendingCommunities();
190 fetchTrendingCommunities() {
191 let listCommunitiesForm = new ListCommunities({
192 type_: Some(ListingType.Local),
193 sort: Some(SortType.Hot),
194 limit: Some(trendingFetchLimit),
196 auth: auth(false).ok(),
198 WebSocketService.Instance.send(
199 wsClient.listCommunities(listCommunitiesForm)
203 componentDidMount() {
204 // This means it hasn't been set up yet
205 if (!this.state.siteRes.site_view.local_site.site_setup) {
206 this.context.router.history.push("/setup");
211 componentWillUnmount() {
212 saveScrollPosition(this.context);
213 this.subscription.unsubscribe();
216 static getDerivedStateFromProps(
221 listingType: getListingTypeFromProps(props, state.listingType),
222 dataType: getDataTypeFromProps(props),
223 sort: getSortTypeFromProps(props),
224 page: getPageFromProps(props),
228 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
229 let pathSplit = req.path.split("/");
230 let dataType: DataType = pathSplit[3]
231 ? DataType[pathSplit[3]]
234 // TODO figure out auth default_listingType, default_sort_type
235 let type_: Option<ListingType> = Some(
237 ? ListingType[pathSplit[5]]
238 : UserService.Instance.myUserInfo.match({
240 Object.values(ListingType)[
241 mui.local_user_view.local_user.default_listing_type
243 none: ListingType.Local,
246 let sort: Option<SortType> = Some(
248 ? SortType[pathSplit[7]]
249 : UserService.Instance.myUserInfo.match({
251 Object.values(SortType)[
252 mui.local_user_view.local_user.default_sort_type
254 none: SortType.Active,
258 let page = Some(pathSplit[9] ? Number(pathSplit[9]) : 1);
260 let promises: Promise<any>[] = [];
262 if (dataType == DataType.Post) {
263 let getPostsForm = new GetPosts({
265 community_name: None,
268 limit: Some(fetchLimit),
270 saved_only: Some(false),
274 promises.push(req.client.getPosts(getPostsForm));
275 promises.push(Promise.resolve());
277 let getCommentsForm = new GetComments({
279 community_name: None,
281 limit: Some(fetchLimit),
283 sort: sort.map(postToCommentSortType),
285 saved_only: Some(false),
290 promises.push(Promise.resolve());
291 promises.push(req.client.getComments(getCommentsForm));
294 let trendingCommunitiesForm = new ListCommunities({
295 type_: Some(ListingType.Local),
296 sort: Some(SortType.Hot),
297 limit: Some(trendingFetchLimit),
301 promises.push(req.client.listCommunities(trendingCommunitiesForm));
306 componentDidUpdate(_: any, lastState: HomeState) {
308 lastState.listingType !== this.state.listingType ||
309 lastState.dataType !== this.state.dataType ||
310 lastState.sort !== this.state.sort ||
311 lastState.page !== this.state.page
313 this.setState({ loading: true });
318 get documentTitle(): string {
319 let siteView = this.state.siteRes.site_view;
320 return this.state.siteRes.site_view.site.description.match({
321 some: desc => `${siteView.site.name} - ${desc}`,
322 none: siteView.site.name,
328 <div className="container-lg">
330 title={this.documentTitle}
331 path={this.context.router.route.match.url}
335 {this.state.siteRes.site_view.local_site.site_setup && (
336 <div className="row">
337 <main role="main" className="col-12 col-md-8">
338 {this.state.tagline.match({
342 dangerouslySetInnerHTML={mdToHtml(tagline)}
347 <div className="d-block d-md-none">{this.mobileView()}</div>
350 <aside className="d-none d-md-block col-md-4">
359 get hasFollows(): boolean {
360 return UserService.Instance.myUserInfo.match({
361 some: mui => mui.follows.length > 0,
367 let siteRes = this.state.siteRes;
368 let siteView = siteRes.site_view;
370 <div className="row">
371 <div className="col-12">
372 {this.hasFollows && (
374 className="btn btn-secondary d-inline-block mb-2 mr-3"
375 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
377 {i18n.t("subscribed")}{" "}
380 this.state.showSubscribedMobile
384 classes="icon-inline"
389 className="btn btn-secondary d-inline-block mb-2 mr-3"
390 onClick={linkEvent(this, this.handleShowTrendingMobile)}
392 {i18n.t("trending")}{" "}
395 this.state.showTrendingMobile ? `minus-square` : `plus-square`
397 classes="icon-inline"
401 className="btn btn-secondary d-inline-block mb-2 mr-3"
402 onClick={linkEvent(this, this.handleShowSidebarMobile)}
404 {i18n.t("sidebar")}{" "}
407 this.state.showSidebarMobile ? `minus-square` : `plus-square`
409 classes="icon-inline"
412 {this.state.showSidebarMobile && (
415 admins={Some(siteRes.admins)}
416 counts={Some(siteView.counts)}
417 online={Some(siteRes.online)}
418 showLocal={showLocal(this.isoData)}
421 {this.state.showTrendingMobile && (
422 <div className="col-12 card border-secondary mb-3">
423 <div className="card-body">{this.trendingCommunities()}</div>
426 {this.state.showSubscribedMobile && (
427 <div className="col-12 card border-secondary mb-3">
428 <div className="card-body">{this.subscribedCommunities()}</div>
437 let siteRes = this.state.siteRes;
438 let siteView = siteRes.site_view;
441 {!this.state.loading && (
443 <div className="card border-secondary mb-3">
444 <div className="card-body">
445 {this.trendingCommunities()}
446 {canCreateCommunity(this.state.siteRes) &&
447 this.createCommunityButton()}
448 {this.exploreCommunitiesButton()}
453 admins={Some(siteRes.admins)}
454 counts={Some(siteView.counts)}
455 online={Some(siteRes.online)}
456 showLocal={showLocal(this.isoData)}
458 {this.hasFollows && (
459 <div className="card border-secondary mb-3">
460 <div className="card-body">{this.subscribedCommunities()}</div>
469 createCommunityButton() {
471 <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
472 {i18n.t("create_a_community")}
477 exploreCommunitiesButton() {
479 <Link className="btn btn-secondary btn-block" to="/communities">
480 {i18n.t("explore_communities")}
485 trendingCommunities() {
489 <T i18nKey="trending_communities">
491 <Link className="text-body" to="/communities">
496 <ul className="list-inline mb-0">
497 {this.state.trendingCommunities.map(cv => (
499 key={cv.community.id}
500 className="list-inline-item d-inline-block"
502 <CommunityLink community={cv.community} />
510 subscribedCommunities() {
514 <T class="d-inline" i18nKey="subscribed_to_communities">
516 <Link className="text-body" to="/communities">
521 className="btn btn-sm text-muted"
522 onClick={linkEvent(this, this.handleCollapseSubscribe)}
523 aria-label={i18n.t("collapse")}
524 data-tippy-content={i18n.t("collapse")}
526 {this.state.subscribedCollapsed ? (
527 <Icon icon="plus-square" classes="icon-inline" />
529 <Icon icon="minus-square" classes="icon-inline" />
533 {!this.state.subscribedCollapsed && (
534 <ul className="list-inline mb-0">
535 {UserService.Instance.myUserInfo
540 key={cfv.community.id}
541 className="list-inline-item d-inline-block"
543 <CommunityLink community={cfv.community} />
552 updateUrl(paramUpdates: UrlParams) {
553 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
554 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
555 const sortStr = paramUpdates.sort || this.state.sort;
556 const page = paramUpdates.page || this.state.page;
557 this.props.history.push(
558 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
564 <div className="main-content-wrapper">
565 {this.state.loading ? (
574 page={this.state.page}
575 onChange={this.handlePageChange}
584 return this.state.dataType == DataType.Post ? (
586 posts={this.state.posts}
589 enableDownvotes={enableDownvotes(this.state.siteRes)}
590 enableNsfw={enableNsfw(this.state.siteRes)}
591 allLanguages={this.state.siteRes.all_languages}
595 nodes={commentsToFlatNodes(this.state.comments)}
596 viewType={CommentViewType.Flat}
599 maxCommentsShown={None}
603 enableDownvotes={enableDownvotes(this.state.siteRes)}
604 allLanguages={this.state.siteRes.all_languages}
610 let allRss = `/feeds/all.xml?sort=${this.state.sort}`;
611 let localRss = `/feeds/local.xml?sort=${this.state.sort}`;
612 let frontRss = auth(false)
614 .map(auth => `/feeds/front/${auth}.xml?sort=${this.state.sort}`);
617 <div className="mb-3">
618 <span className="mr-3">
620 type_={this.state.dataType}
621 onChange={this.handleDataTypeChange}
624 <span className="mr-3">
626 type_={this.state.listingType}
627 showLocal={showLocal(this.isoData)}
629 onChange={this.handleListingTypeChange}
632 <span className="mr-2">
633 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
635 {this.state.listingType == ListingType.All && (
637 <a href={allRss} rel={relTags} title="RSS">
638 <Icon icon="rss" classes="text-muted small" />
640 <link rel="alternate" type="application/atom+xml" href={allRss} />
643 {this.state.listingType == ListingType.Local && (
645 <a href={localRss} rel={relTags} title="RSS">
646 <Icon icon="rss" classes="text-muted small" />
648 <link rel="alternate" type="application/atom+xml" href={localRss} />
651 {this.state.listingType == ListingType.Subscribed &&
655 <a href={rss} title="RSS" rel={relTags}>
656 <Icon icon="rss" classes="text-muted small" />
658 <link rel="alternate" type="application/atom+xml" href={rss} />
667 handleShowSubscribedMobile(i: Home) {
668 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
671 handleShowTrendingMobile(i: Home) {
672 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
675 handleShowSidebarMobile(i: Home) {
676 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
679 handleCollapseSubscribe(i: Home) {
680 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
683 handlePageChange(page: number) {
684 this.updateUrl({ page });
685 window.scrollTo(0, 0);
688 handleSortChange(val: SortType) {
689 this.updateUrl({ sort: val, page: 1 });
690 window.scrollTo(0, 0);
693 handleListingTypeChange(val: ListingType) {
694 this.updateUrl({ listingType: val, page: 1 });
695 window.scrollTo(0, 0);
698 handleDataTypeChange(val: DataType) {
699 this.updateUrl({ dataType: DataType[val], page: 1 });
700 window.scrollTo(0, 0);
704 if (this.state.dataType == DataType.Post) {
705 let getPostsForm = new GetPosts({
707 community_name: None,
708 page: Some(this.state.page),
709 limit: Some(fetchLimit),
710 sort: Some(this.state.sort),
711 saved_only: Some(false),
712 auth: auth(false).ok(),
713 type_: Some(this.state.listingType),
716 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
718 let getCommentsForm = new GetComments({
720 community_name: None,
721 page: Some(this.state.page),
722 limit: Some(fetchLimit),
724 sort: Some(postToCommentSortType(this.state.sort)),
725 saved_only: Some(false),
728 auth: auth(false).ok(),
729 type_: Some(this.state.listingType),
731 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
735 parseMessage(msg: any) {
736 let op = wsUserOp(msg);
739 toast(i18n.t(msg.error), "danger");
741 } else if (msg.reconnect) {
742 WebSocketService.Instance.send(
743 wsClient.communityJoin({ community_id: 0 })
746 } else if (op == UserOperation.ListCommunities) {
747 let data = wsJsonToRes<ListCommunitiesResponse>(
749 ListCommunitiesResponse
751 this.setState({ trendingCommunities: data.communities });
752 } else if (op == UserOperation.EditSite) {
753 let data = wsJsonToRes<SiteResponse>(msg, SiteResponse);
754 this.setState(s => ((s.siteRes.site_view = data.site_view), s));
755 toast(i18n.t("site_saved"));
756 } else if (op == UserOperation.GetPosts) {
757 let data = wsJsonToRes<GetPostsResponse>(msg, GetPostsResponse);
758 this.setState({ posts: data.posts, loading: false });
759 WebSocketService.Instance.send(
760 wsClient.communityJoin({ community_id: 0 })
762 restoreScrollPosition(this.context);
764 } else if (op == UserOperation.CreatePost) {
765 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
767 let showPostNotifs = UserService.Instance.myUserInfo
768 .map(m => m.local_user_view.local_user.show_new_post_notifs)
771 // Only push these if you're on the first page, you pass the nsfw check, and it isn't blocked
773 this.state.page == 1 &&
774 nsfwCheck(data.post_view) &&
775 !isPostBlocked(data.post_view)
777 // If you're on subscribed, only push it if you're subscribed.
778 if (this.state.listingType == ListingType.Subscribed) {
780 UserService.Instance.myUserInfo
783 .map(c => c.community.id)
784 .includes(data.post_view.community.id)
786 this.state.posts.unshift(data.post_view);
787 if (showPostNotifs) {
788 notifyPost(data.post_view, this.context.router);
791 } else if (this.state.listingType == ListingType.Local) {
792 // If you're on the local view, only push it if its local
793 if (data.post_view.post.local) {
794 this.state.posts.unshift(data.post_view);
795 if (showPostNotifs) {
796 notifyPost(data.post_view, this.context.router);
800 this.state.posts.unshift(data.post_view);
801 if (showPostNotifs) {
802 notifyPost(data.post_view, this.context.router);
805 this.setState(this.state);
808 op == UserOperation.EditPost ||
809 op == UserOperation.DeletePost ||
810 op == UserOperation.RemovePost ||
811 op == UserOperation.LockPost ||
812 op == UserOperation.FeaturePost ||
813 op == UserOperation.SavePost
815 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
816 editPostFindRes(data.post_view, this.state.posts);
817 this.setState(this.state);
818 } else if (op == UserOperation.CreatePostLike) {
819 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
820 createPostLikeFindRes(data.post_view, this.state.posts);
821 this.setState(this.state);
822 } else if (op == UserOperation.AddAdmin) {
823 let data = wsJsonToRes<AddAdminResponse>(msg, AddAdminResponse);
824 this.setState(s => ((s.siteRes.admins = data.admins), s));
825 } else if (op == UserOperation.BanPerson) {
826 let data = wsJsonToRes<BanPersonResponse>(msg, BanPersonResponse);
828 .filter(p => p.creator.id == data.person_view.person.id)
829 .forEach(p => (p.creator.banned = data.banned));
831 this.setState(this.state);
832 } else if (op == UserOperation.GetComments) {
833 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
834 this.setState({ comments: data.comments, loading: false });
836 op == UserOperation.EditComment ||
837 op == UserOperation.DeleteComment ||
838 op == UserOperation.RemoveComment
840 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
841 editCommentRes(data.comment_view, this.state.comments);
842 this.setState(this.state);
843 } else if (op == UserOperation.CreateComment) {
844 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
846 // Necessary since it might be a user reply
848 // If you're on subscribed, only push it if you're subscribed.
849 if (this.state.listingType == ListingType.Subscribed) {
851 UserService.Instance.myUserInfo
854 .map(c => c.community.id)
855 .includes(data.comment_view.community.id)
857 this.state.comments.unshift(data.comment_view);
860 this.state.comments.unshift(data.comment_view);
862 this.setState(this.state);
864 } else if (op == UserOperation.SaveComment) {
865 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
866 saveCommentRes(data.comment_view, this.state.comments);
867 this.setState(this.state);
868 } else if (op == UserOperation.CreateCommentLike) {
869 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
870 createCommentLikeRes(data.comment_view, this.state.comments);
871 this.setState(this.state);
872 } else if (op == UserOperation.BlockPerson) {
873 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
874 updatePersonBlock(data);
875 } else if (op == UserOperation.CreatePostReport) {
876 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
878 toast(i18n.t("report_created"));
880 } else if (op == UserOperation.CreateCommentReport) {
881 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
883 toast(i18n.t("report_created"));
886 op == UserOperation.PurgePerson ||
887 op == UserOperation.PurgePost ||
888 op == UserOperation.PurgeComment ||
889 op == UserOperation.PurgeCommunity
891 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
893 toast(i18n.t("purge_success"));
894 this.context.router.history.push(`/`);