1 import autosize from "autosize";
2 import { Component, createRef, linkEvent, RefObject } from "inferno";
5 AddModToCommunityResponse,
6 BanFromCommunityResponse,
26 } from "lemmy-js-client";
27 import { Subscription } from "rxjs";
28 import { i18n } from "../../i18next";
30 CommentNode as CommentNodeI,
34 } from "../../interfaces";
35 import { UserService, WebSocketService } from "../../services";
44 getCommentIdFromProps,
46 insertCommentIntoTree,
50 restoreScrollPosition,
63 import { CommentForm } from "../comment/comment-form";
64 import { CommentNodes } from "../comment/comment-nodes";
65 import { HtmlTags } from "../common/html-tags";
66 import { Icon, Spinner } from "../common/icon";
67 import { Sidebar } from "../community/sidebar";
68 import { PostListing } from "./post-listing";
70 const commentsShownInterval = 15;
73 postRes: GetPostResponse;
75 commentTree: CommentNodeI[];
77 commentSort: CommentSortType;
78 commentViewType: CommentViewType;
81 crossPosts: PostView[];
82 siteRes: GetSiteResponse;
83 commentSectionRef?: RefObject<HTMLDivElement>;
84 showSidebarMobile: boolean;
85 maxCommentsShown: number;
88 export class Post extends Component<any, PostState> {
89 private subscription: Subscription;
90 private isoData = setIsoData(this.context);
91 private commentScrollDebounced: () => void;
92 private emptyState: PostState = {
94 postId: getIdFromProps(this.props),
96 commentId: getCommentIdFromProps(this.props),
97 commentSort: CommentSortType.Hot,
98 commentViewType: CommentViewType.Tree,
102 siteRes: this.isoData.site_res,
103 commentSectionRef: null,
104 showSidebarMobile: false,
105 maxCommentsShown: commentsShownInterval,
108 constructor(props: any, context: any) {
109 super(props, context);
111 this.state = this.emptyState;
112 this.state.commentSectionRef = createRef();
114 this.parseMessage = this.parseMessage.bind(this);
115 this.subscription = wsSubscribe(this.parseMessage);
117 // Only fetch the data if coming from another route
118 if (this.isoData.path == this.context.router.route.match.url) {
119 this.state.postRes = this.isoData.routeData[0];
120 this.state.commentTree = buildCommentsTree(
121 this.state.postRes.comments,
122 this.state.commentSort
124 this.state.loading = false;
127 this.fetchCrossPosts();
128 if (this.state.commentId) {
129 this.scrollCommentIntoView();
132 if (this.checkScrollIntoCommentsParam) {
133 this.scrollIntoCommentSection();
142 let form: GetPost = {
143 id: this.state.postId,
144 auth: authField(false),
146 WebSocketService.Instance.send(wsClient.getPost(form));
150 if (this.state.postRes.post_view.post.url) {
152 q: this.state.postRes.post_view.post.url,
153 type_: SearchType.Url,
154 sort: SortType.TopAll,
155 listing_type: ListingType.All,
158 auth: authField(false),
160 WebSocketService.Instance.send(wsClient.search(form));
164 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
165 let pathSplit = req.path.split("/");
166 let promises: Promise<any>[] = [];
168 let id = Number(pathSplit[2]);
170 let postForm: GetPost = {
173 setOptionalAuth(postForm, req.auth);
175 promises.push(req.client.getPost(postForm));
180 componentWillUnmount() {
181 this.subscription.unsubscribe();
182 document.removeEventListener("scroll", this.commentScrollDebounced);
184 window.isoData.path = undefined;
185 saveScrollPosition(this.context);
188 componentDidMount() {
189 WebSocketService.Instance.send(
190 wsClient.postJoin({ post_id: this.state.postId })
192 autosize(document.querySelectorAll("textarea"));
194 this.commentScrollDebounced = debounce(this.trackCommentsBoxScrolling, 100);
195 document.addEventListener("scroll", this.commentScrollDebounced);
198 componentDidUpdate(_lastProps: any, lastState: PostState) {
200 this.state.commentId &&
201 !this.state.scrolled &&
203 lastState.postRes.comments.length > 0
205 this.scrollCommentIntoView();
208 // Necessary if you are on a post and you click another post (same route)
209 if (_lastProps.location.pathname !== _lastProps.history.location.pathname) {
210 // TODO Couldnt get a refresh working. This does for now.
213 // let currentId = this.props.match.params.id;
214 // WebSocketService.Instance.getPost(currentId);
215 // this.context.refresh();
216 // this.context.router.history.push(_lastProps.location.pathname);
220 scrollCommentIntoView() {
221 var elmnt = document.getElementById(`comment-${this.state.commentId}`);
222 elmnt.scrollIntoView();
223 elmnt.classList.add("mark");
224 this.state.scrolled = true;
225 this.markScrolledAsRead(this.state.commentId);
228 get checkScrollIntoCommentsParam() {
230 new URLSearchParams(this.props.location.search).get("scrollToComments")
234 scrollIntoCommentSection() {
235 this.state.commentSectionRef.current?.scrollIntoView();
238 // TODO this needs some re-work
239 markScrolledAsRead(commentId: number) {
240 let found = this.state.postRes.comments.find(
241 c => c.comment.id == commentId
243 let parent = this.state.postRes.comments.find(
244 c => found.comment.parent_id == c.comment.id
246 let parent_person_id = parent
248 : this.state.postRes.post_view.creator.id;
251 UserService.Instance.myUserInfo &&
252 UserService.Instance.myUserInfo.local_user_view.person.id ==
255 let form: MarkCommentAsRead = {
256 comment_id: found.comment.id,
260 WebSocketService.Instance.send(wsClient.markCommentAsRead(form));
261 UserService.Instance.unreadInboxCountSub.next(
262 UserService.Instance.unreadInboxCountSub.value - 1
267 isBottom(el: Element) {
268 return el.getBoundingClientRect().bottom <= window.innerHeight;
272 * Shows new comments when scrolling to the bottom of the comments div
274 trackCommentsBoxScrolling = () => {
275 const wrappedElement = document.getElementsByClassName("comments")[0];
276 if (this.isBottom(wrappedElement)) {
277 this.state.maxCommentsShown += commentsShownInterval;
278 this.setState(this.state);
282 get documentTitle(): string {
283 return `${this.state.postRes.post_view.post.name} - ${this.state.siteRes.site_view.site.name}`;
286 get imageTag(): string {
287 let post = this.state.postRes.post_view.post;
289 post.thumbnail_url ||
290 (post.url ? (isImage(post.url) ? post.url : undefined) : undefined)
294 get descriptionTag(): string {
295 let body = this.state.postRes.post_view.post.body;
296 return body ? previewLines(body) : undefined;
300 let pv = this.state.postRes?.post_view;
302 <div class="container">
303 {this.state.loading ? (
309 <div class="col-12 col-md-8 mb-3">
311 title={this.documentTitle}
312 path={this.context.router.route.match.url}
313 image={this.imageTag}
314 description={this.descriptionTag}
318 duplicates={this.state.crossPosts}
321 moderators={this.state.postRes.moderators}
322 admins={this.state.siteRes.admins}
324 this.state.siteRes.site_view.site.enable_downvotes
326 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
328 <div ref={this.state.commentSectionRef} className="mb-2" />
330 postId={this.state.postId}
331 disabled={pv.post.locked}
333 <div class="d-block d-md-none">
335 class="btn btn-secondary d-inline-block mb-2 mr-3"
336 onClick={linkEvent(this, this.handleShowSidebarMobile)}
338 {i18n.t("sidebar")}{" "}
341 this.state.showSidebarMobile
345 classes="icon-inline"
348 {this.state.showSidebarMobile && this.sidebar()}
350 {this.state.postRes.comments.length > 0 && this.sortRadios()}
351 {this.state.commentViewType == CommentViewType.Tree &&
353 {this.state.commentViewType == CommentViewType.Chat &&
356 <div class="d-none d-md-block col-md-4">{this.sidebar()}</div>
366 <div class="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
368 className={`btn btn-outline-secondary pointer ${
369 this.state.commentSort === CommentSortType.Hot && "active"
375 value={CommentSortType.Hot}
376 checked={this.state.commentSort === CommentSortType.Hot}
377 onChange={linkEvent(this, this.handleCommentSortChange)}
381 className={`btn btn-outline-secondary pointer ${
382 this.state.commentSort === CommentSortType.Top && "active"
388 value={CommentSortType.Top}
389 checked={this.state.commentSort === CommentSortType.Top}
390 onChange={linkEvent(this, this.handleCommentSortChange)}
394 className={`btn btn-outline-secondary pointer ${
395 this.state.commentSort === CommentSortType.New && "active"
401 value={CommentSortType.New}
402 checked={this.state.commentSort === CommentSortType.New}
403 onChange={linkEvent(this, this.handleCommentSortChange)}
407 className={`btn btn-outline-secondary pointer ${
408 this.state.commentSort === CommentSortType.Old && "active"
414 value={CommentSortType.Old}
415 checked={this.state.commentSort === CommentSortType.Old}
416 onChange={linkEvent(this, this.handleCommentSortChange)}
420 <div class="btn-group btn-group-toggle flex-wrap mb-2">
422 className={`btn btn-outline-secondary pointer ${
423 this.state.commentViewType === CommentViewType.Chat && "active"
429 value={CommentViewType.Chat}
430 checked={this.state.commentViewType === CommentViewType.Chat}
431 onChange={linkEvent(this, this.handleCommentViewTypeChange)}
440 // These are already sorted by new
444 nodes={commentsToFlatNodes(this.state.postRes.comments)}
445 maxCommentsShown={this.state.maxCommentsShown}
447 locked={this.state.postRes.post_view.post.locked}
448 moderators={this.state.postRes.moderators}
449 admins={this.state.siteRes.admins}
450 postCreatorId={this.state.postRes.post_view.creator.id}
452 enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
462 community_view={this.state.postRes.community_view}
463 moderators={this.state.postRes.moderators}
464 admins={this.state.siteRes.admins}
465 online={this.state.postRes.online}
466 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
473 handleCommentSortChange(i: Post, event: any) {
474 i.state.commentSort = Number(event.target.value);
475 i.state.commentViewType = CommentViewType.Tree;
476 i.state.commentTree = buildCommentsTree(
477 i.state.postRes.comments,
483 handleCommentViewTypeChange(i: Post, event: any) {
484 i.state.commentViewType = Number(event.target.value);
485 i.state.commentSort = CommentSortType.New;
486 i.state.commentTree = buildCommentsTree(
487 i.state.postRes.comments,
493 handleShowSidebarMobile(i: Post) {
494 i.state.showSidebarMobile = !i.state.showSidebarMobile;
502 nodes={this.state.commentTree}
503 maxCommentsShown={this.state.maxCommentsShown}
504 locked={this.state.postRes.post_view.post.locked}
505 moderators={this.state.postRes.moderators}
506 admins={this.state.siteRes.admins}
507 postCreatorId={this.state.postRes.post_view.creator.id}
508 enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
514 parseMessage(msg: any) {
515 let op = wsUserOp(msg);
518 toast(i18n.t(msg.error), "danger");
520 } else if (msg.reconnect) {
521 let postId = Number(this.props.match.params.id);
522 WebSocketService.Instance.send(wsClient.postJoin({ post_id: postId }));
523 WebSocketService.Instance.send(
526 auth: authField(false),
529 } else if (op == UserOperation.GetPost) {
530 let data = wsJsonToRes<GetPostResponse>(msg).data;
531 this.state.postRes = data;
532 this.state.commentTree = buildCommentsTree(
533 this.state.postRes.comments,
534 this.state.commentSort
536 this.state.loading = false;
539 this.fetchCrossPosts();
540 this.setState(this.state);
542 if (!this.state.commentId) restoreScrollPosition(this.context);
544 if (this.checkScrollIntoCommentsParam) {
545 this.scrollIntoCommentSection();
547 } else if (op == UserOperation.CreateComment) {
548 let data = wsJsonToRes<CommentResponse>(msg).data;
550 // Necessary since it might be a user reply, which has the recipients, to avoid double
551 if (data.recipient_ids.length == 0) {
552 this.state.postRes.comments.unshift(data.comment_view);
553 insertCommentIntoTree(this.state.commentTree, data.comment_view);
554 this.state.postRes.post_view.counts.comments++;
555 this.setState(this.state);
559 op == UserOperation.EditComment ||
560 op == UserOperation.DeleteComment ||
561 op == UserOperation.RemoveComment
563 let data = wsJsonToRes<CommentResponse>(msg).data;
564 editCommentRes(data.comment_view, this.state.postRes.comments);
565 this.setState(this.state);
566 } else if (op == UserOperation.SaveComment) {
567 let data = wsJsonToRes<CommentResponse>(msg).data;
568 saveCommentRes(data.comment_view, this.state.postRes.comments);
569 this.setState(this.state);
571 } else if (op == UserOperation.CreateCommentLike) {
572 let data = wsJsonToRes<CommentResponse>(msg).data;
573 createCommentLikeRes(data.comment_view, this.state.postRes.comments);
574 this.setState(this.state);
575 } else if (op == UserOperation.CreatePostLike) {
576 let data = wsJsonToRes<PostResponse>(msg).data;
577 createPostLikeRes(data.post_view, this.state.postRes.post_view);
578 this.setState(this.state);
580 op == UserOperation.EditPost ||
581 op == UserOperation.DeletePost ||
582 op == UserOperation.RemovePost ||
583 op == UserOperation.LockPost ||
584 op == UserOperation.StickyPost ||
585 op == UserOperation.SavePost
587 let data = wsJsonToRes<PostResponse>(msg).data;
588 this.state.postRes.post_view = data.post_view;
589 this.setState(this.state);
592 op == UserOperation.EditCommunity ||
593 op == UserOperation.DeleteCommunity ||
594 op == UserOperation.RemoveCommunity ||
595 op == UserOperation.FollowCommunity
597 let data = wsJsonToRes<CommunityResponse>(msg).data;
598 this.state.postRes.community_view = data.community_view;
599 this.state.postRes.post_view.community = data.community_view.community;
600 this.setState(this.state);
601 this.setState(this.state);
602 } else if (op == UserOperation.BanFromCommunity) {
603 let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
604 this.state.postRes.comments
605 .filter(c => c.creator.id == data.person_view.person.id)
606 .forEach(c => (c.creator_banned_from_community = data.banned));
608 this.state.postRes.post_view.creator.id == data.person_view.person.id
610 this.state.postRes.post_view.creator_banned_from_community =
613 this.setState(this.state);
614 } else if (op == UserOperation.AddModToCommunity) {
615 let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
616 this.state.postRes.moderators = data.moderators;
617 this.setState(this.state);
618 } else if (op == UserOperation.BanPerson) {
619 let data = wsJsonToRes<BanPersonResponse>(msg).data;
620 this.state.postRes.comments
621 .filter(c => c.creator.id == data.person_view.person.id)
622 .forEach(c => (c.creator.banned = data.banned));
624 this.state.postRes.post_view.creator.id == data.person_view.person.id
626 this.state.postRes.post_view.creator.banned = data.banned;
628 this.setState(this.state);
629 } else if (op == UserOperation.AddAdmin) {
630 let data = wsJsonToRes<AddAdminResponse>(msg).data;
631 this.state.siteRes.admins = data.admins;
632 this.setState(this.state);
633 } else if (op == UserOperation.Search) {
634 let data = wsJsonToRes<SearchResponse>(msg).data;
635 this.state.crossPosts = data.posts.filter(
636 p => p.post.id != Number(this.props.match.params.id)
638 this.setState(this.state);
639 } else if (op == UserOperation.TransferSite) {
640 let data = wsJsonToRes<GetSiteResponse>(msg).data;
641 this.state.siteRes = data;
642 this.setState(this.state);
643 } else if (op == UserOperation.TransferCommunity) {
644 let data = wsJsonToRes<GetCommunityResponse>(msg).data;
645 this.state.postRes.community_view = data.community_view;
646 this.state.postRes.post_view.community = data.community_view.community;
647 this.state.postRes.moderators = data.moderators;
648 this.setState(this.state);
649 } else if (op == UserOperation.BlockPerson) {
650 let data = wsJsonToRes<BlockPersonResponse>(msg).data;
651 updatePersonBlock(data);
652 } else if (op == UserOperation.CreatePostReport) {
653 let data = wsJsonToRes<PostReportResponse>(msg).data;
655 toast(i18n.t("report_created"));
657 } else if (op == UserOperation.CreateCommentReport) {
658 let data = wsJsonToRes<CommentReportResponse>(msg).data;
660 toast(i18n.t("report_created"));