+import {
+ commentsToFlatNodes,
+ editComment,
+ editPost,
+ editWith,
+ enableDownvotes,
+ enableNsfw,
+ getCommentParentId,
+ getDataTypeString,
+ myAuth,
+ postToCommentSortType,
+ setIsoData,
+ showLocal,
+ updatePersonBlock,
+} from "@utils/app";
+import {
+ getPageFromString,
+ getQueryParams,
+ getQueryString,
+ getRandomFromList,
+} from "@utils/helpers";
+import { canCreateCommunity } from "@utils/roles";
+import type { QueryParams } from "@utils/types";
+import { RouteDataResponse } from "@utils/types";
import { NoOptionI18nKeys } from "i18next";
-import { Component, linkEvent, MouseEventHandler } from "inferno";
+import { Component, MouseEventHandler, linkEvent } from "inferno";
import { T } from "inferno-i18next-dess";
import { Link } from "inferno-router";
import {
- AddAdminResponse,
+ AddAdmin,
+ AddModToCommunity,
+ BanFromCommunity,
+ BanFromCommunityResponse,
+ BanPerson,
BanPersonResponse,
- BlockPersonResponse,
- CommentReportResponse,
+ BlockPerson,
+ CommentId,
+ CommentReplyResponse,
CommentResponse,
- CommentView,
- CommunityView,
+ CreateComment,
+ CreateCommentLike,
+ CreateCommentReport,
+ CreatePostLike,
+ CreatePostReport,
+ DeleteComment,
+ DeletePost,
+ DistinguishComment,
+ EditComment,
+ EditPost,
+ FeaturePost,
GetComments,
GetCommentsResponse,
GetPosts,
ListCommunities,
ListCommunitiesResponse,
ListingType,
- PostReportResponse,
+ LockPost,
+ MarkCommentReplyAsRead,
+ MarkPersonMentionAsRead,
PostResponse,
- PostView,
+ PurgeComment,
PurgeItemResponse,
- SiteResponse,
+ PurgePerson,
+ PurgePost,
+ RemoveComment,
+ RemovePost,
+ SaveComment,
+ SavePost,
SortType,
- UserOperation,
- wsJsonToRes,
- wsUserOp,
+ TransferCommunity,
} from "lemmy-js-client";
-import { Subscription } from "rxjs";
-import { i18n } from "../../i18next";
+import { fetchLimit, relTags, trendingFetchLimit } from "../../config";
import {
CommentViewType,
DataType,
InitialFetchRequest,
} from "../../interfaces";
-import { UserService, WebSocketService } from "../../services";
+import { mdToHtml } from "../../markdown";
import {
- canCreateCommunity,
- commentsToFlatNodes,
- createCommentLikeRes,
- createPostLikeFindRes,
- editCommentRes,
- editPostFindRes,
- enableDownvotes,
- enableNsfw,
- fetchLimit,
- getDataTypeString,
- getPageFromString,
- getQueryParams,
- getQueryString,
- getRandomFromList,
- isBrowser,
- isPostBlocked,
- mdToHtml,
- myAuth,
- notifyPost,
- nsfwCheck,
- postToCommentSortType,
- QueryParams,
- relTags,
- restoreScrollPosition,
- saveCommentRes,
- saveScrollPosition,
- setIsoData,
- setupTippy,
- showLocal,
- toast,
- trendingFetchLimit,
- updatePersonBlock,
- wsClient,
- wsSubscribe,
-} from "../../utils";
+ FirstLoadService,
+ HomeCacheService,
+ I18NextService,
+ UserService,
+} from "../../services";
+import { HttpService, RequestState } from "../../services/HttpService";
+import { setupTippy } from "../../tippy";
+import { toast } from "../../toast";
import { CommentNodes } from "../comment/comment-nodes";
import { DataTypeSelect } from "../common/data-type-select";
import { HtmlTags } from "../common/html-tags";
import { SiteSidebar } from "./site-sidebar";
interface HomeState {
- trendingCommunities: CommunityView[];
- siteRes: GetSiteResponse;
- posts: PostView[];
- comments: CommentView[];
+ postsRes: RequestState<GetPostsResponse>;
+ commentsRes: RequestState<GetCommentsResponse>;
+ trendingCommunitiesRes: RequestState<ListCommunitiesResponse>;
showSubscribedMobile: boolean;
showTrendingMobile: boolean;
showSidebarMobile: boolean;
subscribedCollapsed: boolean;
- loading: boolean;
+ scrolled: boolean;
tagline?: string;
+ siteRes: GetSiteResponse;
+ finished: Map<CommentId, boolean | undefined>;
+ isIsomorphic: boolean;
}
interface HomeProps {
- listingType: ListingType;
+ listingType?: ListingType;
dataType: DataType;
sort: SortType;
- page: bigint;
+ page: number;
+}
+
+type HomeData = RouteDataResponse<{
+ postsRes: GetPostsResponse;
+ commentsRes: GetCommentsResponse;
+ trendingCommunitiesRes: ListCommunitiesResponse;
+}>;
+
+function getRss(listingType: ListingType) {
+ const { sort } = getHomeQueryParams();
+ const auth = myAuth();
+
+ let rss: string | undefined = undefined;
+
+ switch (listingType) {
+ case "All": {
+ rss = `/feeds/all.xml?sort=${sort}`;
+ break;
+ }
+ case "Local": {
+ rss = `/feeds/local.xml?sort=${sort}`;
+ break;
+ }
+ case "Subscribed": {
+ rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
+ break;
+ }
+ }
+
+ return (
+ rss && (
+ <>
+ <a href={rss} rel={relTags} title="RSS">
+ <Icon icon="rss" classes="text-muted small" />
+ </a>
+ <link rel="alternate" type="application/atom+xml" href={rss} />
+ </>
+ )
+ );
}
function getDataTypeFromQuery(type?: string): DataType {
return type ? DataType[type] : DataType.Post;
}
-function getListingTypeFromQuery(type?: string): ListingType {
+function getListingTypeFromQuery(type?: string): ListingType | undefined {
const myListingType =
UserService.Instance.myUserInfo?.local_user_view?.local_user
?.default_listing_type;
- return type ? (type as ListingType) : myListingType ?? "Local";
+ return type ? (type as ListingType) : myListingType;
}
function getSortTypeFromQuery(type?: string): SortType {
UserService.Instance.myUserInfo?.local_user_view?.local_user
?.default_sort_type;
- return type ? (type as SortType) : mySortType ?? "Active";
+ return (type ? (type as SortType) : mySortType) ?? "Active";
}
const getHomeQueryParams = () =>
dataType: getDataTypeFromQuery,
});
-function fetchTrendingCommunities() {
- const listCommunitiesForm: ListCommunities = {
- type_: "Local",
- sort: "Hot",
- limit: trendingFetchLimit,
- auth: myAuth(false),
- };
- WebSocketService.Instance.send(wsClient.listCommunities(listCommunitiesForm));
-}
-
-function fetchData() {
- const auth = myAuth(false);
- const { dataType, page, listingType, sort } = getHomeQueryParams();
- let req: string;
-
- if (dataType === DataType.Post) {
- const getPostsForm: GetPosts = {
- page,
- limit: fetchLimit,
- sort,
- saved_only: false,
- type_: listingType,
- auth,
- };
-
- req = wsClient.getPosts(getPostsForm);
- } else {
- const getCommentsForm: GetComments = {
- page,
- limit: fetchLimit,
- sort: postToCommentSortType(sort),
- saved_only: false,
- type_: listingType,
- auth,
- };
-
- req = wsClient.getComments(getCommentsForm);
- }
-
- WebSocketService.Instance.send(req);
-}
-
const MobileButton = ({
textKey,
show,
onClick: MouseEventHandler<HTMLButtonElement>;
}) => (
<button
- className="btn btn-secondary d-inline-block mb-2 mr-3"
+ className="btn btn-secondary d-inline-block mb-2 me-3"
onClick={onClick}
>
- {i18n.t(textKey)}{" "}
+ {I18NextService.i18n.t(textKey)}{" "}
<Icon icon={show ? `minus-square` : `plus-square`} classes="icon-inline" />
</button>
);
path: string;
translationKey: NoOptionI18nKeys;
}) => (
- <Link className="btn btn-secondary btn-block" to={path}>
- {i18n.t(translationKey)}
+ <Link className="btn btn-secondary d-block" to={path}>
+ {I18NextService.i18n.t(translationKey)}
</Link>
);
-function getRss(listingType: ListingType) {
- const { sort } = getHomeQueryParams();
- const auth = myAuth(false);
-
- let rss: string | undefined = undefined;
-
- switch (listingType) {
- case "All": {
- rss = `/feeds/all.xml?sort=${sort}`;
- break;
- }
- case "Local": {
- rss = `/feeds/local.xml?sort=${sort}`;
- break;
- }
- case "Subscribed": {
- rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
- break;
- }
- }
-
- return (
- rss && (
- <>
- <a href={rss} rel={relTags} title="RSS">
- <Icon icon="rss" classes="text-muted small" />
- </a>
- <link rel="alternate" type="application/atom+xml" href={rss} />
- </>
- )
- );
-}
-
export class Home extends Component<any, HomeState> {
- private isoData = setIsoData(this.context);
- private subscription?: Subscription;
+ private isoData = setIsoData<HomeData>(this.context);
state: HomeState = {
- trendingCommunities: [],
+ postsRes: { state: "empty" },
+ commentsRes: { state: "empty" },
+ trendingCommunitiesRes: { state: "empty" },
+ scrolled: true,
siteRes: this.isoData.site_res,
showSubscribedMobile: false,
showTrendingMobile: false,
showSidebarMobile: false,
subscribedCollapsed: false,
- loading: true,
- posts: [],
- comments: [],
+ finished: new Map(),
+ isIsomorphic: false,
};
constructor(props: any, context: any) {
this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
this.handlePageChange = this.handlePageChange.bind(this);
- this.parseMessage = this.parseMessage.bind(this);
- this.subscription = wsSubscribe(this.parseMessage);
+ this.handleCreateComment = this.handleCreateComment.bind(this);
+ this.handleEditComment = this.handleEditComment.bind(this);
+ this.handleSaveComment = this.handleSaveComment.bind(this);
+ this.handleBlockPerson = this.handleBlockPerson.bind(this);
+ this.handleDeleteComment = this.handleDeleteComment.bind(this);
+ this.handleRemoveComment = this.handleRemoveComment.bind(this);
+ this.handleCommentVote = this.handleCommentVote.bind(this);
+ this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
+ this.handleAddAdmin = this.handleAddAdmin.bind(this);
+ this.handlePurgePerson = this.handlePurgePerson.bind(this);
+ this.handlePurgeComment = this.handlePurgeComment.bind(this);
+ this.handleCommentReport = this.handleCommentReport.bind(this);
+ this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
+ this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
+ this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
+ this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
+ this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
+ this.handleBanPerson = this.handleBanPerson.bind(this);
+ this.handlePostEdit = this.handlePostEdit.bind(this);
+ this.handlePostVote = this.handlePostVote.bind(this);
+ this.handlePostReport = this.handlePostReport.bind(this);
+ this.handleLockPost = this.handleLockPost.bind(this);
+ this.handleDeletePost = this.handleDeletePost.bind(this);
+ this.handleRemovePost = this.handleRemovePost.bind(this);
+ this.handleSavePost = this.handleSavePost.bind(this);
+ this.handlePurgePost = this.handlePurgePost.bind(this);
+ this.handleFeaturePost = this.handleFeaturePost.bind(this);
// Only fetch the data if coming from another route
- if (this.isoData.path === this.context.router.route.match.url) {
- const postsRes = this.isoData.routeData[0] as
- | GetPostsResponse
- | undefined;
- const commentsRes = this.isoData.routeData[1] as
- | GetCommentsResponse
- | undefined;
- const trendingRes = this.isoData.routeData[2] as
- | ListCommunitiesResponse
- | undefined;
-
- if (postsRes) {
- this.state = { ...this.state, posts: postsRes.posts };
- }
-
- if (commentsRes) {
- this.state = { ...this.state, comments: commentsRes.comments };
- }
+ if (FirstLoadService.isFirstLoad) {
+ const { trendingCommunitiesRes, commentsRes, postsRes } =
+ this.isoData.routeData;
- if (isBrowser()) {
- WebSocketService.Instance.send(
- wsClient.communityJoin({ community_id: 0 })
- );
- }
- const taglines = this.state?.siteRes?.taglines ?? [];
this.state = {
...this.state,
- trendingCommunities: trendingRes?.communities ?? [],
- loading: false,
- tagline: getRandomFromList(taglines)?.content,
+ trendingCommunitiesRes,
+ commentsRes,
+ postsRes,
+ isIsomorphic: true,
};
- } else {
- fetchTrendingCommunities();
- fetchData();
- }
- }
- componentDidMount() {
- // This means it hasn't been set up yet
- if (!this.state.siteRes.site_view.local_site.site_setup) {
- this.context.router.history.push("/setup");
+ HomeCacheService.postsRes = postsRes;
}
- setupTippy();
+
+ this.state.tagline = getRandomFromList(
+ this.state?.siteRes?.taglines ?? []
+ )?.content;
}
componentWillUnmount() {
- saveScrollPosition(this.context);
- this.subscription?.unsubscribe();
+ HomeCacheService.activate();
}
- static fetchInitialData({
+ async componentDidMount() {
+ if (
+ !this.state.isIsomorphic ||
+ !Object.values(this.isoData.routeData).some(
+ res => res.state === "success" || res.state === "failed"
+ )
+ ) {
+ await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
+ }
+
+ setupTippy();
+ }
+
+ static async fetchInitialData({
client,
auth,
query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
- }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<any>[] {
+ site,
+ }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<HomeData> {
const dataType = getDataTypeFromQuery(urlDataType);
-
- // TODO figure out auth default_listingType, default_sort_type
- const type_ = getListingTypeFromQuery(listingType);
+ const type_ =
+ getListingTypeFromQuery(listingType) ??
+ site.site_view.local_site.default_post_listing_type;
const sort = getSortTypeFromQuery(urlSort);
- const page = urlPage ? BigInt(urlPage) : 1n;
+ const page = urlPage ? Number(urlPage) : 1;
- const promises: Promise<any>[] = [];
+ let postsRes: RequestState<GetPostsResponse> = { state: "empty" };
+ let commentsRes: RequestState<GetCommentsResponse> = {
+ state: "empty",
+ };
if (dataType === DataType.Post) {
const getPostsForm: GetPosts = {
auth,
};
- promises.push(client.getPosts(getPostsForm));
- promises.push(Promise.resolve());
+ postsRes = await client.getPosts(getPostsForm);
} else {
const getCommentsForm: GetComments = {
page,
saved_only: false,
auth,
};
- promises.push(Promise.resolve());
- promises.push(client.getComments(getCommentsForm));
+
+ commentsRes = await client.getComments(getCommentsForm);
}
const trendingCommunitiesForm: ListCommunities = {
limit: trendingFetchLimit,
auth,
};
- promises.push(client.listCommunities(trendingCommunitiesForm));
- return promises;
+ return {
+ trendingCommunitiesRes: await client.listCommunities(
+ trendingCommunitiesForm
+ ),
+ commentsRes,
+ postsRes,
+ };
}
get documentTitle(): string {
} = this.state;
return (
- <div className="container-lg">
+ <div className="home container-lg">
<HtmlTags
title={this.documentTitle}
path={this.context.router.route.match.url}
/>
{site_setup && (
<div className="row">
- <main role="main" className="col-12 col-md-8">
+ <main role="main" className="col-12 col-md-8 col-lg-9">
{tagline && (
<div
id="tagline"
></div>
)}
<div className="d-block d-md-none">{this.mobileView}</div>
- {this.posts()}
+ {this.posts}
</main>
- <aside className="d-none d-md-block col-md-4">
+ <aside className="d-none d-md-block col-md-4 col-lg-3">
{this.mySidebar}
</aside>
</div>
siteRes: {
site_view: { counts, site },
admins,
- online,
},
showSubscribedMobile,
showTrendingMobile,
site={site}
admins={admins}
counts={counts}
- online={online}
showLocal={showLocal(this.isoData)}
+ isMobile={true}
/>
)}
{showTrendingMobile && (
- <div className="col-12 card border-secondary mb-3">
- <div className="card-body">{this.trendingCommunities(true)}</div>
+ <div className="card border-secondary mb-3">
+ {this.trendingCommunities()}
</div>
)}
{showSubscribedMobile && (
- <div className="col-12 card border-secondary mb-3">
- <div className="card-body">{this.subscribedCommunities}</div>
+ <div className="card border-secondary mb-3">
+ {this.subscribedCommunities(true)}
</div>
)}
</div>
siteRes: {
site_view: { counts, site },
admins,
- online,
},
- loading,
} = this.state;
return (
- <div>
- {!loading && (
- <div>
- <div className="card border-secondary mb-3">
- <div className="card-body">
- {this.trendingCommunities()}
- {canCreateCommunity(this.state.siteRes) && (
- <LinkButton
- path="/create_community"
- translationKey="create_a_community"
- />
- )}
- <LinkButton
- path="/communities"
- translationKey="explore_communities"
- />
- </div>
- </div>
- <SiteSidebar
- site={site}
- admins={admins}
- counts={counts}
- online={online}
- showLocal={showLocal(this.isoData)}
- />
- {this.hasFollows && (
- <div className="card border-secondary mb-3">
- <div className="card-body">{this.subscribedCommunities}</div>
- </div>
- )}
+ <div id="sidebarContainer">
+ <section id="sidebarMain" className="card border-secondary mb-3">
+ {this.trendingCommunities()}
+ </section>
+ <SiteSidebar
+ site={site}
+ admins={admins}
+ counts={counts}
+ showLocal={showLocal(this.isoData)}
+ />
+ {this.hasFollows && (
+ <div className="accordion">
+ <section
+ id="sidebarSubscribed"
+ className="card border-secondary mb-3"
+ >
+ {this.subscribedCommunities(false)}
+ </section>
</div>
)}
</div>
);
}
- trendingCommunities(isMobile = false) {
- return (
- <div className={!isMobile ? "mb-2" : ""}>
- <h5>
- <T i18nKey="trending_communities">
- #
- <Link className="text-body" to="/communities">
- #
- </Link>
- </T>
- </h5>
- <ul className="list-inline mb-0">
- {this.state.trendingCommunities.map(cv => (
- <li
- key={cv.community.id}
- className="list-inline-item d-inline-block"
- >
- <CommunityLink community={cv.community} />
- </li>
- ))}
- </ul>
- </div>
- );
+ trendingCommunities() {
+ switch (this.state.trendingCommunitiesRes?.state) {
+ case "loading":
+ return (
+ <h5>
+ <Spinner large />
+ </h5>
+ );
+ case "success": {
+ const trending = this.state.trendingCommunitiesRes.data.communities;
+ return (
+ <>
+ <header className="card-header d-flex align-items-center">
+ <h5 className="mb-0">
+ <T i18nKey="trending_communities">
+ #
+ <Link className="text-body" to="/communities">
+ #
+ </Link>
+ </T>
+ </h5>
+ </header>
+ <div className="card-body">
+ {trending.length > 0 && (
+ <ul className="list-inline">
+ {trending.map(cv => (
+ <li key={cv.community.id} className="list-inline-item">
+ <CommunityLink community={cv.community} />
+ </li>
+ ))}
+ </ul>
+ )}
+ {canCreateCommunity(this.state.siteRes) && (
+ <LinkButton
+ path="/create_community"
+ translationKey="create_a_community"
+ />
+ )}
+ <LinkButton
+ path="/communities"
+ translationKey="explore_communities"
+ />
+ </div>
+ </>
+ );
+ }
+ }
}
- get subscribedCommunities() {
+ subscribedCommunities(isMobile = false) {
const { subscribedCollapsed } = this.state;
return (
- <div>
- <h5>
- <T class="d-inline" i18nKey="subscribed_to_communities">
- #
- <Link className="text-body" to="/communities">
+ <>
+ <header
+ className="card-header d-flex align-items-center"
+ id="sidebarSubscribedHeader"
+ >
+ <h5 className="mb-0 d-inline">
+ <T class="d-inline" i18nKey="subscribed_to_communities">
#
- </Link>
- </T>
- <button
- className="btn btn-sm text-muted"
- onClick={linkEvent(this, this.handleCollapseSubscribe)}
- aria-label={i18n.t("collapse")}
- data-tippy-content={i18n.t("collapse")}
- >
- <Icon
- icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
- classes="icon-inline"
- />
- </button>
- </h5>
+ <Link className="text-body" to="/communities">
+ #
+ </Link>
+ </T>
+ </h5>
+ {!isMobile && (
+ <button
+ type="button"
+ className="btn btn-sm text-muted"
+ onClick={linkEvent(this, this.handleCollapseSubscribe)}
+ aria-label={
+ subscribedCollapsed
+ ? I18NextService.i18n.t("expand")
+ : I18NextService.i18n.t("collapse")
+ }
+ data-tippy-content={
+ subscribedCollapsed
+ ? I18NextService.i18n.t("expand")
+ : I18NextService.i18n.t("collapse")
+ }
+ aria-expanded="true"
+ aria-controls="sidebarSubscribedBody"
+ >
+ <Icon
+ icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
+ classes="icon-inline"
+ />
+ </button>
+ )}
+ </header>
{!subscribedCollapsed && (
- <ul className="list-inline mb-0">
- {UserService.Instance.myUserInfo?.follows.map(cfv => (
- <li
- key={cfv.community.id}
- className="list-inline-item d-inline-block"
- >
- <CommunityLink community={cfv.community} />
- </li>
- ))}
- </ul>
+ <div
+ id="sidebarSubscribedBody"
+ aria-labelledby="sidebarSubscribedHeader"
+ >
+ <div className="card-body">
+ <ul className="list-inline mb-0">
+ {UserService.Instance.myUserInfo?.follows.map(cfv => (
+ <li
+ key={cfv.community.id}
+ className="list-inline-item d-inline-block"
+ >
+ <CommunityLink community={cfv.community} />
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
)}
- </div>
+ </>
);
}
- updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
+ async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
const {
dataType: urlDataType,
listingType: urlListingType,
search: getQueryString(queryParams),
});
- this.setState({
- loading: true,
- posts: [],
- comments: [],
- });
+ if (!this.state.scrolled) {
+ this.setState({ scrolled: true });
+ setTimeout(() => window.scrollTo(0, 0), 0);
+ }
- fetchData();
+ await this.fetchData();
}
- posts() {
+ get posts() {
const { page } = getHomeQueryParams();
return (
<div className="main-content-wrapper">
- {this.state.loading ? (
- <h5>
- <Spinner large />
- </h5>
- ) : (
- <div>
- {this.selects()}
- {this.listings}
- <Paginator page={page} onChange={this.handlePageChange} />
- </div>
- )}
+ <div>
+ {this.selects}
+ {this.listings}
+ <Paginator page={page} onChange={this.handlePageChange} />
+ </div>
</div>
);
}
get listings() {
const { dataType } = getHomeQueryParams();
- const { siteRes, posts, comments } = this.state;
-
- return dataType === DataType.Post ? (
- <PostListings
- posts={posts}
- showCommunity
- removeDuplicates
- enableDownvotes={enableDownvotes(siteRes)}
- enableNsfw={enableNsfw(siteRes)}
- allLanguages={siteRes.all_languages}
- siteLanguages={siteRes.discussion_languages}
- />
- ) : (
- <CommentNodes
- nodes={commentsToFlatNodes(comments)}
- viewType={CommentViewType.Flat}
- noIndent
- showCommunity
- showContext
- enableDownvotes={enableDownvotes(siteRes)}
- allLanguages={siteRes.all_languages}
- siteLanguages={siteRes.discussion_languages}
- />
- );
+ const siteRes = this.state.siteRes;
+
+ if (dataType === DataType.Post) {
+ switch (this.state.postsRes?.state) {
+ case "empty":
+ return <div style="min-height: 20000px;"></div>;
+ case "loading":
+ return (
+ <h5>
+ <Spinner large />
+ </h5>
+ );
+ case "success": {
+ const posts = this.state.postsRes.data.posts;
+ return (
+ <PostListings
+ posts={posts}
+ showCommunity
+ removeDuplicates
+ enableDownvotes={enableDownvotes(siteRes)}
+ enableNsfw={enableNsfw(siteRes)}
+ allLanguages={siteRes.all_languages}
+ siteLanguages={siteRes.discussion_languages}
+ onBlockPerson={this.handleBlockPerson}
+ onPostEdit={this.handlePostEdit}
+ onPostVote={this.handlePostVote}
+ onPostReport={this.handlePostReport}
+ onLockPost={this.handleLockPost}
+ onDeletePost={this.handleDeletePost}
+ onRemovePost={this.handleRemovePost}
+ onSavePost={this.handleSavePost}
+ onPurgePerson={this.handlePurgePerson}
+ onPurgePost={this.handlePurgePost}
+ onBanPerson={this.handleBanPerson}
+ onBanPersonFromCommunity={this.handleBanFromCommunity}
+ onAddModToCommunity={this.handleAddModToCommunity}
+ onAddAdmin={this.handleAddAdmin}
+ onTransferCommunity={this.handleTransferCommunity}
+ onFeaturePost={this.handleFeaturePost}
+ />
+ );
+ }
+ }
+ } else {
+ switch (this.state.commentsRes.state) {
+ case "loading":
+ return (
+ <h5>
+ <Spinner large />
+ </h5>
+ );
+ case "success": {
+ const comments = this.state.commentsRes.data.comments;
+ return (
+ <CommentNodes
+ nodes={commentsToFlatNodes(comments)}
+ viewType={CommentViewType.Flat}
+ finished={this.state.finished}
+ noIndent
+ showCommunity
+ showContext
+ enableDownvotes={enableDownvotes(siteRes)}
+ allLanguages={siteRes.all_languages}
+ siteLanguages={siteRes.discussion_languages}
+ onSaveComment={this.handleSaveComment}
+ onBlockPerson={this.handleBlockPerson}
+ onDeleteComment={this.handleDeleteComment}
+ onRemoveComment={this.handleRemoveComment}
+ onCommentVote={this.handleCommentVote}
+ onCommentReport={this.handleCommentReport}
+ onDistinguishComment={this.handleDistinguishComment}
+ onAddModToCommunity={this.handleAddModToCommunity}
+ onAddAdmin={this.handleAddAdmin}
+ onTransferCommunity={this.handleTransferCommunity}
+ onPurgeComment={this.handlePurgeComment}
+ onPurgePerson={this.handlePurgePerson}
+ onCommentReplyRead={this.handleCommentReplyRead}
+ onPersonMentionRead={this.handlePersonMentionRead}
+ onBanPersonFromCommunity={this.handleBanFromCommunity}
+ onBanPerson={this.handleBanPerson}
+ onCreateComment={this.handleCreateComment}
+ onEditComment={this.handleEditComment}
+ />
+ );
+ }
+ }
+ }
}
- selects() {
+ get selects() {
const { listingType, dataType, sort } = getHomeQueryParams();
return (
- <div className="mb-3">
- <span className="mr-3">
+ <div className="row align-items-center mb-3 g-3">
+ <div className="col-auto">
<DataTypeSelect
type_={dataType}
onChange={this.handleDataTypeChange}
/>
- </span>
- <span className="mr-3">
+ </div>
+ <div className="col-auto">
<ListingTypeSelect
- type_={listingType}
+ type_={
+ listingType ??
+ this.state.siteRes.site_view.local_site.default_post_listing_type
+ }
showLocal={showLocal(this.isoData)}
showSubscribed
onChange={this.handleListingTypeChange}
/>
- </span>
- <span className="mr-2">
+ </div>
+ <div className="col-auto">
<SortSelect sort={sort} onChange={this.handleSortChange} />
- </span>
- {getRss(listingType)}
+ </div>
+ <div className="col-auto ps-0">
+ {getRss(
+ listingType ??
+ this.state.siteRes.site_view.local_site.default_post_listing_type
+ )}
+ </div>
</div>
);
}
+ async fetchTrendingCommunities() {
+ this.setState({ trendingCommunitiesRes: { state: "loading" } });
+ this.setState({
+ trendingCommunitiesRes: await HttpService.client.listCommunities({
+ type_: "Local",
+ sort: "Hot",
+ limit: trendingFetchLimit,
+ auth: myAuth(),
+ }),
+ });
+ }
+
+ async fetchData() {
+ const auth = myAuth();
+ const { dataType, page, listingType, sort } = getHomeQueryParams();
+
+ if (dataType === DataType.Post) {
+ if (HomeCacheService.active) {
+ const { postsRes, scrollY } = HomeCacheService;
+ HomeCacheService.deactivate();
+ this.setState({ postsRes });
+ window.scrollTo({
+ left: 0,
+ top: scrollY,
+ behavior: "instant",
+ });
+ } else {
+ this.setState({ postsRes: { state: "loading" } });
+ this.setState({
+ postsRes: await HttpService.client.getPosts({
+ page,
+ limit: fetchLimit,
+ sort,
+ saved_only: false,
+ type_: listingType,
+ auth,
+ }),
+ });
+
+ HomeCacheService.postsRes = this.state.postsRes;
+ }
+ } else {
+ this.setState({ commentsRes: { state: "loading" } });
+ this.setState({
+ commentsRes: await HttpService.client.getComments({
+ page,
+ limit: fetchLimit,
+ sort: postToCommentSortType(sort),
+ saved_only: false,
+ type_: listingType,
+ auth,
+ }),
+ });
+ }
+
+ setupTippy();
+ }
+
handleShowSubscribedMobile(i: Home) {
i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
}
i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
}
- handlePageChange(page: bigint) {
+ handlePageChange(page: number) {
+ this.setState({ scrolled: false });
this.updateUrl({ page });
- window.scrollTo(0, 0);
}
handleSortChange(val: SortType) {
- this.updateUrl({ sort: val, page: 1n });
- window.scrollTo(0, 0);
+ this.setState({ scrolled: false });
+ this.updateUrl({ sort: val, page: 1 });
}
handleListingTypeChange(val: ListingType) {
- this.updateUrl({ listingType: val, page: 1n });
- window.scrollTo(0, 0);
+ this.setState({ scrolled: false });
+ this.updateUrl({ listingType: val, page: 1 });
}
handleDataTypeChange(val: DataType) {
- this.updateUrl({ dataType: val, page: 1n });
- window.scrollTo(0, 0);
+ this.setState({ scrolled: false });
+ this.updateUrl({ dataType: val, page: 1 });
}
- parseMessage(msg: any) {
- const op = wsUserOp(msg);
- console.log(msg);
+ async handleAddModToCommunity(form: AddModToCommunity) {
+ // TODO not sure what to do here
+ await HttpService.client.addModToCommunity(form);
+ }
- if (msg.error) {
- toast(i18n.t(msg.error), "danger");
- } else if (msg.reconnect) {
- WebSocketService.Instance.send(
- wsClient.communityJoin({ community_id: 0 })
- );
- fetchData();
- } else {
- switch (op) {
- case UserOperation.ListCommunities: {
- const { communities } = wsJsonToRes<ListCommunitiesResponse>(msg);
- this.setState({ trendingCommunities: communities });
+ async handlePurgePerson(form: PurgePerson) {
+ const purgePersonRes = await HttpService.client.purgePerson(form);
+ this.purgeItem(purgePersonRes);
+ }
- break;
- }
+ async handlePurgeComment(form: PurgeComment) {
+ const purgeCommentRes = await HttpService.client.purgeComment(form);
+ this.purgeItem(purgeCommentRes);
+ }
- case UserOperation.EditSite: {
- const { site_view } = wsJsonToRes<SiteResponse>(msg);
- this.setState(s => ((s.siteRes.site_view = site_view), s));
- toast(i18n.t("site_saved"));
+ async handlePurgePost(form: PurgePost) {
+ const purgeRes = await HttpService.client.purgePost(form);
+ this.purgeItem(purgeRes);
+ }
- break;
- }
+ async handleBlockPerson(form: BlockPerson) {
+ const blockPersonRes = await HttpService.client.blockPerson(form);
+ if (blockPersonRes.state == "success") {
+ updatePersonBlock(blockPersonRes.data);
+ }
+ }
- case UserOperation.GetPosts: {
- const { posts } = wsJsonToRes<GetPostsResponse>(msg);
- this.setState({ posts, loading: false });
- WebSocketService.Instance.send(
- wsClient.communityJoin({ community_id: 0 })
- );
- restoreScrollPosition(this.context);
- setupTippy();
+ async handleCreateComment(form: CreateComment) {
+ const createCommentRes = await HttpService.client.createComment(form);
+ this.createAndUpdateComments(createCommentRes);
- break;
- }
+ return createCommentRes;
+ }
- case UserOperation.CreatePost: {
- const { page, listingType } = getHomeQueryParams();
- const { post_view } = wsJsonToRes<PostResponse>(msg);
-
- // Only push these if you're on the first page, you pass the nsfw check, and it isn't blocked
- if (
- page === 1n &&
- nsfwCheck(post_view) &&
- !isPostBlocked(post_view)
- ) {
- const mui = UserService.Instance.myUserInfo;
- const showPostNotifs =
- mui?.local_user_view.local_user.show_new_post_notifs;
- let shouldAddPost: boolean;
-
- switch (listingType) {
- case "Subscribed": {
- // If you're on subscribed, only push it if you're subscribed.
- shouldAddPost = !!mui?.follows.some(
- ({ community: { id } }) => id === post_view.community.id
- );
- break;
- }
- case "Local": {
- // If you're on the local view, only push it if its local
- shouldAddPost = post_view.post.local;
- break;
- }
- default: {
- shouldAddPost = true;
- break;
- }
- }
+ async handleEditComment(form: EditComment) {
+ const editCommentRes = await HttpService.client.editComment(form);
+ this.findAndUpdateComment(editCommentRes);
- if (shouldAddPost) {
- this.setState(({ posts }) => ({
- posts: [post_view].concat(posts),
- }));
- if (showPostNotifs) {
- notifyPost(post_view, this.context.router);
- }
- }
- }
+ return editCommentRes;
+ }
- break;
- }
+ async handleDeleteComment(form: DeleteComment) {
+ const deleteCommentRes = await HttpService.client.deleteComment(form);
+ this.findAndUpdateComment(deleteCommentRes);
+ }
- case UserOperation.EditPost:
- case UserOperation.DeletePost:
- case UserOperation.RemovePost:
- case UserOperation.LockPost:
- case UserOperation.FeaturePost:
- case UserOperation.SavePost: {
- const { post_view } = wsJsonToRes<PostResponse>(msg);
- editPostFindRes(post_view, this.state.posts);
- this.setState(this.state);
-
- break;
- }
+ async handleDeletePost(form: DeletePost) {
+ const deleteRes = await HttpService.client.deletePost(form);
+ this.findAndUpdatePost(deleteRes);
+ }
- case UserOperation.CreatePostLike: {
- const { post_view } = wsJsonToRes<PostResponse>(msg);
- createPostLikeFindRes(post_view, this.state.posts);
- this.setState(this.state);
+ async handleRemovePost(form: RemovePost) {
+ const removeRes = await HttpService.client.removePost(form);
+ this.findAndUpdatePost(removeRes);
+ }
- break;
- }
+ async handleRemoveComment(form: RemoveComment) {
+ const removeCommentRes = await HttpService.client.removeComment(form);
+ this.findAndUpdateComment(removeCommentRes);
+ }
- case UserOperation.AddAdmin: {
- const { admins } = wsJsonToRes<AddAdminResponse>(msg);
- this.setState(s => ((s.siteRes.admins = admins), s));
+ async handleSaveComment(form: SaveComment) {
+ const saveCommentRes = await HttpService.client.saveComment(form);
+ this.findAndUpdateComment(saveCommentRes);
+ }
- break;
- }
+ async handleSavePost(form: SavePost) {
+ const saveRes = await HttpService.client.savePost(form);
+ this.findAndUpdatePost(saveRes);
+ }
- case UserOperation.BanPerson: {
- const {
- banned,
- person_view: {
- person: { id },
- },
- } = wsJsonToRes<BanPersonResponse>(msg);
+ async handleFeaturePost(form: FeaturePost) {
+ const featureRes = await HttpService.client.featurePost(form);
+ this.findAndUpdatePost(featureRes);
+ }
- this.state.posts
- .filter(p => p.creator.id == id)
- .forEach(p => (p.creator.banned = banned));
- this.setState(this.state);
+ async handleCommentVote(form: CreateCommentLike) {
+ const voteRes = await HttpService.client.likeComment(form);
+ this.findAndUpdateComment(voteRes);
+ }
- break;
- }
+ async handlePostEdit(form: EditPost) {
+ const res = await HttpService.client.editPost(form);
+ this.findAndUpdatePost(res);
+ }
- case UserOperation.GetComments: {
- const { comments } = wsJsonToRes<GetCommentsResponse>(msg);
- this.setState({ comments, loading: false });
+ async handlePostVote(form: CreatePostLike) {
+ const voteRes = await HttpService.client.likePost(form);
+ this.findAndUpdatePost(voteRes);
+ }
- break;
- }
+ async handleCommentReport(form: CreateCommentReport) {
+ const reportRes = await HttpService.client.createCommentReport(form);
+ if (reportRes.state == "success") {
+ toast(I18NextService.i18n.t("report_created"));
+ }
+ }
- case UserOperation.EditComment:
- case UserOperation.DeleteComment:
- case UserOperation.RemoveComment: {
- const { comment_view } = wsJsonToRes<CommentResponse>(msg);
- editCommentRes(comment_view, this.state.comments);
- this.setState(this.state);
+ async handlePostReport(form: CreatePostReport) {
+ const reportRes = await HttpService.client.createPostReport(form);
+ if (reportRes.state == "success") {
+ toast(I18NextService.i18n.t("report_created"));
+ }
+ }
- break;
- }
+ async handleLockPost(form: LockPost) {
+ const lockRes = await HttpService.client.lockPost(form);
+ this.findAndUpdatePost(lockRes);
+ }
- case UserOperation.CreateComment: {
- const { form_id, comment_view } = wsJsonToRes<CommentResponse>(msg);
-
- // Necessary since it might be a user reply
- if (form_id) {
- const { listingType } = getHomeQueryParams();
-
- // If you're on subscribed, only push it if you're subscribed.
- const shouldAddComment =
- listingType === "Subscribed"
- ? UserService.Instance.myUserInfo?.follows.some(
- ({ community: { id } }) => id === comment_view.community.id
- )
- : true;
-
- if (shouldAddComment) {
- this.setState(({ comments }) => ({
- comments: [comment_view].concat(comments),
- }));
- }
- }
+ async handleDistinguishComment(form: DistinguishComment) {
+ const distinguishRes = await HttpService.client.distinguishComment(form);
+ this.findAndUpdateComment(distinguishRes);
+ }
- break;
- }
+ async handleAddAdmin(form: AddAdmin) {
+ const addAdminRes = await HttpService.client.addAdmin(form);
+
+ if (addAdminRes.state == "success") {
+ this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
+ }
+ }
- case UserOperation.SaveComment: {
- const { comment_view } = wsJsonToRes<CommentResponse>(msg);
- saveCommentRes(comment_view, this.state.comments);
- this.setState(this.state);
+ async handleTransferCommunity(form: TransferCommunity) {
+ await HttpService.client.transferCommunity(form);
+ toast(I18NextService.i18n.t("transfer_community"));
+ }
- break;
- }
+ async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
+ const readRes = await HttpService.client.markCommentReplyAsRead(form);
+ this.findAndUpdateCommentReply(readRes);
+ }
- case UserOperation.CreateCommentLike: {
- const { comment_view } = wsJsonToRes<CommentResponse>(msg);
- createCommentLikeRes(comment_view, this.state.comments);
- this.setState(this.state);
+ async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
+ // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
+ await HttpService.client.markPersonMentionAsRead(form);
+ }
- break;
- }
+ async handleBanFromCommunity(form: BanFromCommunity) {
+ const banRes = await HttpService.client.banFromCommunity(form);
+ this.updateBanFromCommunity(banRes);
+ }
- case UserOperation.BlockPerson: {
- const data = wsJsonToRes<BlockPersonResponse>(msg);
- updatePersonBlock(data);
+ async handleBanPerson(form: BanPerson) {
+ const banRes = await HttpService.client.banPerson(form);
+ this.updateBan(banRes);
+ }
- break;
+ updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
+ // Maybe not necessary
+ if (banRes.state == "success") {
+ this.setState(s => {
+ if (s.postsRes.state == "success") {
+ s.postsRes.data.posts
+ .filter(c => c.creator.id == banRes.data.person_view.person.id)
+ .forEach(
+ c => (c.creator_banned_from_community = banRes.data.banned)
+ );
}
+ if (s.commentsRes.state == "success") {
+ s.commentsRes.data.comments
+ .filter(c => c.creator.id == banRes.data.person_view.person.id)
+ .forEach(
+ c => (c.creator_banned_from_community = banRes.data.banned)
+ );
+ }
+ return s;
+ });
+ }
+ }
- case UserOperation.CreatePostReport: {
- const data = wsJsonToRes<PostReportResponse>(msg);
- if (data) {
- toast(i18n.t("report_created"));
- }
-
- break;
+ updateBan(banRes: RequestState<BanPersonResponse>) {
+ // Maybe not necessary
+ if (banRes.state == "success") {
+ this.setState(s => {
+ if (s.postsRes.state == "success") {
+ s.postsRes.data.posts
+ .filter(c => c.creator.id == banRes.data.person_view.person.id)
+ .forEach(c => (c.creator.banned = banRes.data.banned));
+ }
+ if (s.commentsRes.state == "success") {
+ s.commentsRes.data.comments
+ .filter(c => c.creator.id == banRes.data.person_view.person.id)
+ .forEach(c => (c.creator.banned = banRes.data.banned));
}
+ return s;
+ });
+ }
+ }
- case UserOperation.CreateCommentReport: {
- const data = wsJsonToRes<CommentReportResponse>(msg);
- if (data) {
- toast(i18n.t("report_created"));
- }
+ purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
+ if (purgeRes.state == "success") {
+ toast(I18NextService.i18n.t("purge_success"));
+ this.context.router.history.push(`/`);
+ }
+ }
- break;
- }
+ findAndUpdateComment(res: RequestState<CommentResponse>) {
+ this.setState(s => {
+ if (s.commentsRes.state == "success" && res.state == "success") {
+ s.commentsRes.data.comments = editComment(
+ res.data.comment_view,
+ s.commentsRes.data.comments
+ );
+ s.finished.set(res.data.comment_view.comment.id, true);
+ }
+ return s;
+ });
+ }
- case UserOperation.PurgePerson:
- case UserOperation.PurgePost:
- case UserOperation.PurgeComment:
- case UserOperation.PurgeCommunity: {
- const data = wsJsonToRes<PurgeItemResponse>(msg);
- if (data.success) {
- toast(i18n.t("purge_success"));
- this.context.router.history.push(`/`);
- }
-
- break;
- }
+ createAndUpdateComments(res: RequestState<CommentResponse>) {
+ this.setState(s => {
+ if (s.commentsRes.state == "success" && res.state == "success") {
+ s.commentsRes.data.comments.unshift(res.data.comment_view);
+
+ // Set finished for the parent
+ s.finished.set(
+ getCommentParentId(res.data.comment_view.comment) ?? 0,
+ true
+ );
}
- }
+ return s;
+ });
+ }
+
+ findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
+ this.setState(s => {
+ if (s.commentsRes.state == "success" && res.state == "success") {
+ s.commentsRes.data.comments = editWith(
+ res.data.comment_reply_view,
+ s.commentsRes.data.comments
+ );
+ }
+ return s;
+ });
+ }
+
+ findAndUpdatePost(res: RequestState<PostResponse>) {
+ this.setState(s => {
+ if (s.postsRes.state == "success" && res.state == "success") {
+ s.postsRes.data.posts = editPost(
+ res.data.post_view,
+ s.postsRes.data.posts
+ );
+ }
+ return s;
+ });
}
}