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,
55 postToCommentSortType,
57 restoreScrollPosition,
69 import { CommentNodes } from "../comment/comment-nodes";
70 import { BannerIconHeader } from "../common/banner-icon-header";
71 import { DataTypeSelect } from "../common/data-type-select";
72 import { HtmlTags } from "../common/html-tags";
73 import { Icon, Spinner } from "../common/icon";
74 import { Paginator } from "../common/paginator";
75 import { SortSelect } from "../common/sort-select";
76 import { Sidebar } from "../community/sidebar";
77 import { SiteSidebar } from "../home/site-sidebar";
78 import { PostListings } from "../post/post-listings";
79 import { CommunityLink } from "./community-link";
82 communityRes: Option<GetCommunityResponse>;
83 siteRes: GetSiteResponse;
84 communityName: string;
85 communityLoading: boolean;
86 postsLoading: boolean;
87 commentsLoading: boolean;
89 comments: CommentView[];
93 showSidebarMobile: boolean;
96 interface CommunityProps {
102 interface UrlParams {
108 export class Community extends Component<any, State> {
109 private isoData = setIsoData(
111 GetCommunityResponse,
115 private subscription: Subscription;
116 private emptyState: State = {
118 communityName: this.props.match.params.name,
119 communityLoading: true,
121 commentsLoading: true,
124 dataType: getDataTypeFromProps(this.props),
125 sort: getSortTypeFromProps(this.props),
126 page: getPageFromProps(this.props),
127 siteRes: this.isoData.site_res,
128 showSidebarMobile: false,
131 constructor(props: any, context: any) {
132 super(props, context);
134 this.state = this.emptyState;
135 this.handleSortChange = this.handleSortChange.bind(this);
136 this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
137 this.handlePageChange = this.handlePageChange.bind(this);
139 this.parseMessage = this.parseMessage.bind(this);
140 this.subscription = wsSubscribe(this.parseMessage);
142 // Only fetch the data if coming from another route
143 if (this.isoData.path == this.context.router.route.match.url) {
146 communityRes: Some(this.isoData.routeData[0] as GetCommunityResponse),
148 let postsRes = Some(this.isoData.routeData[1] as GetPostsResponse);
149 let commentsRes = Some(this.isoData.routeData[2] as GetCommentsResponse);
151 if (postsRes.isSome()) {
152 this.state = { ...this.state, posts: postsRes.unwrap().posts };
155 if (commentsRes.isSome()) {
156 this.state = { ...this.state, comments: commentsRes.unwrap().comments };
161 communityLoading: false,
163 commentsLoading: false,
166 this.fetchCommunity();
172 let form = new GetCommunity({
173 name: Some(this.state.communityName),
175 auth: auth(false).ok(),
177 WebSocketService.Instance.send(wsClient.getCommunity(form));
180 componentDidMount() {
184 componentWillUnmount() {
185 saveScrollPosition(this.context);
186 this.subscription.unsubscribe();
189 static getDerivedStateFromProps(props: any): CommunityProps {
191 dataType: getDataTypeFromProps(props),
192 sort: getSortTypeFromProps(props),
193 page: getPageFromProps(props),
197 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
198 let pathSplit = req.path.split("/");
199 let promises: Promise<any>[] = [];
201 let communityName = pathSplit[2];
202 let communityForm = new GetCommunity({
203 name: Some(communityName),
207 promises.push(req.client.getCommunity(communityForm));
209 let dataType: DataType = pathSplit[4]
210 ? DataType[pathSplit[4]]
213 let sort: Option<SortType> = toOption(
215 ? SortType[pathSplit[6]]
216 : UserService.Instance.myUserInfo.match({
218 Object.values(SortType)[
219 mui.local_user_view.local_user.default_sort_type
221 none: SortType.Active,
225 let page = toOption(pathSplit[8] ? Number(pathSplit[8]) : 1);
227 if (dataType == DataType.Post) {
228 let getPostsForm = new GetPosts({
229 community_name: Some(communityName),
232 limit: Some(fetchLimit),
234 type_: Some(ListingType.All),
235 saved_only: Some(false),
238 promises.push(req.client.getPosts(getPostsForm));
239 promises.push(Promise.resolve());
241 let getCommentsForm = new GetComments({
242 community_name: Some(communityName),
245 limit: Some(fetchLimit),
247 sort: sort.map(postToCommentSortType),
248 type_: Some(ListingType.All),
249 saved_only: Some(false),
254 promises.push(Promise.resolve());
255 promises.push(req.client.getComments(getCommentsForm));
261 componentDidUpdate(_: any, lastState: State) {
263 lastState.dataType !== this.state.dataType ||
264 lastState.sort !== this.state.sort ||
265 lastState.page !== this.state.page
267 this.setState({ postsLoading: true, commentsLoading: true });
272 get documentTitle(): string {
273 return this.state.communityRes.match({
275 `${res.community_view.community.title} - ${this.state.siteRes.site_view.site.name}`,
282 <div className="container-lg">
283 {this.state.communityLoading ? (
288 this.state.communityRes.match({
292 title={this.documentTitle}
293 path={this.context.router.route.match.url}
294 description={res.community_view.community.description}
295 image={res.community_view.community.icon}
298 <div className="row">
299 <div className="col-12 col-md-8">
300 {this.communityInfo()}
301 <div className="d-block d-md-none">
303 className="btn btn-secondary d-inline-block mb-2 mr-3"
304 onClick={linkEvent(this, this.handleShowSidebarMobile)}
306 {i18n.t("sidebar")}{" "}
309 this.state.showSidebarMobile
313 classes="icon-inline"
316 {this.state.showSidebarMobile && (
319 community_view={res.community_view}
320 moderators={res.moderators}
321 admins={this.state.siteRes.admins}
323 enableNsfw={enableNsfw(this.state.siteRes)}
325 {!res.community_view.community.local &&
330 showLocal={showLocal(this.isoData)}
344 page={this.state.page}
345 onChange={this.handlePageChange}
348 <div className="d-none d-md-block col-md-4">
350 community_view={res.community_view}
351 moderators={res.moderators}
352 admins={this.state.siteRes.admins}
354 enableNsfw={enableNsfw(this.state.siteRes)}
356 {!res.community_view.community.local &&
361 showLocal={showLocal(this.isoData)}
381 return this.state.dataType == DataType.Post ? (
382 this.state.postsLoading ? (
388 posts={this.state.posts}
390 enableDownvotes={enableDownvotes(this.state.siteRes)}
391 enableNsfw={enableNsfw(this.state.siteRes)}
392 allLanguages={this.state.siteRes.all_languages}
395 ) : this.state.commentsLoading ? (
401 nodes={commentsToFlatNodes(this.state.comments)}
402 viewType={CommentViewType.Flat}
405 enableDownvotes={enableDownvotes(this.state.siteRes)}
406 moderators={this.state.communityRes.map(r => r.moderators)}
407 admins={Some(this.state.siteRes.admins)}
408 maxCommentsShown={None}
409 allLanguages={this.state.siteRes.all_languages}
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.FeaturePost ||
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);
596 let showPostNotifs = UserService.Instance.myUserInfo
597 .map(m => m.local_user_view.local_user.show_new_post_notifs)
600 // Only push these if you're on the first page, you pass the nsfw check, and it isn't blocked
603 this.state.page == 1 &&
604 nsfwCheck(data.post_view) &&
605 !isPostBlocked(data.post_view)
607 this.state.posts.unshift(data.post_view);
608 if (showPostNotifs) {
609 notifyPost(data.post_view, this.context.router);
611 this.setState(this.state);
613 } else if (op == UserOperation.CreatePostLike) {
614 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
615 createPostLikeFindRes(data.post_view, this.state.posts);
616 this.setState(this.state);
617 } else if (op == UserOperation.AddModToCommunity) {
618 let data = wsJsonToRes<AddModToCommunityResponse>(
620 AddModToCommunityResponse
622 this.state.communityRes.match({
623 some: res => (res.moderators = data.moderators),
626 this.setState(this.state);
627 } else if (op == UserOperation.BanFromCommunity) {
628 let data = wsJsonToRes<BanFromCommunityResponse>(
630 BanFromCommunityResponse
633 // TODO this might be incorrect
635 .filter(p => p.creator.id == data.person_view.person.id)
636 .forEach(p => (p.creator_banned_from_community = data.banned));
638 this.setState(this.state);
639 } else if (op == UserOperation.GetComments) {
640 let data = wsJsonToRes<GetCommentsResponse>(msg, GetCommentsResponse);
641 this.setState({ comments: data.comments, commentsLoading: false });
643 op == UserOperation.EditComment ||
644 op == UserOperation.DeleteComment ||
645 op == UserOperation.RemoveComment
647 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
648 editCommentRes(data.comment_view, this.state.comments);
649 this.setState(this.state);
650 } else if (op == UserOperation.CreateComment) {
651 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
653 // Necessary since it might be a user reply
655 this.state.comments.unshift(data.comment_view);
656 this.setState(this.state);
658 } else if (op == UserOperation.SaveComment) {
659 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
660 saveCommentRes(data.comment_view, this.state.comments);
661 this.setState(this.state);
662 } else if (op == UserOperation.CreateCommentLike) {
663 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
664 createCommentLikeRes(data.comment_view, this.state.comments);
665 this.setState(this.state);
666 } else if (op == UserOperation.BlockPerson) {
667 let data = wsJsonToRes<BlockPersonResponse>(msg, BlockPersonResponse);
668 updatePersonBlock(data);
669 } else if (op == UserOperation.CreatePostReport) {
670 let data = wsJsonToRes<PostReportResponse>(msg, PostReportResponse);
672 toast(i18n.t("report_created"));
674 } else if (op == UserOperation.CreateCommentReport) {
675 let data = wsJsonToRes<CommentReportResponse>(msg, CommentReportResponse);
677 toast(i18n.t("report_created"));
679 } else if (op == UserOperation.PurgeCommunity) {
680 let data = wsJsonToRes<PurgeItemResponse>(msg, PurgeItemResponse);
682 toast(i18n.t("purge_success"));
683 this.context.router.history.push(`/`);
685 } else if (op == UserOperation.BlockCommunity) {
686 let data = wsJsonToRes<BlockCommunityResponse>(
688 BlockCommunityResponse
690 this.state.communityRes.match({
691 some: res => (res.community_view.blocked = data.blocked),
694 updateCommunityBlock(data);
695 this.setState(this.state);