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 postsRes: GetPostsResponse;
123 commentsRes: GetCommentsResponse;
124 trendingCommunitiesRes: 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 trendingCommunitiesRes: trendingCommunitiesRes,
240 commentsRes: commentsRes,
242 } = this.isoData.routeData;
246 trendingCommunitiesRes,
249 tagline: getRandomFromList(this.state?.siteRes?.taglines ?? [])
256 async componentDidMount() {
258 !this.state.isIsomorphic ||
259 !Object.values(this.isoData.routeData).some(
260 res => res.state === "success" || res.state === "failed"
263 await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
269 componentWillUnmount() {
270 saveScrollPosition(this.context);
273 static async fetchInitialData({
276 query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
277 }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<HomeData> {
278 const dataType = getDataTypeFromQuery(urlDataType);
280 // TODO figure out auth default_listingType, default_sort_type
281 const type_ = getListingTypeFromQuery(listingType);
282 const sort = getSortTypeFromQuery(urlSort);
284 const page = urlPage ? Number(urlPage) : 1;
286 let postsRes: RequestState<GetPostsResponse> = { state: "empty" };
287 let commentsRes: RequestState<GetCommentsResponse> = {
291 if (dataType === DataType.Post) {
292 const getPostsForm: GetPosts = {
301 postsRes = await client.getPosts(getPostsForm);
303 const getCommentsForm: GetComments = {
306 sort: postToCommentSortType(sort),
312 commentsRes = await client.getComments(getCommentsForm);
315 const trendingCommunitiesForm: ListCommunities = {
318 limit: trendingFetchLimit,
323 trendingCommunitiesRes: await client.listCommunities(
324 trendingCommunitiesForm
331 get documentTitle(): string {
332 const { name, description } = this.state.siteRes.site_view.site;
334 return description ? `${name} - ${description}` : name;
342 local_site: { site_setup },
348 <div className="container-lg">
350 title={this.documentTitle}
351 path={this.context.router.route.match.url}
354 <div className="row">
355 <main role="main" className="col-12 col-md-8">
359 dangerouslySetInnerHTML={mdToHtml(tagline)}
362 <div className="d-block d-md-none">{this.mobileView}</div>
365 <aside className="d-none d-md-block col-md-4">
374 get hasFollows(): boolean {
375 const mui = UserService.Instance.myUserInfo;
376 return !!mui && mui.follows.length > 0;
382 site_view: { counts, site },
386 showSubscribedMobile,
392 <div className="row">
393 <div className="col-12">
394 {this.hasFollows && (
397 show={showSubscribedMobile}
398 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
403 show={showTrendingMobile}
404 onClick={linkEvent(this, this.handleShowTrendingMobile)}
408 show={showSidebarMobile}
409 onClick={linkEvent(this, this.handleShowSidebarMobile)}
411 {showSidebarMobile && (
417 showLocal={showLocal(this.isoData)}
420 {showTrendingMobile && (
421 <div className="col-12 card border-secondary mb-3">
422 <div className="card-body">{this.trendingCommunities(true)}</div>
425 {showSubscribedMobile && (
426 <div className="col-12 card border-secondary mb-3">
427 <div className="card-body">{this.subscribedCommunities}</div>
438 site_view: { counts, site },
447 <div className="card border-secondary mb-3">
448 <div className="card-body">
449 {this.trendingCommunities()}
450 {canCreateCommunity(this.state.siteRes) && (
452 path="/create_community"
453 translationKey="create_a_community"
458 translationKey="explore_communities"
467 showLocal={showLocal(this.isoData)}
469 {this.hasFollows && (
470 <div className="card border-secondary mb-3">
471 <div className="card-body">{this.subscribedCommunities}</div>
479 trendingCommunities(isMobile = false) {
480 switch (this.state.trendingCommunitiesRes?.state) {
488 const trending = this.state.trendingCommunitiesRes.data.communities;
490 <div className={!isMobile ? "mb-2" : ""}>
492 <T i18nKey="trending_communities">
494 <Link className="text-body" to="/communities">
499 <ul className="list-inline mb-0">
500 {trending.map(cv => (
502 key={cv.community.id}
503 className="list-inline-item d-inline-block"
505 <CommunityLink community={cv.community} />
515 get subscribedCommunities() {
516 const { subscribedCollapsed } = this.state;
521 <T class="d-inline" i18nKey="subscribed_to_communities">
523 <Link className="text-body" to="/communities">
528 className="btn btn-sm text-muted"
529 onClick={linkEvent(this, this.handleCollapseSubscribe)}
530 aria-label={i18n.t("collapse")}
531 data-tippy-content={i18n.t("collapse")}
534 icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
535 classes="icon-inline"
539 {!subscribedCollapsed && (
540 <ul className="list-inline mb-0">
541 {UserService.Instance.myUserInfo?.follows.map(cfv => (
543 key={cfv.community.id}
544 className="list-inline-item d-inline-block"
546 <CommunityLink community={cfv.community} />
555 async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
557 dataType: urlDataType,
558 listingType: urlListingType,
561 } = getHomeQueryParams();
563 const queryParams: QueryParams<HomeProps> = {
564 dataType: getDataTypeString(dataType ?? urlDataType),
565 listingType: listingType ?? urlListingType,
566 page: (page ?? urlPage).toString(),
567 sort: sort ?? urlSort,
570 this.props.history.push({
572 search: getQueryString(queryParams),
575 await this.fetchData();
579 const { page } = getHomeQueryParams();
582 <div className="main-content-wrapper">
586 <Paginator page={page} onChange={this.handlePageChange} />
593 const { dataType } = getHomeQueryParams();
594 const siteRes = this.state.siteRes;
596 if (dataType === DataType.Post) {
597 switch (this.state.postsRes?.state) {
605 const posts = this.state.postsRes.data.posts;
611 enableDownvotes={enableDownvotes(siteRes)}
612 enableNsfw={enableNsfw(siteRes)}
613 allLanguages={siteRes.all_languages}
614 siteLanguages={siteRes.discussion_languages}
615 onBlockPerson={this.handleBlockPerson}
616 onPostEdit={this.handlePostEdit}
617 onPostVote={this.handlePostVote}
618 onPostReport={this.handlePostReport}
619 onLockPost={this.handleLockPost}
620 onDeletePost={this.handleDeletePost}
621 onRemovePost={this.handleRemovePost}
622 onSavePost={this.handleSavePost}
623 onPurgePerson={this.handlePurgePerson}
624 onPurgePost={this.handlePurgePost}
625 onBanPerson={this.handleBanPerson}
626 onBanPersonFromCommunity={this.handleBanFromCommunity}
627 onAddModToCommunity={this.handleAddModToCommunity}
628 onAddAdmin={this.handleAddAdmin}
629 onTransferCommunity={this.handleTransferCommunity}
630 onFeaturePost={this.handleFeaturePost}
636 switch (this.state.commentsRes.state) {
644 const comments = this.state.commentsRes.data.comments;
647 nodes={commentsToFlatNodes(comments)}
648 viewType={CommentViewType.Flat}
649 finished={this.state.finished}
653 enableDownvotes={enableDownvotes(siteRes)}
654 allLanguages={siteRes.all_languages}
655 siteLanguages={siteRes.discussion_languages}
656 onSaveComment={this.handleSaveComment}
657 onBlockPerson={this.handleBlockPerson}
658 onDeleteComment={this.handleDeleteComment}
659 onRemoveComment={this.handleRemoveComment}
660 onCommentVote={this.handleCommentVote}
661 onCommentReport={this.handleCommentReport}
662 onDistinguishComment={this.handleDistinguishComment}
663 onAddModToCommunity={this.handleAddModToCommunity}
664 onAddAdmin={this.handleAddAdmin}
665 onTransferCommunity={this.handleTransferCommunity}
666 onPurgeComment={this.handlePurgeComment}
667 onPurgePerson={this.handlePurgePerson}
668 onCommentReplyRead={this.handleCommentReplyRead}
669 onPersonMentionRead={this.handlePersonMentionRead}
670 onBanPersonFromCommunity={this.handleBanFromCommunity}
671 onBanPerson={this.handleBanPerson}
672 onCreateComment={this.handleCreateComment}
673 onEditComment={this.handleEditComment}
682 const { listingType, dataType, sort } = getHomeQueryParams();
685 <div className="mb-3">
686 <span className="mr-3">
689 onChange={this.handleDataTypeChange}
692 <span className="mr-3">
695 showLocal={showLocal(this.isoData)}
697 onChange={this.handleListingTypeChange}
700 <span className="mr-2">
701 <SortSelect sort={sort} onChange={this.handleSortChange} />
703 {this.getRss(listingType)}
708 getRss(listingType: ListingType) {
709 const { sort } = getHomeQueryParams();
710 const auth = myAuth();
712 let rss: string | undefined = undefined;
714 switch (listingType) {
716 rss = `/feeds/all.xml?sort=${sort}`;
720 rss = `/feeds/local.xml?sort=${sort}`;
724 rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
732 <a href={rss} rel={relTags} title="RSS">
733 <Icon icon="rss" classes="text-muted small" />
735 <link rel="alternate" type="application/atom+xml" href={rss} />
741 async fetchTrendingCommunities() {
742 this.setState({ trendingCommunitiesRes: { state: "loading" } });
744 trendingCommunitiesRes: await HttpService.client.listCommunities({
747 limit: trendingFetchLimit,
754 const auth = myAuth();
755 const { dataType, page, listingType, sort } = getHomeQueryParams();
757 if (dataType === DataType.Post) {
758 this.setState({ postsRes: { state: "loading" } });
760 postsRes: await HttpService.client.getPosts({
770 this.setState({ commentsRes: { state: "loading" } });
772 commentsRes: await HttpService.client.getComments({
775 sort: postToCommentSortType(sort),
783 restoreScrollPosition(this.context);
787 handleShowSubscribedMobile(i: Home) {
788 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
791 handleShowTrendingMobile(i: Home) {
792 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
795 handleShowSidebarMobile(i: Home) {
796 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
799 handleCollapseSubscribe(i: Home) {
800 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
803 handlePageChange(page: number) {
804 this.updateUrl({ page });
805 window.scrollTo(0, 0);
808 handleSortChange(val: SortType) {
809 this.updateUrl({ sort: val, page: 1 });
810 window.scrollTo(0, 0);
813 handleListingTypeChange(val: ListingType) {
814 this.updateUrl({ listingType: val, page: 1 });
815 window.scrollTo(0, 0);
818 handleDataTypeChange(val: DataType) {
819 this.updateUrl({ dataType: val, page: 1 });
820 window.scrollTo(0, 0);
823 async handleAddModToCommunity(form: AddModToCommunity) {
824 // TODO not sure what to do here
825 await HttpService.client.addModToCommunity(form);
828 async handlePurgePerson(form: PurgePerson) {
829 const purgePersonRes = await HttpService.client.purgePerson(form);
830 this.purgeItem(purgePersonRes);
833 async handlePurgeComment(form: PurgeComment) {
834 const purgeCommentRes = await HttpService.client.purgeComment(form);
835 this.purgeItem(purgeCommentRes);
838 async handlePurgePost(form: PurgePost) {
839 const purgeRes = await HttpService.client.purgePost(form);
840 this.purgeItem(purgeRes);
843 async handleBlockPerson(form: BlockPerson) {
844 const blockPersonRes = await HttpService.client.blockPerson(form);
845 if (blockPersonRes.state == "success") {
846 updatePersonBlock(blockPersonRes.data);
850 async handleCreateComment(form: CreateComment) {
851 const createCommentRes = await HttpService.client.createComment(form);
852 this.createAndUpdateComments(createCommentRes);
854 return createCommentRes;
857 async handleEditComment(form: EditComment) {
858 const editCommentRes = await HttpService.client.editComment(form);
859 this.findAndUpdateComment(editCommentRes);
861 return editCommentRes;
864 async handleDeleteComment(form: DeleteComment) {
865 const deleteCommentRes = await HttpService.client.deleteComment(form);
866 this.findAndUpdateComment(deleteCommentRes);
869 async handleDeletePost(form: DeletePost) {
870 const deleteRes = await HttpService.client.deletePost(form);
871 this.findAndUpdatePost(deleteRes);
874 async handleRemovePost(form: RemovePost) {
875 const removeRes = await HttpService.client.removePost(form);
876 this.findAndUpdatePost(removeRes);
879 async handleRemoveComment(form: RemoveComment) {
880 const removeCommentRes = await HttpService.client.removeComment(form);
881 this.findAndUpdateComment(removeCommentRes);
884 async handleSaveComment(form: SaveComment) {
885 const saveCommentRes = await HttpService.client.saveComment(form);
886 this.findAndUpdateComment(saveCommentRes);
889 async handleSavePost(form: SavePost) {
890 const saveRes = await HttpService.client.savePost(form);
891 this.findAndUpdatePost(saveRes);
894 async handleFeaturePost(form: FeaturePost) {
895 const featureRes = await HttpService.client.featurePost(form);
896 this.findAndUpdatePost(featureRes);
899 async handleCommentVote(form: CreateCommentLike) {
900 const voteRes = await HttpService.client.likeComment(form);
901 this.findAndUpdateComment(voteRes);
904 async handlePostEdit(form: EditPost) {
905 const res = await HttpService.client.editPost(form);
906 this.findAndUpdatePost(res);
909 async handlePostVote(form: CreatePostLike) {
910 const voteRes = await HttpService.client.likePost(form);
911 this.findAndUpdatePost(voteRes);
914 async handleCommentReport(form: CreateCommentReport) {
915 const reportRes = await HttpService.client.createCommentReport(form);
916 if (reportRes.state == "success") {
917 toast(i18n.t("report_created"));
921 async handlePostReport(form: CreatePostReport) {
922 const reportRes = await HttpService.client.createPostReport(form);
923 if (reportRes.state == "success") {
924 toast(i18n.t("report_created"));
928 async handleLockPost(form: LockPost) {
929 const lockRes = await HttpService.client.lockPost(form);
930 this.findAndUpdatePost(lockRes);
933 async handleDistinguishComment(form: DistinguishComment) {
934 const distinguishRes = await HttpService.client.distinguishComment(form);
935 this.findAndUpdateComment(distinguishRes);
938 async handleAddAdmin(form: AddAdmin) {
939 const addAdminRes = await HttpService.client.addAdmin(form);
941 if (addAdminRes.state == "success") {
942 this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
946 async handleTransferCommunity(form: TransferCommunity) {
947 await HttpService.client.transferCommunity(form);
948 toast(i18n.t("transfer_community"));
951 async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
952 const readRes = await HttpService.client.markCommentReplyAsRead(form);
953 this.findAndUpdateCommentReply(readRes);
956 async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
957 // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
958 await HttpService.client.markPersonMentionAsRead(form);
961 async handleBanFromCommunity(form: BanFromCommunity) {
962 const banRes = await HttpService.client.banFromCommunity(form);
963 this.updateBanFromCommunity(banRes);
966 async handleBanPerson(form: BanPerson) {
967 const banRes = await HttpService.client.banPerson(form);
968 this.updateBan(banRes);
971 updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
972 // Maybe not necessary
973 if (banRes.state == "success") {
975 if (s.postsRes.state == "success") {
976 s.postsRes.data.posts
977 .filter(c => c.creator.id == banRes.data.person_view.person.id)
979 c => (c.creator_banned_from_community = banRes.data.banned)
982 if (s.commentsRes.state == "success") {
983 s.commentsRes.data.comments
984 .filter(c => c.creator.id == banRes.data.person_view.person.id)
986 c => (c.creator_banned_from_community = banRes.data.banned)
994 updateBan(banRes: RequestState<BanPersonResponse>) {
995 // Maybe not necessary
996 if (banRes.state == "success") {
998 if (s.postsRes.state == "success") {
999 s.postsRes.data.posts
1000 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1001 .forEach(c => (c.creator.banned = banRes.data.banned));
1003 if (s.commentsRes.state == "success") {
1004 s.commentsRes.data.comments
1005 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1006 .forEach(c => (c.creator.banned = banRes.data.banned));
1013 purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
1014 if (purgeRes.state == "success") {
1015 toast(i18n.t("purge_success"));
1016 this.context.router.history.push(`/`);
1020 findAndUpdateComment(res: RequestState<CommentResponse>) {
1021 this.setState(s => {
1022 if (s.commentsRes.state == "success" && res.state == "success") {
1023 s.commentsRes.data.comments = editComment(
1024 res.data.comment_view,
1025 s.commentsRes.data.comments
1027 s.finished.set(res.data.comment_view.comment.id, true);
1033 createAndUpdateComments(res: RequestState<CommentResponse>) {
1034 this.setState(s => {
1035 if (s.commentsRes.state == "success" && res.state == "success") {
1036 s.commentsRes.data.comments.unshift(res.data.comment_view);
1038 // Set finished for the parent
1040 getCommentParentId(res.data.comment_view.comment) ?? 0,
1048 findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1049 this.setState(s => {
1050 if (s.commentsRes.state == "success" && res.state == "success") {
1051 s.commentsRes.data.comments = editWith(
1052 res.data.comment_reply_view,
1053 s.commentsRes.data.comments
1060 findAndUpdatePost(res: RequestState<PostResponse>) {
1061 this.setState(s => {
1062 if (s.postsRes.state == "success" && res.state == "success") {
1063 s.postsRes.data.posts = editPost(
1065 s.postsRes.data.posts