import autosize from "autosize";
import { Component, createRef, linkEvent, RefObject } from "inferno";
import {
- AddAdminResponse,
+ AddAdmin,
+ AddModToCommunity,
AddModToCommunityResponse,
+ BanFromCommunity,
BanFromCommunityResponse,
+ BanPerson,
BanPersonResponse,
- BlockPersonResponse,
+ BlockCommunity,
+ BlockPerson,
+ CommentId,
+ CommentReplyResponse,
CommentResponse,
+ CommentSortType,
CommunityResponse,
+ CreateComment,
+ CreateCommentLike,
+ CreateCommentReport,
+ CreatePostLike,
+ CreatePostReport,
+ DeleteComment,
+ DeleteCommunity,
+ DeletePost,
+ DistinguishComment,
+ EditComment,
+ EditCommunity,
+ EditPost,
+ FeaturePost,
+ FollowCommunity,
+ GetComments,
+ GetCommentsResponse,
GetCommunityResponse,
GetPost,
GetPostResponse,
GetSiteResponse,
- ListingType,
- MarkCommentAsRead,
+ LockPost,
+ MarkCommentReplyAsRead,
+ MarkPersonMentionAsRead,
PostResponse,
- PostView,
- Search,
- SearchResponse,
- SearchType,
- SortType,
- UserOperation,
+ PurgeComment,
+ PurgeCommunity,
+ PurgeItemResponse,
+ PurgePerson,
+ PurgePost,
+ RemoveComment,
+ RemoveCommunity,
+ RemovePost,
+ SaveComment,
+ SavePost,
+ TransferCommunity,
} from "lemmy-js-client";
-import { Subscription } from "rxjs";
import { i18n } from "../../i18next";
import {
- CommentNode as CommentNodeI,
- CommentSortType,
+ CommentNodeI,
CommentViewType,
InitialFetchRequest,
} from "../../interfaces";
-import { UserService, WebSocketService } from "../../services";
+import { UserService } from "../../services";
+import { FirstLoadService } from "../../services/FirstLoadService";
+import { HttpService, RequestState } from "../../services/HttpService";
import {
- authField,
buildCommentsTree,
commentsToFlatNodes,
- createCommentLikeRes,
- createPostLikeRes,
- editCommentRes,
+ commentTreeMaxDepth,
+ debounce,
+ editComment,
+ editWith,
+ enableDownvotes,
+ enableNsfw,
getCommentIdFromProps,
+ getCommentParentId,
+ getDepthFromComment,
getIdFromProps,
- insertCommentIntoTree,
isBrowser,
isImage,
- previewLines,
+ myAuth,
restoreScrollPosition,
- saveCommentRes,
+ RouteDataResponse,
saveScrollPosition,
setIsoData,
- setOptionalAuth,
setupTippy,
toast,
+ updateCommunityBlock,
updatePersonBlock,
- wsClient,
- wsJsonToRes,
- wsSubscribe,
- wsUserOp,
} from "../../utils";
import { CommentForm } from "../comment/comment-form";
import { CommentNodes } from "../comment/comment-nodes";
import { Sidebar } from "../community/sidebar";
import { PostListing } from "./post-listing";
-interface PostState {
+const commentsShownInterval = 15;
+
+type PostData = RouteDataResponse<{
postRes: GetPostResponse;
- postId: number;
- commentTree: CommentNodeI[];
+ commentsRes: GetCommentsResponse;
+}>;
+
+interface PostState {
+ postId?: number;
commentId?: number;
+ postRes: RequestState<GetPostResponse>;
+ commentsRes: RequestState<GetCommentsResponse>;
commentSort: CommentSortType;
commentViewType: CommentViewType;
scrolled?: boolean;
- loading: boolean;
- crossPosts: PostView[];
siteRes: GetSiteResponse;
commentSectionRef?: RefObject<HTMLDivElement>;
showSidebarMobile: boolean;
+ maxCommentsShown: number;
+ finished: Map<CommentId, boolean | undefined>;
+ isIsomorphic: boolean;
}
export class Post extends Component<any, PostState> {
- private subscription: Subscription;
- private isoData = setIsoData(this.context);
- private emptyState: PostState = {
- postRes: null,
+ private isoData = setIsoData<PostData>(this.context);
+ private commentScrollDebounced: () => void;
+ state: PostState = {
+ postRes: { state: "empty" },
+ commentsRes: { state: "empty" },
postId: getIdFromProps(this.props),
- commentTree: [],
commentId: getCommentIdFromProps(this.props),
- commentSort: CommentSortType.Hot,
+ commentSort: "Hot",
commentViewType: CommentViewType.Tree,
scrolled: false,
- loading: true,
- crossPosts: [],
siteRes: this.isoData.site_res,
- commentSectionRef: null,
showSidebarMobile: false,
+ maxCommentsShown: commentsShownInterval,
+ finished: new Map(),
+ isIsomorphic: false,
};
constructor(props: any, context: any) {
super(props, context);
- this.state = this.emptyState;
- this.state.commentSectionRef = createRef();
+ this.handleDeleteCommunityClick =
+ this.handleDeleteCommunityClick.bind(this);
+ this.handleEditCommunity = this.handleEditCommunity.bind(this);
+ this.handleFollow = this.handleFollow.bind(this);
+ this.handleModRemoveCommunity = this.handleModRemoveCommunity.bind(this);
+ this.handleCreateComment = this.handleCreateComment.bind(this);
+ this.handleEditComment = this.handleEditComment.bind(this);
+ this.handleSaveComment = this.handleSaveComment.bind(this);
+ this.handleBlockCommunity = this.handleBlockCommunity.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.handleFetchChildren = this.handleFetchChildren.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);
- this.parseMessage = this.parseMessage.bind(this);
- this.subscription = wsSubscribe(this.parseMessage);
+ this.state = { ...this.state, commentSectionRef: createRef() };
// Only fetch the data if coming from another route
- if (this.isoData.path == this.context.router.route.match.url) {
- this.state.postRes = this.isoData.routeData[0];
- this.state.commentTree = buildCommentsTree(
- this.state.postRes.comments,
- this.state.commentSort
- );
- this.state.loading = false;
+ if (FirstLoadService.isFirstLoad) {
+ const { commentsRes, postRes } = this.isoData.routeData;
- if (isBrowser()) {
- this.fetchCrossPosts();
- if (this.state.commentId) {
- this.scrollCommentIntoView();
- }
+ this.state = {
+ ...this.state,
+ postRes,
+ commentsRes,
+ isIsomorphic: true,
+ };
+ if (isBrowser()) {
if (this.checkScrollIntoCommentsParam) {
this.scrollIntoCommentSection();
}
}
- } else {
- this.fetchPost();
}
}
- fetchPost() {
- let form: GetPost = {
- id: this.state.postId,
- auth: authField(false),
- };
- WebSocketService.Instance.send(wsClient.getPost(form));
- }
-
- fetchCrossPosts() {
- if (this.state.postRes.post_view.post.url) {
- let form: Search = {
- q: this.state.postRes.post_view.post.url,
- type_: SearchType.Url,
- sort: SortType.TopAll,
- listing_type: ListingType.All,
- page: 1,
- limit: 6,
- auth: authField(false),
- };
- WebSocketService.Instance.send(wsClient.search(form));
+ async fetchPost() {
+ this.setState({
+ postRes: { state: "loading" },
+ commentsRes: { state: "loading" },
+ });
+
+ const auth = myAuth();
+
+ this.setState({
+ postRes: await HttpService.client.getPost({
+ id: this.state.postId,
+ comment_id: this.state.commentId,
+ auth,
+ }),
+ commentsRes: await HttpService.client.getComments({
+ post_id: this.state.postId,
+ parent_id: this.state.commentId,
+ max_depth: commentTreeMaxDepth,
+ sort: this.state.commentSort,
+ type_: "All",
+ saved_only: false,
+ auth,
+ }),
+ });
+
+ setupTippy();
+
+ if (!this.state.commentId) restoreScrollPosition(this.context);
+
+ if (this.checkScrollIntoCommentsParam) {
+ this.scrollIntoCommentSection();
}
}
- static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
- let pathSplit = req.path.split("/");
- let promises: Promise<any>[] = [];
+ static async fetchInitialData({
+ client,
+ path,
+ auth,
+ }: InitialFetchRequest): Promise<PostData> {
+ const pathSplit = path.split("/");
- let id = Number(pathSplit[2]);
+ const pathType = pathSplit.at(1);
+ const id = pathSplit.at(2) ? Number(pathSplit.at(2)) : undefined;
- let postForm: GetPost = {
- id,
+ const postForm: GetPost = {
+ auth,
};
- setOptionalAuth(postForm, req.auth);
- promises.push(req.client.getPost(postForm));
+ const commentsForm: GetComments = {
+ max_depth: commentTreeMaxDepth,
+ sort: "Hot",
+ type_: "All",
+ saved_only: false,
+ auth,
+ };
+
+ // Set the correct id based on the path type
+ if (pathType === "post") {
+ postForm.id = id;
+ commentsForm.post_id = id;
+ } else {
+ postForm.comment_id = id;
+ commentsForm.parent_id = id;
+ }
- return promises;
+ return {
+ postRes: await client.getPost(postForm),
+ commentsRes: await client.getComments(commentsForm),
+ };
}
componentWillUnmount() {
- this.subscription.unsubscribe();
- window.isoData.path = undefined;
- saveScrollPosition(this.context);
- }
+ document.removeEventListener("scroll", this.commentScrollDebounced);
- componentDidMount() {
- WebSocketService.Instance.send(
- wsClient.postJoin({ post_id: this.state.postId })
- );
- autosize(document.querySelectorAll("textarea"));
+ saveScrollPosition(this.context);
}
- componentDidUpdate(_lastProps: any, lastState: PostState) {
- if (
- this.state.commentId &&
- !this.state.scrolled &&
- lastState.postRes &&
- lastState.postRes.comments.length > 0
- ) {
- this.scrollCommentIntoView();
+ async componentDidMount() {
+ if (!this.state.isIsomorphic) {
+ await this.fetchPost();
}
- if (this.checkScrollIntoCommentsParam) {
- this.scrollIntoCommentSection();
- }
+ autosize(document.querySelectorAll("textarea"));
+
+ this.commentScrollDebounced = debounce(this.trackCommentsBoxScrolling, 100);
+ document.addEventListener("scroll", this.commentScrollDebounced);
+ }
+ async componentDidUpdate(_lastProps: any) {
// Necessary if you are on a post and you click another post (same route)
if (_lastProps.location.pathname !== _lastProps.history.location.pathname) {
- // TODO Couldnt get a refresh working. This does for now.
- location.reload();
-
- // let currentId = this.props.match.params.id;
- // WebSocketService.Instance.getPost(currentId);
- // this.context.refresh();
- // this.context.router.history.push(_lastProps.location.pathname);
+ await this.fetchPost();
}
}
- scrollCommentIntoView() {
- var elmnt = document.getElementById(`comment-${this.state.commentId}`);
- elmnt.scrollIntoView();
- elmnt.classList.add("mark");
- this.state.scrolled = true;
- this.markScrolledAsRead(this.state.commentId);
- }
-
get checkScrollIntoCommentsParam() {
return Boolean(
new URLSearchParams(this.props.location.search).get("scrollToComments")
}
scrollIntoCommentSection() {
- this.state.commentSectionRef.current?.scrollIntoView();
+ this.state.commentSectionRef?.current?.scrollIntoView();
}
- // TODO this needs some re-work
- markScrolledAsRead(commentId: number) {
- let found = this.state.postRes.comments.find(
- c => c.comment.id == commentId
- );
- let parent = this.state.postRes.comments.find(
- c => found.comment.parent_id == c.comment.id
- );
- let parent_person_id = parent
- ? parent.creator.id
- : this.state.postRes.post_view.creator.id;
+ isBottom(el: Element): boolean {
+ return el?.getBoundingClientRect().bottom <= window.innerHeight;
+ }
- if (
- UserService.Instance.myUserInfo &&
- UserService.Instance.myUserInfo.local_user_view.person.id ==
- parent_person_id
- ) {
- let form: MarkCommentAsRead = {
- comment_id: found.comment.id,
- read: true,
- auth: authField(),
- };
- WebSocketService.Instance.send(wsClient.markCommentAsRead(form));
- UserService.Instance.unreadCountSub.next(
- UserService.Instance.unreadCountSub.value - 1
- );
+ /**
+ * Shows new comments when scrolling to the bottom of the comments div
+ */
+ trackCommentsBoxScrolling = () => {
+ const wrappedElement = document.getElementsByClassName("comments")[0];
+ if (wrappedElement && this.isBottom(wrappedElement)) {
+ const commentCount =
+ this.state.commentsRes.state == "success"
+ ? this.state.commentsRes.data.comments.length
+ : 0;
+
+ if (this.state.maxCommentsShown < commentCount) {
+ this.setState({
+ maxCommentsShown: this.state.maxCommentsShown + commentsShownInterval,
+ });
+ }
}
- }
+ };
get documentTitle(): string {
- return `${this.state.postRes.post_view.post.name} - ${this.state.siteRes.site_view.site.name}`;
+ const siteName = this.state.siteRes.site_view.site.name;
+ return this.state.postRes.state == "success"
+ ? `${this.state.postRes.data.post_view.post.name} - ${siteName}`
+ : siteName;
}
- get imageTag(): string {
- let post = this.state.postRes.post_view.post;
- return (
- post.thumbnail_url ||
- (post.url ? (isImage(post.url) ? post.url : undefined) : undefined)
- );
+ get imageTag(): string | undefined {
+ if (this.state.postRes.state == "success") {
+ const post = this.state.postRes.data.post_view.post;
+ const thumbnail = post.thumbnail_url;
+ const url = post.url;
+ return thumbnail || (url && isImage(url) ? url : undefined);
+ } else return undefined;
}
- get descriptionTag(): string {
- let body = this.state.postRes.post_view.post.body;
- return body ? previewLines(body) : undefined;
- }
-
- render() {
- let pv = this.state.postRes?.post_view;
- return (
- <div class="container">
- {this.state.loading ? (
+ renderPostRes() {
+ switch (this.state.postRes.state) {
+ case "loading":
+ return (
<h5>
<Spinner large />
</h5>
- ) : (
- <div class="row">
- <div class="col-12 col-md-8 mb-3">
+ );
+ case "success": {
+ const res = this.state.postRes.data;
+ return (
+ <div className="row">
+ <div className="col-12 col-md-8 mb-3">
<HtmlTags
title={this.documentTitle}
path={this.context.router.route.match.url}
image={this.imageTag}
- description={this.descriptionTag}
+ description={res.post_view.post.body}
/>
<PostListing
- post_view={pv}
- duplicates={this.state.crossPosts}
+ post_view={res.post_view}
+ crossPosts={res.cross_posts}
showBody
showCommunity
- moderators={this.state.postRes.moderators}
+ moderators={res.moderators}
admins={this.state.siteRes.admins}
- enableDownvotes={
- this.state.siteRes.site_view.site.enable_downvotes
- }
- enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
+ enableDownvotes={enableDownvotes(this.state.siteRes)}
+ enableNsfw={enableNsfw(this.state.siteRes)}
+ allLanguages={this.state.siteRes.all_languages}
+ siteLanguages={this.state.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}
/>
<div ref={this.state.commentSectionRef} className="mb-2" />
<CommentForm
- postId={this.state.postId}
- disabled={pv.post.locked}
+ node={res.post_view.post.id}
+ disabled={res.post_view.post.locked}
+ allLanguages={this.state.siteRes.all_languages}
+ siteLanguages={this.state.siteRes.discussion_languages}
+ onUpsertComment={this.handleCreateComment}
+ finished={this.state.finished.get(0)}
/>
- <div class="d-block d-md-none">
+ <div className="d-block d-md-none">
<button
- class="btn btn-secondary d-inline-block mb-2 mr-3"
+ className="btn btn-secondary d-inline-block mb-2 mr-3"
onClick={linkEvent(this, this.handleShowSidebarMobile)}
>
{i18n.t("sidebar")}{" "}
</button>
{this.state.showSidebarMobile && this.sidebar()}
</div>
- {this.state.postRes.comments.length > 0 && this.sortRadios()}
+ {this.sortRadios()}
{this.state.commentViewType == CommentViewType.Tree &&
this.commentsTree()}
- {this.state.commentViewType == CommentViewType.Chat &&
+ {this.state.commentViewType == CommentViewType.Flat &&
this.commentsFlat()}
</div>
- <div class="d-none d-md-block col-md-4">{this.sidebar()}</div>
+ <div className="d-none d-md-block col-md-4">{this.sidebar()}</div>
</div>
- )}
- </div>
- );
+ );
+ }
+ }
+ }
+
+ render() {
+ return <div className="container-lg">{this.renderPostRes()}</div>;
}
sortRadios() {
return (
<>
- <div class="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
+ <div className="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
<label
className={`btn btn-outline-secondary pointer ${
- this.state.commentSort === CommentSortType.Hot && "active"
+ this.state.commentSort === "Hot" && "active"
}`}
>
{i18n.t("hot")}
<input
type="radio"
- value={CommentSortType.Hot}
- checked={this.state.commentSort === CommentSortType.Hot}
+ value={"Hot"}
+ checked={this.state.commentSort === "Hot"}
onChange={linkEvent(this, this.handleCommentSortChange)}
/>
</label>
<label
className={`btn btn-outline-secondary pointer ${
- this.state.commentSort === CommentSortType.Top && "active"
+ this.state.commentSort === "Top" && "active"
}`}
>
{i18n.t("top")}
<input
type="radio"
- value={CommentSortType.Top}
- checked={this.state.commentSort === CommentSortType.Top}
+ value={"Top"}
+ checked={this.state.commentSort === "Top"}
onChange={linkEvent(this, this.handleCommentSortChange)}
/>
</label>
<label
className={`btn btn-outline-secondary pointer ${
- this.state.commentSort === CommentSortType.New && "active"
+ this.state.commentSort === "New" && "active"
}`}
>
{i18n.t("new")}
<input
type="radio"
- value={CommentSortType.New}
- checked={this.state.commentSort === CommentSortType.New}
+ value={"New"}
+ checked={this.state.commentSort === "New"}
onChange={linkEvent(this, this.handleCommentSortChange)}
/>
</label>
<label
className={`btn btn-outline-secondary pointer ${
- this.state.commentSort === CommentSortType.Old && "active"
+ this.state.commentSort === "Old" && "active"
}`}
>
{i18n.t("old")}
<input
type="radio"
- value={CommentSortType.Old}
- checked={this.state.commentSort === CommentSortType.Old}
+ value={"Old"}
+ checked={this.state.commentSort === "Old"}
onChange={linkEvent(this, this.handleCommentSortChange)}
/>
</label>
</div>
- <div class="btn-group btn-group-toggle flex-wrap mb-2">
+ <div className="btn-group btn-group-toggle flex-wrap mb-2">
<label
className={`btn btn-outline-secondary pointer ${
- this.state.commentViewType === CommentViewType.Chat && "active"
+ this.state.commentViewType === CommentViewType.Flat && "active"
}`}
>
{i18n.t("chat")}
<input
type="radio"
- value={CommentViewType.Chat}
- checked={this.state.commentViewType === CommentViewType.Chat}
+ value={CommentViewType.Flat}
+ checked={this.state.commentViewType === CommentViewType.Flat}
onChange={linkEvent(this, this.handleCommentViewTypeChange)}
/>
</label>
commentsFlat() {
// These are already sorted by new
- return (
- <div>
- <CommentNodes
- nodes={commentsToFlatNodes(this.state.postRes.comments)}
- noIndent
- locked={this.state.postRes.post_view.post.locked}
- moderators={this.state.postRes.moderators}
- admins={this.state.siteRes.admins}
- postCreatorId={this.state.postRes.post_view.creator.id}
- showContext
- enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
- />
- </div>
- );
+ const commentsRes = this.state.commentsRes;
+ const postRes = this.state.postRes;
+
+ if (commentsRes.state == "success" && postRes.state == "success") {
+ return (
+ <div>
+ <CommentNodes
+ nodes={commentsToFlatNodes(commentsRes.data.comments)}
+ viewType={this.state.commentViewType}
+ maxCommentsShown={this.state.maxCommentsShown}
+ noIndent
+ locked={postRes.data.post_view.post.locked}
+ moderators={postRes.data.moderators}
+ admins={this.state.siteRes.admins}
+ enableDownvotes={enableDownvotes(this.state.siteRes)}
+ showContext
+ finished={this.state.finished}
+ allLanguages={this.state.siteRes.all_languages}
+ siteLanguages={this.state.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}
+ onFetchChildren={this.handleFetchChildren}
+ onPurgeComment={this.handlePurgeComment}
+ onPurgePerson={this.handlePurgePerson}
+ onCommentReplyRead={this.handleCommentReplyRead}
+ onPersonMentionRead={this.handlePersonMentionRead}
+ onBanPersonFromCommunity={this.handleBanFromCommunity}
+ onBanPerson={this.handleBanPerson}
+ onCreateComment={this.handleCreateComment}
+ onEditComment={this.handleEditComment}
+ />
+ </div>
+ );
+ }
}
sidebar() {
+ const res = this.state.postRes;
+ if (res.state === "success") {
+ return (
+ <div className="mb-3">
+ <Sidebar
+ community_view={res.data.community_view}
+ moderators={res.data.moderators}
+ admins={this.state.siteRes.admins}
+ online={res.data.online}
+ enableNsfw={enableNsfw(this.state.siteRes)}
+ showIcon
+ allLanguages={this.state.siteRes.all_languages}
+ siteLanguages={this.state.siteRes.discussion_languages}
+ onDeleteCommunity={this.handleDeleteCommunityClick}
+ onLeaveModTeam={this.handleAddModToCommunity}
+ onFollowCommunity={this.handleFollow}
+ onRemoveCommunity={this.handleModRemoveCommunity}
+ onPurgeCommunity={this.handlePurgeCommunity}
+ onBlockCommunity={this.handleBlockCommunity}
+ onEditCommunity={this.handleEditCommunity}
+ />
+ </div>
+ );
+ }
+ }
+
+ commentsTree() {
+ const res = this.state.postRes;
+ const firstComment = this.commentTree().at(0)?.comment_view.comment;
+ const depth = getDepthFromComment(firstComment);
+ const showContextButton = depth ? depth > 0 : false;
+
return (
- <div class="mb-3">
- <Sidebar
- community_view={this.state.postRes.community_view}
- moderators={this.state.postRes.moderators}
- admins={this.state.siteRes.admins}
- online={this.state.postRes.online}
- enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
- showIcon
- />
- </div>
+ res.state == "success" && (
+ <div>
+ {!!this.state.commentId && (
+ <>
+ <button
+ className="pl-0 d-block btn btn-link text-muted"
+ onClick={linkEvent(this, this.handleViewPost)}
+ >
+ {i18n.t("view_all_comments")} ➔
+ </button>
+ {showContextButton && (
+ <button
+ className="pl-0 d-block btn btn-link text-muted"
+ onClick={linkEvent(this, this.handleViewContext)}
+ >
+ {i18n.t("show_context")} ➔
+ </button>
+ )}
+ </>
+ )}
+ <CommentNodes
+ nodes={this.commentTree()}
+ viewType={this.state.commentViewType}
+ maxCommentsShown={this.state.maxCommentsShown}
+ locked={res.data.post_view.post.locked}
+ moderators={res.data.moderators}
+ admins={this.state.siteRes.admins}
+ enableDownvotes={enableDownvotes(this.state.siteRes)}
+ finished={this.state.finished}
+ allLanguages={this.state.siteRes.all_languages}
+ siteLanguages={this.state.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}
+ onFetchChildren={this.handleFetchChildren}
+ onPurgeComment={this.handlePurgeComment}
+ onPurgePerson={this.handlePurgePerson}
+ onCommentReplyRead={this.handleCommentReplyRead}
+ onPersonMentionRead={this.handlePersonMentionRead}
+ onBanPersonFromCommunity={this.handleBanFromCommunity}
+ onBanPerson={this.handleBanPerson}
+ onCreateComment={this.handleCreateComment}
+ onEditComment={this.handleEditComment}
+ />
+ </div>
+ )
);
}
- handleCommentSortChange(i: Post, event: any) {
- i.state.commentSort = Number(event.target.value);
- i.state.commentViewType = CommentViewType.Tree;
- i.state.commentTree = buildCommentsTree(
- i.state.postRes.comments,
- i.state.commentSort
- );
- i.setState(i.state);
+ commentTree(): CommentNodeI[] {
+ if (this.state.commentsRes.state == "success") {
+ return buildCommentsTree(
+ this.state.commentsRes.data.comments,
+ !!this.state.commentId
+ );
+ } else {
+ return [];
+ }
+ }
+
+ async handleCommentSortChange(i: Post, event: any) {
+ i.setState({
+ commentSort: event.target.value as CommentSortType,
+ commentViewType: CommentViewType.Tree,
+ commentsRes: { state: "loading" },
+ postRes: { state: "loading" },
+ });
+ await i.fetchPost();
}
handleCommentViewTypeChange(i: Post, event: any) {
- i.state.commentViewType = Number(event.target.value);
- i.state.commentSort = CommentSortType.New;
- i.state.commentTree = buildCommentsTree(
- i.state.postRes.comments,
- i.state.commentSort
- );
- i.setState(i.state);
+ i.setState({
+ commentViewType: Number(event.target.value),
+ commentSort: "New",
+ });
}
handleShowSidebarMobile(i: Post) {
- i.state.showSidebarMobile = !i.state.showSidebarMobile;
- i.setState(i.state);
+ i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
}
- commentsTree() {
- return (
- <div>
- <CommentNodes
- nodes={this.state.commentTree}
- locked={this.state.postRes.post_view.post.locked}
- moderators={this.state.postRes.moderators}
- admins={this.state.siteRes.admins}
- postCreatorId={this.state.postRes.post_view.creator.id}
- enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
- />
- </div>
- );
+ handleViewPost(i: Post) {
+ if (i.state.postRes.state == "success") {
+ const id = i.state.postRes.data.post_view.post.id;
+ i.context.router.history.push(`/post/${id}`);
+ }
}
- parseMessage(msg: any) {
- let op = wsUserOp(msg);
- console.log(msg);
- if (msg.error) {
- toast(i18n.t(msg.error), "danger");
- return;
- } else if (msg.reconnect) {
- let postId = Number(this.props.match.params.id);
- WebSocketService.Instance.send(wsClient.postJoin({ post_id: postId }));
- WebSocketService.Instance.send(
- wsClient.getPost({
- id: postId,
- auth: authField(false),
- })
+ handleViewContext(i: Post) {
+ if (i.state.commentsRes.state == "success") {
+ const parentId = getCommentParentId(
+ i.state.commentsRes.data.comments.at(0)?.comment
);
- } else if (op == UserOperation.GetPost) {
- let data = wsJsonToRes<GetPostResponse>(msg).data;
- this.state.postRes = data;
- this.state.commentTree = buildCommentsTree(
- this.state.postRes.comments,
- this.state.commentSort
- );
- this.state.loading = false;
+ if (parentId) {
+ i.context.router.history.push(`/comment/${parentId}`);
+ }
+ }
+ }
- // Get cross-posts
- this.fetchCrossPosts();
- this.setState(this.state);
- setupTippy();
- if (!this.state.commentId) restoreScrollPosition(this.context);
+ async handleDeleteCommunityClick(form: DeleteCommunity) {
+ const deleteCommunityRes = await HttpService.client.deleteCommunity(form);
+ this.updateCommunity(deleteCommunityRes);
+ }
- if (this.checkScrollIntoCommentsParam) {
- this.scrollIntoCommentSection();
- }
- } else if (op == UserOperation.CreateComment) {
- let data = wsJsonToRes<CommentResponse>(msg).data;
-
- // Necessary since it might be a user reply, which has the recipients, to avoid double
- if (data.recipient_ids.length == 0) {
- this.state.postRes.comments.unshift(data.comment_view);
- insertCommentIntoTree(this.state.commentTree, data.comment_view);
- this.state.postRes.post_view.counts.comments++;
- this.setState(this.state);
- setupTippy();
+ async handleAddModToCommunity(form: AddModToCommunity) {
+ const addModRes = await HttpService.client.addModToCommunity(form);
+ this.updateModerators(addModRes);
+ }
+
+ async handleFollow(form: FollowCommunity) {
+ const followCommunityRes = await HttpService.client.followCommunity(form);
+ this.updateCommunity(followCommunityRes);
+
+ // Update myUserInfo
+ if (followCommunityRes.state === "success") {
+ const communityId = followCommunityRes.data.community_view.community.id;
+ const mui = UserService.Instance.myUserInfo;
+ if (mui) {
+ mui.follows = mui.follows.filter(i => i.community.id != communityId);
}
- } else if (
- op == UserOperation.EditComment ||
- op == UserOperation.DeleteComment ||
- op == UserOperation.RemoveComment
- ) {
- let data = wsJsonToRes<CommentResponse>(msg).data;
- editCommentRes(data.comment_view, this.state.postRes.comments);
- this.setState(this.state);
- } else if (op == UserOperation.SaveComment) {
- let data = wsJsonToRes<CommentResponse>(msg).data;
- saveCommentRes(data.comment_view, this.state.postRes.comments);
- this.setState(this.state);
- setupTippy();
- } else if (op == UserOperation.CreateCommentLike) {
- let data = wsJsonToRes<CommentResponse>(msg).data;
- createCommentLikeRes(data.comment_view, this.state.postRes.comments);
- this.setState(this.state);
- } else if (op == UserOperation.CreatePostLike) {
- let data = wsJsonToRes<PostResponse>(msg).data;
- createPostLikeRes(data.post_view, this.state.postRes.post_view);
- this.setState(this.state);
- } else if (
- op == UserOperation.EditPost ||
- op == UserOperation.DeletePost ||
- op == UserOperation.RemovePost ||
- op == UserOperation.LockPost ||
- op == UserOperation.StickyPost ||
- op == UserOperation.SavePost
- ) {
- let data = wsJsonToRes<PostResponse>(msg).data;
- this.state.postRes.post_view = data.post_view;
- this.setState(this.state);
- setupTippy();
- } else if (
- op == UserOperation.EditCommunity ||
- op == UserOperation.DeleteCommunity ||
- op == UserOperation.RemoveCommunity ||
- op == UserOperation.FollowCommunity
- ) {
- let data = wsJsonToRes<CommunityResponse>(msg).data;
- this.state.postRes.community_view = data.community_view;
- this.state.postRes.post_view.community = data.community_view.community;
- this.setState(this.state);
- this.setState(this.state);
- } else if (op == UserOperation.BanFromCommunity) {
- let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
- this.state.postRes.comments
- .filter(c => c.creator.id == data.person_view.person.id)
- .forEach(c => (c.creator_banned_from_community = data.banned));
+ }
+ }
+
+ async handlePurgeCommunity(form: PurgeCommunity) {
+ const purgeCommunityRes = await HttpService.client.purgeCommunity(form);
+ this.purgeItem(purgeCommunityRes);
+ }
+
+ async handlePurgePerson(form: PurgePerson) {
+ const purgePersonRes = await HttpService.client.purgePerson(form);
+ this.purgeItem(purgePersonRes);
+ }
+
+ async handlePurgeComment(form: PurgeComment) {
+ const purgeCommentRes = await HttpService.client.purgeComment(form);
+ this.purgeItem(purgeCommentRes);
+ }
+
+ async handlePurgePost(form: PurgePost) {
+ const purgeRes = await HttpService.client.purgePost(form);
+ this.purgeItem(purgeRes);
+ }
+
+ async handleBlockCommunity(form: BlockCommunity) {
+ const blockCommunityRes = await HttpService.client.blockCommunity(form);
+ // TODO Probably isn't necessary
+ this.setState(s => {
if (
- this.state.postRes.post_view.creator.id == data.person_view.person.id
+ s.postRes.state == "success" &&
+ blockCommunityRes.state == "success"
) {
- this.state.postRes.post_view.creator_banned_from_community =
- data.banned;
+ s.postRes.data.community_view = blockCommunityRes.data.community_view;
}
- this.setState(this.state);
- } else if (op == UserOperation.AddModToCommunity) {
- let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
- this.state.postRes.moderators = data.moderators;
- this.setState(this.state);
- } else if (op == UserOperation.BanPerson) {
- let data = wsJsonToRes<BanPersonResponse>(msg).data;
- this.state.postRes.comments
- .filter(c => c.creator.id == data.person_view.person.id)
- .forEach(c => (c.creator.banned = data.banned));
- if (
- this.state.postRes.post_view.creator.id == data.person_view.person.id
- ) {
- this.state.postRes.post_view.creator.banned = data.banned;
+ return s;
+ });
+
+ if (blockCommunityRes.state == "success") {
+ updateCommunityBlock(blockCommunityRes.data);
+ }
+ }
+
+ async handleBlockPerson(form: BlockPerson) {
+ const blockPersonRes = await HttpService.client.blockPerson(form);
+ if (blockPersonRes.state == "success") {
+ updatePersonBlock(blockPersonRes.data);
+ }
+ }
+
+ async handleModRemoveCommunity(form: RemoveCommunity) {
+ const removeCommunityRes = await HttpService.client.removeCommunity(form);
+ this.updateCommunity(removeCommunityRes);
+ }
+
+ async handleEditCommunity(form: EditCommunity) {
+ const res = await HttpService.client.editCommunity(form);
+ this.updateCommunity(res);
+
+ return res;
+ }
+
+ async handleCreateComment(form: CreateComment) {
+ const createCommentRes = await HttpService.client.createComment(form);
+ this.createAndUpdateComments(createCommentRes);
+
+ return createCommentRes;
+ }
+
+ async handleEditComment(form: EditComment) {
+ const editCommentRes = await HttpService.client.editComment(form);
+ this.findAndUpdateComment(editCommentRes);
+
+ return editCommentRes;
+ }
+
+ async handleDeleteComment(form: DeleteComment) {
+ const deleteCommentRes = await HttpService.client.deleteComment(form);
+ this.findAndUpdateComment(deleteCommentRes);
+ }
+
+ async handleDeletePost(form: DeletePost) {
+ const deleteRes = await HttpService.client.deletePost(form);
+ this.updatePost(deleteRes);
+ }
+
+ async handleRemovePost(form: RemovePost) {
+ const removeRes = await HttpService.client.removePost(form);
+ this.updatePost(removeRes);
+ }
+
+ async handleRemoveComment(form: RemoveComment) {
+ const removeCommentRes = await HttpService.client.removeComment(form);
+ this.findAndUpdateComment(removeCommentRes);
+ }
+
+ async handleSaveComment(form: SaveComment) {
+ const saveCommentRes = await HttpService.client.saveComment(form);
+ this.findAndUpdateComment(saveCommentRes);
+ }
+
+ async handleSavePost(form: SavePost) {
+ const saveRes = await HttpService.client.savePost(form);
+ this.updatePost(saveRes);
+ }
+
+ async handleFeaturePost(form: FeaturePost) {
+ const featureRes = await HttpService.client.featurePost(form);
+ this.updatePost(featureRes);
+ }
+
+ async handleCommentVote(form: CreateCommentLike) {
+ const voteRes = await HttpService.client.likeComment(form);
+ this.findAndUpdateComment(voteRes);
+ }
+
+ async handlePostVote(form: CreatePostLike) {
+ const voteRes = await HttpService.client.likePost(form);
+ this.updatePost(voteRes);
+ }
+
+ async handlePostEdit(form: EditPost) {
+ const res = await HttpService.client.editPost(form);
+ this.updatePost(res);
+ }
+
+ async handleCommentReport(form: CreateCommentReport) {
+ const reportRes = await HttpService.client.createCommentReport(form);
+ if (reportRes.state == "success") {
+ toast(i18n.t("report_created"));
+ }
+ }
+
+ async handlePostReport(form: CreatePostReport) {
+ const reportRes = await HttpService.client.createPostReport(form);
+ if (reportRes.state == "success") {
+ toast(i18n.t("report_created"));
+ }
+ }
+
+ async handleLockPost(form: LockPost) {
+ const lockRes = await HttpService.client.lockPost(form);
+ this.updatePost(lockRes);
+ }
+
+ async handleDistinguishComment(form: DistinguishComment) {
+ const distinguishRes = await HttpService.client.distinguishComment(form);
+ this.findAndUpdateComment(distinguishRes);
+ }
+
+ 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));
+ }
+ }
+
+ async handleTransferCommunity(form: TransferCommunity) {
+ const transferCommunityRes = await HttpService.client.transferCommunity(
+ form
+ );
+ this.updateCommunityFull(transferCommunityRes);
+ }
+
+ async handleFetchChildren(form: GetComments) {
+ const moreCommentsRes = await HttpService.client.getComments(form);
+ if (
+ this.state.commentsRes.state == "success" &&
+ moreCommentsRes.state == "success"
+ ) {
+ const newComments = moreCommentsRes.data.comments;
+ // Remove the first comment, since it is the parent
+ newComments.shift();
+ const newRes = this.state.commentsRes;
+ newRes.data.comments.push(...newComments);
+ this.setState({ commentsRes: newRes });
+ }
+ }
+
+ async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
+ const readRes = await HttpService.client.markCommentReplyAsRead(form);
+ this.findAndUpdateCommentReply(readRes);
+ }
+
+ 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);
+ }
+
+ async handleBanFromCommunity(form: BanFromCommunity) {
+ const banRes = await HttpService.client.banFromCommunity(form);
+ this.updateBan(banRes);
+ }
+
+ async handleBanPerson(form: BanPerson) {
+ const banRes = await HttpService.client.banPerson(form);
+ this.updateBan(banRes);
+ }
+
+ updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
+ // Maybe not necessary
+ if (banRes.state == "success") {
+ this.setState(s => {
+ if (
+ s.postRes.state == "success" &&
+ s.postRes.data.post_view.creator.id ==
+ banRes.data.person_view.person.id
+ ) {
+ s.postRes.data.post_view.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;
+ });
+ }
+ }
+
+ updateBan(banRes: RequestState<BanPersonResponse>) {
+ // Maybe not necessary
+ if (banRes.state == "success") {
+ this.setState(s => {
+ if (
+ s.postRes.state == "success" &&
+ s.postRes.data.post_view.creator.id ==
+ banRes.data.person_view.person.id
+ ) {
+ s.postRes.data.post_view.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;
+ });
+ }
+ }
+
+ updateCommunity(communityRes: RequestState<CommunityResponse>) {
+ this.setState(s => {
+ if (s.postRes.state == "success" && communityRes.state == "success") {
+ s.postRes.data.community_view = communityRes.data.community_view;
}
- this.setState(this.state);
- } else if (op == UserOperation.AddAdmin) {
- let data = wsJsonToRes<AddAdminResponse>(msg).data;
- this.state.siteRes.admins = data.admins;
- this.setState(this.state);
- } else if (op == UserOperation.Search) {
- let data = wsJsonToRes<SearchResponse>(msg).data;
- this.state.crossPosts = data.posts.filter(
- p => p.post.id != Number(this.props.match.params.id)
- );
- this.setState(this.state);
- } else if (op == UserOperation.TransferSite) {
- let data = wsJsonToRes<GetSiteResponse>(msg).data;
- this.state.siteRes = data;
- this.setState(this.state);
- } else if (op == UserOperation.TransferCommunity) {
- let data = wsJsonToRes<GetCommunityResponse>(msg).data;
- this.state.postRes.community_view = data.community_view;
- this.state.postRes.post_view.community = data.community_view.community;
- this.state.postRes.moderators = data.moderators;
- this.setState(this.state);
- } else if (op == UserOperation.BlockPerson) {
- let data = wsJsonToRes<BlockPersonResponse>(msg).data;
- updatePersonBlock(data);
+ return s;
+ });
+ }
+
+ updateCommunityFull(res: RequestState<GetCommunityResponse>) {
+ this.setState(s => {
+ if (s.postRes.state == "success" && res.state == "success") {
+ s.postRes.data.community_view = res.data.community_view;
+ s.postRes.data.moderators = res.data.moderators;
+ }
+ return s;
+ });
+ }
+
+ updatePost(post: RequestState<PostResponse>) {
+ this.setState(s => {
+ if (s.postRes.state == "success" && post.state == "success") {
+ s.postRes.data.post_view = post.data.post_view;
+ }
+ return s;
+ });
+ }
+
+ purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
+ if (purgeRes.state == "success") {
+ toast(i18n.t("purge_success"));
+ this.context.router.history.push(`/`);
}
}
+
+ 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;
+ });
+ }
+
+ 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;
+ });
+ }
+
+ 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;
+ });
+ }
+
+ updateModerators(res: RequestState<AddModToCommunityResponse>) {
+ // Update the moderators
+ this.setState(s => {
+ if (s.postRes.state == "success" && res.state == "success") {
+ s.postRes.data.moderators = res.data.moderators;
+ }
+ return s;
+ });
+ }
}