1 import { None, Option, Some } from "@sniptt/monads";
2 import { Component, linkEvent } from "inferno";
4 AddModToCommunityResponse,
5 BanFromCommunityResponse,
6 BlockCommunityResponse,
29 } from "lemmy-js-client";
30 import { Subscription } from "rxjs";
31 import { i18n } from "../../i18next";
36 } from "../../interfaces";
37 import { UserService, WebSocketService } from "../../services";
43 createPostLikeFindRes,
53 postToCommentSortType,
55 restoreScrollPosition,
67 import { CommentNodes } from "../comment/comment-nodes";
68 import { BannerIconHeader } from "../common/banner-icon-header";
69 import { DataTypeSelect } from "../common/data-type-select";
70 import { HtmlTags } from "../common/html-tags";
71 import { Icon, Spinner } from "../common/icon";
72 import { Paginator } from "../common/paginator";
73 import { SortSelect } from "../common/sort-select";
74 import { Sidebar } from "../community/sidebar";
75 import { SiteSidebar } from "../home/site-sidebar";
76 import { PostListings } from "../post/post-listings";
77 import { CommunityLink } from "./community-link";
80 communityRes: Option<GetCommunityResponse>;
81 siteRes: GetSiteResponse;
82 communityName: string;
83 communityLoading: boolean;
84 postsLoading: boolean;
85 commentsLoading: boolean;
87 comments: CommentView[];
91 showSidebarMobile: boolean;
94 interface CommunityProps {
100 interface UrlParams {
106 export class Community extends Component<any, State> {
107 private isoData = setIsoData(
109 GetCommunityResponse,
113 private subscription: Subscription;
114 private emptyState: State = {
116 communityName: this.props.match.params.name,
117 communityLoading: true,
119 commentsLoading: true,
122 dataType: getDataTypeFromProps(this.props),
123 sort: getSortTypeFromProps(this.props),
124 page: getPageFromProps(this.props),
125 siteRes: this.isoData.site_res,
126 showSidebarMobile: false,
129 constructor(props: any, context: any) {
130 super(props, context);
132 this.state = this.emptyState;
133 this.handleSortChange = this.handleSortChange.bind(this);
134 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
135 this.handlePageChange = this.handlePageChange.bind(this);
137 this.parseMessage = this.parseMessage.bind(this);
138 this.subscription = wsSubscribe(this.parseMessage);
140 // Only fetch the data if coming from another route
141 if (this.isoData.path == this.context.router.route.match.url) {
144 communityRes: Some(this.isoData.routeData[0] as GetCommunityResponse),
146 let postsRes = Some(this.isoData.routeData[1] as GetPostsResponse);
147 let commentsRes = Some(this.isoData.routeData[2] as GetCommentsResponse);
149 if (postsRes.isSome()) {
150 this.state = { ...this.state, posts: postsRes.unwrap().posts };
153 if (commentsRes.isSome()) {
154 this.state = { ...this.state, comments: commentsRes.unwrap().comments };
159 communityLoading: false,
161 commentsLoading: false,
164 this.fetchCommunity();
170 let form = new GetCommunity({
171 name: Some(this.state.communityName),
173 auth: auth(false).ok(),
175 WebSocketService.Instance.send(wsClient.getCommunity(form));
178 componentDidMount() {
182 componentWillUnmount() {
183 saveScrollPosition(this.context);
184 this.subscription.unsubscribe();
187 static getDerivedStateFromProps(props: any): CommunityProps {
189 dataType: getDataTypeFromProps(props),
190 sort: getSortTypeFromProps(props),
191 page: getPageFromProps(props),
195 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
196 let pathSplit = req.path.split("/");
197 let promises: Promise<any>[] = [];
199 let communityName = pathSplit[2];
200 let communityForm = new GetCommunity({
201 name: Some(communityName),
205 promises.push(req.client.getCommunity(communityForm));
207 let dataType: DataType = pathSplit[4]
208 ? DataType[pathSplit[4]]
211 let sort: Option<SortType> = toOption(
213 ? SortType[pathSplit[6]]
214 : UserService.Instance.myUserInfo.match({
216 Object.values(SortType)[
217 mui.local_user_view.local_user.default_sort_type
219 none: SortType.Active,
223 let page = toOption(pathSplit[8] ? Number(pathSplit[8]) : 1);
225 if (dataType == DataType.Post) {
226 let getPostsForm = new GetPosts({
227 community_name: Some(communityName),
230 limit: Some(fetchLimit),
232 type_: Some(ListingType.All),
233 saved_only: Some(false),
236 promises.push(req.client.getPosts(getPostsForm));
237 promises.push(Promise.resolve());
239 let getCommentsForm = new GetComments({
240 community_name: Some(communityName),
243 limit: Some(fetchLimit),
245 sort: sort.map(postToCommentSortType),
246 type_: Some(ListingType.All),
247 saved_only: Some(false),
252 promises.push(Promise.resolve());
253 promises.push(req.client.getComments(getCommentsForm));
259 componentDidUpdate(_: any, lastState: State) {
261 lastState.dataType !== this.state.dataType ||
262 lastState.sort !== this.state.sort ||
263 lastState.page !== this.state.page
265 this.setState({ postsLoading: true, commentsLoading: true });
270 get documentTitle(): string {
271 return this.state.communityRes.match({
273 this.state.siteRes.site_view.match({
275 `${res.community_view.community.title} - ${siteView.site.name}`,
284 <div className="container">
285 {this.state.communityLoading ? (
290 this.state.communityRes.match({
294 title={this.documentTitle}
295 path={this.context.router.route.match.url}
296 description={res.community_view.community.description}
297 image={res.community_view.community.icon}
300 <div className="row">
301 <div className="col-12 col-md-8">
302 {this.communityInfo()}
303 <div className="d-block d-md-none">
305 className="btn btn-secondary d-inline-block mb-2 mr-3"
306 onClick={linkEvent(this, this.handleShowSidebarMobile)}
308 {i18n.t("sidebar")}{" "}
311 this.state.showSidebarMobile
315 classes="icon-inline"
318 {this.state.showSidebarMobile && (
321 community_view={res.community_view}
322 moderators={res.moderators}
323 admins={this.state.siteRes.admins}
325 enableNsfw={enableNsfw(this.state.siteRes)}
327 {!res.community_view.community.local &&
332 showLocal={showLocal(this.isoData)}
346 page={this.state.page}
347 onChange={this.handlePageChange}
350 <div className="d-none d-md-block col-md-4">
352 community_view={res.community_view}
353 moderators={res.moderators}
354 admins={this.state.siteRes.admins}
356 enableNsfw={enableNsfw(this.state.siteRes)}
358 {!res.community_view.community.local &&
363 showLocal={showLocal(this.isoData)}
383 return this.state.dataType == DataType.Post ? (
384 this.state.postsLoading ? (
390 posts={this.state.posts}
392 enableDownvotes={enableDownvotes(this.state.siteRes)}
393 enableNsfw={enableNsfw(this.state.siteRes)}
396 ) : this.state.commentsLoading ? (
402 nodes={commentsToFlatNodes(this.state.comments)}
403 viewType={CommentViewType.Flat}
406 enableDownvotes={enableDownvotes(this.state.siteRes)}
407 moderators={this.state.communityRes.map(r => r.moderators)}
408 admins={Some(this.state.siteRes.admins)}
409 maxCommentsShown={None}
415 return this.state.communityRes
416 .map(r => r.community_view.community)
419 <div className="mb-2">
420 <BannerIconHeader banner={community.banner} icon={community.icon} />
421 <h5 className="mb-0 overflow-wrap-anywhere">{community.title}</h5>
423 community={community}
436 let communityRss = this.state.communityRes.map(r =>
437 communityRSSUrl(r.community_view.community.actor_id, this.state.sort)
440 <div className="mb-3">
441 <span className="mr-3">
443 type_={this.state.dataType}
444 onChange={this.handleDataTypeChange}
447 <span className="mr-2">
448 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
450 {communityRss.match({
453 <a href={rss} title="RSS" rel={relTags}>
454 <Icon icon="rss" classes="text-muted small" />
456 <link rel="alternate" type="application/atom+xml" href={rss} />
465 handlePageChange(page: number) {
466 this.updateUrl({ page });
467 window.scrollTo(0, 0);
470 handleSortChange(val: SortType) {
471 this.updateUrl({ sort: val, page: 1 });
472 window.scrollTo(0, 0);
475 handleDataTypeChange(val: DataType) {
476 this.updateUrl({ dataType: DataType[val], page: 1 });
477 window.scrollTo(0, 0);
480 handleShowSidebarMobile(i: Community) {
481 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
484 updateUrl(paramUpdates: UrlParams) {
485 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
486 const sortStr = paramUpdates.sort || this.state.sort;
487 const page = paramUpdates.page || this.state.page;
489 let typeView = `/c/${this.state.communityName}`;
491 this.props.history.push(
492 `${typeView}/data_type/${dataTypeStr}/sort/${sortStr}/page/${page}`
497 if (this.state.dataType == DataType.Post) {
498 let form = new GetPosts({
499 page: Some(this.state.page),
500 limit: Some(fetchLimit),
501 sort: Some(this.state.sort),
502 type_: Some(ListingType.All),
503 community_name: Some(this.state.communityName),
505 saved_only: Some(false),
506 auth: auth(false).ok(),
508 WebSocketService.Instance.send(wsClient.getPosts(form));
510 let form = new GetComments({
511 page: Some(this.state.page),
512 limit: Some(fetchLimit),
514 sort: Some(postToCommentSortType(this.state.sort)),
515 type_: Some(ListingType.All),
516 community_name: Some(this.state.communityName),
518 saved_only: Some(false),
521 auth: auth(false).ok(),
523 WebSocketService.Instance.send(wsClient.getComments(form));
527 parseMessage(msg: any) {
528 let op = wsUserOp(msg);
531 toast(i18n.t(msg.error), "danger");
532 this.context.router.history.push("/");
534 } else if (msg.reconnect) {
535 this.state.communityRes.match({
537 WebSocketService.Instance.send(
538 wsClient.communityJoin({
539 community_id: res.community_view.community.id,
546 } else if (op == UserOperation.GetCommunity) {
547 let data = wsJsonToRes<GetCommunityResponse>(msg, GetCommunityResponse);
548 this.setState({ communityRes: Some(data), communityLoading: false });
549 // TODO why is there no auth in this form?
550 WebSocketService.Instance.send(
551 wsClient.communityJoin({
552 community_id: data.community_view.community.id,
556 op == UserOperation.EditCommunity ||
557 op == UserOperation.DeleteCommunity ||
558 op == UserOperation.RemoveCommunity
560 let data = wsJsonToRes<CommunityResponse>(msg, CommunityResponse);
561 this.state.communityRes.match({
562 some: res => (res.community_view = data.community_view),
565 this.setState(this.state);
566 } else if (op == UserOperation.FollowCommunity) {
567 let data = wsJsonToRes<CommunityResponse>(msg, CommunityResponse);
568 this.state.communityRes.match({
570 res.community_view.subscribed = data.community_view.subscribed;
571 res.community_view.counts.subscribers =
572 data.community_view.counts.subscribers;
576 this.setState(this.state);
577 } else if (op == UserOperation.GetPosts) {
578 let data = wsJsonToRes<GetPostsResponse>(msg, GetPostsResponse);
579 this.setState({ posts: data.posts, postsLoading: false });
580 restoreScrollPosition(this.context);
583 op == UserOperation.EditPost ||
584 op == UserOperation.DeletePost ||
585 op == UserOperation.RemovePost ||
586 op == UserOperation.LockPost ||
587 op == UserOperation.StickyPost ||
588 op == UserOperation.SavePost
590 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
591 editPostFindRes(data.post_view, this.state.posts);
592 this.setState(this.state);
593 } else if (op == UserOperation.CreatePost) {
594 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
595 this.state.posts.unshift(data.post_view);
597 UserService.Instance.myUserInfo
598 .map(m => m.local_user_view.local_user.show_new_post_notifs)
601 notifyPost(data.post_view, this.context.router);
603 this.setState(this.state);
604 } else if (op == UserOperation.CreatePostLike) {
605 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
606 createPostLikeFindRes(data.post_view, this.state.posts);
607 this.setState(this.state);
608 } else if (op == UserOperation.AddModToCommunity) {
609 let data = wsJsonToRes<AddModToCommunityResponse>(
611 AddModToCommunityResponse
613 this.state.communityRes.match({
614 some: res => (res.moderators = data.moderators),
617 this.setState(this.state);
618 } else if (op == UserOperation.BanFromCommunity) {
619 let data = wsJsonToRes<BanFromCommunityResponse>(
621 BanFromCommunityResponse
624 // TODO this might be incorrect
626 .filter(p => p.creator.id == data.person_view.person.id)
627 .forEach(p => (p.creator_banned_from_community = data.banned));
629 this.setState(this.state);
630 } else if (op == UserOperation.GetComments) {
631 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
632 this.setState({ comments: data.comments, commentsLoading: false });
634 op == UserOperation.EditComment ||
635 op == UserOperation.DeleteComment ||
636 op == UserOperation.RemoveComment
638 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
639 editCommentRes(data.comment_view, this.state.comments);
640 this.setState(this.state);
641 } else if (op == UserOperation.CreateComment) {
642 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
644 // Necessary since it might be a user reply
646 this.state.comments.unshift(data.comment_view);
647 this.setState(this.state);
649 } else if (op == UserOperation.SaveComment) {
650 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
651 saveCommentRes(data.comment_view, this.state.comments);
652 this.setState(this.state);
653 } else if (op == UserOperation.CreateCommentLike) {
654 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
655 createCommentLikeRes(data.comment_view, this.state.comments);
656 this.setState(this.state);
657 } else if (op == UserOperation.BlockPerson) {
658 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
659 updatePersonBlock(data);
660 } else if (op == UserOperation.CreatePostReport) {
661 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
663 toast(i18n.t("report_created"));
665 } else if (op == UserOperation.CreateCommentReport) {
666 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
668 toast(i18n.t("report_created"));
670 } else if (op == UserOperation.PurgeCommunity) {
671 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
673 toast(i18n.t("purge_success"));
674 this.context.router.history.push(`/`);
676 } else if (op == UserOperation.BlockCommunity) {
677 let data = wsJsonToRes<BlockCommunityResponse>(
679 BlockCommunityResponse
681 this.state.communityRes.match({
682 some: res => (res.community_view.blocked = data.blocked),
685 updateCommunityBlock(data);
686 this.setState(this.state);