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.match({
135 some: type_ => type_.site.default_post_listing_type,
136 none: ListingType.Local,
140 dataType: getDataTypeFromProps(this.props),
141 sort: getSortTypeFromProps(this.props),
142 page: getPageFromProps(this.props),
145 constructor(props: any, context: any) {
146 super(props, context);
148 this.state = this.emptyState;
149 this.handleSortChange = this.handleSortChange.bind(this);
150 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
151 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
152 this.handlePageChange = this.handlePageChange.bind(this);
154 this.parseMessage = this.parseMessage.bind(this);
155 this.subscription = wsSubscribe(this.parseMessage);
157 // Only fetch the data if coming from another route
158 if (this.isoData.path == this.context.router.route.match.url) {
159 let postsRes = Some(this.isoData.routeData[0] as GetPostsResponse);
160 let commentsRes = Some(this.isoData.routeData[1] as GetCommentsResponse);
161 let trendingRes = this.isoData.routeData[2] as ListCommunitiesResponse;
163 if (postsRes.isSome()) {
164 this.state = { ...this.state, posts: postsRes.unwrap().posts };
167 if (commentsRes.isSome()) {
168 this.state = { ...this.state, comments: commentsRes.unwrap().comments };
172 WebSocketService.Instance.send(
173 wsClient.communityJoin({ community_id: 0 })
178 trendingCommunities: trendingRes.communities,
182 this.fetchTrendingCommunities();
187 fetchTrendingCommunities() {
188 let listCommunitiesForm = new ListCommunities({
189 type_: Some(ListingType.Local),
190 sort: Some(SortType.Hot),
191 limit: Some(trendingFetchLimit),
193 auth: auth(false).ok(),
195 WebSocketService.Instance.send(
196 wsClient.listCommunities(listCommunitiesForm)
200 componentDidMount() {
201 // This means it hasn't been set up yet
202 if (this.state.siteRes.site_view.isNone()) {
203 this.context.router.history.push("/setup");
208 componentWillUnmount() {
209 saveScrollPosition(this.context);
210 this.subscription.unsubscribe();
213 static getDerivedStateFromProps(
218 listingType: getListingTypeFromProps(props, state.listingType),
219 dataType: getDataTypeFromProps(props),
220 sort: getSortTypeFromProps(props),
221 page: getPageFromProps(props),
225 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
226 let pathSplit = req.path.split("/");
227 let dataType: DataType = pathSplit[3]
228 ? DataType[pathSplit[3]]
231 // TODO figure out auth default_listingType, default_sort_type
232 let type_: Option<ListingType> = Some(
234 ? ListingType[pathSplit[5]]
235 : UserService.Instance.myUserInfo.match({
237 Object.values(ListingType)[
238 mui.local_user_view.local_user.default_listing_type
240 none: ListingType.Local,
243 let sort: Option<SortType> = Some(
245 ? SortType[pathSplit[7]]
246 : UserService.Instance.myUserInfo.match({
248 Object.values(SortType)[
249 mui.local_user_view.local_user.default_sort_type
251 none: SortType.Active,
255 let page = Some(pathSplit[9] ? Number(pathSplit[9]) : 1);
257 let promises: Promise<any>[] = [];
259 if (dataType == DataType.Post) {
260 let getPostsForm = new GetPosts({
262 community_name: None,
265 limit: Some(fetchLimit),
267 saved_only: Some(false),
271 promises.push(req.client.getPosts(getPostsForm));
272 promises.push(Promise.resolve());
274 let getCommentsForm = new GetComments({
276 community_name: None,
278 limit: Some(fetchLimit),
280 sort: sort.map(postToCommentSortType),
282 saved_only: Some(false),
287 promises.push(Promise.resolve());
288 promises.push(req.client.getComments(getCommentsForm));
291 let trendingCommunitiesForm = new ListCommunities({
292 type_: Some(ListingType.Local),
293 sort: Some(SortType.Hot),
294 limit: Some(trendingFetchLimit),
298 promises.push(req.client.listCommunities(trendingCommunitiesForm));
303 componentDidUpdate(_: any, lastState: HomeState) {
305 lastState.listingType !== this.state.listingType ||
306 lastState.dataType !== this.state.dataType ||
307 lastState.sort !== this.state.sort ||
308 lastState.page !== this.state.page
310 this.setState({ loading: true });
315 get documentTitle(): string {
316 return this.state.siteRes.site_view.match({
318 siteView.site.description.match({
319 some: desc => `${siteView.site.name} - ${desc}`,
320 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.isSome() && (
336 <div className="row">
337 <main role="main" className="col-12 col-md-8">
338 <div className="d-block d-md-none">{this.mobileView()}</div>
341 <aside className="d-none d-md-block col-md-4">
350 get hasFollows(): boolean {
351 return UserService.Instance.myUserInfo.match({
352 some: mui => mui.follows.length > 0,
358 let siteRes = this.state.siteRes;
360 <div className="row">
361 <div className="col-12">
362 {this.hasFollows && (
364 className="btn btn-secondary d-inline-block mb-2 mr-3"
365 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
367 {i18n.t("subscribed")}{" "}
370 this.state.showSubscribedMobile
374 classes="icon-inline"
379 className="btn btn-secondary d-inline-block mb-2 mr-3"
380 onClick={linkEvent(this, this.handleShowTrendingMobile)}
382 {i18n.t("trending")}{" "}
385 this.state.showTrendingMobile ? `minus-square` : `plus-square`
387 classes="icon-inline"
391 className="btn btn-secondary d-inline-block mb-2 mr-3"
392 onClick={linkEvent(this, this.handleShowSidebarMobile)}
394 {i18n.t("sidebar")}{" "}
397 this.state.showSidebarMobile ? `minus-square` : `plus-square`
399 classes="icon-inline"
402 {this.state.showSidebarMobile &&
403 siteRes.site_view.match({
407 admins={Some(siteRes.admins)}
408 counts={Some(siteView.counts)}
409 online={Some(siteRes.online)}
410 showLocal={showLocal(this.isoData)}
415 {this.state.showTrendingMobile && (
416 <div className="col-12 card border-secondary mb-3">
417 <div className="card-body">{this.trendingCommunities()}</div>
420 {this.state.showSubscribedMobile && (
421 <div className="col-12 card border-secondary mb-3">
422 <div className="card-body">{this.subscribedCommunities()}</div>
431 let siteRes = this.state.siteRes;
434 {!this.state.loading && (
436 <div className="card border-secondary mb-3">
437 <div className="card-body">
438 {this.trendingCommunities()}
439 {canCreateCommunity(this.state.siteRes) &&
440 this.createCommunityButton()}
441 {this.exploreCommunitiesButton()}
444 {siteRes.site_view.match({
448 admins={Some(siteRes.admins)}
449 counts={Some(siteView.counts)}
450 online={Some(siteRes.online)}
451 showLocal={showLocal(this.isoData)}
456 {this.hasFollows && (
457 <div className="card border-secondary mb-3">
458 <div className="card-body">{this.subscribedCommunities()}</div>
467 createCommunityButton() {
469 <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
470 {i18n.t("create_a_community")}
475 exploreCommunitiesButton() {
477 <Link className="btn btn-secondary btn-block" to="/communities">
478 {i18n.t("explore_communities")}
483 trendingCommunities() {
487 <T i18nKey="trending_communities">
489 <Link className="text-body" to="/communities">
494 <ul className="list-inline mb-0">
495 {this.state.trendingCommunities.map(cv => (
497 key={cv.community.id}
498 className="list-inline-item d-inline-block"
500 <CommunityLink community={cv.community} />
508 subscribedCommunities() {
512 <T class="d-inline" i18nKey="subscribed_to_communities">
514 <Link className="text-body" to="/communities">
519 className="btn btn-sm text-muted"
520 onClick={linkEvent(this, this.handleCollapseSubscribe)}
521 aria-label={i18n.t("collapse")}
522 data-tippy-content={i18n.t("collapse")}
524 {this.state.subscribedCollapsed ? (
525 <Icon icon="plus-square" classes="icon-inline" />
527 <Icon icon="minus-square" classes="icon-inline" />
531 {!this.state.subscribedCollapsed && (
532 <ul className="list-inline mb-0">
533 {UserService.Instance.myUserInfo
538 key={cfv.community.id}
539 className="list-inline-item d-inline-block"
541 <CommunityLink community={cfv.community} />
550 updateUrl(paramUpdates: UrlParams) {
551 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
552 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
553 const sortStr = paramUpdates.sort || this.state.sort;
554 const page = paramUpdates.page || this.state.page;
555 this.props.history.push(
556 `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
562 <div className="main-content-wrapper">
563 {this.state.loading ? (
572 page={this.state.page}
573 onChange={this.handlePageChange}
582 return this.state.dataType == DataType.Post ? (
584 posts={this.state.posts}
587 enableDownvotes={enableDownvotes(this.state.siteRes)}
588 enableNsfw={enableNsfw(this.state.siteRes)}
589 allLanguages={this.state.siteRes.all_languages}
593 nodes={commentsToFlatNodes(this.state.comments)}
594 viewType={CommentViewType.Flat}
597 maxCommentsShown={None}
601 enableDownvotes={enableDownvotes(this.state.siteRes)}
602 allLanguages={this.state.siteRes.all_languages}
608 let allRss = `/feeds/all.xml?sort=${this.state.sort}`;
609 let localRss = `/feeds/local.xml?sort=${this.state.sort}`;
610 let frontRss = auth(false)
612 .map(auth => `/feeds/front/${auth}.xml?sort=${this.state.sort}`);
615 <div className="mb-3">
616 <span className="mr-3">
618 type_={this.state.dataType}
619 onChange={this.handleDataTypeChange}
622 <span className="mr-3">
624 type_={this.state.listingType}
625 showLocal={showLocal(this.isoData)}
627 onChange={this.handleListingTypeChange}
630 <span className="mr-2">
631 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
633 {this.state.listingType == ListingType.All && (
635 <a href={allRss} rel={relTags} title="RSS">
636 <Icon icon="rss" classes="text-muted small" />
638 <link rel="alternate" type="application/atom+xml" href={allRss} />
641 {this.state.listingType == ListingType.Local && (
643 <a href={localRss} rel={relTags} title="RSS">
644 <Icon icon="rss" classes="text-muted small" />
646 <link rel="alternate" type="application/atom+xml" href={localRss} />
649 {this.state.listingType == ListingType.Subscribed &&
653 <a href={rss} title="RSS" rel={relTags}>
654 <Icon icon="rss" classes="text-muted small" />
656 <link rel="alternate" type="application/atom+xml" href={rss} />
665 handleShowSubscribedMobile(i: Home) {
666 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
669 handleShowTrendingMobile(i: Home) {
670 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
673 handleShowSidebarMobile(i: Home) {
674 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
677 handleCollapseSubscribe(i: Home) {
678 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
681 handlePageChange(page: number) {
682 this.updateUrl({ page });
683 window.scrollTo(0, 0);
686 handleSortChange(val: SortType) {
687 this.updateUrl({ sort: val, page: 1 });
688 window.scrollTo(0, 0);
691 handleListingTypeChange(val: ListingType) {
692 this.updateUrl({ listingType: val, page: 1 });
693 window.scrollTo(0, 0);
696 handleDataTypeChange(val: DataType) {
697 this.updateUrl({ dataType: DataType[val], page: 1 });
698 window.scrollTo(0, 0);
702 if (this.state.dataType == DataType.Post) {
703 let getPostsForm = new GetPosts({
705 community_name: None,
706 page: Some(this.state.page),
707 limit: Some(fetchLimit),
708 sort: Some(this.state.sort),
709 saved_only: Some(false),
710 auth: auth(false).ok(),
711 type_: Some(this.state.listingType),
714 WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
716 let getCommentsForm = new GetComments({
718 community_name: None,
719 page: Some(this.state.page),
720 limit: Some(fetchLimit),
722 sort: Some(postToCommentSortType(this.state.sort)),
723 saved_only: Some(false),
726 auth: auth(false).ok(),
727 type_: Some(this.state.listingType),
729 WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
733 parseMessage(msg: any) {
734 let op = wsUserOp(msg);
737 toast(i18n.t(msg.error), "danger");
739 } else if (msg.reconnect) {
740 WebSocketService.Instance.send(
741 wsClient.communityJoin({ community_id: 0 })
744 } else if (op == UserOperation.ListCommunities) {
745 let data = wsJsonToRes<ListCommunitiesResponse>(
747 ListCommunitiesResponse
749 this.setState({ trendingCommunities: data.communities });
750 } else if (op == UserOperation.EditSite) {
751 let data = wsJsonToRes<SiteResponse>(msg, SiteResponse);
752 this.setState(s => ((s.siteRes.site_view = Some(data.site_view)), s));
753 toast(i18n.t("site_saved"));
754 } else if (op == UserOperation.GetPosts) {
755 let data = wsJsonToRes<GetPostsResponse>(msg, GetPostsResponse);
756 this.setState({ posts: data.posts, loading: false });
757 WebSocketService.Instance.send(
758 wsClient.communityJoin({ community_id: 0 })
760 restoreScrollPosition(this.context);
762 } else if (op == UserOperation.CreatePost) {
763 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
765 let showPostNotifs = UserService.Instance.myUserInfo
766 .map(m => m.local_user_view.local_user.show_new_post_notifs)
769 // Only push these if you're on the first page, you pass the nsfw check, and it isn't blocked
771 this.state.page == 1 &&
772 nsfwCheck(data.post_view) &&
773 !isPostBlocked(data.post_view)
775 // If you're on subscribed, only push it if you're subscribed.
776 if (this.state.listingType == ListingType.Subscribed) {
778 UserService.Instance.myUserInfo
781 .map(c => c.community.id)
782 .includes(data.post_view.community.id)
784 this.state.posts.unshift(data.post_view);
785 if (showPostNotifs) {
786 notifyPost(data.post_view, this.context.router);
789 } else if (this.state.listingType == ListingType.Local) {
790 // If you're on the local view, only push it if its local
791 if (data.post_view.post.local) {
792 this.state.posts.unshift(data.post_view);
793 if (showPostNotifs) {
794 notifyPost(data.post_view, this.context.router);
798 this.state.posts.unshift(data.post_view);
799 if (showPostNotifs) {
800 notifyPost(data.post_view, this.context.router);
803 this.setState(this.state);
806 op == UserOperation.EditPost ||
807 op == UserOperation.DeletePost ||
808 op == UserOperation.RemovePost ||
809 op == UserOperation.LockPost ||
810 op == UserOperation.StickyPost ||
811 op == UserOperation.SavePost
813 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
814 editPostFindRes(data.post_view, this.state.posts);
815 this.setState(this.state);
816 } else if (op == UserOperation.CreatePostLike) {
817 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
818 createPostLikeFindRes(data.post_view, this.state.posts);
819 this.setState(this.state);
820 } else if (op == UserOperation.AddAdmin) {
821 let data = wsJsonToRes<AddAdminResponse>(msg, AddAdminResponse);
822 this.setState(s => ((s.siteRes.admins = data.admins), s));
823 } else if (op == UserOperation.BanPerson) {
824 let data = wsJsonToRes<BanPersonResponse>(msg, BanPersonResponse);
826 .filter(p => p.creator.id == data.person_view.person.id)
827 .forEach(p => (p.creator.banned = data.banned));
829 this.setState(this.state);
830 } else if (op == UserOperation.GetComments) {
831 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
832 this.setState({ comments: data.comments, loading: false });
834 op == UserOperation.EditComment ||
835 op == UserOperation.DeleteComment ||
836 op == UserOperation.RemoveComment
838 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
839 editCommentRes(data.comment_view, this.state.comments);
840 this.setState(this.state);
841 } else if (op == UserOperation.CreateComment) {
842 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
844 // Necessary since it might be a user reply
846 // If you're on subscribed, only push it if you're subscribed.
847 if (this.state.listingType == ListingType.Subscribed) {
849 UserService.Instance.myUserInfo
852 .map(c => c.community.id)
853 .includes(data.comment_view.community.id)
855 this.state.comments.unshift(data.comment_view);
858 this.state.comments.unshift(data.comment_view);
860 this.setState(this.state);
862 } else if (op == UserOperation.SaveComment) {
863 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
864 saveCommentRes(data.comment_view, this.state.comments);
865 this.setState(this.state);
866 } else if (op == UserOperation.CreateCommentLike) {
867 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
868 createCommentLikeRes(data.comment_view, this.state.comments);
869 this.setState(this.state);
870 } else if (op == UserOperation.BlockPerson) {
871 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
872 updatePersonBlock(data);
873 } else if (op == UserOperation.CreatePostReport) {
874 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
876 toast(i18n.t("report_created"));
878 } else if (op == UserOperation.CreateCommentReport) {
879 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
881 toast(i18n.t("report_created"));
884 op == UserOperation.PurgePerson ||
885 op == UserOperation.PurgePost ||
886 op == UserOperation.PurgeComment ||
887 op == UserOperation.PurgeCommunity
889 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
891 toast(i18n.t("purge_success"));
892 this.context.router.history.push(`/`);