1 import { NoOptionI18nKeys } from "i18next";
2 import { Component, linkEvent, MouseEventHandler } from "inferno";
3 import { T } from "inferno-i18next-dess";
4 import { Link } from "inferno-router";
9 BanFromCommunityResponse,
33 ListCommunitiesResponse,
36 MarkCommentReplyAsRead,
37 MarkPersonMentionAsRead,
49 } from "lemmy-js-client";
50 import { i18n } from "../../i18next";
55 } from "../../interfaces";
56 import { UserService } from "../../services";
57 import { FirstLoadService } from "../../services/FirstLoadService";
58 import { HttpService, RequestState } from "../../services/HttpService";
76 postToCommentSortType,
79 restoreScrollPosition,
89 import { CommentNodes } from "../comment/comment-nodes";
90 import { DataTypeSelect } from "../common/data-type-select";
91 import { HtmlTags } from "../common/html-tags";
92 import { Icon, Spinner } from "../common/icon";
93 import { ListingTypeSelect } from "../common/listing-type-select";
94 import { Paginator } from "../common/paginator";
95 import { SortSelect } from "../common/sort-select";
96 import { CommunityLink } from "../community/community-link";
97 import { PostListings } from "../post/post-listings";
98 import { SiteSidebar } from "./site-sidebar";
100 interface HomeState {
101 postsRes: RequestState<GetPostsResponse>;
102 commentsRes: RequestState<GetCommentsResponse>;
103 trendingCommunitiesRes: RequestState<ListCommunitiesResponse>;
104 showSubscribedMobile: boolean;
105 showTrendingMobile: boolean;
106 showSidebarMobile: boolean;
107 subscribedCollapsed: boolean;
109 siteRes: GetSiteResponse;
110 finished: Map<CommentId, boolean | undefined>;
111 isIsomorphic: boolean;
114 interface HomeProps {
115 listingType: ListingType;
121 type HomeData = RouteDataResponse<{
122 postsResponse?: GetPostsResponse;
123 commentsResponse?: GetCommentsResponse;
124 trendingResponse: ListCommunitiesResponse;
127 function getDataTypeFromQuery(type?: string): DataType {
128 return type ? DataType[type] : DataType.Post;
131 function getListingTypeFromQuery(type?: string): ListingType {
132 const myListingType =
133 UserService.Instance.myUserInfo?.local_user_view?.local_user
134 ?.default_listing_type;
136 return (type ? (type as ListingType) : myListingType) ?? "Local";
139 function getSortTypeFromQuery(type?: string): SortType {
141 UserService.Instance.myUserInfo?.local_user_view?.local_user
144 return (type ? (type as SortType) : mySortType) ?? "Active";
147 const getHomeQueryParams = () =>
148 getQueryParams<HomeProps>({
149 sort: getSortTypeFromQuery,
150 listingType: getListingTypeFromQuery,
151 page: getPageFromString,
152 dataType: getDataTypeFromQuery,
155 const MobileButton = ({
160 textKey: NoOptionI18nKeys;
162 onClick: MouseEventHandler<HTMLButtonElement>;
165 className="btn btn-secondary d-inline-block mb-2 mr-3"
168 {i18n.t(textKey)}{" "}
169 <Icon icon={show ? `minus-square` : `plus-square`} classes="icon-inline" />
173 const LinkButton = ({
178 translationKey: NoOptionI18nKeys;
180 <Link className="btn btn-secondary btn-block" to={path}>
181 {i18n.t(translationKey)}
185 export class Home extends Component<any, HomeState> {
186 private isoData = setIsoData<HomeData>(this.context);
188 postsRes: { state: "empty" },
189 commentsRes: { state: "empty" },
190 trendingCommunitiesRes: { state: "empty" },
191 siteRes: this.isoData.site_res,
192 showSubscribedMobile: false,
193 showTrendingMobile: false,
194 showSidebarMobile: false,
195 subscribedCollapsed: false,
200 constructor(props: any, context: any) {
201 super(props, context);
203 this.handleSortChange = this.handleSortChange.bind(this);
204 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
205 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
206 this.handlePageChange = this.handlePageChange.bind(this);
208 this.handleCreateComment = this.handleCreateComment.bind(this);
209 this.handleEditComment = this.handleEditComment.bind(this);
210 this.handleSaveComment = this.handleSaveComment.bind(this);
211 this.handleBlockPerson = this.handleBlockPerson.bind(this);
212 this.handleDeleteComment = this.handleDeleteComment.bind(this);
213 this.handleRemoveComment = this.handleRemoveComment.bind(this);
214 this.handleCommentVote = this.handleCommentVote.bind(this);
215 this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
216 this.handleAddAdmin = this.handleAddAdmin.bind(this);
217 this.handlePurgePerson = this.handlePurgePerson.bind(this);
218 this.handlePurgeComment = this.handlePurgeComment.bind(this);
219 this.handleCommentReport = this.handleCommentReport.bind(this);
220 this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
221 this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
222 this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
223 this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
224 this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
225 this.handleBanPerson = this.handleBanPerson.bind(this);
226 this.handlePostEdit = this.handlePostEdit.bind(this);
227 this.handlePostVote = this.handlePostVote.bind(this);
228 this.handlePostReport = this.handlePostReport.bind(this);
229 this.handleLockPost = this.handleLockPost.bind(this);
230 this.handleDeletePost = this.handleDeletePost.bind(this);
231 this.handleRemovePost = this.handleRemovePost.bind(this);
232 this.handleSavePost = this.handleSavePost.bind(this);
233 this.handlePurgePost = this.handlePurgePost.bind(this);
234 this.handleFeaturePost = this.handleFeaturePost.bind(this);
236 // Only fetch the data if coming from another route
237 if (FirstLoadService.isFirstLoad) {
239 trendingResponse: trendingCommunitiesRes,
240 commentsResponse: commentsRes,
241 postsResponse: postsRes,
242 } = this.isoData.routeData;
246 trendingCommunitiesRes,
247 tagline: getRandomFromList(this.state?.siteRes?.taglines ?? [])
252 if (commentsRes?.state === "success") {
259 if (postsRes?.state === "success") {
268 async componentDidMount() {
269 if (!this.state.isIsomorphic) {
270 await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
275 componentWillUnmount() {
276 saveScrollPosition(this.context);
279 static async fetchInitialData({
282 query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
283 }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<HomeData> {
284 const dataType = getDataTypeFromQuery(urlDataType);
286 // TODO figure out auth default_listingType, default_sort_type
287 const type_ = getListingTypeFromQuery(listingType);
288 const sort = getSortTypeFromQuery(urlSort);
290 const page = urlPage ? Number(urlPage) : 1;
292 let postsResponse: RequestState<GetPostsResponse> | undefined = undefined;
293 let commentsResponse: RequestState<GetCommentsResponse> | undefined =
296 if (dataType === DataType.Post) {
297 const getPostsForm: GetPosts = {
306 postsResponse = await client.getPosts(getPostsForm);
308 const getCommentsForm: GetComments = {
311 sort: postToCommentSortType(sort),
317 commentsResponse = await client.getComments(getCommentsForm);
320 const trendingCommunitiesForm: ListCommunities = {
323 limit: trendingFetchLimit,
328 trendingResponse: await client.listCommunities(trendingCommunitiesForm),
334 get documentTitle(): string {
335 const { name, description } = this.state.siteRes.site_view.site;
337 return description ? `${name} - ${description}` : name;
345 local_site: { site_setup },
351 <div className="container-lg">
353 title={this.documentTitle}
354 path={this.context.router.route.match.url}
357 <div className="row">
358 <main role="main" className="col-12 col-md-8">
362 dangerouslySetInnerHTML={mdToHtml(tagline)}
365 <div className="d-block d-md-none">{this.mobileView}</div>
368 <aside className="d-none d-md-block col-md-4">
377 get hasFollows(): boolean {
378 const mui = UserService.Instance.myUserInfo;
379 return !!mui && mui.follows.length > 0;
385 site_view: { counts, site },
389 showSubscribedMobile,
395 <div className="row">
396 <div className="col-12">
397 {this.hasFollows && (
400 show={showSubscribedMobile}
401 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
406 show={showTrendingMobile}
407 onClick={linkEvent(this, this.handleShowTrendingMobile)}
411 show={showSidebarMobile}
412 onClick={linkEvent(this, this.handleShowSidebarMobile)}
414 {showSidebarMobile && (
420 showLocal={showLocal(this.isoData)}
423 {showTrendingMobile && (
424 <div className="col-12 card border-secondary mb-3">
425 <div className="card-body">{this.trendingCommunities(true)}</div>
428 {showSubscribedMobile && (
429 <div className="col-12 card border-secondary mb-3">
430 <div className="card-body">{this.subscribedCommunities}</div>
441 site_view: { counts, site },
450 <div className="card border-secondary mb-3">
451 <div className="card-body">
452 {this.trendingCommunities()}
453 {canCreateCommunity(this.state.siteRes) && (
455 path="/create_community"
456 translationKey="create_a_community"
461 translationKey="explore_communities"
470 showLocal={showLocal(this.isoData)}
472 {this.hasFollows && (
473 <div className="card border-secondary mb-3">
474 <div className="card-body">{this.subscribedCommunities}</div>
482 trendingCommunities(isMobile = false) {
483 switch (this.state.trendingCommunitiesRes.state) {
491 const trending = this.state.trendingCommunitiesRes.data.communities;
493 <div className={!isMobile ? "mb-2" : ""}>
495 <T i18nKey="trending_communities">
497 <Link className="text-body" to="/communities">
502 <ul className="list-inline mb-0">
503 {trending.map(cv => (
505 key={cv.community.id}
506 className="list-inline-item d-inline-block"
508 <CommunityLink community={cv.community} />
518 get subscribedCommunities() {
519 const { subscribedCollapsed } = this.state;
524 <T class="d-inline" i18nKey="subscribed_to_communities">
526 <Link className="text-body" to="/communities">
531 className="btn btn-sm text-muted"
532 onClick={linkEvent(this, this.handleCollapseSubscribe)}
533 aria-label={i18n.t("collapse")}
534 data-tippy-content={i18n.t("collapse")}
537 icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
538 classes="icon-inline"
542 {!subscribedCollapsed && (
543 <ul className="list-inline mb-0">
544 {UserService.Instance.myUserInfo?.follows.map(cfv => (
546 key={cfv.community.id}
547 className="list-inline-item d-inline-block"
549 <CommunityLink community={cfv.community} />
558 async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
560 dataType: urlDataType,
561 listingType: urlListingType,
564 } = getHomeQueryParams();
566 const queryParams: QueryParams<HomeProps> = {
567 dataType: getDataTypeString(dataType ?? urlDataType),
568 listingType: listingType ?? urlListingType,
569 page: (page ?? urlPage).toString(),
570 sort: sort ?? urlSort,
573 this.props.history.push({
575 search: getQueryString(queryParams),
578 await this.fetchData();
582 const { page } = getHomeQueryParams();
585 <div className="main-content-wrapper">
589 <Paginator page={page} onChange={this.handlePageChange} />
596 const { dataType } = getHomeQueryParams();
597 const siteRes = this.state.siteRes;
599 if (dataType === DataType.Post) {
600 switch (this.state.postsRes.state) {
608 const posts = this.state.postsRes.data.posts;
614 enableDownvotes={enableDownvotes(siteRes)}
615 enableNsfw={enableNsfw(siteRes)}
616 allLanguages={siteRes.all_languages}
617 siteLanguages={siteRes.discussion_languages}
618 onBlockPerson={this.handleBlockPerson}
619 onPostEdit={this.handlePostEdit}
620 onPostVote={this.handlePostVote}
621 onPostReport={this.handlePostReport}
622 onLockPost={this.handleLockPost}
623 onDeletePost={this.handleDeletePost}
624 onRemovePost={this.handleRemovePost}
625 onSavePost={this.handleSavePost}
626 onPurgePerson={this.handlePurgePerson}
627 onPurgePost={this.handlePurgePost}
628 onBanPerson={this.handleBanPerson}
629 onBanPersonFromCommunity={this.handleBanFromCommunity}
630 onAddModToCommunity={this.handleAddModToCommunity}
631 onAddAdmin={this.handleAddAdmin}
632 onTransferCommunity={this.handleTransferCommunity}
633 onFeaturePost={this.handleFeaturePost}
639 switch (this.state.commentsRes.state) {
647 const comments = this.state.commentsRes.data.comments;
650 nodes={commentsToFlatNodes(comments)}
651 viewType={CommentViewType.Flat}
652 finished={this.state.finished}
656 enableDownvotes={enableDownvotes(siteRes)}
657 allLanguages={siteRes.all_languages}
658 siteLanguages={siteRes.discussion_languages}
659 onSaveComment={this.handleSaveComment}
660 onBlockPerson={this.handleBlockPerson}
661 onDeleteComment={this.handleDeleteComment}
662 onRemoveComment={this.handleRemoveComment}
663 onCommentVote={this.handleCommentVote}
664 onCommentReport={this.handleCommentReport}
665 onDistinguishComment={this.handleDistinguishComment}
666 onAddModToCommunity={this.handleAddModToCommunity}
667 onAddAdmin={this.handleAddAdmin}
668 onTransferCommunity={this.handleTransferCommunity}
669 onPurgeComment={this.handlePurgeComment}
670 onPurgePerson={this.handlePurgePerson}
671 onCommentReplyRead={this.handleCommentReplyRead}
672 onPersonMentionRead={this.handlePersonMentionRead}
673 onBanPersonFromCommunity={this.handleBanFromCommunity}
674 onBanPerson={this.handleBanPerson}
675 onCreateComment={this.handleCreateComment}
676 onEditComment={this.handleEditComment}
685 const { listingType, dataType, sort } = getHomeQueryParams();
688 <div className="mb-3">
689 <span className="mr-3">
692 onChange={this.handleDataTypeChange}
695 <span className="mr-3">
698 showLocal={showLocal(this.isoData)}
700 onChange={this.handleListingTypeChange}
703 <span className="mr-2">
704 <SortSelect sort={sort} onChange={this.handleSortChange} />
706 {this.getRss(listingType)}
711 getRss(listingType: ListingType) {
712 const { sort } = getHomeQueryParams();
713 const auth = myAuth();
715 let rss: string | undefined = undefined;
717 switch (listingType) {
719 rss = `/feeds/all.xml?sort=${sort}`;
723 rss = `/feeds/local.xml?sort=${sort}`;
727 rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
735 <a href={rss} rel={relTags} title="RSS">
736 <Icon icon="rss" classes="text-muted small" />
738 <link rel="alternate" type="application/atom+xml" href={rss} />
744 async fetchTrendingCommunities() {
745 this.setState({ trendingCommunitiesRes: { state: "loading" } });
747 trendingCommunitiesRes: await HttpService.client.listCommunities({
750 limit: trendingFetchLimit,
757 const auth = myAuth();
758 const { dataType, page, listingType, sort } = getHomeQueryParams();
760 if (dataType === DataType.Post) {
761 this.setState({ postsRes: { state: "loading" } });
763 postsRes: await HttpService.client.getPosts({
773 this.setState({ commentsRes: { state: "loading" } });
775 commentsRes: await HttpService.client.getComments({
778 sort: postToCommentSortType(sort),
786 restoreScrollPosition(this.context);
790 handleShowSubscribedMobile(i: Home) {
791 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
794 handleShowTrendingMobile(i: Home) {
795 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
798 handleShowSidebarMobile(i: Home) {
799 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
802 handleCollapseSubscribe(i: Home) {
803 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
806 handlePageChange(page: number) {
807 this.updateUrl({ page });
808 window.scrollTo(0, 0);
811 handleSortChange(val: SortType) {
812 this.updateUrl({ sort: val, page: 1 });
813 window.scrollTo(0, 0);
816 handleListingTypeChange(val: ListingType) {
817 this.updateUrl({ listingType: val, page: 1 });
818 window.scrollTo(0, 0);
821 handleDataTypeChange(val: DataType) {
822 this.updateUrl({ dataType: val, page: 1 });
823 window.scrollTo(0, 0);
826 async handleAddModToCommunity(form: AddModToCommunity) {
827 // TODO not sure what to do here
828 await HttpService.client.addModToCommunity(form);
831 async handlePurgePerson(form: PurgePerson) {
832 const purgePersonRes = await HttpService.client.purgePerson(form);
833 this.purgeItem(purgePersonRes);
836 async handlePurgeComment(form: PurgeComment) {
837 const purgeCommentRes = await HttpService.client.purgeComment(form);
838 this.purgeItem(purgeCommentRes);
841 async handlePurgePost(form: PurgePost) {
842 const purgeRes = await HttpService.client.purgePost(form);
843 this.purgeItem(purgeRes);
846 async handleBlockPerson(form: BlockPerson) {
847 const blockPersonRes = await HttpService.client.blockPerson(form);
848 if (blockPersonRes.state == "success") {
849 updatePersonBlock(blockPersonRes.data);
853 async handleCreateComment(form: CreateComment) {
854 const createCommentRes = await HttpService.client.createComment(form);
855 this.createAndUpdateComments(createCommentRes);
857 return createCommentRes;
860 async handleEditComment(form: EditComment) {
861 const editCommentRes = await HttpService.client.editComment(form);
862 this.findAndUpdateComment(editCommentRes);
864 return editCommentRes;
867 async handleDeleteComment(form: DeleteComment) {
868 const deleteCommentRes = await HttpService.client.deleteComment(form);
869 this.findAndUpdateComment(deleteCommentRes);
872 async handleDeletePost(form: DeletePost) {
873 const deleteRes = await HttpService.client.deletePost(form);
874 this.findAndUpdatePost(deleteRes);
877 async handleRemovePost(form: RemovePost) {
878 const removeRes = await HttpService.client.removePost(form);
879 this.findAndUpdatePost(removeRes);
882 async handleRemoveComment(form: RemoveComment) {
883 const removeCommentRes = await HttpService.client.removeComment(form);
884 this.findAndUpdateComment(removeCommentRes);
887 async handleSaveComment(form: SaveComment) {
888 const saveCommentRes = await HttpService.client.saveComment(form);
889 this.findAndUpdateComment(saveCommentRes);
892 async handleSavePost(form: SavePost) {
893 const saveRes = await HttpService.client.savePost(form);
894 this.findAndUpdatePost(saveRes);
897 async handleFeaturePost(form: FeaturePost) {
898 const featureRes = await HttpService.client.featurePost(form);
899 this.findAndUpdatePost(featureRes);
902 async handleCommentVote(form: CreateCommentLike) {
903 const voteRes = await HttpService.client.likeComment(form);
904 this.findAndUpdateComment(voteRes);
907 async handlePostEdit(form: EditPost) {
908 const res = await HttpService.client.editPost(form);
909 this.findAndUpdatePost(res);
912 async handlePostVote(form: CreatePostLike) {
913 const voteRes = await HttpService.client.likePost(form);
914 this.findAndUpdatePost(voteRes);
917 async handleCommentReport(form: CreateCommentReport) {
918 const reportRes = await HttpService.client.createCommentReport(form);
919 if (reportRes.state == "success") {
920 toast(i18n.t("report_created"));
924 async handlePostReport(form: CreatePostReport) {
925 const reportRes = await HttpService.client.createPostReport(form);
926 if (reportRes.state == "success") {
927 toast(i18n.t("report_created"));
931 async handleLockPost(form: LockPost) {
932 const lockRes = await HttpService.client.lockPost(form);
933 this.findAndUpdatePost(lockRes);
936 async handleDistinguishComment(form: DistinguishComment) {
937 const distinguishRes = await HttpService.client.distinguishComment(form);
938 this.findAndUpdateComment(distinguishRes);
941 async handleAddAdmin(form: AddAdmin) {
942 const addAdminRes = await HttpService.client.addAdmin(form);
944 if (addAdminRes.state == "success") {
945 this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
949 async handleTransferCommunity(form: TransferCommunity) {
950 await HttpService.client.transferCommunity(form);
951 toast(i18n.t("transfer_community"));
954 async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
955 const readRes = await HttpService.client.markCommentReplyAsRead(form);
956 this.findAndUpdateCommentReply(readRes);
959 async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
960 // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
961 await HttpService.client.markPersonMentionAsRead(form);
964 async handleBanFromCommunity(form: BanFromCommunity) {
965 const banRes = await HttpService.client.banFromCommunity(form);
966 this.updateBanFromCommunity(banRes);
969 async handleBanPerson(form: BanPerson) {
970 const banRes = await HttpService.client.banPerson(form);
971 this.updateBan(banRes);
974 updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
975 // Maybe not necessary
976 if (banRes.state == "success") {
978 if (s.postsRes.state == "success") {
979 s.postsRes.data.posts
980 .filter(c => c.creator.id == banRes.data.person_view.person.id)
982 c => (c.creator_banned_from_community = banRes.data.banned)
985 if (s.commentsRes.state == "success") {
986 s.commentsRes.data.comments
987 .filter(c => c.creator.id == banRes.data.person_view.person.id)
989 c => (c.creator_banned_from_community = banRes.data.banned)
997 updateBan(banRes: RequestState<BanPersonResponse>) {
998 // Maybe not necessary
999 if (banRes.state == "success") {
1000 this.setState(s => {
1001 if (s.postsRes.state == "success") {
1002 s.postsRes.data.posts
1003 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1004 .forEach(c => (c.creator.banned = banRes.data.banned));
1006 if (s.commentsRes.state == "success") {
1007 s.commentsRes.data.comments
1008 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1009 .forEach(c => (c.creator.banned = banRes.data.banned));
1016 purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
1017 if (purgeRes.state == "success") {
1018 toast(i18n.t("purge_success"));
1019 this.context.router.history.push(`/`);
1023 findAndUpdateComment(res: RequestState<CommentResponse>) {
1024 this.setState(s => {
1025 if (s.commentsRes.state == "success" && res.state == "success") {
1026 s.commentsRes.data.comments = editComment(
1027 res.data.comment_view,
1028 s.commentsRes.data.comments
1030 s.finished.set(res.data.comment_view.comment.id, true);
1036 createAndUpdateComments(res: RequestState<CommentResponse>) {
1037 this.setState(s => {
1038 if (s.commentsRes.state == "success" && res.state == "success") {
1039 s.commentsRes.data.comments.unshift(res.data.comment_view);
1041 // Set finished for the parent
1043 getCommentParentId(res.data.comment_view.comment) ?? 0,
1051 findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1052 this.setState(s => {
1053 if (s.commentsRes.state == "success" && res.state == "success") {
1054 s.commentsRes.data.comments = editWith(
1055 res.data.comment_reply_view,
1056 s.commentsRes.data.comments
1063 findAndUpdatePost(res: RequestState<PostResponse>) {
1064 this.setState(s => {
1065 if (s.postsRes.state == "success" && res.state == "success") {
1066 s.postsRes.data.posts = editPost(
1068 s.postsRes.data.posts