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 || !this.isoData.routeData.length) {
270 await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
276 componentWillUnmount() {
277 saveScrollPosition(this.context);
280 static async fetchInitialData({
283 query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
284 }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<HomeData> {
285 const dataType = getDataTypeFromQuery(urlDataType);
287 // TODO figure out auth default_listingType, default_sort_type
288 const type_ = getListingTypeFromQuery(listingType);
289 const sort = getSortTypeFromQuery(urlSort);
291 const page = urlPage ? Number(urlPage) : 1;
293 let postsResponse: RequestState<GetPostsResponse> | undefined = undefined;
294 let commentsResponse: RequestState<GetCommentsResponse> | undefined =
297 if (dataType === DataType.Post) {
298 const getPostsForm: GetPosts = {
307 postsResponse = await client.getPosts(getPostsForm);
309 const getCommentsForm: GetComments = {
312 sort: postToCommentSortType(sort),
318 commentsResponse = await client.getComments(getCommentsForm);
321 const trendingCommunitiesForm: ListCommunities = {
324 limit: trendingFetchLimit,
329 trendingResponse: await client.listCommunities(trendingCommunitiesForm),
335 get documentTitle(): string {
336 const { name, description } = this.state.siteRes.site_view.site;
338 return description ? `${name} - ${description}` : name;
346 local_site: { site_setup },
352 <div className="container-lg">
354 title={this.documentTitle}
355 path={this.context.router.route.match.url}
358 <div className="row">
359 <main role="main" className="col-12 col-md-8">
363 dangerouslySetInnerHTML={mdToHtml(tagline)}
366 <div className="d-block d-md-none">{this.mobileView}</div>
369 <aside className="d-none d-md-block col-md-4">
378 get hasFollows(): boolean {
379 const mui = UserService.Instance.myUserInfo;
380 return !!mui && mui.follows.length > 0;
386 site_view: { counts, site },
390 showSubscribedMobile,
396 <div className="row">
397 <div className="col-12">
398 {this.hasFollows && (
401 show={showSubscribedMobile}
402 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
407 show={showTrendingMobile}
408 onClick={linkEvent(this, this.handleShowTrendingMobile)}
412 show={showSidebarMobile}
413 onClick={linkEvent(this, this.handleShowSidebarMobile)}
415 {showSidebarMobile && (
421 showLocal={showLocal(this.isoData)}
424 {showTrendingMobile && (
425 <div className="col-12 card border-secondary mb-3">
426 <div className="card-body">{this.trendingCommunities(true)}</div>
429 {showSubscribedMobile && (
430 <div className="col-12 card border-secondary mb-3">
431 <div className="card-body">{this.subscribedCommunities}</div>
442 site_view: { counts, site },
451 <div className="card border-secondary mb-3">
452 <div className="card-body">
453 {this.trendingCommunities()}
454 {canCreateCommunity(this.state.siteRes) && (
456 path="/create_community"
457 translationKey="create_a_community"
462 translationKey="explore_communities"
471 showLocal={showLocal(this.isoData)}
473 {this.hasFollows && (
474 <div className="card border-secondary mb-3">
475 <div className="card-body">{this.subscribedCommunities}</div>
483 trendingCommunities(isMobile = false) {
484 switch (this.state.trendingCommunitiesRes?.state) {
492 const trending = this.state.trendingCommunitiesRes.data.communities;
494 <div className={!isMobile ? "mb-2" : ""}>
496 <T i18nKey="trending_communities">
498 <Link className="text-body" to="/communities">
503 <ul className="list-inline mb-0">
504 {trending.map(cv => (
506 key={cv.community.id}
507 className="list-inline-item d-inline-block"
509 <CommunityLink community={cv.community} />
519 get subscribedCommunities() {
520 const { subscribedCollapsed } = this.state;
525 <T class="d-inline" i18nKey="subscribed_to_communities">
527 <Link className="text-body" to="/communities">
532 className="btn btn-sm text-muted"
533 onClick={linkEvent(this, this.handleCollapseSubscribe)}
534 aria-label={i18n.t("collapse")}
535 data-tippy-content={i18n.t("collapse")}
538 icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
539 classes="icon-inline"
543 {!subscribedCollapsed && (
544 <ul className="list-inline mb-0">
545 {UserService.Instance.myUserInfo?.follows.map(cfv => (
547 key={cfv.community.id}
548 className="list-inline-item d-inline-block"
550 <CommunityLink community={cfv.community} />
559 async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
561 dataType: urlDataType,
562 listingType: urlListingType,
565 } = getHomeQueryParams();
567 const queryParams: QueryParams<HomeProps> = {
568 dataType: getDataTypeString(dataType ?? urlDataType),
569 listingType: listingType ?? urlListingType,
570 page: (page ?? urlPage).toString(),
571 sort: sort ?? urlSort,
574 this.props.history.push({
576 search: getQueryString(queryParams),
579 await this.fetchData();
583 const { page } = getHomeQueryParams();
586 <div className="main-content-wrapper">
590 <Paginator page={page} onChange={this.handlePageChange} />
597 const { dataType } = getHomeQueryParams();
598 const siteRes = this.state.siteRes;
600 if (dataType === DataType.Post) {
601 switch (this.state.postsRes?.state) {
609 const posts = this.state.postsRes.data.posts;
615 enableDownvotes={enableDownvotes(siteRes)}
616 enableNsfw={enableNsfw(siteRes)}
617 allLanguages={siteRes.all_languages}
618 siteLanguages={siteRes.discussion_languages}
619 onBlockPerson={this.handleBlockPerson}
620 onPostEdit={this.handlePostEdit}
621 onPostVote={this.handlePostVote}
622 onPostReport={this.handlePostReport}
623 onLockPost={this.handleLockPost}
624 onDeletePost={this.handleDeletePost}
625 onRemovePost={this.handleRemovePost}
626 onSavePost={this.handleSavePost}
627 onPurgePerson={this.handlePurgePerson}
628 onPurgePost={this.handlePurgePost}
629 onBanPerson={this.handleBanPerson}
630 onBanPersonFromCommunity={this.handleBanFromCommunity}
631 onAddModToCommunity={this.handleAddModToCommunity}
632 onAddAdmin={this.handleAddAdmin}
633 onTransferCommunity={this.handleTransferCommunity}
634 onFeaturePost={this.handleFeaturePost}
640 switch (this.state.commentsRes.state) {
648 const comments = this.state.commentsRes.data.comments;
651 nodes={commentsToFlatNodes(comments)}
652 viewType={CommentViewType.Flat}
653 finished={this.state.finished}
657 enableDownvotes={enableDownvotes(siteRes)}
658 allLanguages={siteRes.all_languages}
659 siteLanguages={siteRes.discussion_languages}
660 onSaveComment={this.handleSaveComment}
661 onBlockPerson={this.handleBlockPerson}
662 onDeleteComment={this.handleDeleteComment}
663 onRemoveComment={this.handleRemoveComment}
664 onCommentVote={this.handleCommentVote}
665 onCommentReport={this.handleCommentReport}
666 onDistinguishComment={this.handleDistinguishComment}
667 onAddModToCommunity={this.handleAddModToCommunity}
668 onAddAdmin={this.handleAddAdmin}
669 onTransferCommunity={this.handleTransferCommunity}
670 onPurgeComment={this.handlePurgeComment}
671 onPurgePerson={this.handlePurgePerson}
672 onCommentReplyRead={this.handleCommentReplyRead}
673 onPersonMentionRead={this.handlePersonMentionRead}
674 onBanPersonFromCommunity={this.handleBanFromCommunity}
675 onBanPerson={this.handleBanPerson}
676 onCreateComment={this.handleCreateComment}
677 onEditComment={this.handleEditComment}
686 const { listingType, dataType, sort } = getHomeQueryParams();
689 <div className="mb-3">
690 <span className="mr-3">
693 onChange={this.handleDataTypeChange}
696 <span className="mr-3">
699 showLocal={showLocal(this.isoData)}
701 onChange={this.handleListingTypeChange}
704 <span className="mr-2">
705 <SortSelect sort={sort} onChange={this.handleSortChange} />
707 {this.getRss(listingType)}
712 getRss(listingType: ListingType) {
713 const { sort } = getHomeQueryParams();
714 const auth = myAuth();
716 let rss: string | undefined = undefined;
718 switch (listingType) {
720 rss = `/feeds/all.xml?sort=${sort}`;
724 rss = `/feeds/local.xml?sort=${sort}`;
728 rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
736 <a href={rss} rel={relTags} title="RSS">
737 <Icon icon="rss" classes="text-muted small" />
739 <link rel="alternate" type="application/atom+xml" href={rss} />
745 async fetchTrendingCommunities() {
746 this.setState({ trendingCommunitiesRes: { state: "loading" } });
748 trendingCommunitiesRes: await HttpService.client.listCommunities({
751 limit: trendingFetchLimit,
758 const auth = myAuth();
759 const { dataType, page, listingType, sort } = getHomeQueryParams();
761 if (dataType === DataType.Post) {
762 this.setState({ postsRes: { state: "loading" } });
764 postsRes: await HttpService.client.getPosts({
774 this.setState({ commentsRes: { state: "loading" } });
776 commentsRes: await HttpService.client.getComments({
779 sort: postToCommentSortType(sort),
787 restoreScrollPosition(this.context);
791 handleShowSubscribedMobile(i: Home) {
792 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
795 handleShowTrendingMobile(i: Home) {
796 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
799 handleShowSidebarMobile(i: Home) {
800 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
803 handleCollapseSubscribe(i: Home) {
804 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
807 handlePageChange(page: number) {
808 this.updateUrl({ page });
809 window.scrollTo(0, 0);
812 handleSortChange(val: SortType) {
813 this.updateUrl({ sort: val, page: 1 });
814 window.scrollTo(0, 0);
817 handleListingTypeChange(val: ListingType) {
818 this.updateUrl({ listingType: val, page: 1 });
819 window.scrollTo(0, 0);
822 handleDataTypeChange(val: DataType) {
823 this.updateUrl({ dataType: val, page: 1 });
824 window.scrollTo(0, 0);
827 async handleAddModToCommunity(form: AddModToCommunity) {
828 // TODO not sure what to do here
829 await HttpService.client.addModToCommunity(form);
832 async handlePurgePerson(form: PurgePerson) {
833 const purgePersonRes = await HttpService.client.purgePerson(form);
834 this.purgeItem(purgePersonRes);
837 async handlePurgeComment(form: PurgeComment) {
838 const purgeCommentRes = await HttpService.client.purgeComment(form);
839 this.purgeItem(purgeCommentRes);
842 async handlePurgePost(form: PurgePost) {
843 const purgeRes = await HttpService.client.purgePost(form);
844 this.purgeItem(purgeRes);
847 async handleBlockPerson(form: BlockPerson) {
848 const blockPersonRes = await HttpService.client.blockPerson(form);
849 if (blockPersonRes.state == "success") {
850 updatePersonBlock(blockPersonRes.data);
854 async handleCreateComment(form: CreateComment) {
855 const createCommentRes = await HttpService.client.createComment(form);
856 this.createAndUpdateComments(createCommentRes);
858 return createCommentRes;
861 async handleEditComment(form: EditComment) {
862 const editCommentRes = await HttpService.client.editComment(form);
863 this.findAndUpdateComment(editCommentRes);
865 return editCommentRes;
868 async handleDeleteComment(form: DeleteComment) {
869 const deleteCommentRes = await HttpService.client.deleteComment(form);
870 this.findAndUpdateComment(deleteCommentRes);
873 async handleDeletePost(form: DeletePost) {
874 const deleteRes = await HttpService.client.deletePost(form);
875 this.findAndUpdatePost(deleteRes);
878 async handleRemovePost(form: RemovePost) {
879 const removeRes = await HttpService.client.removePost(form);
880 this.findAndUpdatePost(removeRes);
883 async handleRemoveComment(form: RemoveComment) {
884 const removeCommentRes = await HttpService.client.removeComment(form);
885 this.findAndUpdateComment(removeCommentRes);
888 async handleSaveComment(form: SaveComment) {
889 const saveCommentRes = await HttpService.client.saveComment(form);
890 this.findAndUpdateComment(saveCommentRes);
893 async handleSavePost(form: SavePost) {
894 const saveRes = await HttpService.client.savePost(form);
895 this.findAndUpdatePost(saveRes);
898 async handleFeaturePost(form: FeaturePost) {
899 const featureRes = await HttpService.client.featurePost(form);
900 this.findAndUpdatePost(featureRes);
903 async handleCommentVote(form: CreateCommentLike) {
904 const voteRes = await HttpService.client.likeComment(form);
905 this.findAndUpdateComment(voteRes);
908 async handlePostEdit(form: EditPost) {
909 const res = await HttpService.client.editPost(form);
910 this.findAndUpdatePost(res);
913 async handlePostVote(form: CreatePostLike) {
914 const voteRes = await HttpService.client.likePost(form);
915 this.findAndUpdatePost(voteRes);
918 async handleCommentReport(form: CreateCommentReport) {
919 const reportRes = await HttpService.client.createCommentReport(form);
920 if (reportRes.state == "success") {
921 toast(i18n.t("report_created"));
925 async handlePostReport(form: CreatePostReport) {
926 const reportRes = await HttpService.client.createPostReport(form);
927 if (reportRes.state == "success") {
928 toast(i18n.t("report_created"));
932 async handleLockPost(form: LockPost) {
933 const lockRes = await HttpService.client.lockPost(form);
934 this.findAndUpdatePost(lockRes);
937 async handleDistinguishComment(form: DistinguishComment) {
938 const distinguishRes = await HttpService.client.distinguishComment(form);
939 this.findAndUpdateComment(distinguishRes);
942 async handleAddAdmin(form: AddAdmin) {
943 const addAdminRes = await HttpService.client.addAdmin(form);
945 if (addAdminRes.state == "success") {
946 this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
950 async handleTransferCommunity(form: TransferCommunity) {
951 await HttpService.client.transferCommunity(form);
952 toast(i18n.t("transfer_community"));
955 async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
956 const readRes = await HttpService.client.markCommentReplyAsRead(form);
957 this.findAndUpdateCommentReply(readRes);
960 async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
961 // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
962 await HttpService.client.markPersonMentionAsRead(form);
965 async handleBanFromCommunity(form: BanFromCommunity) {
966 const banRes = await HttpService.client.banFromCommunity(form);
967 this.updateBanFromCommunity(banRes);
970 async handleBanPerson(form: BanPerson) {
971 const banRes = await HttpService.client.banPerson(form);
972 this.updateBan(banRes);
975 updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
976 // Maybe not necessary
977 if (banRes.state == "success") {
979 if (s.postsRes.state == "success") {
980 s.postsRes.data.posts
981 .filter(c => c.creator.id == banRes.data.person_view.person.id)
983 c => (c.creator_banned_from_community = banRes.data.banned)
986 if (s.commentsRes.state == "success") {
987 s.commentsRes.data.comments
988 .filter(c => c.creator.id == banRes.data.person_view.person.id)
990 c => (c.creator_banned_from_community = banRes.data.banned)
998 updateBan(banRes: RequestState<BanPersonResponse>) {
999 // Maybe not necessary
1000 if (banRes.state == "success") {
1001 this.setState(s => {
1002 if (s.postsRes.state == "success") {
1003 s.postsRes.data.posts
1004 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1005 .forEach(c => (c.creator.banned = banRes.data.banned));
1007 if (s.commentsRes.state == "success") {
1008 s.commentsRes.data.comments
1009 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1010 .forEach(c => (c.creator.banned = banRes.data.banned));
1017 purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
1018 if (purgeRes.state == "success") {
1019 toast(i18n.t("purge_success"));
1020 this.context.router.history.push(`/`);
1024 findAndUpdateComment(res: RequestState<CommentResponse>) {
1025 this.setState(s => {
1026 if (s.commentsRes.state == "success" && res.state == "success") {
1027 s.commentsRes.data.comments = editComment(
1028 res.data.comment_view,
1029 s.commentsRes.data.comments
1031 s.finished.set(res.data.comment_view.comment.id, true);
1037 createAndUpdateComments(res: RequestState<CommentResponse>) {
1038 this.setState(s => {
1039 if (s.commentsRes.state == "success" && res.state == "success") {
1040 s.commentsRes.data.comments.unshift(res.data.comment_view);
1042 // Set finished for the parent
1044 getCommentParentId(res.data.comment_view.comment) ?? 0,
1052 findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1053 this.setState(s => {
1054 if (s.commentsRes.state == "success" && res.state == "success") {
1055 s.commentsRes.data.comments = editWith(
1056 res.data.comment_reply_view,
1057 s.commentsRes.data.comments
1064 findAndUpdatePost(res: RequestState<PostResponse>) {
1065 this.setState(s => {
1066 if (s.postsRes.state == "success" && res.state == "success") {
1067 s.postsRes.data.posts = editPost(
1069 s.postsRes.data.posts