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";
73 postToCommentSortType,
75 restoreScrollPosition,
84 import { getQueryParams } from "../../utils/helpers/get-query-params";
85 import { getQueryString } from "../../utils/helpers/get-query-string";
86 import { canCreateCommunity } from "../../utils/roles/can-create-community";
87 import type { QueryParams } from "../../utils/types/query-params";
88 import { CommentNodes } from "../comment/comment-nodes";
89 import { DataTypeSelect } from "../common/data-type-select";
90 import { HtmlTags } from "../common/html-tags";
91 import { Icon, Spinner } from "../common/icon";
92 import { ListingTypeSelect } from "../common/listing-type-select";
93 import { Paginator } from "../common/paginator";
94 import { SortSelect } from "../common/sort-select";
95 import { CommunityLink } from "../community/community-link";
96 import { PostListings } from "../post/post-listings";
97 import { SiteSidebar } from "./site-sidebar";
100 postsRes: RequestState<GetPostsResponse>;
101 commentsRes: RequestState<GetCommentsResponse>;
102 trendingCommunitiesRes: RequestState<ListCommunitiesResponse>;
103 showSubscribedMobile: boolean;
104 showTrendingMobile: boolean;
105 showSidebarMobile: boolean;
106 subscribedCollapsed: boolean;
108 siteRes: GetSiteResponse;
109 finished: Map<CommentId, boolean | undefined>;
110 isIsomorphic: boolean;
113 interface HomeProps {
114 listingType: ListingType;
120 function getDataTypeFromQuery(type?: string): DataType {
121 return type ? DataType[type] : DataType.Post;
124 function getListingTypeFromQuery(type?: string): ListingType {
125 const myListingType =
126 UserService.Instance.myUserInfo?.local_user_view?.local_user
127 ?.default_listing_type;
129 return (type ? (type as ListingType) : myListingType) ?? "Local";
132 function getSortTypeFromQuery(type?: string): SortType {
134 UserService.Instance.myUserInfo?.local_user_view?.local_user
137 return (type ? (type as SortType) : mySortType) ?? "Active";
140 const getHomeQueryParams = () =>
141 getQueryParams<HomeProps>({
142 sort: getSortTypeFromQuery,
143 listingType: getListingTypeFromQuery,
144 page: getPageFromString,
145 dataType: getDataTypeFromQuery,
148 const MobileButton = ({
153 textKey: NoOptionI18nKeys;
155 onClick: MouseEventHandler<HTMLButtonElement>;
158 className="btn btn-secondary d-inline-block mb-2 mr-3"
161 {i18n.t(textKey)}{" "}
162 <Icon icon={show ? `minus-square` : `plus-square`} classes="icon-inline" />
166 const LinkButton = ({
171 translationKey: NoOptionI18nKeys;
173 <Link className="btn btn-secondary btn-block" to={path}>
174 {i18n.t(translationKey)}
178 export class Home extends Component<any, HomeState> {
179 private isoData = setIsoData(this.context);
181 postsRes: { state: "empty" },
182 commentsRes: { state: "empty" },
183 trendingCommunitiesRes: { state: "empty" },
184 siteRes: this.isoData.site_res,
185 showSubscribedMobile: false,
186 showTrendingMobile: false,
187 showSidebarMobile: false,
188 subscribedCollapsed: false,
193 constructor(props: any, context: any) {
194 super(props, context);
196 this.handleSortChange = this.handleSortChange.bind(this);
197 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
198 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
199 this.handlePageChange = this.handlePageChange.bind(this);
201 this.handleCreateComment = this.handleCreateComment.bind(this);
202 this.handleEditComment = this.handleEditComment.bind(this);
203 this.handleSaveComment = this.handleSaveComment.bind(this);
204 this.handleBlockPerson = this.handleBlockPerson.bind(this);
205 this.handleDeleteComment = this.handleDeleteComment.bind(this);
206 this.handleRemoveComment = this.handleRemoveComment.bind(this);
207 this.handleCommentVote = this.handleCommentVote.bind(this);
208 this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
209 this.handleAddAdmin = this.handleAddAdmin.bind(this);
210 this.handlePurgePerson = this.handlePurgePerson.bind(this);
211 this.handlePurgeComment = this.handlePurgeComment.bind(this);
212 this.handleCommentReport = this.handleCommentReport.bind(this);
213 this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
214 this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
215 this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
216 this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
217 this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
218 this.handleBanPerson = this.handleBanPerson.bind(this);
219 this.handlePostEdit = this.handlePostEdit.bind(this);
220 this.handlePostVote = this.handlePostVote.bind(this);
221 this.handlePostReport = this.handlePostReport.bind(this);
222 this.handleLockPost = this.handleLockPost.bind(this);
223 this.handleDeletePost = this.handleDeletePost.bind(this);
224 this.handleRemovePost = this.handleRemovePost.bind(this);
225 this.handleSavePost = this.handleSavePost.bind(this);
226 this.handlePurgePost = this.handlePurgePost.bind(this);
227 this.handleFeaturePost = this.handleFeaturePost.bind(this);
229 // Only fetch the data if coming from another route
230 if (FirstLoadService.isFirstLoad) {
231 const [postsRes, commentsRes, trendingCommunitiesRes] =
232 this.isoData.routeData;
238 trendingCommunitiesRes,
239 tagline: getRandomFromList(this.state?.siteRes?.taglines ?? [])
246 async componentDidMount() {
247 if (!this.state.isIsomorphic || !this.isoData.routeData.length) {
248 await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
254 componentWillUnmount() {
255 saveScrollPosition(this.context);
258 static fetchInitialData({
261 query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
262 }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<
265 const dataType = getDataTypeFromQuery(urlDataType);
267 // TODO figure out auth default_listingType, default_sort_type
268 const type_ = getListingTypeFromQuery(listingType);
269 const sort = getSortTypeFromQuery(urlSort);
271 const page = urlPage ? Number(urlPage) : 1;
273 const promises: Promise<RequestState<any>>[] = [];
275 if (dataType === DataType.Post) {
276 const getPostsForm: GetPosts = {
285 promises.push(client.getPosts(getPostsForm));
286 promises.push(Promise.resolve({ state: "empty" }));
288 const getCommentsForm: GetComments = {
291 sort: postToCommentSortType(sort),
296 promises.push(Promise.resolve({ state: "empty" }));
297 promises.push(client.getComments(getCommentsForm));
300 const trendingCommunitiesForm: ListCommunities = {
303 limit: trendingFetchLimit,
306 promises.push(client.listCommunities(trendingCommunitiesForm));
311 get documentTitle(): string {
312 const { name, description } = this.state.siteRes.site_view.site;
314 return description ? `${name} - ${description}` : name;
322 local_site: { site_setup },
328 <div className="container-lg">
330 title={this.documentTitle}
331 path={this.context.router.route.match.url}
334 <div className="row">
335 <main role="main" className="col-12 col-md-8">
339 dangerouslySetInnerHTML={mdToHtml(tagline)}
342 <div className="d-block d-md-none">{this.mobileView}</div>
345 <aside className="d-none d-md-block col-md-4">
354 get hasFollows(): boolean {
355 const mui = UserService.Instance.myUserInfo;
356 return !!mui && mui.follows.length > 0;
362 site_view: { counts, site },
365 showSubscribedMobile,
371 <div className="row">
372 <div className="col-12">
373 {this.hasFollows && (
376 show={showSubscribedMobile}
377 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
382 show={showTrendingMobile}
383 onClick={linkEvent(this, this.handleShowTrendingMobile)}
387 show={showSidebarMobile}
388 onClick={linkEvent(this, this.handleShowSidebarMobile)}
390 {showSidebarMobile && (
395 showLocal={showLocal(this.isoData)}
398 {showTrendingMobile && (
399 <div className="col-12 card border-secondary mb-3">
400 <div className="card-body">{this.trendingCommunities(true)}</div>
403 {showSubscribedMobile && (
404 <div className="col-12 card border-secondary mb-3">
405 <div className="card-body">{this.subscribedCommunities}</div>
416 site_view: { counts, site },
424 <div className="card border-secondary mb-3">
425 <div className="card-body">
426 {this.trendingCommunities()}
427 {canCreateCommunity(this.state.siteRes) && (
429 path="/create_community"
430 translationKey="create_a_community"
435 translationKey="explore_communities"
443 showLocal={showLocal(this.isoData)}
445 {this.hasFollows && (
446 <div className="card border-secondary mb-3">
447 <div className="card-body">{this.subscribedCommunities}</div>
455 trendingCommunities(isMobile = false) {
456 switch (this.state.trendingCommunitiesRes?.state) {
464 const trending = this.state.trendingCommunitiesRes.data.communities;
466 <div className={!isMobile ? "mb-2" : ""}>
468 <T i18nKey="trending_communities">
470 <Link className="text-body" to="/communities">
475 <ul className="list-inline mb-0">
476 {trending.map(cv => (
478 key={cv.community.id}
479 className="list-inline-item d-inline-block"
481 <CommunityLink community={cv.community} />
491 get subscribedCommunities() {
492 const { subscribedCollapsed } = this.state;
497 <T class="d-inline" i18nKey="subscribed_to_communities">
499 <Link className="text-body" to="/communities">
504 className="btn btn-sm text-muted"
505 onClick={linkEvent(this, this.handleCollapseSubscribe)}
506 aria-label={i18n.t("collapse")}
507 data-tippy-content={i18n.t("collapse")}
510 icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
511 classes="icon-inline"
515 {!subscribedCollapsed && (
516 <ul className="list-inline mb-0">
517 {UserService.Instance.myUserInfo?.follows.map(cfv => (
519 key={cfv.community.id}
520 className="list-inline-item d-inline-block"
522 <CommunityLink community={cfv.community} />
531 async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
533 dataType: urlDataType,
534 listingType: urlListingType,
537 } = getHomeQueryParams();
539 const queryParams: QueryParams<HomeProps> = {
540 dataType: getDataTypeString(dataType ?? urlDataType),
541 listingType: listingType ?? urlListingType,
542 page: (page ?? urlPage).toString(),
543 sort: sort ?? urlSort,
546 this.props.history.push({
548 search: getQueryString(queryParams),
551 await this.fetchData();
555 const { page } = getHomeQueryParams();
558 <div className="main-content-wrapper">
562 <Paginator page={page} onChange={this.handlePageChange} />
569 const { dataType } = getHomeQueryParams();
570 const siteRes = this.state.siteRes;
572 if (dataType === DataType.Post) {
573 switch (this.state.postsRes?.state) {
581 const posts = this.state.postsRes.data.posts;
587 enableDownvotes={enableDownvotes(siteRes)}
588 enableNsfw={enableNsfw(siteRes)}
589 allLanguages={siteRes.all_languages}
590 siteLanguages={siteRes.discussion_languages}
591 onBlockPerson={this.handleBlockPerson}
592 onPostEdit={this.handlePostEdit}
593 onPostVote={this.handlePostVote}
594 onPostReport={this.handlePostReport}
595 onLockPost={this.handleLockPost}
596 onDeletePost={this.handleDeletePost}
597 onRemovePost={this.handleRemovePost}
598 onSavePost={this.handleSavePost}
599 onPurgePerson={this.handlePurgePerson}
600 onPurgePost={this.handlePurgePost}
601 onBanPerson={this.handleBanPerson}
602 onBanPersonFromCommunity={this.handleBanFromCommunity}
603 onAddModToCommunity={this.handleAddModToCommunity}
604 onAddAdmin={this.handleAddAdmin}
605 onTransferCommunity={this.handleTransferCommunity}
606 onFeaturePost={this.handleFeaturePost}
612 switch (this.state.commentsRes.state) {
620 const comments = this.state.commentsRes.data.comments;
623 nodes={commentsToFlatNodes(comments)}
624 viewType={CommentViewType.Flat}
625 finished={this.state.finished}
629 enableDownvotes={enableDownvotes(siteRes)}
630 allLanguages={siteRes.all_languages}
631 siteLanguages={siteRes.discussion_languages}
632 onSaveComment={this.handleSaveComment}
633 onBlockPerson={this.handleBlockPerson}
634 onDeleteComment={this.handleDeleteComment}
635 onRemoveComment={this.handleRemoveComment}
636 onCommentVote={this.handleCommentVote}
637 onCommentReport={this.handleCommentReport}
638 onDistinguishComment={this.handleDistinguishComment}
639 onAddModToCommunity={this.handleAddModToCommunity}
640 onAddAdmin={this.handleAddAdmin}
641 onTransferCommunity={this.handleTransferCommunity}
642 onPurgeComment={this.handlePurgeComment}
643 onPurgePerson={this.handlePurgePerson}
644 onCommentReplyRead={this.handleCommentReplyRead}
645 onPersonMentionRead={this.handlePersonMentionRead}
646 onBanPersonFromCommunity={this.handleBanFromCommunity}
647 onBanPerson={this.handleBanPerson}
648 onCreateComment={this.handleCreateComment}
649 onEditComment={this.handleEditComment}
658 const { listingType, dataType, sort } = getHomeQueryParams();
661 <div className="mb-3">
662 <span className="mr-3">
665 onChange={this.handleDataTypeChange}
668 <span className="mr-3">
671 showLocal={showLocal(this.isoData)}
673 onChange={this.handleListingTypeChange}
676 <span className="mr-2">
677 <SortSelect sort={sort} onChange={this.handleSortChange} />
679 {this.getRss(listingType)}
684 getRss(listingType: ListingType) {
685 const { sort } = getHomeQueryParams();
686 const auth = myAuth();
688 let rss: string | undefined = undefined;
690 switch (listingType) {
692 rss = `/feeds/all.xml?sort=${sort}`;
696 rss = `/feeds/local.xml?sort=${sort}`;
700 rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
708 <a href={rss} rel={relTags} title="RSS">
709 <Icon icon="rss" classes="text-muted small" />
711 <link rel="alternate" type="application/atom+xml" href={rss} />
717 async fetchTrendingCommunities() {
718 this.setState({ trendingCommunitiesRes: { state: "loading" } });
720 trendingCommunitiesRes: await HttpService.client.listCommunities({
723 limit: trendingFetchLimit,
730 const auth = myAuth();
731 const { dataType, page, listingType, sort } = getHomeQueryParams();
733 if (dataType === DataType.Post) {
734 this.setState({ postsRes: { state: "loading" } });
736 postsRes: await HttpService.client.getPosts({
746 this.setState({ commentsRes: { state: "loading" } });
748 commentsRes: await HttpService.client.getComments({
751 sort: postToCommentSortType(sort),
759 restoreScrollPosition(this.context);
763 handleShowSubscribedMobile(i: Home) {
764 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
767 handleShowTrendingMobile(i: Home) {
768 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
771 handleShowSidebarMobile(i: Home) {
772 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
775 handleCollapseSubscribe(i: Home) {
776 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
779 handlePageChange(page: number) {
780 this.updateUrl({ page });
781 window.scrollTo(0, 0);
784 handleSortChange(val: SortType) {
785 this.updateUrl({ sort: val, page: 1 });
786 window.scrollTo(0, 0);
789 handleListingTypeChange(val: ListingType) {
790 this.updateUrl({ listingType: val, page: 1 });
791 window.scrollTo(0, 0);
794 handleDataTypeChange(val: DataType) {
795 this.updateUrl({ dataType: val, page: 1 });
796 window.scrollTo(0, 0);
799 async handleAddModToCommunity(form: AddModToCommunity) {
800 // TODO not sure what to do here
801 await HttpService.client.addModToCommunity(form);
804 async handlePurgePerson(form: PurgePerson) {
805 const purgePersonRes = await HttpService.client.purgePerson(form);
806 this.purgeItem(purgePersonRes);
809 async handlePurgeComment(form: PurgeComment) {
810 const purgeCommentRes = await HttpService.client.purgeComment(form);
811 this.purgeItem(purgeCommentRes);
814 async handlePurgePost(form: PurgePost) {
815 const purgeRes = await HttpService.client.purgePost(form);
816 this.purgeItem(purgeRes);
819 async handleBlockPerson(form: BlockPerson) {
820 const blockPersonRes = await HttpService.client.blockPerson(form);
821 if (blockPersonRes.state == "success") {
822 updatePersonBlock(blockPersonRes.data);
826 async handleCreateComment(form: CreateComment) {
827 const createCommentRes = await HttpService.client.createComment(form);
828 this.createAndUpdateComments(createCommentRes);
830 return createCommentRes;
833 async handleEditComment(form: EditComment) {
834 const editCommentRes = await HttpService.client.editComment(form);
835 this.findAndUpdateComment(editCommentRes);
837 return editCommentRes;
840 async handleDeleteComment(form: DeleteComment) {
841 const deleteCommentRes = await HttpService.client.deleteComment(form);
842 this.findAndUpdateComment(deleteCommentRes);
845 async handleDeletePost(form: DeletePost) {
846 const deleteRes = await HttpService.client.deletePost(form);
847 this.findAndUpdatePost(deleteRes);
850 async handleRemovePost(form: RemovePost) {
851 const removeRes = await HttpService.client.removePost(form);
852 this.findAndUpdatePost(removeRes);
855 async handleRemoveComment(form: RemoveComment) {
856 const removeCommentRes = await HttpService.client.removeComment(form);
857 this.findAndUpdateComment(removeCommentRes);
860 async handleSaveComment(form: SaveComment) {
861 const saveCommentRes = await HttpService.client.saveComment(form);
862 this.findAndUpdateComment(saveCommentRes);
865 async handleSavePost(form: SavePost) {
866 const saveRes = await HttpService.client.savePost(form);
867 this.findAndUpdatePost(saveRes);
870 async handleFeaturePost(form: FeaturePost) {
871 const featureRes = await HttpService.client.featurePost(form);
872 this.findAndUpdatePost(featureRes);
875 async handleCommentVote(form: CreateCommentLike) {
876 const voteRes = await HttpService.client.likeComment(form);
877 this.findAndUpdateComment(voteRes);
880 async handlePostEdit(form: EditPost) {
881 const res = await HttpService.client.editPost(form);
882 this.findAndUpdatePost(res);
885 async handlePostVote(form: CreatePostLike) {
886 const voteRes = await HttpService.client.likePost(form);
887 this.findAndUpdatePost(voteRes);
890 async handleCommentReport(form: CreateCommentReport) {
891 const reportRes = await HttpService.client.createCommentReport(form);
892 if (reportRes.state == "success") {
893 toast(i18n.t("report_created"));
897 async handlePostReport(form: CreatePostReport) {
898 const reportRes = await HttpService.client.createPostReport(form);
899 if (reportRes.state == "success") {
900 toast(i18n.t("report_created"));
904 async handleLockPost(form: LockPost) {
905 const lockRes = await HttpService.client.lockPost(form);
906 this.findAndUpdatePost(lockRes);
909 async handleDistinguishComment(form: DistinguishComment) {
910 const distinguishRes = await HttpService.client.distinguishComment(form);
911 this.findAndUpdateComment(distinguishRes);
914 async handleAddAdmin(form: AddAdmin) {
915 const addAdminRes = await HttpService.client.addAdmin(form);
917 if (addAdminRes.state == "success") {
918 this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
922 async handleTransferCommunity(form: TransferCommunity) {
923 await HttpService.client.transferCommunity(form);
924 toast(i18n.t("transfer_community"));
927 async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
928 const readRes = await HttpService.client.markCommentReplyAsRead(form);
929 this.findAndUpdateCommentReply(readRes);
932 async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
933 // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
934 await HttpService.client.markPersonMentionAsRead(form);
937 async handleBanFromCommunity(form: BanFromCommunity) {
938 const banRes = await HttpService.client.banFromCommunity(form);
939 this.updateBanFromCommunity(banRes);
942 async handleBanPerson(form: BanPerson) {
943 const banRes = await HttpService.client.banPerson(form);
944 this.updateBan(banRes);
947 updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
948 // Maybe not necessary
949 if (banRes.state == "success") {
951 if (s.postsRes.state == "success") {
952 s.postsRes.data.posts
953 .filter(c => c.creator.id == banRes.data.person_view.person.id)
955 c => (c.creator_banned_from_community = banRes.data.banned)
958 if (s.commentsRes.state == "success") {
959 s.commentsRes.data.comments
960 .filter(c => c.creator.id == banRes.data.person_view.person.id)
962 c => (c.creator_banned_from_community = banRes.data.banned)
970 updateBan(banRes: RequestState<BanPersonResponse>) {
971 // Maybe not necessary
972 if (banRes.state == "success") {
974 if (s.postsRes.state == "success") {
975 s.postsRes.data.posts
976 .filter(c => c.creator.id == banRes.data.person_view.person.id)
977 .forEach(c => (c.creator.banned = banRes.data.banned));
979 if (s.commentsRes.state == "success") {
980 s.commentsRes.data.comments
981 .filter(c => c.creator.id == banRes.data.person_view.person.id)
982 .forEach(c => (c.creator.banned = banRes.data.banned));
989 purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
990 if (purgeRes.state == "success") {
991 toast(i18n.t("purge_success"));
992 this.context.router.history.push(`/`);
996 findAndUpdateComment(res: RequestState<CommentResponse>) {
998 if (s.commentsRes.state == "success" && res.state == "success") {
999 s.commentsRes.data.comments = editComment(
1000 res.data.comment_view,
1001 s.commentsRes.data.comments
1003 s.finished.set(res.data.comment_view.comment.id, true);
1009 createAndUpdateComments(res: RequestState<CommentResponse>) {
1010 this.setState(s => {
1011 if (s.commentsRes.state == "success" && res.state == "success") {
1012 s.commentsRes.data.comments.unshift(res.data.comment_view);
1014 // Set finished for the parent
1016 getCommentParentId(res.data.comment_view.comment) ?? 0,
1024 findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1025 this.setState(s => {
1026 if (s.commentsRes.state == "success" && res.state == "success") {
1027 s.commentsRes.data.comments = editWith(
1028 res.data.comment_reply_view,
1029 s.commentsRes.data.comments
1036 findAndUpdatePost(res: RequestState<PostResponse>) {
1037 this.setState(s => {
1038 if (s.postsRes.state == "success" && res.state == "success") {
1039 s.postsRes.data.posts = editPost(
1041 s.postsRes.data.posts