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)}
394 allLanguages={this.state.siteRes.all_languages}
397 ) : this.state.commentsLoading ? (
403 nodes={commentsToFlatNodes(this.state.comments)}
404 viewType={CommentViewType.Flat}
407 enableDownvotes={enableDownvotes(this.state.siteRes)}
408 moderators={this.state.communityRes.map(r => r.moderators)}
409 admins={Some(this.state.siteRes.admins)}
410 maxCommentsShown={None}
411 allLanguages={this.state.siteRes.all_languages}
417 return this.state.communityRes
418 .map(r => r.community_view.community)
421 <div className="mb-2">
422 <BannerIconHeader banner={community.banner} icon={community.icon} />
423 <h5 className="mb-0 overflow-wrap-anywhere">{community.title}</h5>
425 community={community}
438 let communityRss = this.state.communityRes.map(r =>
439 communityRSSUrl(r.community_view.community.actor_id, this.state.sort)
442 <div className="mb-3">
443 <span className="mr-3">
445 type_={this.state.dataType}
446 onChange={this.handleDataTypeChange}
449 <span className="mr-2">
450 <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
452 {communityRss.match({
455 <a href={rss} title="RSS" rel={relTags}>
456 <Icon icon="rss" classes="text-muted small" />
458 <link rel="alternate" type="application/atom+xml" href={rss} />
467 handlePageChange(page: number) {
468 this.updateUrl({ page });
469 window.scrollTo(0, 0);
472 handleSortChange(val: SortType) {
473 this.updateUrl({ sort: val, page: 1 });
474 window.scrollTo(0, 0);
477 handleDataTypeChange(val: DataType) {
478 this.updateUrl({ dataType: DataType[val], page: 1 });
479 window.scrollTo(0, 0);
482 handleShowSidebarMobile(i: Community) {
483 i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
486 updateUrl(paramUpdates: UrlParams) {
487 const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
488 const sortStr = paramUpdates.sort || this.state.sort;
489 const page = paramUpdates.page || this.state.page;
491 let typeView = `/c/${this.state.communityName}`;
493 this.props.history.push(
494 `${typeView}/data_type/${dataTypeStr}/sort/${sortStr}/page/${page}`
499 if (this.state.dataType == DataType.Post) {
500 let form = new GetPosts({
501 page: Some(this.state.page),
502 limit: Some(fetchLimit),
503 sort: Some(this.state.sort),
504 type_: Some(ListingType.All),
505 community_name: Some(this.state.communityName),
507 saved_only: Some(false),
508 auth: auth(false).ok(),
510 WebSocketService.Instance.send(wsClient.getPosts(form));
512 let form = new GetComments({
513 page: Some(this.state.page),
514 limit: Some(fetchLimit),
516 sort: Some(postToCommentSortType(this.state.sort)),
517 type_: Some(ListingType.All),
518 community_name: Some(this.state.communityName),
520 saved_only: Some(false),
523 auth: auth(false).ok(),
525 WebSocketService.Instance.send(wsClient.getComments(form));
529 parseMessage(msg: any) {
530 let op = wsUserOp(msg);
533 toast(i18n.t(msg.error), "danger");
534 this.context.router.history.push("/");
536 } else if (msg.reconnect) {
537 this.state.communityRes.match({
539 WebSocketService.Instance.send(
540 wsClient.communityJoin({
541 community_id: res.community_view.community.id,
548 } else if (op == UserOperation.GetCommunity) {
549 let data = wsJsonToRes<GetCommunityResponse>(msg, GetCommunityResponse);
550 this.setState({ communityRes: Some(data), communityLoading: false });
551 // TODO why is there no auth in this form?
552 WebSocketService.Instance.send(
553 wsClient.communityJoin({
554 community_id: data.community_view.community.id,
558 op == UserOperation.EditCommunity ||
559 op == UserOperation.DeleteCommunity ||
560 op == UserOperation.RemoveCommunity
562 let data = wsJsonToRes<CommunityResponse>(msg, CommunityResponse);
563 this.state.communityRes.match({
564 some: res => (res.community_view = data.community_view),
567 this.setState(this.state);
568 } else if (op == UserOperation.FollowCommunity) {
569 let data = wsJsonToRes<CommunityResponse>(msg, CommunityResponse);
570 this.state.communityRes.match({
572 res.community_view.subscribed = data.community_view.subscribed;
573 res.community_view.counts.subscribers =
574 data.community_view.counts.subscribers;
578 this.setState(this.state);
579 } else if (op == UserOperation.GetPosts) {
580 let data = wsJsonToRes<GetPostsResponse>(msg, GetPostsResponse);
581 this.setState({ posts: data.posts, postsLoading: false });
582 restoreScrollPosition(this.context);
585 op == UserOperation.EditPost ||
586 op == UserOperation.DeletePost ||
587 op == UserOperation.RemovePost ||
588 op == UserOperation.LockPost ||
589 op == UserOperation.StickyPost ||
590 op == UserOperation.SavePost
592 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
593 editPostFindRes(data.post_view, this.state.posts);
594 this.setState(this.state);
595 } else if (op == UserOperation.CreatePost) {
596 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
597 this.state.posts.unshift(data.post_view);
599 UserService.Instance.myUserInfo
600 .map(m => m.local_user_view.local_user.show_new_post_notifs)
603 notifyPost(data.post_view, this.context.router);
605 this.setState(this.state);
606 } else if (op == UserOperation.CreatePostLike) {
607 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
608 createPostLikeFindRes(data.post_view, this.state.posts);
609 this.setState(this.state);
610 } else if (op == UserOperation.AddModToCommunity) {
611 let data = wsJsonToRes<AddModToCommunityResponse>(
613 AddModToCommunityResponse
615 this.state.communityRes.match({
616 some: res => (res.moderators = data.moderators),
619 this.setState(this.state);
620 } else if (op == UserOperation.BanFromCommunity) {
621 let data = wsJsonToRes<BanFromCommunityResponse>(
623 BanFromCommunityResponse
626 // TODO this might be incorrect
628 .filter(p => p.creator.id == data.person_view.person.id)
629 .forEach(p => (p.creator_banned_from_community = data.banned));
631 this.setState(this.state);
632 } else if (op == UserOperation.GetComments) {
633 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
634 this.setState({ comments: data.comments, commentsLoading: false });
636 op == UserOperation.EditComment ||
637 op == UserOperation.DeleteComment ||
638 op == UserOperation.RemoveComment
640 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
641 editCommentRes(data.comment_view, this.state.comments);
642 this.setState(this.state);
643 } else if (op == UserOperation.CreateComment) {
644 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
646 // Necessary since it might be a user reply
648 this.state.comments.unshift(data.comment_view);
649 this.setState(this.state);
651 } else if (op == UserOperation.SaveComment) {
652 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
653 saveCommentRes(data.comment_view, this.state.comments);
654 this.setState(this.state);
655 } else if (op == UserOperation.CreateCommentLike) {
656 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
657 createCommentLikeRes(data.comment_view, this.state.comments);
658 this.setState(this.state);
659 } else if (op == UserOperation.BlockPerson) {
660 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
661 updatePersonBlock(data);
662 } else if (op == UserOperation.CreatePostReport) {
663 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
665 toast(i18n.t("report_created"));
667 } else if (op == UserOperation.CreateCommentReport) {
668 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
670 toast(i18n.t("report_created"));
672 } else if (op == UserOperation.PurgeCommunity) {
673 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
675 toast(i18n.t("purge_success"));
676 this.context.router.history.push(`/`);
678 } else if (op == UserOperation.BlockCommunity) {
679 let data = wsJsonToRes<BlockCommunityResponse>(
681 BlockCommunityResponse
683 this.state.communityRes.match({
684 some: res => (res.community_view.blocked = data.blocked),
687 updateCommunityBlock(data);
688 this.setState(this.state);