]> Untitled Git - lemmy-ui.git/blobdiff - src/shared/components/home/home.tsx
Merge branch 'main' into breakout-role-utils
[lemmy-ui.git] / src / shared / components / home / home.tsx
index 3a74901416aeb8067b21fc0a675ca4337e7f5c1d..3613b0f8329a1329e9e522641ac07bfd6b7c0995 100644 (file)
@@ -1,61 +1,91 @@
-import { Component, linkEvent } from "inferno";
-import { T } from "inferno-i18next";
+import { NoOptionI18nKeys } from "i18next";
+import { Component, linkEvent, MouseEventHandler } from "inferno";
+import { T } from "inferno-i18next-dess";
 import { Link } from "inferno-router";
 import {
-  AddAdminResponse,
+  AddAdmin,
+  AddModToCommunity,
+  BanFromCommunity,
+  BanFromCommunityResponse,
+  BanPerson,
   BanPersonResponse,
+  BlockPerson,
+  CommentId,
+  CommentReplyResponse,
   CommentResponse,
-  CommentView,
-  CommunityFollowerView,
-  CommunityView,
+  CreateComment,
+  CreateCommentLike,
+  CreateCommentReport,
+  CreatePostLike,
+  CreatePostReport,
+  DeleteComment,
+  DeletePost,
+  DistinguishComment,
+  EditComment,
+  EditPost,
+  FeaturePost,
   GetComments,
   GetCommentsResponse,
-  GetFollowedCommunitiesResponse,
   GetPosts,
   GetPostsResponse,
   GetSiteResponse,
   ListCommunities,
   ListCommunitiesResponse,
   ListingType,
+  LockPost,
+  MarkCommentReplyAsRead,
+  MarkPersonMentionAsRead,
   PostResponse,
-  PostView,
-  SiteResponse,
+  PurgeComment,
+  PurgeItemResponse,
+  PurgePerson,
+  PurgePost,
+  RemoveComment,
+  RemovePost,
+  SaveComment,
+  SavePost,
   SortType,
-  UserOperation,
+  TransferCommunity,
 } from "lemmy-js-client";
-import { Subscription } from "rxjs";
 import { i18n } from "../../i18next";
-import { DataType, InitialFetchRequest } from "../../interfaces";
-import { UserService, WebSocketService } from "../../services";
 import {
-  authField,
+  CommentViewType,
+  DataType,
+  InitialFetchRequest,
+} from "../../interfaces";
+import { UserService } from "../../services";
+import { FirstLoadService } from "../../services/FirstLoadService";
+import { HttpService, RequestState } from "../../services/HttpService";
+import {
   commentsToFlatNodes,
-  createCommentLikeRes,
-  createPostLikeFindRes,
-  editCommentRes,
-  editPostFindRes,
+  editComment,
+  editPost,
+  editWith,
+  enableDownvotes,
+  enableNsfw,
   fetchLimit,
-  getDataTypeFromProps,
-  getListingTypeFromProps,
-  getPageFromProps,
-  getSortTypeFromProps,
+  getCommentParentId,
+  getDataTypeString,
+  getPageFromString,
+  getRandomFromList,
   mdToHtml,
-  notifyPost,
+  myAuth,
+  postToCommentSortType,
+  relTags,
   restoreScrollPosition,
-  saveCommentRes,
   saveScrollPosition,
   setIsoData,
-  setOptionalAuth,
   setupTippy,
   showLocal,
   toast,
-  wsClient,
-  wsJsonToRes,
-  wsSubscribe,
-  wsUserOp,
+  trendingFetchLimit,
+  updatePersonBlock,
 } from "../../utils";
+import { getQueryParams } from "../../utils/helpers/get-query-params";
+import { getQueryString } from "../../utils/helpers/get-query-string";
+import { canCreateCommunity } from "../../utils/roles/can-create-community";
+import type { QueryParams } from "../../utils/types/query-params";
 import { CommentNodes } from "../comment/comment-nodes";
-import { BannerIconHeader } from "../common/banner-icon-header";
 import { DataTypeSelect } from "../common/data-type-select";
 import { HtmlTags } from "../common/html-tags";
 import { Icon, Spinner } from "../common/icon";
@@ -63,25 +93,21 @@ import { ListingTypeSelect } from "../common/listing-type-select";
 import { Paginator } from "../common/paginator";
 import { SortSelect } from "../common/sort-select";
 import { CommunityLink } from "../community/community-link";
-import { PersonListing } from "../person/person-listing";
 import { PostListings } from "../post/post-listings";
