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 getRss(listingType: ListingType) {
128 const { sort } = getHomeQueryParams();
129 const auth = myAuth();
131 let rss: string | undefined = undefined;
133 switch (listingType) {
135 rss = `/feeds/all.xml?sort=${sort}`;
139 rss = `/feeds/local.xml?sort=${sort}`;
143 rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
151 <a href={rss} rel={relTags} title="RSS">
152 <Icon icon="rss" classes="text-muted small" />
154 <link rel="alternate" type="application/atom+xml" href={rss} />
160 function getDataTypeFromQuery(type?: string): DataType {
161 return type ? DataType[type] : DataType.Post;
164 function getListingTypeFromQuery(type?: string): ListingType {
165 const myListingType =
166 UserService.Instance.myUserInfo?.local_user_view?.local_user
167 ?.default_listing_type;
169 return (type ? (type as ListingType) : myListingType) ?? "Local";
172 function getSortTypeFromQuery(type?: string): SortType {
174 UserService.Instance.myUserInfo?.local_user_view?.local_user
177 return (type ? (type as SortType) : mySortType) ?? "Active";
180 const getHomeQueryParams = () =>
181 getQueryParams<HomeProps>({
182 sort: getSortTypeFromQuery,
183 listingType: getListingTypeFromQuery,
184 page: getPageFromString,
185 dataType: getDataTypeFromQuery,
188 const MobileButton = ({
193 textKey: NoOptionI18nKeys;
195 onClick: MouseEventHandler<HTMLButtonElement>;
198 className="btn btn-secondary d-inline-block mb-2 mr-3"
201 {i18n.t(textKey)}{" "}
202 <Icon icon={show ? `minus-square` : `plus-square`} classes="icon-inline" />
206 const LinkButton = ({
211 translationKey: NoOptionI18nKeys;
213 <Link className="btn btn-secondary btn-block" to={path}>
214 {i18n.t(translationKey)}
218 export class Home extends Component<any, HomeState> {
219 private isoData = setIsoData<HomeData>(this.context);
221 postsRes: { state: "empty" },
222 commentsRes: { state: "empty" },
223 trendingCommunitiesRes: { state: "empty" },
224 siteRes: this.isoData.site_res,
225 showSubscribedMobile: false,
226 showTrendingMobile: false,
227 showSidebarMobile: false,
228 subscribedCollapsed: false,
233 constructor(props: any, context: any) {
234 super(props, context);
236 this.handleSortChange = this.handleSortChange.bind(this);
237 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
238 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
239 this.handlePageChange = this.handlePageChange.bind(this);
241 this.handleCreateComment = this.handleCreateComment.bind(this);
242 this.handleEditComment = this.handleEditComment.bind(this);
243 this.handleSaveComment = this.handleSaveComment.bind(this);
244 this.handleBlockPerson = this.handleBlockPerson.bind(this);
245 this.handleDeleteComment = this.handleDeleteComment.bind(this);
246 this.handleRemoveComment = this.handleRemoveComment.bind(this);
247 this.handleCommentVote = this.handleCommentVote.bind(this);
248 this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
249 this.handleAddAdmin = this.handleAddAdmin.bind(this);
250 this.handlePurgePerson = this.handlePurgePerson.bind(this);
251 this.handlePurgeComment = this.handlePurgeComment.bind(this);
252 this.handleCommentReport = this.handleCommentReport.bind(this);
253 this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
254 this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
255 this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
256 this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
257 this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
258 this.handleBanPerson = this.handleBanPerson.bind(this);
259 this.handlePostEdit = this.handlePostEdit.bind(this);
260 this.handlePostVote = this.handlePostVote.bind(this);
261 this.handlePostReport = this.handlePostReport.bind(this);
262 this.handleLockPost = this.handleLockPost.bind(this);
263 this.handleDeletePost = this.handleDeletePost.bind(this);
264 this.handleRemovePost = this.handleRemovePost.bind(this);
265 this.handleSavePost = this.handleSavePost.bind(this);
266 this.handlePurgePost = this.handlePurgePost.bind(this);
267 this.handleFeaturePost = this.handleFeaturePost.bind(this);
269 // Only fetch the data if coming from another route
270 if (FirstLoadService.isFirstLoad) {
271 const { trendingCommunitiesRes, commentsRes, postsRes } =
272 this.isoData.routeData;
276 trendingCommunitiesRes,
279 tagline: getRandomFromList(this.state?.siteRes?.taglines ?? [])
286 async componentDidMount() {
288 !this.state.isIsomorphic ||
289 !Object.values(this.isoData.routeData).some(
290 res => res.state === "success" || res.state === "failed"
293 await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
299 componentWillUnmount() {
300 saveScrollPosition(this.context);
303 static async fetchInitialData({
306 query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
307 }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<HomeData> {
308 const dataType = getDataTypeFromQuery(urlDataType);
310 // TODO figure out auth default_listingType, default_sort_type
311 const type_ = getListingTypeFromQuery(listingType);
312 const sort = getSortTypeFromQuery(urlSort);
314 const page = urlPage ? Number(urlPage) : 1;
316 let postsRes: RequestState<GetPostsResponse> = { state: "empty" };
317 let commentsRes: RequestState<GetCommentsResponse> = {
321 if (dataType === DataType.Post) {
322 const getPostsForm: GetPosts = {
331 postsRes = await client.getPosts(getPostsForm);
333 const getCommentsForm: GetComments = {
336 sort: postToCommentSortType(sort),
342 commentsRes = await client.getComments(getCommentsForm);
345 const trendingCommunitiesForm: ListCommunities = {
348 limit: trendingFetchLimit,
353 trendingCommunitiesRes: await client.listCommunities(
354 trendingCommunitiesForm
361 get documentTitle(): string {
362 const { name, description } = this.state.siteRes.site_view.site;
364 return description ? `${name} - ${description}` : name;
372 local_site: { site_setup },
378 <div className="container-lg">
380 title={this.documentTitle}
381 path={this.context.router.route.match.url}
384 <div className="row">
385 <main role="main" className="col-12 col-md-8">
389 dangerouslySetInnerHTML={mdToHtml(tagline)}
392 <div className="d-block d-md-none">{this.mobileView}</div>
395 <aside className="d-none d-md-block col-md-4">
404 get hasFollows(): boolean {
405 const mui = UserService.Instance.myUserInfo;
406 return !!mui && mui.follows.length > 0;
412 site_view: { counts, site },
415 showSubscribedMobile,
421 <div className="row">
422 <div className="col-12">
423 {this.hasFollows && (
426 show={showSubscribedMobile}
427 onClick={linkEvent(this, this.handleShowSubscribedMobile)}
432 show={showTrendingMobile}
433 onClick={linkEvent(this, this.handleShowTrendingMobile)}
437 show={showSidebarMobile}
438 onClick={linkEvent(this, this.handleShowSidebarMobile)}
440 {showSidebarMobile && (
445 showLocal={showLocal(this.isoData)}
448 {showTrendingMobile && (
449 <div className="col-12 card border-secondary mb-3">
450 <div className="card-body">{this.trendingCommunities(true)}</div>
453 {showSubscribedMobile && (
454 <div className="col-12 card border-secondary mb-3">
455 <div className="card-body">{this.subscribedCommunities}</div>
466 site_view: { counts, site },
472 <div id="sidebarContainer">
473 <section id="sidebarMain" className="card border-secondary mb-3">
474 <div className="card-body">
475 {this.trendingCommunities()}
476 {canCreateCommunity(this.state.siteRes) && (
478 path="/create_community"
479 translationKey="create_a_community"
484 translationKey="explore_communities"
492 showLocal={showLocal(this.isoData)}
494 {this.hasFollows && (
496 id="sidebarSubscribed"
497 className="card border-secondary mb-3"
499 <div className="card-body">{this.subscribedCommunities}</div>
506 trendingCommunities(isMobile = false) {
507 switch (this.state.trendingCommunitiesRes?.state) {
515 const trending = this.state.trendingCommunitiesRes.data.communities;
517 <div className={!isMobile ? "mb-2" : ""}>
519 <T i18nKey="trending_communities">
521 <Link className="text-body" to="/communities">
526 <ul className="list-inline mb-0">
527 {trending.map(cv => (
529 key={cv.community.id}
530 className="list-inline-item d-inline-block"
532 <CommunityLink community={cv.community} />
542 get subscribedCommunities() {
543 const { subscribedCollapsed } = this.state;
548 <T class="d-inline" i18nKey="subscribed_to_communities">
550 <Link className="text-body" to="/communities">
555 className="btn btn-sm text-muted"
556 onClick={linkEvent(this, this.handleCollapseSubscribe)}
557 aria-label={i18n.t("collapse")}
558 data-tippy-content={i18n.t("collapse")}
561 icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
562 classes="icon-inline"
566 {!subscribedCollapsed && (
567 <ul className="list-inline mb-0">
568 {UserService.Instance.myUserInfo?.follows.map(cfv => (
570 key={cfv.community.id}
571 className="list-inline-item d-inline-block"
573 <CommunityLink community={cfv.community} />
582 async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
584 dataType: urlDataType,
585 listingType: urlListingType,
588 } = getHomeQueryParams();
590 const queryParams: QueryParams<HomeProps> = {
591 dataType: getDataTypeString(dataType ?? urlDataType),
592 listingType: listingType ?? urlListingType,
593 page: (page ?? urlPage).toString(),
594 sort: sort ?? urlSort,
597 this.props.history.push({
599 search: getQueryString(queryParams),
602 await this.fetchData();
606 const { page } = getHomeQueryParams();
609 <div className="main-content-wrapper">
613 <Paginator page={page} onChange={this.handlePageChange} />
620 const { dataType } = getHomeQueryParams();
621 const siteRes = this.state.siteRes;
623 if (dataType === DataType.Post) {
624 switch (this.state.postsRes.state) {
632 const posts = this.state.postsRes.data.posts;
638 enableDownvotes={enableDownvotes(siteRes)}
639 enableNsfw={enableNsfw(siteRes)}
640 allLanguages={siteRes.all_languages}
641 siteLanguages={siteRes.discussion_languages}
642 onBlockPerson={this.handleBlockPerson}
643 onPostEdit={this.handlePostEdit}
644 onPostVote={this.handlePostVote}
645 onPostReport={this.handlePostReport}
646 onLockPost={this.handleLockPost}
647 onDeletePost={this.handleDeletePost}
648 onRemovePost={this.handleRemovePost}
649 onSavePost={this.handleSavePost}
650 onPurgePerson={this.handlePurgePerson}
651 onPurgePost={this.handlePurgePost}
652 onBanPerson={this.handleBanPerson}
653 onBanPersonFromCommunity={this.handleBanFromCommunity}
654 onAddModToCommunity={this.handleAddModToCommunity}
655 onAddAdmin={this.handleAddAdmin}
656 onTransferCommunity={this.handleTransferCommunity}
657 onFeaturePost={this.handleFeaturePost}
663 switch (this.state.commentsRes.state) {
671 const comments = this.state.commentsRes.data.comments;
674 nodes={commentsToFlatNodes(comments)}
675 viewType={CommentViewType.Flat}
676 finished={this.state.finished}
680 enableDownvotes={enableDownvotes(siteRes)}
681 allLanguages={siteRes.all_languages}
682 siteLanguages={siteRes.discussion_languages}
683 onSaveComment={this.handleSaveComment}
684 onBlockPerson={this.handleBlockPerson}
685 onDeleteComment={this.handleDeleteComment}
686 onRemoveComment={this.handleRemoveComment}
687 onCommentVote={this.handleCommentVote}
688 onCommentReport={this.handleCommentReport}
689 onDistinguishComment={this.handleDistinguishComment}
690 onAddModToCommunity={this.handleAddModToCommunity}
691 onAddAdmin={this.handleAddAdmin}
692 onTransferCommunity={this.handleTransferCommunity}
693 onPurgeComment={this.handlePurgeComment}
694 onPurgePerson={this.handlePurgePerson}
695 onCommentReplyRead={this.handleCommentReplyRead}
696 onPersonMentionRead={this.handlePersonMentionRead}
697 onBanPersonFromCommunity={this.handleBanFromCommunity}
698 onBanPerson={this.handleBanPerson}
699 onCreateComment={this.handleCreateComment}
700 onEditComment={this.handleEditComment}
709 const { listingType, dataType, sort } = getHomeQueryParams();
712 <div className="mb-3">
713 <span className="mr-3">
716 onChange={this.handleDataTypeChange}
719 <span className="mr-3">
722 showLocal={showLocal(this.isoData)}
724 onChange={this.handleListingTypeChange}
727 <span className="mr-2">
728 <SortSelect sort={sort} onChange={this.handleSortChange} />
730 {getRss(listingType)}
735 async fetchTrendingCommunities() {
736 this.setState({ trendingCommunitiesRes: { state: "loading" } });
738 trendingCommunitiesRes: await HttpService.client.listCommunities({
741 limit: trendingFetchLimit,
748 const auth = myAuth();
749 const { dataType, page, listingType, sort } = getHomeQueryParams();
751 if (dataType === DataType.Post) {
752 this.setState({ postsRes: { state: "loading" } });
754 postsRes: await HttpService.client.getPosts({
764 this.setState({ commentsRes: { state: "loading" } });
766 commentsRes: await HttpService.client.getComments({
769 sort: postToCommentSortType(sort),
777 restoreScrollPosition(this.context);
781 handleShowSubscribedMobile(i: Home) {
782 i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
785 handleShowTrendingMobile(i: Home) {
786 i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
789 handleShowSidebarMobile(i: Home) {
790 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
793 handleCollapseSubscribe(i: Home) {
794 i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
797 handlePageChange(page: number) {
798 this.updateUrl({ page });
799 window.scrollTo(0, 0);
802 handleSortChange(val: SortType) {
803 this.updateUrl({ sort: val, page: 1 });
804 window.scrollTo(0, 0);
807 handleListingTypeChange(val: ListingType) {
808 this.updateUrl({ listingType: val, page: 1 });
809 window.scrollTo(0, 0);
812 handleDataTypeChange(val: DataType) {
813 this.updateUrl({ dataType: val, page: 1 });
814 window.scrollTo(0, 0);
817 async handleAddModToCommunity(form: AddModToCommunity) {
818 // TODO not sure what to do here
819 await HttpService.client.addModToCommunity(form);
822 async handlePurgePerson(form: PurgePerson) {
823 const purgePersonRes = await HttpService.client.purgePerson(form);
824 this.purgeItem(purgePersonRes);
827 async handlePurgeComment(form: PurgeComment) {
828 const purgeCommentRes = await HttpService.client.purgeComment(form);
829 this.purgeItem(purgeCommentRes);
832 async handlePurgePost(form: PurgePost) {
833 const purgeRes = await HttpService.client.purgePost(form);
834 this.purgeItem(purgeRes);
837 async handleBlockPerson(form: BlockPerson) {
838 const blockPersonRes = await HttpService.client.blockPerson(form);
839 if (blockPersonRes.state == "success") {
840 updatePersonBlock(blockPersonRes.data);
844 async handleCreateComment(form: CreateComment) {
845 const createCommentRes = await HttpService.client.createComment(form);
846 this.createAndUpdateComments(createCommentRes);
848 return createCommentRes;
851 async handleEditComment(form: EditComment) {
852 const editCommentRes = await HttpService.client.editComment(form);
853 this.findAndUpdateComment(editCommentRes);
855 return editCommentRes;
858 async handleDeleteComment(form: DeleteComment) {
859 const deleteCommentRes = await HttpService.client.deleteComment(form);
860 this.findAndUpdateComment(deleteCommentRes);
863 async handleDeletePost(form: DeletePost) {
864 const deleteRes = await HttpService.client.deletePost(form);
865 this.findAndUpdatePost(deleteRes);
868 async handleRemovePost(form: RemovePost) {
869 const removeRes = await HttpService.client.removePost(form);
870 this.findAndUpdatePost(removeRes);
873 async handleRemoveComment(form: RemoveComment) {
874 const removeCommentRes = await HttpService.client.removeComment(form);
875 this.findAndUpdateComment(removeCommentRes);
878 async handleSaveComment(form: SaveComment) {
879 const saveCommentRes = await HttpService.client.saveComment(form);
880 this.findAndUpdateComment(saveCommentRes);
883 async handleSavePost(form: SavePost) {
884 const saveRes = await HttpService.client.savePost(form);
885 this.findAndUpdatePost(saveRes);
888 async handleFeaturePost(form: FeaturePost) {
889 const featureRes = await HttpService.client.featurePost(form);
890 this.findAndUpdatePost(featureRes);
893 async handleCommentVote(form: CreateCommentLike) {
894 const voteRes = await HttpService.client.likeComment(form);
895 this.findAndUpdateComment(voteRes);
898 async handlePostEdit(form: EditPost) {
899 const res = await HttpService.client.editPost(form);
900 this.findAndUpdatePost(res);
903 async handlePostVote(form: CreatePostLike) {
904 const voteRes = await HttpService.client.likePost(form);
905 this.findAndUpdatePost(voteRes);
908 async handleCommentReport(form: CreateCommentReport) {
909 const reportRes = await HttpService.client.createCommentReport(form);
910 if (reportRes.state == "success") {
911 toast(i18n.t("report_created"));
915 async handlePostReport(form: CreatePostReport) {
916 const reportRes = await HttpService.client.createPostReport(form);
917 if (reportRes.state == "success") {
918 toast(i18n.t("report_created"));
922 async handleLockPost(form: LockPost) {
923 const lockRes = await HttpService.client.lockPost(form);
924 this.findAndUpdatePost(lockRes);
927 async handleDistinguishComment(form: DistinguishComment) {
928 const distinguishRes = await HttpService.client.distinguishComment(form);
929 this.findAndUpdateComment(distinguishRes);
932 async handleAddAdmin(form: AddAdmin) {
933 const addAdminRes = await HttpService.client.addAdmin(form);
935 if (addAdminRes.state == "success") {
936 this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
940 async handleTransferCommunity(form: TransferCommunity) {
941 await HttpService.client.transferCommunity(form);
942 toast(i18n.t("transfer_community"));
945 async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
946 const readRes = await HttpService.client.markCommentReplyAsRead(form);
947 this.findAndUpdateCommentReply(readRes);
950 async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
951 // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
952 await HttpService.client.markPersonMentionAsRead(form);
955 async handleBanFromCommunity(form: BanFromCommunity) {
956 const banRes = await HttpService.client.banFromCommunity(form);
957 this.updateBanFromCommunity(banRes);
960 async handleBanPerson(form: BanPerson) {
961 const banRes = await HttpService.client.banPerson(form);
962 this.updateBan(banRes);
965 updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
966 // Maybe not necessary
967 if (banRes.state == "success") {
969 if (s.postsRes.state == "success") {
970 s.postsRes.data.posts
971 .filter(c => c.creator.id == banRes.data.person_view.person.id)
973 c => (c.creator_banned_from_community = banRes.data.banned)
976 if (s.commentsRes.state == "success") {
977 s.commentsRes.data.comments
978 .filter(c => c.creator.id == banRes.data.person_view.person.id)
980 c => (c.creator_banned_from_community = banRes.data.banned)
988 updateBan(banRes: RequestState<BanPersonResponse>) {
989 // Maybe not necessary
990 if (banRes.state == "success") {
992 if (s.postsRes.state == "success") {
993 s.postsRes.data.posts
994 .filter(c => c.creator.id == banRes.data.person_view.person.id)
995 .forEach(c => (c.creator.banned = banRes.data.banned));
997 if (s.commentsRes.state == "success") {
998 s.commentsRes.data.comments
999 .filter(c => c.creator.id == banRes.data.person_view.person.id)
1000 .forEach(c => (c.creator.banned = banRes.data.banned));
1007 purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
1008 if (purgeRes.state == "success") {
1009 toast(i18n.t("purge_success"));
1010 this.context.router.history.push(`/`);
1014 findAndUpdateComment(res: RequestState<CommentResponse>) {
1015 this.setState(s => {
1016 if (s.commentsRes.state == "success" && res.state == "success") {
1017 s.commentsRes.data.comments = editComment(
1018 res.data.comment_view,
1019 s.commentsRes.data.comments
1021 s.finished.set(res.data.comment_view.comment.id, true);
1027 createAndUpdateComments(res: RequestState<CommentResponse>) {
1028 this.setState(s => {
1029 if (s.commentsRes.state == "success" && res.state == "success") {
1030 s.commentsRes.data.comments.unshift(res.data.comment_view);
1032 // Set finished for the parent
1034 getCommentParentId(res.data.comment_view.comment) ?? 0,
1042 findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1043 this.setState(s => {
1044 if (s.commentsRes.state == "success" && res.state == "success") {
1045 s.commentsRes.data.comments = editWith(
1046 res.data.comment_reply_view,
1047 s.commentsRes.data.comments
1054 findAndUpdatePost(res: RequestState<PostResponse>) {
1055 this.setState(s => {
1056 if (s.postsRes.state == "success" && res.state == "success") {
1057 s.postsRes.data.posts = editPost(
1059 s.postsRes.data.posts