1 import { Component, linkEvent, createRef, RefObject } from "inferno";
2 import autosize from "autosize";
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();
120 } else if (new URLSearchParams(this.props.location.search).get('scrollToComments')) {
121 this.scrollIntoCommentSection();
130 let form: GetPost = {
131 id: this.state.postId,
132 auth: authField(false),
134 WebSocketService.Instance.send(wsClient.getPost(form));
138 if (this.state.postRes.post_view.post.url) {
140 q: this.state.postRes.post_view.post.url,
141 type_: SearchType.Url,
142 sort: SortType.TopAll,
143 listing_type: ListingType.All,
146 auth: authField(false),
148 WebSocketService.Instance.send(wsClient.search(form));
152 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
153 let pathSplit = req.path.split("/");
154 let promises: Promise<any>[] = [];
156 let id = Number(pathSplit[2]);
158 let postForm: GetPost = {
161 setOptionalAuth(postForm, req.auth);
163 promises.push(req.client.getPost(postForm));
168 componentWillUnmount() {
169 this.subscription.unsubscribe();
170 window.isoData.path = undefined;
171 saveScrollPosition(this.context);
174 componentDidMount() {
175 WebSocketService.Instance.send(
176 wsClient.postJoin({ post_id: this.state.postId })
178 autosize(document.querySelectorAll("textarea"));
181 componentDidUpdate(_lastProps: any, lastState: PostState) {
183 this.state.commentId &&
184 !this.state.scrolled &&
186 lastState.postRes.comments.length > 0
188 this.scrollCommentIntoView();
191 if (new URLSearchParams(this.props.location.search).get('scrollToComments') ) {
192 this.scrollIntoCommentSection();
195 // Necessary if you are on a post and you click another post (same route)
196 if (_lastProps.location.pathname !== _lastProps.history.location.pathname) {
197 // TODO Couldnt get a refresh working. This does for now.
200 // let currentId = this.props.match.params.id;
201 // WebSocketService.Instance.getPost(currentId);
202 // this.context.refresh();
203 // this.context.router.history.push(_lastProps.location.pathname);
207 scrollCommentIntoView() {
208 var elmnt = document.getElementById(`comment-${this.state.commentId}`);
209 elmnt.scrollIntoView();
210 elmnt.classList.add("mark");
211 this.state.scrolled = true;
212 this.markScrolledAsRead(this.state.commentId);
215 scrollIntoCommentSection() {
216 this.state.commentSectionRef.current?.scrollIntoView();
219 // TODO this needs some re-work
220 markScrolledAsRead(commentId: number) {
221 let found = this.state.postRes.comments.find(
222 c => c.comment.id == commentId
224 let parent = this.state.postRes.comments.find(
225 c => found.comment.parent_id == c.comment.id
227 let parent_person_id = parent
229 : this.state.postRes.post_view.creator.id;
232 UserService.Instance.localUserView &&
233 UserService.Instance.localUserView.person.id == parent_person_id
235 let form: MarkCommentAsRead = {
236 comment_id: found.comment.id,
240 WebSocketService.Instance.send(wsClient.markCommentAsRead(form));
241 UserService.Instance.unreadCountSub.next(
242 UserService.Instance.unreadCountSub.value - 1
247 get documentTitle(): string {
248 return `${this.state.postRes.post_view.post.name} - ${this.state.siteRes.site_view.site.name}`;
251 get imageTag(): string {
252 let post = this.state.postRes.post_view.post;
254 post.thumbnail_url ||
255 (post.url ? (isImage(post.url) ? post.url : undefined) : undefined)
259 get descriptionTag(): string {
260 let body = this.state.postRes.post_view.post.body;
261 return body ? previewLines(body) : undefined;
265 let pv = this.state.postRes?.post_view;
267 <div class="container">
268 {this.state.loading ? (
274 <div class="col-12 col-md-8 mb-3">
276 title={this.documentTitle}
277 path={this.context.router.route.match.url}
278 image={this.imageTag}
279 description={this.descriptionTag}
283 duplicates={this.state.crossPosts}
286 moderators={this.state.postRes.moderators}
287 admins={this.state.siteRes.admins}
289 this.state.siteRes.site_view.site.enable_downvotes
291 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
293 <div ref={this.state.commentSectionRef} className="mb-2" />
295 postId={this.state.postId}
296 disabled={pv.post.locked}
298 <div class="d-block d-md-none">
300 class="btn btn-secondary d-inline-block mb-2 mr-3"
301 onClick={linkEvent(this, this.handleShowSidebarMobile)}
303 {i18n.t("sidebar")}{" "}
306 this.state.showSidebarMobile
310 classes="icon-inline"
313 {this.state.showSidebarMobile && this.sidebar()}
315 {this.state.postRes.comments.length > 0 && this.sortRadios()}
316 {this.state.commentViewType == CommentViewType.Tree &&
318 {this.state.commentViewType == CommentViewType.Chat &&
321 <div class="d-none d-md-block col-md-4">{this.sidebar()}</div>
331 <div class="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
333 className={`btn btn-outline-secondary pointer ${
334 this.state.commentSort === CommentSortType.Hot && "active"
340 value={CommentSortType.Hot}
341 checked={this.state.commentSort === CommentSortType.Hot}
342 onChange={linkEvent(this, this.handleCommentSortChange)}
346 className={`btn btn-outline-secondary pointer ${
347 this.state.commentSort === CommentSortType.Top && "active"
353 value={CommentSortType.Top}
354 checked={this.state.commentSort === CommentSortType.Top}
355 onChange={linkEvent(this, this.handleCommentSortChange)}
359 className={`btn btn-outline-secondary pointer ${
360 this.state.commentSort === CommentSortType.New && "active"
366 value={CommentSortType.New}
367 checked={this.state.commentSort === CommentSortType.New}
368 onChange={linkEvent(this, this.handleCommentSortChange)}
372 className={`btn btn-outline-secondary pointer ${
373 this.state.commentSort === CommentSortType.Old && "active"
379 value={CommentSortType.Old}
380 checked={this.state.commentSort === CommentSortType.Old}
381 onChange={linkEvent(this, this.handleCommentSortChange)}
385 <div class="btn-group btn-group-toggle flex-wrap mb-2">
387 className={`btn btn-outline-secondary pointer ${
388 this.state.commentViewType === CommentViewType.Chat && "active"
394 value={CommentViewType.Chat}
395 checked={this.state.commentViewType === CommentViewType.Chat}
396 onChange={linkEvent(this, this.handleCommentViewTypeChange)}
405 // These are already sorted by new
409 nodes={commentsToFlatNodes(this.state.postRes.comments)}
411 locked={this.state.postRes.post_view.post.locked}
412 moderators={this.state.postRes.moderators}
413 admins={this.state.siteRes.admins}
414 postCreatorId={this.state.postRes.post_view.creator.id}
416 enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
426 community_view={this.state.postRes.community_view}
427 moderators={this.state.postRes.moderators}
428 admins={this.state.siteRes.admins}
429 online={this.state.postRes.online}
430 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
437 handleCommentSortChange(i: Post, event: any) {
438 i.state.commentSort = Number(event.target.value);
439 i.state.commentViewType = CommentViewType.Tree;
440 i.state.commentTree = buildCommentsTree(
441 i.state.postRes.comments,
447 handleCommentViewTypeChange(i: Post, event: any) {
448 i.state.commentViewType = Number(event.target.value);
449 i.state.commentSort = CommentSortType.New;
450 i.state.commentTree = buildCommentsTree(
451 i.state.postRes.comments,
457 handleShowSidebarMobile(i: Post) {
458 i.state.showSidebarMobile = !i.state.showSidebarMobile;
466 nodes={this.state.commentTree}
467 locked={this.state.postRes.post_view.post.locked}
468 moderators={this.state.postRes.moderators}
469 admins={this.state.siteRes.admins}
470 postCreatorId={this.state.postRes.post_view.creator.id}
471 enableDownvotes={this.state.siteRes.site_view.site.enable_downvotes}
477 parseMessage(msg: any) {
478 let op = wsUserOp(msg);
481 toast(i18n.t(msg.error), "danger");
483 } else if (msg.reconnect) {
484 let postId = Number(this.props.match.params.id);
485 WebSocketService.Instance.send(wsClient.postJoin({ post_id: postId }));
486 WebSocketService.Instance.send(
489 auth: authField(false),
492 } else if (op == UserOperation.GetPost) {
493 let data = wsJsonToRes<GetPostResponse>(msg).data;
494 this.state.postRes = data;
495 this.state.commentTree = buildCommentsTree(
496 this.state.postRes.comments,
497 this.state.commentSort
499 this.state.loading = false;
502 this.fetchCrossPosts();
503 this.setState(this.state);
505 if (!this.state.commentId) restoreScrollPosition(this.context);
506 if (new URLSearchParams(this.props.location.search).get('scrollToComments') ) {
507 this.scrollIntoCommentSection();
509 } else if (op == UserOperation.CreateComment) {
510 let data = wsJsonToRes<CommentResponse>(msg).data;
512 // Necessary since it might be a user reply, which has the recipients, to avoid double
513 if (data.recipient_ids.length == 0) {
514 this.state.postRes.comments.unshift(data.comment_view);
515 insertCommentIntoTree(this.state.commentTree, data.comment_view);
516 this.state.postRes.post_view.counts.comments++;
517 this.setState(this.state);
521 op == UserOperation.EditComment ||
522 op == UserOperation.DeleteComment ||
523 op == UserOperation.RemoveComment
525 let data = wsJsonToRes<CommentResponse>(msg).data;
526 editCommentRes(data.comment_view, this.state.postRes.comments);
527 this.setState(this.state);
528 } else if (op == UserOperation.SaveComment) {
529 let data = wsJsonToRes<CommentResponse>(msg).data;
530 saveCommentRes(data.comment_view, this.state.postRes.comments);
531 this.setState(this.state);
533 } else if (op == UserOperation.CreateCommentLike) {
534 let data = wsJsonToRes<CommentResponse>(msg).data;
535 createCommentLikeRes(data.comment_view, this.state.postRes.comments);
536 this.setState(this.state);
537 } else if (op == UserOperation.CreatePostLike) {
538 let data = wsJsonToRes<PostResponse>(msg).data;
539 createPostLikeRes(data.post_view, this.state.postRes.post_view);
540 this.setState(this.state);
542 op == UserOperation.EditPost ||
543 op == UserOperation.DeletePost ||
544 op == UserOperation.RemovePost ||
545 op == UserOperation.LockPost ||
546 op == UserOperation.StickyPost ||
547 op == UserOperation.SavePost
549 let data = wsJsonToRes<PostResponse>(msg).data;
550 this.state.postRes.post_view = data.post_view;
551 this.setState(this.state);
554 op == UserOperation.EditCommunity ||
555 op == UserOperation.DeleteCommunity ||
556 op == UserOperation.RemoveCommunity ||
557 op == UserOperation.FollowCommunity
559 let data = wsJsonToRes<CommunityResponse>(msg).data;
560 this.state.postRes.community_view = data.community_view;
561 this.state.postRes.post_view.community = data.community_view.community;
562 this.setState(this.state);
563 this.setState(this.state);
564 } else if (op == UserOperation.BanFromCommunity) {
565 let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
566 this.state.postRes.comments
567 .filter(c => c.creator.id == data.person_view.person.id)
568 .forEach(c => (c.creator_banned_from_community = data.banned));
570 this.state.postRes.post_view.creator.id == data.person_view.person.id
572 this.state.postRes.post_view.creator_banned_from_community =
575 this.setState(this.state);
576 } else if (op == UserOperation.AddModToCommunity) {
577 let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
578 this.state.postRes.moderators = data.moderators;
579 this.setState(this.state);
580 } else if (op == UserOperation.BanPerson) {
581 let data = wsJsonToRes<BanPersonResponse>(msg).data;
582 this.state.postRes.comments
583 .filter(c => c.creator.id == data.person_view.person.id)
584 .forEach(c => (c.creator.banned = data.banned));
586 this.state.postRes.post_view.creator.id == data.person_view.person.id
588 this.state.postRes.post_view.creator.banned = data.banned;
590 this.setState(this.state);
591 } else if (op == UserOperation.AddAdmin) {
592 let data = wsJsonToRes<AddAdminResponse>(msg).data;
593 this.state.siteRes.admins = data.admins;
594 this.setState(this.state);
595 } else if (op == UserOperation.Search) {
596 let data = wsJsonToRes<SearchResponse>(msg).data;
597 this.state.crossPosts = data.posts.filter(
598 p => p.post.id != Number(this.props.match.params.id)
600 this.setState(this.state);
601 } else if (op == UserOperation.TransferSite) {
602 let data = wsJsonToRes<GetSiteResponse>(msg).data;
603 this.state.siteRes = data;
604 this.setState(this.state);
605 } else if (op == UserOperation.TransferCommunity) {
606 let data = wsJsonToRes<GetCommunityResponse>(msg).data;
607 this.state.postRes.community_view = data.community_view;
608 this.state.postRes.post_view.community = data.community_view.community;
609 this.state.postRes.moderators = data.moderators;
610 this.setState(this.state);