1 import autosize from "autosize";
2 import { Component, createRef, linkEvent, RefObject } from "inferno";
5 AddModToCommunityResponse,
6 BanFromCommunityResponse,
23 } from "lemmy-js-client";
24 import { Subscription } from "rxjs";
25 import { i18n } from "../../i18next";
27 CommentNode as CommentNodeI,
31 } from "../../interfaces";
32 import { UserService, WebSocketService } from "../../services";
40 getCommentIdFromProps,
42 insertCommentIntoTree,
46 restoreScrollPosition,
58 import { CommentForm } from "../comment/comment-form";
59 import { CommentNodes } from "../comment/comment-nodes";
60 import { HtmlTags } from "../common/html-tags";
61 import { Icon, Spinner } from "../common/icon";
62 import { Sidebar } from "../community/sidebar";
63 import { PostListing } from "./post-listing";
66 postRes: GetPostResponse;
68 commentTree: CommentNodeI[];
70 commentSort: CommentSortType;
71 commentViewType: CommentViewType;
74 crossPosts: PostView[];
75 siteRes: GetSiteResponse;
76 commentSectionRef?: RefObject<HTMLDivElement>;
77 showSidebarMobile: boolean;
80 export class Post extends Component<any, PostState> {
81 private subscription: Subscription;
82 private isoData = setIsoData(this.context);
83 private emptyState: PostState = {
85 postId: getIdFromProps(this.props),
87 commentId: getCommentIdFromProps(this.props),
88 commentSort: CommentSortType.Hot,
89 commentViewType: CommentViewType.Tree,
93 siteRes: this.isoData.site_res,
94 commentSectionRef: null,
95 showSidebarMobile: false,
98 constructor(props: any, context: any) {
99 super(props, context);
101 this.state = this.emptyState;
102 this.state.commentSectionRef = createRef();
104 this.parseMessage = this.parseMessage.bind(this);
105 this.subscription = wsSubscribe(this.parseMessage);
107 // Only fetch the data if coming from another route
108 if (this.isoData.path == this.context.router.route.match.url) {
109 this.state.postRes = this.isoData.routeData[0];
110 this.state.commentTree = buildCommentsTree(
111 this.state.postRes.comments,
112 this.state.commentSort
114 this.state.loading = false;
117 this.fetchCrossPosts();
118 if (this.state.commentId) {
119 this.scrollCommentIntoView();
122 if (this.checkScrollIntoCommentsParam) {
123 this.scrollIntoCommentSection();
132 let form: GetPost = {
133 id: this.state.postId,
134 auth: authField(false),
136 WebSocketService.Instance.send(wsClient.getPost(form));
140 if (this.state.postRes.post_view.post.url) {
142 q: this.state.postRes.post_view.post.url,
143 type_: SearchType.Url,
144 sort: SortType.TopAll,
145 listing_type: ListingType.All,
148 auth: authField(false),
150 WebSocketService.Instance.send(wsClient.search(form));
154 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
155 let pathSplit = req.path.split("/");
156 let promises: Promise<any>[] = [];
158 let id = Number(pathSplit[2]);
160 let postForm: GetPost = {
163 setOptionalAuth(postForm, req.auth);
165 promises.push(req.client.getPost(postForm));
170 componentWillUnmount() {
171 this.subscription.unsubscribe();
172 window.isoData.path = undefined;
173 saveScrollPosition(this.context);
176 componentDidMount() {
177 WebSocketService.Instance.send(
178 wsClient.postJoin({ post_id: this.state.postId })
180 autosize(document.querySelectorAll("textarea"));
183 componentDidUpdate(_lastProps: any, lastState: PostState) {
185 this.state.commentId &&
186 !this.state.scrolled &&
188 lastState.postRes.comments.length > 0
190 this.scrollCommentIntoView();
193 if (this.checkScrollIntoCommentsParam) {
194 this.scrollIntoCommentSection();
197 // Necessary if you are on a post and you click another post (same route)
198 if (_lastProps.location.pathname !== _lastProps.history.location.pathname) {
199 // TODO Couldnt get a refresh working. This does for now.
202 // let currentId = this.props.match.params.id;
203 // WebSocketService.Instance.getPost(currentId);
204 // this.context.refresh();
205 // this.context.router.history.push(_lastProps.location.pathname);
209 scrollCommentIntoView() {
210 var elmnt = document.getElementById(`comment-${this.state.commentId}`);
211 elmnt.scrollIntoView();
212 elmnt.classList.add("mark");
213 this.state.scrolled = true;
214 this.markScrolledAsRead(this.state.commentId);
217 get checkScrollIntoCommentsParam() {
219 new URLSearchParams(this.props.location.search).get("scrollToComments")
223 scrollIntoCommentSection() {
224 this.state.commentSectionRef.current?.scrollIntoView();
227 // TODO this needs some re-work
228 markScrolledAsRead(commentId: number) {
229 let found = this.state.postRes.comments.find(
230 c => c.comment.id == commentId
232 let parent = this.state.postRes.comments.find(
233 c => found.comment.parent_id == c.comment.id
235 let parent_person_id = parent
237 : this.state.postRes.post_view.creator.id;
240 UserService.Instance.localUserView &&
241 UserService.Instance.localUserView.person.id == parent_person_id
243 let form: MarkCommentAsRead = {
244 comment_id: found.comment.id,
248 WebSocketService.Instance.send(wsClient.markCommentAsRead(form));
249 UserService.Instance.unreadCountSub.next(
250 UserService.Instance.unreadCountSub.value - 1
255 get documentTitle(): string {
256 return `${this.state.postRes.post_view.post.name} - ${this.state.siteRes.site_view.site.name}`;
259 get imageTag(): string {
260 let post = this.state.postRes.post_view.post;
262 post.thumbnail_url ||
263 (post.url ? (isImage(post.url) ? post.url : undefined) : undefined)
267 get descriptionTag(): string {
268 let body = this.state.postRes.post_view.post.body;
269 return body ? previewLines(body) : undefined;
273 let pv = this.state.postRes?.post_view;
275 <div class="container">
276 {this.state.loading ? (
282 <div class="col-12 col-md-8 mb-3">
284 title={this.documentTitle}
285 path={this.context.router.route.match.url}
286 image={this.imageTag}
287 description={this.descriptionTag}
291 duplicates={this.state.crossPosts}
294 moderators={this.state.postRes.moderators}
295 admins={this.state.siteRes.admins}
297 this.state.siteRes.site_view.site.enable_downvotes
299 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
301 <div ref={this.state.commentSectionRef} className="mb-2" />
303 postId={this.state.postId}
304 disabled={pv.post.locked}
306 <div class="d-block d-md-none">
308 class="btn btn-secondary d-inline-block mb-2 mr-3"
309 onClick={linkEvent(this, this.handleShowSidebarMobile)}
311 {i18n.t("sidebar")}{" "}
314 this.state.showSidebarMobile
318 classes="icon-inline"
321 {this.state.showSidebarMobile && this.sidebar()}
323 {this.state.postRes.comments.length > 0 && this.sortRadios()}
324 {this.state.commentViewType == CommentViewType.Tree &&
326 {this.state.commentViewType == CommentViewType.Chat &&
329 <div class="d-none d-md-block col-md-4">{this.sidebar()}</div>
339 <div class="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
341 className={`btn btn-outline-secondary pointer ${
342 this.state.commentSort === CommentSortType.Hot && "active"
348 value={CommentSortType.Hot}
349 checked={this.state.commentSort === CommentSortType.Hot}
350 onChange={linkEvent(this, this.handleCommentSortChange)}
354 className={`btn btn-outline-secondary pointer ${
355 this.state.commentSort === CommentSortType.Top && "active"
361 value={CommentSortType.Top}
362 checked={this.state.commentSort === CommentSortType.Top}
363 onChange={linkEvent(this, this.handleCommentSortChange)}
367 className={`btn btn-outline-secondary pointer ${
368 this.state.commentSort === CommentSortType.New && "active"
374 value={CommentSortType.New}
375 checked={this.state.commentSort === CommentSortType.New}
376 onChange={linkEvent(this, this.handleCommentSortChange)}
380 className={`btn btn-outline-secondary pointer ${
381 this.state.commentSort === CommentSortType.Old && "active"
387 value={CommentSortType.Old}
388 checked={this.state.commentSort === CommentSortType.Old}
389 onChange={linkEvent(this, this.handleCommentSortChange)}
393 <div class="btn-group btn-group-toggle flex-wrap mb-2">
395 className={`btn btn-outline-secondary pointer ${
396 this.state.commentViewType === CommentViewType.Chat && "active"
402 value={CommentViewType.Chat}
403 checked={this.state.commentViewType === CommentViewType.Chat}
404 onChange={linkEvent(this, this.handleCommentViewTypeChange)}
413 // These are already sorted by new
417 nodes={commentsToFlatNodes(this.state.postRes.comments)}
419 locked={this.state.postRes.post_view.post.locked}
420 moderators={this.state.postRes.moderators}
421 admins={this.state.siteRes.admins}
422 postCreatorId={this.state.postRes.post_view.creator.id}
424 enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
434 community_view={this.state.postRes.community_view}
435 moderators={this.state.postRes.moderators}
436 admins={this.state.siteRes.admins}
437 online={this.state.postRes.online}
438 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
445 handleCommentSortChange(i: Post, event: any) {
446 i.state.commentSort = Number(event.target.value);
447 i.state.commentViewType = CommentViewType.Tree;
448 i.state.commentTree = buildCommentsTree(
449 i.state.postRes.comments,
455 handleCommentViewTypeChange(i: Post, event: any) {
456 i.state.commentViewType = Number(event.target.value);
457 i.state.commentSort = CommentSortType.New;
458 i.state.commentTree = buildCommentsTree(
459 i.state.postRes.comments,
465 handleShowSidebarMobile(i: Post) {
466 i.state.showSidebarMobile = !i.state.showSidebarMobile;
474 nodes={this.state.commentTree}
475 locked={this.state.postRes.post_view.post.locked}
476 moderators={this.state.postRes.moderators}
477 admins={this.state.siteRes.admins}
478 postCreatorId={this.state.postRes.post_view.creator.id}
479 enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
485 parseMessage(msg: any) {
486 let op = wsUserOp(msg);
489 toast(i18n.t(msg.error), "danger");
491 } else if (msg.reconnect) {
492 let postId = Number(this.props.match.params.id);
493 WebSocketService.Instance.send(wsClient.postJoin({ post_id: postId }));
494 WebSocketService.Instance.send(
497 auth: authField(false),
500 } else if (op == UserOperation.GetPost) {
501 let data = wsJsonToRes<GetPostResponse>(msg).data;
502 this.state.postRes = data;
503 this.state.commentTree = buildCommentsTree(
504 this.state.postRes.comments,
505 this.state.commentSort
507 this.state.loading = false;
510 this.fetchCrossPosts();
511 this.setState(this.state);
513 if (!this.state.commentId) restoreScrollPosition(this.context);
515 if (this.checkScrollIntoCommentsParam) {
516 this.scrollIntoCommentSection();
518 } else if (op == UserOperation.CreateComment) {
519 let data = wsJsonToRes<CommentResponse>(msg).data;
521 // Necessary since it might be a user reply, which has the recipients, to avoid double
522 if (data.recipient_ids.length == 0) {
523 this.state.postRes.comments.unshift(data.comment_view);
524 insertCommentIntoTree(this.state.commentTree, data.comment_view);
525 this.state.postRes.post_view.counts.comments++;
526 this.setState(this.state);
530 op == UserOperation.EditComment ||
531 op == UserOperation.DeleteComment ||
532 op == UserOperation.RemoveComment
534 let data = wsJsonToRes<CommentResponse>(msg).data;
535 editCommentRes(data.comment_view, this.state.postRes.comments);
536 this.setState(this.state);
537 } else if (op == UserOperation.SaveComment) {
538 let data = wsJsonToRes<CommentResponse>(msg).data;
539 saveCommentRes(data.comment_view, this.state.postRes.comments);
540 this.setState(this.state);
542 } else if (op == UserOperation.CreateCommentLike) {
543 let data = wsJsonToRes<CommentResponse>(msg).data;
544 createCommentLikeRes(data.comment_view, this.state.postRes.comments);
545 this.setState(this.state);
546 } else if (op == UserOperation.CreatePostLike) {
547 let data = wsJsonToRes<PostResponse>(msg).data;
548 createPostLikeRes(data.post_view, this.state.postRes.post_view);
549 this.setState(this.state);
551 op == UserOperation.EditPost ||
552 op == UserOperation.DeletePost ||
553 op == UserOperation.RemovePost ||
554 op == UserOperation.LockPost ||
555 op == UserOperation.StickyPost ||
556 op == UserOperation.SavePost
558 let data = wsJsonToRes<PostResponse>(msg).data;
559 this.state.postRes.post_view = data.post_view;
560 this.setState(this.state);
563 op == UserOperation.EditCommunity ||
564 op == UserOperation.DeleteCommunity ||
565 op == UserOperation.RemoveCommunity ||
566 op == UserOperation.FollowCommunity
568 let data = wsJsonToRes<CommunityResponse>(msg).data;
569 this.state.postRes.community_view = data.community_view;
570 this.state.postRes.post_view.community = data.community_view.community;
571 this.setState(this.state);
572 this.setState(this.state);
573 } else if (op == UserOperation.BanFromCommunity) {
574 let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
575 this.state.postRes.comments
576 .filter(c => c.creator.id == data.person_view.person.id)
577 .forEach(c => (c.creator_banned_from_community = data.banned));
579 this.state.postRes.post_view.creator.id == data.person_view.person.id
581 this.state.postRes.post_view.creator_banned_from_community =
584 this.setState(this.state);
585 } else if (op == UserOperation.AddModToCommunity) {
586 let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
587 this.state.postRes.moderators = data.moderators;
588 this.setState(this.state);
589 } else if (op == UserOperation.BanPerson) {
590 let data = wsJsonToRes<BanPersonResponse>(msg).data;
591 this.state.postRes.comments
592 .filter(c => c.creator.id == data.person_view.person.id)
593 .forEach(c => (c.creator.banned = data.banned));
595 this.state.postRes.post_view.creator.id == data.person_view.person.id
597 this.state.postRes.post_view.creator.banned = data.banned;
599 this.setState(this.state);
600 } else if (op == UserOperation.AddAdmin) {
601 let data = wsJsonToRes<AddAdminResponse>(msg).data;
602 this.state.siteRes.admins = data.admins;
603 this.setState(this.state);
604 } else if (op == UserOperation.Search) {
605 let data = wsJsonToRes<SearchResponse>(msg).data;
606 this.state.crossPosts = data.posts.filter(
607 p => p.post.id != Number(this.props.match.params.id)
609 this.setState(this.state);
610 } else if (op == UserOperation.TransferSite) {
611 let data = wsJsonToRes<GetSiteResponse>(msg).data;
612 this.state.siteRes = data;
613 this.setState(this.state);
614 } else if (op == UserOperation.TransferCommunity) {
615 let data = wsJsonToRes<GetCommunityResponse>(msg).data;
616 this.state.postRes.community_view = data.community_view;
617 this.state.postRes.post_view.community = data.community_view.community;
618 this.state.postRes.moderators = data.moderators;
619 this.setState(this.state);