-import { SiteForm } from "./site-form";
+import { SiteSidebar } from "./site-sidebar";
 
 interface HomeState {
-  subscribedCommunities: CommunityFollowerView[];
-  trendingCommunities: CommunityView[];
-  siteRes: GetSiteResponse;
-  showEditSite: boolean;
+  postsRes: RequestState<GetPostsResponse>;
+  commentsRes: RequestState<GetCommentsResponse>;
+  trendingCommunitiesRes: RequestState<ListCommunitiesResponse>;
   showSubscribedMobile: boolean;
   showTrendingMobile: boolean;
   showSidebarMobile: boolean;
-  loading: boolean;
-  posts: PostView[];
-  comments: CommentView[];
-  listingType: ListingType;
-  dataType: DataType;
-  sort: SortType;
-  page: number;
+  subscribedCollapsed: boolean;
+  tagline?: string;
+  siteRes: GetSiteResponse;
+  finished: Map<CommentId, boolean | undefined>;
+  isIsomorphic: boolean;
 }
 
 interface HomeProps {
@@ -91,272 +117,292 @@ interface HomeProps {
   page: number;
 }
 
-interface UrlParams {
-  listingType?: ListingType;
-  dataType?: string;
-  sort?: SortType;
-  page?: number;
+function getDataTypeFromQuery(type?: string): DataType {
+  return type ? DataType[type] : DataType.Post;
+}
+
+function getListingTypeFromQuery(type?: string): ListingType {
+  const myListingType =
+    UserService.Instance.myUserInfo?.local_user_view?.local_user
+      ?.default_listing_type;
+
+  return (type ? (type as ListingType) : myListingType) ?? "Local";
 }
 
+function getSortTypeFromQuery(type?: string): SortType {
+  const mySortType =
+    UserService.Instance.myUserInfo?.local_user_view?.local_user
+      ?.default_sort_type;
+
+  return (type ? (type as SortType) : mySortType) ?? "Active";
+}
+
+const getHomeQueryParams = () =>
+  getQueryParams<HomeProps>({
+    sort: getSortTypeFromQuery,
+    listingType: getListingTypeFromQuery,
+    page: getPageFromString,
+    dataType: getDataTypeFromQuery,
+  });
+
+const MobileButton = ({
+  textKey,
+  show,
+  onClick,
+}: {
+  textKey: NoOptionI18nKeys;
+  show: boolean;
+  onClick: MouseEventHandler<HTMLButtonElement>;
+}) => (
+  <button
+    className="btn btn-secondary d-inline-block mb-2 mr-3"
+    onClick={onClick}
+  >
+    {i18n.t(textKey)}{" "}
+    <Icon icon={show ? `minus-square` : `plus-square`} classes="icon-inline" />
+  </button>
+);
+
+const LinkButton = ({
+  path,
+  translationKey,
+}: {
+  path: string;
+  translationKey: NoOptionI18nKeys;
+}) => (
+  <Link className="btn btn-secondary btn-block" to={path}>
+    {i18n.t(translationKey)}
+  </Link>
+);
+
 export class Home extends Component<any, HomeState> {
   private isoData = setIsoData(this.context);
-  private subscription: Subscription;
-  private emptyState: HomeState = {
-    subscribedCommunities: [],
-    trendingCommunities: [],
+  state: HomeState = {
+    postsRes: { state: "empty" },
+    commentsRes: { state: "empty" },
+    trendingCommunitiesRes: { state: "empty" },
     siteRes: this.isoData.site_res,
-    showEditSite: false,
     showSubscribedMobile: false,
     showTrendingMobile: false,
     showSidebarMobile: false,
-    loading: true,
-    posts: [],
-    comments: [],
-    listingType: getListingTypeFromProps(this.props),
-    dataType: getDataTypeFromProps(this.props),
-    sort: getSortTypeFromProps(this.props),
-    page: getPageFromProps(this.props),
+    subscribedCollapsed: false,
+    finished: new Map(),
+    isIsomorphic: false,
   };
 
   constructor(props: any, context: any) {
     super(props, context);
 
-    this.state = this.emptyState;
-    this.handleEditCancel = this.handleEditCancel.bind(this);
     this.handleSortChange = this.handleSortChange.bind(this);
     this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
     this.handlePageChange = this.handlePageChange.bind(this);
 
-    this.parseMessage = this.parseMessage.bind(this);
-    this.subscription = wsSubscribe(this.parseMessage);
+    this.handleCreateComment = this.handleCreateComment.bind(this);
+    this.handleEditComment = this.handleEditComment.bind(this);
+    this.handleSaveComment = this.handleSaveComment.bind(this);
+    this.handleBlockPerson = this.handleBlockPerson.bind(this);
+    this.handleDeleteComment = this.handleDeleteComment.bind(this);
+    this.handleRemoveComment = this.handleRemoveComment.bind(this);
+    this.handleCommentVote = this.handleCommentVote.bind(this);
+    this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
+    this.handleAddAdmin = this.handleAddAdmin.bind(this);
+    this.handlePurgePerson = this.handlePurgePerson.bind(this);
+    this.handlePurgeComment = this.handlePurgeComment.bind(this);
+    this.handleCommentReport = this.handleCommentReport.bind(this);
+    this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
+    this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
+    this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
+    this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
+    this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
+    this.handleBanPerson = this.handleBanPerson.bind(this);
+    this.handlePostEdit = this.handlePostEdit.bind(this);
+    this.handlePostVote = this.handlePostVote.bind(this);
+    this.handlePostReport = this.handlePostReport.bind(this);
+    this.handleLockPost = this.handleLockPost.bind(this);
+    this.handleDeletePost = this.handleDeletePost.bind(this);
+    this.handleRemovePost = this.handleRemovePost.bind(this);
+    this.handleSavePost = this.handleSavePost.bind(this);
+    this.handlePurgePost = this.handlePurgePost.bind(this);
+    this.handleFeaturePost = this.handleFeaturePost.bind(this);
 
     // Only fetch the data if coming from another route
-    if (this.isoData.path == this.context.router.route.match.url) {
-      if (this.state.dataType == DataType.Post) {
-        this.state.posts = this.isoData.routeData[0].posts;
-      } else {
-        this.state.comments = this.isoData.routeData[0].comments;
-      }
-      this.state.trendingCommunities = this.isoData.routeData[1].communities;
-      if (UserService.Instance.localUserView) {
-        this.state.subscribedCommunities =
-          this.isoData.routeData[2].communities;
-      }
-      this.state.loading = false;
-    } else {
-      this.fetchTrendingCommunities();
-      this.fetchData();
-      if (UserService.Instance.localUserView) {
-        WebSocketService.Instance.send(
-          wsClient.getFollowedCommunities({
-            auth: authField(),
-          })
-        );
-      }
-    }
+    if (FirstLoadService.isFirstLoad) {
+      const [postsRes, commentsRes, trendingCommunitiesRes] =
+        this.isoData.routeData;
 
-    setupTippy();
-  }
-
-  fetchTrendingCommunities() {
-    let listCommunitiesForm: ListCommunities = {
-      type_: ListingType.Local,
-      sort: SortType.Hot,
-      limit: 6,
-      auth: authField(false),
-    };
-    WebSocketService.Instance.send(
-      wsClient.listCommunities(listCommunitiesForm)
-    );
+      this.state = {
+        ...this.state,
+        postsRes,
+        commentsRes,
+        trendingCommunitiesRes,
+        tagline: getRandomFromList(this.state?.siteRes?.taglines ?? [])
+          ?.content,
+        isIsomorphic: true,
+      };
+    }
   }
 
-  componentDidMount() {
-    // This means it hasn't been set up yet
-    if (!this.state.siteRes.site_view) {
-      this.context.router.history.push("/setup");
+  async componentDidMount() {
+    if (!this.state.isIsomorphic || !this.isoData.routeData.length) {
+      await Promise.all([this.fetchTrendingCommunities(), this.fetchData()]);
     }
 
-    WebSocketService.Instance.send(wsClient.communityJoin({ community_id: 0 }));
+    setupTippy();
   }
 
   componentWillUnmount() {
     saveScrollPosition(this.context);
-    this.subscription.unsubscribe();
-    window.isoData.path = undefined;
-  }
-
-  static getDerivedStateFromProps(props: any): HomeProps {
-    return {
-      listingType: getListingTypeFromProps(props),
-      dataType: getDataTypeFromProps(props),
-      sort: getSortTypeFromProps(props),
-      page: getPageFromProps(props),
-    };
   }
 
-  static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
-    let pathSplit = req.path.split("/");
-    let dataType: DataType = pathSplit[3]
-      ? DataType[pathSplit[3]]
-      : DataType.Post;
+  static fetchInitialData({
+    client,
+    auth,
+    query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
+  }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<
+    RequestState<any>
+  >[] {
+    const dataType = getDataTypeFromQuery(urlDataType);
 
     // TODO figure out auth default_listingType, default_sort_type
-    let type_: ListingType = pathSplit[5]
-      ? ListingType[pathSplit[5]]
-      : UserService.Instance.localUserView
-      ? Object.values(ListingType)[
-          UserService.Instance.localUserView.local_user.default_listing_type
-        ]
-      : ListingType.Local;
-    let sort: SortType = pathSplit[7]
-      ? SortType[pathSplit[7]]
-      : UserService.Instance.localUserView
-      ? Object.values(SortType)[
-          UserService.Instance.localUserView.local_user.default_sort_type
-        ]
-      : SortType.Active;
-
-    let page = pathSplit[9] ? Number(pathSplit[9]) : 1;
-
-    let promises: Promise<any>[] = [];
-
-    if (dataType == DataType.Post) {
-      let getPostsForm: GetPosts = {
+    const type_ = getListingTypeFromQuery(listingType);
+    const sort = getSortTypeFromQuery(urlSort);
+
+    const page = urlPage ? Number(urlPage) : 1;
+
+    const promises: Promise<RequestState<any>>[] = [];
+
+    if (dataType === DataType.Post) {
+      const getPostsForm: GetPosts = {
+        type_,
         page,
         limit: fetchLimit,
         sort,
-        type_,
         saved_only: false,
+        auth,
       };
-      setOptionalAuth(getPostsForm, req.auth);
-      promises.push(req.client.getPosts(getPostsForm));
+
+      promises.push(client.getPosts(getPostsForm));
+      promises.push(Promise.resolve({ state: "empty" }));
     } else {
-      let getCommentsForm: GetComments = {
+      const getCommentsForm: GetComments = {
         page,
         limit: fetchLimit,
-        sort,
+        sort: postToCommentSortType(sort),
         type_,
         saved_only: false,
+        auth,
       };
-      setOptionalAuth(getCommentsForm, req.auth);
-      promises.push(req.client.getComments(getCommentsForm));
+      promises.push(Promise.resolve({ state: "empty" }));
+      promises.push(client.getComments(getCommentsForm));
     }
 
-    let trendingCommunitiesForm: ListCommunities = {
-      type_: ListingType.Local,
-      sort: SortType.Hot,
-      limit: 6,
+    const trendingCommunitiesForm: ListCommunities = {
+      type_: "Local",
+      sort: "Hot",
+      limit: trendingFetchLimit,
+      auth,
     };
-    promises.push(req.client.listCommunities(trendingCommunitiesForm));
-
-    if (req.auth) {
-      promises.push(req.client.getFollowedCommunities({ auth: req.auth }));
-    }
+    promises.push(client.listCommunities(trendingCommunitiesForm));
 
     return promises;
   }
 
-  componentDidUpdate(_: any, lastState: HomeState) {
-    if (
-      lastState.listingType !== this.state.listingType ||
-      lastState.dataType !== this.state.dataType ||
-      lastState.sort !== this.state.sort ||
-      lastState.page !== this.state.page
-    ) {
-      this.setState({ loading: true });
-      this.fetchData();
-    }
-  }
-
   get documentTitle(): string {
-    return `${
-      this.state.siteRes.site_view
-        ? this.state.siteRes.site_view.site.description
-          ? `${this.state.siteRes.site_view.site.name} - ${this.state.siteRes.site_view.site.description}`
-          : this.state.siteRes.site_view.site.name
-        : "Lemmy"
-    }`;
+    const { name, description } = this.state.siteRes.site_view.site;
+
+    return description ? `${name} - ${description}` : name;
   }
 
   render() {
+    const {
+      tagline,
+      siteRes: {
+        site_view: {
+          local_site: { site_setup },
+        },
+      },
+    } = this.state;
+
     return (
-      <div class="container">
+      <div className="container-lg">
         <HtmlTags
           title={this.documentTitle}
           path={this.context.router.route.match.url}
         />
-        {this.state.siteRes.site_view?.site && (
-          <div class="row">
-            <main role="main" class="col-12 col-md-8">
-              <div class="d-block d-md-none">{this.mobileView()}</div>
+        {site_setup && (
+          <div className="row">
+            <main role="main" className="col-12 col-md-8">
+              {tagline && (
+                <div
+                  id="tagline"
+                  dangerouslySetInnerHTML={mdToHtml(tagline)}
+                ></div>
+              )}
+              <div className="d-block d-md-none">{this.mobileView}</div>
               {this.posts()}
             </main>
-            <aside class="d-none d-md-block col-md-4">{this.mySidebar()}</aside>
+            <aside className="d-none d-md-block col-md-4">
+              {this.mySidebar}
+            </aside>
           </div>
         )}
       </div>
     );
   }
 
-  mobileView() {
+  get hasFollows(): boolean {
+    const mui = UserService.Instance.myUserInfo;
+    return !!mui && mui.follows.length > 0;
+  }
+
+  get mobileView() {
+    const {
+      siteRes: {
+        site_view: { counts, site },
+        admins,
+      },
+      showSubscribedMobile,
+      showTrendingMobile,
+      showSidebarMobile,
+    } = this.state;
+
     return (
-      <div class="row">
-        <div class="col-12">
-          {UserService.Instance.localUserView &&
-            this.state.subscribedCommunities.length > 0 && (
-              <button
-                class="btn btn-secondary d-inline-block mb-2 mr-3"
-                onClick={linkEvent(this, this.handleShowSubscribedMobile)}
-              >
-                {i18n.t("subscribed")}{" "}
-                <Icon
-                  icon={
-                    this.state.showSubscribedMobile
-                      ? `minus-square`
-                      : `plus-square`
-                  }
-                  classes="icon-inline"
-                />
-              </button>
-            )}
-          <button
-            class="btn btn-secondary d-inline-block mb-2 mr-3"
-            onClick={linkEvent(this, this.handleShowTrendingMobile)}
-          >
-            {i18n.t("trending")}{" "}
-            <Icon
-              icon={
-                this.state.showTrendingMobile ? `minus-square` : `plus-square`
-              }
-              classes="icon-inline"
+      <div className="row">
+        <div className="col-12">
+          {this.hasFollows && (
+            <MobileButton
+              textKey="subscribed"
+              show={showSubscribedMobile}
+              onClick={linkEvent(this, this.handleShowSubscribedMobile)}
             />
-          </button>
-          <button
-            class="btn btn-secondary d-inline-block mb-2 mr-3"
+          )}
+          <MobileButton
+            textKey="trending"
+            show={showTrendingMobile}
+            onClick={linkEvent(this, this.handleShowTrendingMobile)}
+          />
+          <MobileButton
+            textKey="sidebar"
+            show={showSidebarMobile}
             onClick={linkEvent(this, this.handleShowSidebarMobile)}
-          >
-            {i18n.t("sidebar")}{" "}
-            <Icon
-              icon={
-                this.state.showSidebarMobile ? `minus-square` : `plus-square`
-              }
-              classes="icon-inline"
+          />
+          {showSidebarMobile && (
+            <SiteSidebar
+              site={site}
+              admins={admins}
+              counts={counts}
+              showLocal={showLocal(this.isoData)}
             />
-          </button>
-          {this.state.showSubscribedMobile && (
-            <div class="col-12 card border-secondary mb-3">
-              <div class="card-body">{this.subscribedCommunities()}</div>
-            </div>
           )}
-          {this.state.showTrendingMobile && (
-            <div class="col-12 card border-secondary mb-3">
-              <div class="card-body">{this.trendingCommunities()}</div>
+          {showTrendingMobile && (
+            <div className="col-12 card border-secondary mb-3">
+              <div className="card-body">{this.trendingCommunities(true)}</div>
             </div>
           )}
-          {this.state.showSidebarMobile && (
-            <div class="col-12 card border-secondary mb-3">
-              <div class="card-body">{this.sidebar()}</div>
+          {showSubscribedMobile && (
+            <div className="col-12 card border-secondary mb-3">
+              <div className="card-body">{this.subscribedCommunities}</div>
             </div>
           )}
         </div>
@@ -364,392 +410,370 @@ export class Home extends Component<any, HomeState> {
     );
   }
 
-  mySidebar() {
+  get mySidebar() {
+    const {
+      siteRes: {
+        site_view: { counts, site },
+        admins,
+      },
+    } = this.state;
+
     return (
       <div>
-        {!this.state.loading && (
-          <div>
-            <div class="card border-secondary mb-3">
-              <div class="card-body">
-                {this.trendingCommunities()}
-                {this.createCommunityButton()}
-                {this.exploreCommunitiesButton()}
-              </div>
-            </div>
-
-            {UserService.Instance.localUserView &&
-              this.state.subscribedCommunities.length > 0 && (
-                <div class="card border-secondary mb-3">
-                  <div class="card-body">{this.subscribedCommunities()}</div>
-                </div>
+        <div>
+          <div className="card border-secondary mb-3">
+            <div className="card-body">
+              {this.trendingCommunities()}
+              {canCreateCommunity(this.state.siteRes) && (
+                <LinkButton
+                  path="/create_community"
+                  translationKey="create_a_community"
+                />
               )}
-
-            <div class="card border-secondary mb-3">
-              <div class="card-body">{this.sidebar()}</div>
+              <LinkButton
+                path="/communities"
+                translationKey="explore_communities"
+              />
             </div>
           </div>
-        )}
+          <SiteSidebar
+            site={site}
+            admins={admins}
+            counts={counts}
+            showLocal={showLocal(this.isoData)}
+          />
+          {this.hasFollows && (
+            <div className="card border-secondary mb-3">
+              <div className="card-body">{this.subscribedCommunities}</div>
+            </div>
+          )}
+        </div>
       </div>
     );
   }
 
-  createCommunityButton() {
-    return (
-      <Link className="mt-2 btn btn-secondary btn-block" to="/create_community">
-        {i18n.t("create_a_community")}
-      </Link>
-    );
+  trendingCommunities(isMobile = false) {
+    switch (this.state.trendingCommunitiesRes?.state) {
+      case "loading":
+        return (
+          <h5>
+            <Spinner large />
+          </h5>
+        );
+      case "success": {
+        const trending = this.state.trendingCommunitiesRes.data.communities;
+        return (
+          <div className={!isMobile ? "mb-2" : ""}>
+            <h5>
+              <T i18nKey="trending_communities">
+                #
+                <Link className="text-body" to="/communities">
+                  #
+                </Link>
+              </T>
+            </h5>
+            <ul className="list-inline mb-0">
+              {trending.map(cv => (
+                <li
+                  key={cv.community.id}
+                  className="list-inline-item d-inline-block"
+                >
+                  <CommunityLink community={cv.community} />
+                </li>
+              ))}
+            </ul>
+          </div>
+        );
+      }
+    }
   }
 
-  exploreCommunitiesButton() {
-    return (
-      <Link className="btn btn-secondary btn-block" to="/communities">
-        {i18n.t("explore_communities")}
-      </Link>
-    );
-  }
+  get subscribedCommunities() {
+    const { subscribedCollapsed } = this.state;
 
-  trendingCommunities() {
     return (
       <div>
         <h5>
-          <T i18nKey="trending_communities">
-            #
-            <Link className="text-body" to="/communities">
-              #
-            </Link>
-          </T>
-        </h5>
-        <ul class="list-inline mb-0">
-          {this.state.trendingCommunities.map(cv => (
-            <li class="list-inline-item d-inline-block">
-              <CommunityLink community={cv.community} />
-            </li>
-          ))}
-        </ul>
-      </div>
-    );
-  }
-
-  subscribedCommunities() {
-    return (
-      <div>
-        <h5>
-          <T i18nKey="subscribed_to_communities">
+          <T class="d-inline" i18nKey="subscribed_to_communities">
             #
             <Link className="text-body" to="/communities">
               #
             </Link>
           </T>
+          <button
+            className="btn btn-sm text-muted"
+            onClick={linkEvent(this, this.handleCollapseSubscribe)}
+            aria-label={i18n.t("collapse")}
+            data-tippy-content={i18n.t("collapse")}
+          >
+            <Icon
+              icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
+              classes="icon-inline"
+            />
+          </button>
         </h5>
-        <ul class="list-inline mb-0">
-          {this.state.subscribedCommunities.map(cfv => (
-            <li class="list-inline-item d-inline-block">
-              <CommunityLink community={cfv.community} />
-            </li>
-          ))}
-        </ul>
-      </div>
-    );
-  }
-
-  sidebar() {
-    let site = this.state.siteRes.site_view.site;
-    return (
-      <div>
-        {!this.state.showEditSite ? (
-          <div>
-            <div class="mb-2">
-              {this.siteName()}
-              {this.adminButtons()}
-            </div>
-            <BannerIconHeader banner={site.banner} />
-            {this.siteInfo()}
-          </div>
-        ) : (
-          <SiteForm site={site} onCancel={this.handleEditCancel} />
+        {!subscribedCollapsed && (
+          <ul className="list-inline mb-0">
+            {UserService.Instance.myUserInfo?.follows.map(cfv => (
+              <li
+                key={cfv.community.id}
+                className="list-inline-item d-inline-block"
+              >
+                <CommunityLink community={cfv.community} />
+              </li>
+            ))}
+          </ul>
         )}
       </div>
     );
   }
 
-  updateUrl(paramUpdates: UrlParams) {
-    const listingTypeStr = paramUpdates.listingType || this.state.listingType;
-    const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
-    const sortStr = paramUpdates.sort || this.state.sort;
-    const page = paramUpdates.page || this.state.page;
-    this.props.history.push(
-      `/home/data_type/${dataTypeStr}/listing_type/${listingTypeStr}/sort/${sortStr}/page/${page}`
-    );
-  }
+  async updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
+    const {
+      dataType: urlDataType,
+      listingType: urlListingType,
+      page: urlPage,
+      sort: urlSort,
+    } = getHomeQueryParams();
 
-  siteInfo() {
-    let site = this.state.siteRes.site_view.site;
-    return (
-      <div>
-        {site.description && <h6>{site.description}</h6>}
-        {site.sidebar && this.siteSidebar()}
-        {this.badges()}
-        {this.admins()}
-      </div>
-    );
-  }
+    const queryParams: QueryParams<HomeProps> = {
+      dataType: getDataTypeString(dataType ?? urlDataType),
+      listingType: listingType ?? urlListingType,
+      page: (page ?? urlPage).toString(),
+      sort: sort ?? urlSort,
+    };
 
-  siteName() {
-    let site = this.state.siteRes.site_view.site;
-    return site.name && <h5 class="mb-0">{site.name}</h5>;
-  }
+    this.props.history.push({
+      pathname: "/",
+      search: getQueryString(queryParams),
+    });
 
-  admins() {
-    return (
-      <ul class="mt-1 list-inline small mb-0">
-        <li class="list-inline-item">{i18n.t("admins")}:</li>
-        {this.state.siteRes.admins.map(av => (
-          <li class="list-inline-item">
-            <PersonListing person={av.person} />
-          </li>
-        ))}
-      </ul>
-    );
+    await this.fetchData();
   }
 
-  badges() {
-    let counts = this.state.siteRes.site_view.counts;
-    return (
-      <ul class="my-2 list-inline">
-        <li className="list-inline-item badge badge-secondary">
-          {i18n.t("number_online", { count: this.state.siteRes.online })}
-        </li>
-        <li
-          className="list-inline-item badge badge-secondary pointer"
-          data-tippy-content={`${i18n.t("number_of_users", {
-            count: counts.users_active_day,
-          })} ${i18n.t("active_in_the_last")} ${i18n.t("day")}`}
-        >
-          {i18n.t("number_of_users", {
-            count: counts.users_active_day,
-          })}{" "}
-          / {i18n.t("day")}
-        </li>
-        <li
-          className="list-inline-item badge badge-secondary pointer"
-          data-tippy-content={`${i18n.t("number_of_users", {
-            count: counts.users_active_week,
-          })} ${i18n.t("active_in_the_last")} ${i18n.t("week")}`}
-        >
-          {i18n.t("number_of_users", {
-            count: counts.users_active_week,
-          })}{" "}
-          / {i18n.t("week")}
-        </li>
-        <li
-          className="list-inline-item badge badge-secondary pointer"
-          data-tippy-content={`${i18n.t("number_of_users", {
-            count: counts.users_active_month,
-          })} ${i18n.t("active_in_the_last")} ${i18n.t("month")}`}
-        >
-          {i18n.t("number_of_users", {
-            count: counts.users_active_month,
-          })}{" "}
-          / {i18n.t("month")}
-        </li>
-        <li
-          className="list-inline-item badge badge-secondary pointer"
-          data-tippy-content={`${i18n.t("number_of_users", {
-            count: counts.users_active_half_year,
-          })} ${i18n.t("active_in_the_last")} ${i18n.t("number_of_months", {
-            count: 6,
-          })}`}
-        >
-          {i18n.t("number_of_users", {
-            count: counts.users_active_half_year,
-          })}{" "}
-          / {i18n.t("number_of_months", { count: 6 })}
-        </li>
-        <li className="list-inline-item badge badge-secondary">
-          {i18n.t("number_of_users", {
-            count: counts.users,
-          })}
-        </li>
-        <li className="list-inline-item badge badge-secondary">
-          {i18n.t("number_of_communities", {
-            count: counts.communities,
-          })}
-        </li>
-        <li className="list-inline-item badge badge-secondary">
-          {i18n.t("number_of_posts", {
-            count: counts.posts,
-          })}
-        </li>
-        <li className="list-inline-item badge badge-secondary">
-          {i18n.t("number_of_comments", {
-            count: counts.comments,
-          })}
-        </li>
-        <li className="list-inline-item">
-          <Link className="badge badge-secondary" to="/modlog">
-            {i18n.t("modlog")}
-          </Link>
-        </li>
-      </ul>
-    );
-  }
+  posts() {
+    const { page } = getHomeQueryParams();
 
-  adminButtons() {
     return (
-      this.canAdmin && (
-        <ul class="list-inline mb-1 text-muted font-weight-bold">
-          <li className="list-inline-item-action">
-            <button
-              class="btn btn-link d-inline-block text-muted"
-              onClick={linkEvent(this, this.handleEditClick)}
-              aria-label={i18n.t("edit")}
-              data-tippy-content={i18n.t("edit")}
-            >
-              <Icon icon="edit" classes="icon-inline" />
-            </button>
-          </li>
-        </ul>
-      )
+      <div className="main-content-wrapper">
+        <div>
+          {this.selects}
+          {this.listings}
+          <Paginator page={page} onChange={this.handlePageChange} />
+        </div>
+      </div>
     );
   }
 
-  siteSidebar() {
-    return (
-      <div
-        className="md-div"
-        dangerouslySetInnerHTML={mdToHtml(
-          this.state.siteRes.site_view.site.sidebar
-        )}
-      />
-    );
-  }
+  get listings() {
+    const { dataType } = getHomeQueryParams();
+    const siteRes = this.state.siteRes;
 
-  posts() {
-    return (
-      <div class="main-content-wrapper">
-        {this.state.loading ? (
-          <h5>
-            <Spinner large />
-          </h5>
-        ) : (
-          <div>
-            {this.selects()}
-            {this.listings()}
-            <Paginator
-              page={this.state.page}
-              onChange={this.handlePageChange}
+    if (dataType === DataType.Post) {
+      switch (this.state.postsRes?.state) {
+        case "loading":
+          return (
+            <h5>
+              <Spinner large />
+            </h5>
+          );
+        case "success": {
+          const posts = this.state.postsRes.data.posts;
+          return (
+            <PostListings
+              posts={posts}
+              showCommunity
+              removeDuplicates
+              enableDownvotes={enableDownvotes(siteRes)}
+              enableNsfw={enableNsfw(siteRes)}
+              allLanguages={siteRes.all_languages}
+              siteLanguages={siteRes.discussion_languages}
+              onBlockPerson={this.handleBlockPerson}
+              onPostEdit={this.handlePostEdit}
+              onPostVote={this.handlePostVote}
+              onPostReport={this.handlePostReport}
+              onLockPost={this.handleLockPost}
+              onDeletePost={this.handleDeletePost}
+              onRemovePost={this.handleRemovePost}
+              onSavePost={this.handleSavePost}
+              onPurgePerson={this.handlePurgePerson}
+              onPurgePost={this.handlePurgePost}
+              onBanPerson={this.handleBanPerson}
+              onBanPersonFromCommunity={this.handleBanFromCommunity}
+              onAddModToCommunity={this.handleAddModToCommunity}
+              onAddAdmin={this.handleAddAdmin}
+              onTransferCommunity={this.handleTransferCommunity}
+              onFeaturePost={this.handleFeaturePost}
             />
-          </div>
-        )}
-      </div>
-    );
+          );
+        }
+      }
+    } else {
+      switch (this.state.commentsRes.state) {
+        case "loading":
+          return (
+            <h5>
+              <Spinner large />
+            </h5>
+          );
+        case "success": {
+          const comments = this.state.commentsRes.data.comments;
+          return (
+            <CommentNodes
+              nodes={commentsToFlatNodes(comments)}
+              viewType={CommentViewType.Flat}
+              finished={this.state.finished}
+              noIndent
+              showCommunity
+              showContext
+              enableDownvotes={enableDownvotes(siteRes)}
+              allLanguages={siteRes.all_languages}
+              siteLanguages={siteRes.discussion_languages}
+              onSaveComment={this.handleSaveComment}
+              onBlockPerson={this.handleBlockPerson}
+              onDeleteComment={this.handleDeleteComment}
+              onRemoveComment={this.handleRemoveComment}
+              onCommentVote={this.handleCommentVote}
+              onCommentReport={this.handleCommentReport}
+              onDistinguishComment={this.handleDistinguishComment}
+              onAddModToCommunity={this.handleAddModToCommunity}
+              onAddAdmin={this.handleAddAdmin}
+              onTransferCommunity={this.handleTransferCommunity}
+              onPurgeComment={this.handlePurgeComment}
+              onPurgePerson={this.handlePurgePerson}
+              onCommentReplyRead={this.handleCommentReplyRead}
+              onPersonMentionRead={this.handlePersonMentionRead}
+              onBanPersonFromCommunity={this.handleBanFromCommunity}
+              onBanPerson={this.handleBanPerson}
+              onCreateComment={this.handleCreateComment}
+              onEditComment={this.handleEditComment}
+            />
+          );
+        }
+      }
+    }
   }
 
-  listings() {
-    let site = this.state.siteRes.site_view.site;
-    return this.state.dataType == DataType.Post ? (
-      <PostListings
-        posts={this.state.posts}
-        showCommunity
-        removeDuplicates
-        enableDownvotes={site.enable_downvotes}
-        enableNsfw={site.enable_nsfw}
-      />
-    ) : (
-      <CommentNodes
-        nodes={commentsToFlatNodes(this.state.comments)}
-        noIndent
-        showCommunity
-        showContext
-        enableDownvotes={site.enable_downvotes}
-      />
-    );
-  }
+  get selects() {
+    const { listingType, dataType, sort } = getHomeQueryParams();
 
-  selects() {
     return (
       <div className="mb-3">
-        <span class="mr-3">
+        <span className="mr-3">
           <DataTypeSelect
-            type_={this.state.dataType}
+            type_={dataType}
             onChange={this.handleDataTypeChange}
           />
         </span>
-        <span class="mr-3">
+        <span className="mr-3">
           <ListingTypeSelect
-            type_={this.state.listingType}
+            type_={listingType}
             showLocal={showLocal(this.isoData)}
+            showSubscribed
             onChange={this.handleListingTypeChange}
           />
         </span>
-        <span class="mr-2">
-          <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
+        <span className="mr-2">
+          <SortSelect sort={sort} onChange={this.handleSortChange} />
         </span>
-        {this.state.listingType == ListingType.All && (
-          <a
-            href={`/feeds/all.xml?sort=${this.state.sort}`}
-            rel="noopener"
-            title="RSS"
-          >
-            <Icon icon="rss" classes="text-muted small" />
-          </a>
-        )}
-        {this.state.listingType == ListingType.Local && (
-          <a
-            href={`/feeds/local.xml?sort=${this.state.sort}`}
-            rel="noopener"
-            title="RSS"
-          >
-            <Icon icon="rss" classes="text-muted small" />
-          </a>
-        )}
-        {UserService.Instance.localUserView &&
-          this.state.listingType == ListingType.Subscribed && (
-            <a
-              href={`/feeds/front/${UserService.Instance.auth}.xml?sort=${this.state.sort}`}
-              title="RSS"
-              rel="noopener"
-            >
-              <Icon icon="rss" classes="text-muted small" />
-            </a>
-          )}
+        {this.getRss(listingType)}
       </div>
     );
   }
 
-  get canAdmin(): boolean {
+  getRss(listingType: ListingType) {
+    const { sort } = getHomeQueryParams();
+    const auth = myAuth();
+
+    let rss: string | undefined = undefined;
+
+    switch (listingType) {
+      case "All": {
+        rss = `/feeds/all.xml?sort=${sort}`;
+        break;
+      }
+      case "Local": {
+        rss = `/feeds/local.xml?sort=${sort}`;
+        break;
+      }
+      case "Subscribed": {
+        rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
+        break;
+      }
+    }
+
     return (
-      UserService.Instance.localUserView &&
-      this.state.siteRes.admins
-        .map(a => a.person.id)
-        .includes(UserService.Instance.localUserView.person.id)
+      rss && (
+        <>
+          <a href={rss} rel={relTags} title="RSS">
+            <Icon icon="rss" classes="text-muted small" />
+          </a>
+          <link rel="alternate" type="application/atom+xml" href={rss} />
+        </>
+      )
     );
   }
 
-  handleEditClick(i: Home) {
-    i.state.showEditSite = true;
-    i.setState(i.state);
+  async fetchTrendingCommunities() {
+    this.setState({ trendingCommunitiesRes: { state: "loading" } });
+    this.setState({
+      trendingCommunitiesRes: await HttpService.client.listCommunities({
+        type_: "Local",
+        sort: "Hot",
+        limit: trendingFetchLimit,
+        auth: myAuth(),
+      }),
+    });
   }
 
-  handleEditCancel() {
-    this.state.showEditSite = false;
-    this.setState(this.state);
+  async fetchData() {
+    const auth = myAuth();
+    const { dataType, page, listingType, sort } = getHomeQueryParams();
+
+    if (dataType === DataType.Post) {
+      this.setState({ postsRes: { state: "loading" } });
+      this.setState({
+        postsRes: await HttpService.client.getPosts({
+          page,
+          limit: fetchLimit,
+          sort,
+          saved_only: false,
+          type_: listingType,
+          auth,
+        }),
+      });
+    } else {
+      this.setState({ commentsRes: { state: "loading" } });
+      this.setState({
+        commentsRes: await HttpService.client.getComments({
+          page,
+          limit: fetchLimit,
+          sort: postToCommentSortType(sort),
+          saved_only: false,
+          type_: listingType,
+          auth,
+        }),
+      });
+    }
+
+    restoreScrollPosition(this.context);
+    setupTippy();
   }
 
   handleShowSubscribedMobile(i: Home) {
-    i.state.showSubscribedMobile = !i.state.showSubscribedMobile;
-    i.setState(i.state);
+    i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
   }
 
   handleShowTrendingMobile(i: Home) {
-    i.state.showTrendingMobile = !i.state.showTrendingMobile;
-    i.setState(i.state);
+    i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
   }
 
   handleShowSidebarMobile(i: Home) {
-    i.state.showSidebarMobile = !i.state.showSidebarMobile;
-    i.setState(i.state);
+    i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
+  }
+
+  handleCollapseSubscribe(i: Home) {
+    i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
   }
 
   handlePageChange(page: number) {
@@ -768,180 +792,256 @@ export class Home extends Component<any, HomeState> {
   }
 
   handleDataTypeChange(val: DataType) {
-    this.updateUrl({ dataType: DataType[val], page: 1 });
+    this.updateUrl({ dataType: val, page: 1 });
     window.scrollTo(0, 0);
   }
 
-  fetchData() {
-    if (this.state.dataType == DataType.Post) {
-      let getPostsForm: GetPosts = {
-        page: this.state.page,
-        limit: fetchLimit,
-        sort: this.state.sort,
-        type_: this.state.listingType,
-        saved_only: false,
-        auth: authField(false),
-      };
-      WebSocketService.Instance.send(wsClient.getPosts(getPostsForm));
-    } else {
-      let getCommentsForm: GetComments = {
-        page: this.state.page,
-        limit: fetchLimit,
-        sort: this.state.sort,
-        type_: this.state.listingType,
-        saved_only: false,
-        auth: authField(false),
-      };
-      WebSocketService.Instance.send(wsClient.getComments(getCommentsForm));
+  async handleAddModToCommunity(form: AddModToCommunity) {
+    // TODO not sure what to do here
+    await HttpService.client.addModToCommunity(form);
+  }
+
+  async handlePurgePerson(form: PurgePerson) {
+    const purgePersonRes = await HttpService.client.purgePerson(form);
+    this.purgeItem(purgePersonRes);
+  }
+
+  async handlePurgeComment(form: PurgeComment) {
+    const purgeCommentRes = await HttpService.client.purgeComment(form);
+    this.purgeItem(purgeCommentRes);
+  }
+
+  async handlePurgePost(form: PurgePost) {
+    const purgeRes = await HttpService.client.purgePost(form);
+    this.purgeItem(purgeRes);
+  }
+
+  async handleBlockPerson(form: BlockPerson) {
+    const blockPersonRes = await HttpService.client.blockPerson(form);
+    if (blockPersonRes.state == "success") {
+      updatePersonBlock(blockPersonRes.data);
+    }
+  }
+
+  async handleCreateComment(form: CreateComment) {
+    const createCommentRes = await HttpService.client.createComment(form);
+    this.createAndUpdateComments(createCommentRes);
+
+    return createCommentRes;
+  }
+
+  async handleEditComment(form: EditComment) {
+    const editCommentRes = await HttpService.client.editComment(form);
+    this.findAndUpdateComment(editCommentRes);
+
+    return editCommentRes;
+  }
+
+  async handleDeleteComment(form: DeleteComment) {
+    const deleteCommentRes = await HttpService.client.deleteComment(form);
+    this.findAndUpdateComment(deleteCommentRes);
+  }
+
+  async handleDeletePost(form: DeletePost) {
+    const deleteRes = await HttpService.client.deletePost(form);
+    this.findAndUpdatePost(deleteRes);
+  }
+
+  async handleRemovePost(form: RemovePost) {
+    const removeRes = await HttpService.client.removePost(form);
+    this.findAndUpdatePost(removeRes);
+  }
+
+  async handleRemoveComment(form: RemoveComment) {
+    const removeCommentRes = await HttpService.client.removeComment(form);
+    this.findAndUpdateComment(removeCommentRes);
+  }
+
+  async handleSaveComment(form: SaveComment) {
+    const saveCommentRes = await HttpService.client.saveComment(form);
+    this.findAndUpdateComment(saveCommentRes);
+  }
+
+  async handleSavePost(form: SavePost) {
+    const saveRes = await HttpService.client.savePost(form);
+    this.findAndUpdatePost(saveRes);
+  }
+
+  async handleFeaturePost(form: FeaturePost) {
+    const featureRes = await HttpService.client.featurePost(form);
+    this.findAndUpdatePost(featureRes);
+  }
+
+  async handleCommentVote(form: CreateCommentLike) {
+    const voteRes = await HttpService.client.likeComment(form);
+    this.findAndUpdateComment(voteRes);
+  }
+
+  async handlePostEdit(form: EditPost) {
+    const res = await HttpService.client.editPost(form);
+    this.findAndUpdatePost(res);
+  }
+
+  async handlePostVote(form: CreatePostLike) {
+    const voteRes = await HttpService.client.likePost(form);
+    this.findAndUpdatePost(voteRes);
+  }
+
+  async handleCommentReport(form: CreateCommentReport) {
+    const reportRes = await HttpService.client.createCommentReport(form);
+    if (reportRes.state == "success") {
+      toast(i18n.t("report_created"));
+    }
+  }
+
+  async handlePostReport(form: CreatePostReport) {
+    const reportRes = await HttpService.client.createPostReport(form);
+    if (reportRes.state == "success") {
+      toast(i18n.t("report_created"));
+    }
+  }
+
+  async handleLockPost(form: LockPost) {
+    const lockRes = await HttpService.client.lockPost(form);
+    this.findAndUpdatePost(lockRes);
+  }
+
+  async handleDistinguishComment(form: DistinguishComment) {
+    const distinguishRes = await HttpService.client.distinguishComment(form);
+    this.findAndUpdateComment(distinguishRes);
+  }
+
+  async handleAddAdmin(form: AddAdmin) {
+    const addAdminRes = await HttpService.client.addAdmin(form);
+
+    if (addAdminRes.state == "success") {
+      this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
     }
   }
 
-  parseMessage(msg: any) {
-    let op = wsUserOp(msg);
-    console.log(msg);
-    if (msg.error) {
-      toast(i18n.t(msg.error), "danger");
-      return;
-    } else if (msg.reconnect) {
-      WebSocketService.Instance.send(
-        wsClient.communityJoin({ community_id: 0 })
-      );
-      this.fetchData();
-    } else if (op == UserOperation.GetFollowedCommunities) {
-      let data = wsJsonToRes<GetFollowedCommunitiesResponse>(msg).data;
-      this.state.subscribedCommunities = data.communities;
-      this.setState(this.state);
-    } else if (op == UserOperation.ListCommunities) {
-      let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
-      this.state.trendingCommunities = data.communities;
-      this.setState(this.state);
-    } else if (op == UserOperation.EditSite) {
-      let data = wsJsonToRes<SiteResponse>(msg).data;
-      this.state.siteRes.site_view = data.site_view;
-      this.state.showEditSite = false;
-      this.setState(this.state);
-      toast(i18n.t("site_saved"));
-    } else if (op == UserOperation.GetPosts) {
-      let data = wsJsonToRes<GetPostsResponse>(msg).data;
-      this.state.posts = data.posts;
-      this.state.loading = false;
-      this.setState(this.state);
-      restoreScrollPosition(this.context);
-      setupTippy();
-    } else if (op == UserOperation.CreatePost) {
-      let data = wsJsonToRes<PostResponse>(msg).data;
-
-      // NSFW check
-      let nsfw = data.post_view.post.nsfw || data.post_view.community.nsfw;
-      let nsfwCheck =
-        !nsfw ||
-        (nsfw &&
-          UserService.Instance.localUserView &&
-          UserService.Instance.localUserView.local_user.show_nsfw);
-
-      // Only push these if you're on the first page, and you pass the nsfw check
-      if (this.state.page == 1 && nsfwCheck) {
-        // If you're on subscribed, only push it if you're subscribed.
-        if (this.state.listingType == ListingType.Subscribed) {
-          if (
-            this.state.subscribedCommunities
-              .map(c => c.community.id)
-              .includes(data.post_view.community.id)
-          ) {
-            this.state.posts.unshift(data.post_view);
-            notifyPost(data.post_view, this.context.router);
-          }
-        } else if (this.state.listingType == ListingType.Local) {
-          // If you're on the local view, only push it if its local
-          if (data.post_view.post.local) {
-            this.state.posts.unshift(data.post_view);
-            notifyPost(data.post_view, this.context.router);
-          }
-        } else {
-          this.state.posts.unshift(data.post_view);
-          notifyPost(data.post_view, this.context.router);
+  async handleTransferCommunity(form: TransferCommunity) {
+    await HttpService.client.transferCommunity(form);
+    toast(i18n.t("transfer_community"));
+  }
+
+  async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
+    const readRes = await HttpService.client.markCommentReplyAsRead(form);
+    this.findAndUpdateCommentReply(readRes);
+  }
+
+  async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
+    // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
+    await HttpService.client.markPersonMentionAsRead(form);
+  }
+
+  async handleBanFromCommunity(form: BanFromCommunity) {
+    const banRes = await HttpService.client.banFromCommunity(form);
+    this.updateBanFromCommunity(banRes);
+  }
+
+  async handleBanPerson(form: BanPerson) {
+    const banRes = await HttpService.client.banPerson(form);
+    this.updateBan(banRes);
+  }
+
+  updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
+    // Maybe not necessary
+    if (banRes.state == "success") {
+      this.setState(s => {
+        if (s.postsRes.state == "success") {
+          s.postsRes.data.posts
+            .filter(c => c.creator.id == banRes.data.person_view.person.id)
+            .forEach(
+              c => (c.creator_banned_from_community = banRes.data.banned)
+            );
+        }
+        if (s.commentsRes.state == "success") {
+          s.commentsRes.data.comments
+            .filter(c => c.creator.id == banRes.data.person_view.person.id)
+            .forEach(
+              c => (c.creator_banned_from_community = banRes.data.banned)
+            );
+        }
+        return s;
+      });
+    }
+  }
+
+  updateBan(banRes: RequestState<BanPersonResponse>) {
+    // Maybe not necessary
+    if (banRes.state == "success") {
+      this.setState(s => {
+        if (s.postsRes.state == "success") {
+          s.postsRes.data.posts
+            .filter(c => c.creator.id == banRes.data.person_view.person.id)
+            .forEach(c => (c.creator.banned = banRes.data.banned));
         }
-        this.setState(this.state);
+        if (s.commentsRes.state == "success") {
+          s.commentsRes.data.comments
+            .filter(c => c.creator.id == banRes.data.person_view.person.id)
+            .forEach(c => (c.creator.banned = banRes.data.banned));
+        }
+        return s;
+      });
+    }
+  }
+
+  purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
+    if (purgeRes.state == "success") {
+      toast(i18n.t("purge_success"));
+      this.context.router.history.push(`/`);
+    }
+  }
+
+  findAndUpdateComment(res: RequestState<CommentResponse>) {
+    this.setState(s => {
+      if (s.commentsRes.state == "success" && res.state == "success") {
+        s.commentsRes.data.comments = editComment(
+          res.data.comment_view,
+          s.commentsRes.data.comments
+        );
+        s.finished.set(res.data.comment_view.comment.id, true);
       }
-    } else if (
-      op == UserOperation.EditPost ||
-      op == UserOperation.DeletePost ||
-      op == UserOperation.RemovePost ||
-      op == UserOperation.LockPost ||
-      op == UserOperation.StickyPost ||
-      op == UserOperation.SavePost
-    ) {
-      let data = wsJsonToRes<PostResponse>(msg).data;
-      editPostFindRes(data.post_view, this.state.posts);
-      this.setState(this.state);
-    } else if (op == UserOperation.CreatePostLike) {
-      let data = wsJsonToRes<PostResponse>(msg).data;
-      createPostLikeFindRes(data.post_view, this.state.posts);
-      this.setState(this.state);
-    } else if (op == UserOperation.AddAdmin) {
-      let data = wsJsonToRes<AddAdminResponse>(msg).data;
-      this.state.siteRes.admins = data.admins;
-      this.setState(this.state);
-    } else if (op == UserOperation.BanPerson) {
-      let data = wsJsonToRes<BanPersonResponse>(msg).data;
-      let found = this.state.siteRes.banned.find(
-        p => (p.person.id = data.person_view.person.id)
-      );
-
-      // Remove the banned if its found in the list, and the action is an unban
-      if (found && !data.banned) {
-        this.state.siteRes.banned = this.state.siteRes.banned.filter(
-          i => i.person.id !== data.person_view.person.id
+      return s;
+    });
+  }
+
+  createAndUpdateComments(res: RequestState<CommentResponse>) {
+    this.setState(s => {
+      if (s.commentsRes.state == "success" && res.state == "success") {
+        s.commentsRes.data.comments.unshift(res.data.comment_view);
+
+        // Set finished for the parent
+        s.finished.set(
+          getCommentParentId(res.data.comment_view.comment) ?? 0,
+          true
         );
-      } else {
-        this.state.siteRes.banned.push(data.person_view);
       }
+      return s;
+    });
+  }
 
-      this.state.posts
-        .filter(p => p.creator.id == data.person_view.person.id)
-        .forEach(p => (p.creator.banned = data.banned));
-
-      this.setState(this.state);
-    } else if (op == UserOperation.GetComments) {
-      let data = wsJsonToRes<GetCommentsResponse>(msg).data;
-      this.state.comments = data.comments;
-      this.state.loading = false;
-      this.setState(this.state);
-    } else if (
-      op == UserOperation.EditComment ||
-      op == UserOperation.DeleteComment ||
-      op == UserOperation.RemoveComment
-    ) {
-      let data = wsJsonToRes<CommentResponse>(msg).data;
-      editCommentRes(data.comment_view, this.state.comments);
-      this.setState(this.state);
-    } else if (op == UserOperation.CreateComment) {
-      let data = wsJsonToRes<CommentResponse>(msg).data;
-
-      // Necessary since it might be a user reply
-      if (data.form_id) {
-        // If you're on subscribed, only push it if you're subscribed.
-        if (this.state.listingType == ListingType.Subscribed) {
-          if (
-            this.state.subscribedCommunities
-              .map(c => c.community.id)
-              .includes(data.comment_view.community.id)
-          ) {
-            this.state.comments.unshift(data.comment_view);
-          }
-        } else {
-          this.state.comments.unshift(data.comment_view);
-        }
-        this.setState(this.state);
+  findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
+    this.setState(s => {
+      if (s.commentsRes.state == "success" && res.state == "success") {
+        s.commentsRes.data.comments = editWith(
+          res.data.comment_reply_view,
+          s.commentsRes.data.comments
+        );
       }
-    } else if (op == UserOperation.SaveComment) {
-      let data = wsJsonToRes<CommentResponse>(msg).data;
-      saveCommentRes(data.comment_view, this.state.comments);
-      this.setState(this.state);
-    } else if (op == UserOperation.CreateCommentLike) {
-      let data = wsJsonToRes<CommentResponse>(msg).data;
-      createCommentLikeRes(data.comment_view, this.state.comments);
-      this.setState(this.state);
-    }
+      return s;
+    });
+  }
+
+  findAndUpdatePost(res: RequestState<PostResponse>) {
+    this.setState(s => {
+      if (s.postsRes.state == "success" && res.state == "success") {
+        s.postsRes.data.posts = editPost(
+          res.data.post_view,
+          s.postsRes.data.posts
+        );
+      }
+      return s;
+    });
   }
 }