]> Untitled Git - lemmy-ui.git/blobdiff - src/shared/components/community/communities.tsx
component classes v2
[lemmy-ui.git] / src / shared / components / community / communities.tsx
index a9d4a6c1e84bde3081387d9941263122289decf9..0126ab11101dfab58c6605057a12c7e9145541d7 100644 (file)
@@ -1,32 +1,27 @@
-import { None, Option, Some } from "@sniptt/monads";
 import { Component, linkEvent } from "inferno";
 import {
   CommunityResponse,
-  FollowCommunity,
   GetSiteResponse,
   ListCommunities,
   ListCommunitiesResponse,
   ListingType,
-  SortType,
-  UserOperation,
-  wsJsonToRes,
-  wsUserOp,
 } from "lemmy-js-client";
-import { Subscription } from "rxjs";
-import { InitialFetchRequest } from "shared/interfaces";
 import { i18n } from "../../i18next";
-import { WebSocketService } from "../../services";
+import { InitialFetchRequest } from "../../interfaces";
+import { FirstLoadService } from "../../services/FirstLoadService";
+import { HttpService, RequestState } from "../../services/HttpService";
 import {
-  auth,
-  getListingTypeFromPropsNoDefault,
-  getPageFromProps,
-  isBrowser,
+  QueryParams,
+  RouteDataResponse,
+  editCommunity,
+  getPageFromString,
+  getQueryParams,
+  getQueryString,
+  myAuth,
+  myAuthRequired,
   numToSI,
   setIsoData,
   showLocal,
-  toast,
-  wsClient,
-  wsSubscribe,
 } from "../../utils";
 import { HtmlTags } from "../common/html-tags";
 import { Spinner } from "../common/icon";
@@ -34,188 +29,191 @@ import { ListingTypeSelect } from "../common/listing-type-select";
 import { Paginator } from "../common/paginator";
 import { CommunityLink } from "./community-link";
 
-const communityLimit = 100;
+const communityLimit = 50;
+
+type CommunitiesData = RouteDataResponse<{
+  listCommunitiesResponse: ListCommunitiesResponse;
+}>;
 
 interface CommunitiesState {
-  listCommunitiesResponse: Option<ListCommunitiesResponse>;
-  page: number;
-  loading: boolean;
+  listCommunitiesResponse: RequestState<ListCommunitiesResponse>;
   siteRes: GetSiteResponse;
   searchText: string;
-  listingType: ListingType;
+  isIsomorphic: boolean;
 }
 
 interface CommunitiesProps {
-  listingType?: ListingType;
-  page?: number;
+  listingType: ListingType;
+  page: number;
+}
+
+function getListingTypeFromQuery(listingType?: string): ListingType {
+  return listingType ? (listingType as ListingType) : "Local";
 }
 
 export class Communities extends Component<any, CommunitiesState> {
-  private subscription: Subscription;
-  private isoData = setIsoData(this.context, ListCommunitiesResponse);
-  private emptyState: CommunitiesState = {
-    listCommunitiesResponse: None,
-    loading: true,
-    page: getPageFromProps(this.props),
-    listingType: getListingTypeFromPropsNoDefault(this.props),
+  private isoData = setIsoData<CommunitiesData>(this.context);
+  state: CommunitiesState = {
+    listCommunitiesResponse: { state: "empty" },
     siteRes: this.isoData.site_res,
     searchText: "",
+    isIsomorphic: false,
   };
 
   constructor(props: any, context: any) {
     super(props, context);
-    this.state = this.emptyState;
     this.handlePageChange = this.handlePageChange.bind(this);
     this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
 
-    this.parseMessage = this.parseMessage.bind(this);
-    this.subscription = wsSubscribe(this.parseMessage);
-
     // Only fetch the data if coming from another route
-    if (this.isoData.path == this.context.router.route.match.url) {
-      let listRes = Some(this.isoData.routeData[0] as ListCommunitiesResponse);
-      this.state.listCommunitiesResponse = listRes;
-      this.state.loading = false;
-    } else {
-      this.refetch();
-    }
-  }
+    if (FirstLoadService.isFirstLoad) {
+      const { listCommunitiesResponse } = this.isoData.routeData;
 
-  componentWillUnmount() {
-    if (isBrowser()) {
-      this.subscription.unsubscribe();
+      this.state = {
+        ...this.state,
+        listCommunitiesResponse,
+        isIsomorphic: true,
+      };
     }
   }
 
-  static getDerivedStateFromProps(props: any): CommunitiesProps {
-    return {
-      listingType: getListingTypeFromPropsNoDefault(props),
-      page: getPageFromProps(props),
-    };
-  }
-
-  componentDidUpdate(_: any, lastState: CommunitiesState) {
-    if (
-      lastState.page !== this.state.page ||
-      lastState.listingType !== this.state.listingType
-    ) {
-      this.setState({ loading: true });
-      this.refetch();
+  async componentDidMount() {
+    if (!this.state.isIsomorphic) {
+      await this.refetch();
     }
   }
 
   get documentTitle(): string {
-    return this.state.siteRes.site_view.match({
-      some: siteView => `${i18n.t("communities")} - ${siteView.site.name}`,
-      none: "",
-    });
+    return `${i18n.t("communities")} - ${
+      this.state.siteRes.site_view.site.name
+    }`;
   }
 
-  render() {
-    return (
-      <div class="container">
-        <HtmlTags
-          title={this.documentTitle}
-          path={this.context.router.route.match.url}
-          description={None}
-          image={None}
-        />
-        {this.state.loading ? (
+  renderListings() {
+    switch (this.state.listCommunitiesResponse.state) {
+      case "loading":
+        return (
           <h5>
             <Spinner large />
           </h5>
-        ) : (
+        );
+      case "success": {
+        const { listingType, page } = this.getCommunitiesQueryParams();
+        return (
           <div>
-            <div class="row">
-              <div class="col-md-6">
+            <div className="row">
+              <div className="col-md-6">
                 <h4>{i18n.t("list_of_communities")}</h4>
-                <span class="mb-2">
+                <span className="mb-2">
                   <ListingTypeSelect
-                    type_={this.state.listingType}
+                    type_={listingType}
                     showLocal={showLocal(this.isoData)}
                     showSubscribed
                     onChange={this.handleListingTypeChange}
                   />
                 </span>
               </div>
-              <div class="col-md-6">
-                <div class="float-md-right">{this.searchForm()}</div>
-              </div>
+              <div className="col-md-6">{this.searchForm()}</div>
             </div>
 
-            <div class="table-responsive">
-              <table id="community_table" class="table table-sm table-hover">
-                <thead class="pointer">
+            <div className="table-responsive">
+              <table
+                id="community_table"
+                className="table table-sm table-hover"
+              >
+                <thead className="pointer">
                   <tr>
                     <th>{i18n.t("name")}</th>
-                    <th class="text-right">{i18n.t("subscribers")}</th>
-                    <th class="text-right">
+                    <th className="text-right">{i18n.t("subscribers")}</th>
+                    <th className="text-right">
                       {i18n.t("users")} / {i18n.t("month")}
                     </th>
-                    <th class="text-right d-none d-lg-table-cell">
+                    <th className="text-right d-none d-lg-table-cell">
                       {i18n.t("posts")}
                     </th>
-                    <th class="text-right d-none d-lg-table-cell">
+                    <th className="text-right d-none d-lg-table-cell">
                       {i18n.t("comments")}
                     </th>
                     <th></th>
                   </tr>
                 </thead>
                 <tbody>
-                  {this.state.listCommunitiesResponse
-                    .map(l => l.communities)
-                    .unwrapOr([])
-                    .map(cv => (
-                      <tr>
+                  {this.state.listCommunitiesResponse.data.communities.map(
+                    cv => (
+                      <tr key={cv.community.id}>
                         <td>
                           <CommunityLink community={cv.community} />
                         </td>
-                        <td class="text-right">
+                        <td className="text-right">
                           {numToSI(cv.counts.subscribers)}
                         </td>
-                        <td class="text-right">
+                        <td className="text-right">
                           {numToSI(cv.counts.users_active_month)}
                         </td>
-                        <td class="text-right d-none d-lg-table-cell">
+                        <td className="text-right d-none d-lg-table-cell">
                           {numToSI(cv.counts.posts)}
                         </td>
-                        <td class="text-right d-none d-lg-table-cell">
+                        <td className="text-right d-none d-lg-table-cell">
                           {numToSI(cv.counts.comments)}
                         </td>
-                        <td class="text-right">
-                          {cv.subscribed ? (
+                        <td className="text-right">
+                          {cv.subscribed == "Subscribed" && (
                             <button
-                              class="btn btn-link d-inline-block"
+                              className="btn btn-link d-inline-block"
                               onClick={linkEvent(
-                                cv.community.id,
-                                this.handleUnsubscribe
+                                {
+                                  i: this,
+                                  communityId: cv.community.id,
+                                  follow: false,
+                                },
+                                this.handleFollow
                               )}
                             >
                               {i18n.t("unsubscribe")}
                             </button>
-                          ) : (
+                          )}
+                          {cv.subscribed === "NotSubscribed" && (
                             <button
-                              class="btn btn-link d-inline-block"
+                              className="btn btn-link d-inline-block"
                               onClick={linkEvent(
-                                cv.community.id,
-                                this.handleSubscribe
+                                {
+                                  i: this,
+                                  communityId: cv.community.id,
+                                  follow: true,
+                                },
+                                this.handleFollow
                               )}
                             >
                               {i18n.t("subscribe")}
                             </button>
                           )}
+                          {cv.subscribed === "Pending" && (
+                            <div className="text-warning d-inline-block">
+                              {i18n.t("subscribe_pending")}
+                            </div>
+                          )}
                         </td>
                       </tr>
-                    ))}
+                    )
+                  )}
                 </tbody>
               </table>
             </div>
-            <Paginator
-              page={this.state.page}
-              onChange={this.handlePageChange}
-            />
+            <Paginator page={page} onChange={this.handlePageChange} />
           </div>
-        )}
+        );
+      }
+    }
+  }
+
+  render() {
+    return (
+      <div className="communities container-lg">
+        <HtmlTags
+          title={this.documentTitle}
+          path={this.context.router.route.match.url}
+        />
+        {this.renderListings()}
       </div>
     );
   }
@@ -223,35 +221,45 @@ export class Communities extends Component<any, CommunitiesState> {
   searchForm() {
     return (
       <form
-        class="form-inline"
+        className="row justify-content-end"
         onSubmit={linkEvent(this, this.handleSearchSubmit)}
       >
-        <input
-          type="text"
-          id="communities-search"
-          class="form-control mr-2 mb-2"
-          value={this.state.searchText}
-          placeholder={`${i18n.t("search")}...`}
-          onInput={linkEvent(this, this.handleSearchChange)}
-          required
-          minLength={3}
-        />
-        <label class="sr-only" htmlFor="communities-search">
-          {i18n.t("search")}
-        </label>
-        <button type="submit" class="btn btn-secondary mr-2 mb-2">
-          <span>{i18n.t("search")}</span>
-        </button>
+        <div className="col-auto">
+          <input
+            type="text"
+            id="communities-search"
+            className="form-control me-2 mb-2"
+            value={this.state.searchText}
+            placeholder={`${i18n.t("search")}...`}
+            onInput={linkEvent(this, this.handleSearchChange)}
+            required
+            minLength={3}
+          />
+        </div>
+        <div className="col-auto">
+          <label className="visually-hidden" htmlFor="communities-search">
+            {i18n.t("search")}
+          </label>
+          <button type="submit" className="btn btn-secondary mb-2">
+            <span>{i18n.t("search")}</span>
+          </button>
+        </div>
       </form>
     );
   }
 
-  updateUrl(paramUpdates: CommunitiesProps) {
-    const page = paramUpdates.page || this.state.page;
-    const listingTypeStr = paramUpdates.listingType || this.state.listingType;
-    this.props.history.push(
-      `/communities/listing_type/${listingTypeStr}/page/${page}`
-    );
+  async updateUrl({ listingType, page }: Partial<CommunitiesProps>) {
+    const { listingType: urlListingType, page: urlPage } =
+      this.getCommunitiesQueryParams();
+
+    const queryParams: QueryParams<CommunitiesProps> = {
+      listingType: listingType ?? urlListingType,
+      page: (page ?? urlPage)?.toString(),
+    };
+
+    this.props.history.push(`/communities${getQueryString(queryParams)}`);
+
+    await this.refetch();
   }
 
   handlePageChange(page: number) {
@@ -265,94 +273,88 @@ export class Communities extends Component<any, CommunitiesState> {
     });
   }
 
-  handleUnsubscribe(communityId: number) {
-    let form = new FollowCommunity({
-      community_id: communityId,
-      follow: false,
-      auth: auth().unwrap(),
-    });
-    WebSocketService.Instance.send(wsClient.followCommunity(form));
-  }
-
-  handleSubscribe(communityId: number) {
-    let form = new FollowCommunity({
-      community_id: communityId,
-      follow: true,
-      auth: auth().unwrap(),
-    });
-    WebSocketService.Instance.send(wsClient.followCommunity(form));
-  }
-
   handleSearchChange(i: Communities, event: any) {
     i.setState({ searchText: event.target.value });
   }
 
-  handleSearchSubmit(i: Communities) {
+  handleSearchSubmit(i: Communities, event: any) {
+    event.preventDefault();
     const searchParamEncoded = encodeURIComponent(i.state.searchText);
-    i.context.router.history.push(
-      `/search/q/${searchParamEncoded}/type/Communities/sort/TopAll/listing_type/All/community_id/0/creator_id/0/page/1`
-    );
+    i.context.router.history.push(`/search?q=${searchParamEncoded}`);
+  }
+
+  static async fetchInitialData({
+    query: { listingType, page },
+    client,
+    auth,
+  }: InitialFetchRequest<
+    QueryParams<CommunitiesProps>
+  >): Promise<CommunitiesData> {
+    const listCommunitiesForm: ListCommunities = {
+      type_: getListingTypeFromQuery(listingType),
+      sort: "TopMonth",
+      limit: communityLimit,
+      page: getPageFromString(page),
+      auth: auth,
+    };
+
+    return {
+      listCommunitiesResponse: await client.listCommunities(
+        listCommunitiesForm
+      ),
+    };
   }
 
-  refetch() {
-    let listCommunitiesForm = new ListCommunities({
-      type_: Some(this.state.listingType),
-      sort: Some(SortType.TopMonth),
-      limit: Some(communityLimit),
-      page: Some(this.state.page),
-      auth: auth(false).ok(),
+  getCommunitiesQueryParams() {
+    return getQueryParams<CommunitiesProps>({
+      listingType: getListingTypeFromQuery,
+      page: getPageFromString,
     });
+  }
 
-    WebSocketService.Instance.send(
-      wsClient.listCommunities(listCommunitiesForm)
-    );
+  async handleFollow(data: {
+    i: Communities;
+    communityId: number;
+    follow: boolean;
+  }) {
+    const res = await HttpService.client.followCommunity({
+      community_id: data.communityId,
+      follow: data.follow,
+      auth: myAuthRequired(),
+    });
+    data.i.findAndUpdateCommunity(res);
   }
 
-  static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
-    let pathSplit = req.path.split("/");
-    let type_: Option<ListingType> = Some(
-      pathSplit[3] ? ListingType[pathSplit[3]] : ListingType.Local
-    );
-    let page = Some(pathSplit[5] ? Number(pathSplit[5]) : 1);
-    let listCommunitiesForm = new ListCommunities({
-      type_,
-      sort: Some(SortType.TopMonth),
-      limit: Some(communityLimit),
-      page,
-      auth: req.auth,
+  async refetch() {
+    this.setState({ listCommunitiesResponse: { state: "loading" } });
+
+    const { listingType, page } = this.getCommunitiesQueryParams();
+
+    this.setState({
+      listCommunitiesResponse: await HttpService.client.listCommunities({
+        type_: listingType,
+        sort: "TopMonth",
+        limit: communityLimit,
+        page,
+        auth: myAuth(),
+      }),
     });
 
-    return [req.client.listCommunities(listCommunitiesForm)];
+    window.scrollTo(0, 0);
   }
 
-  parseMessage(msg: any) {
-    let op = wsUserOp(msg);
-    console.log(msg);
-    if (msg.error) {
-      toast(i18n.t(msg.error), "danger");
-      return;
-    } else if (op == UserOperation.ListCommunities) {
-      let data = wsJsonToRes<ListCommunitiesResponse>(
-        msg,
-        ListCommunitiesResponse
-      );
-      this.state.listCommunitiesResponse = Some(data);
-      this.state.loading = false;
-      window.scrollTo(0, 0);
-      this.setState(this.state);
-    } else if (op == UserOperation.FollowCommunity) {
-      let data = wsJsonToRes<CommunityResponse>(msg, CommunityResponse);
-      this.state.listCommunitiesResponse.match({
-        some: res => {
-          let found = res.communities.find(
-            c => c.community.id == data.community_view.community.id
-          );
-          found.subscribed = data.community_view.subscribed;
-          found.counts.subscribers = data.community_view.counts.subscribers;
-        },
-        none: void 0,
-      });
-      this.setState(this.state);
-    }
+  findAndUpdateCommunity(res: RequestState<CommunityResponse>) {
+    this.setState(s => {
+      if (
+        s.listCommunitiesResponse.state == "success" &&
+        res.state == "success"
+      ) {
+        s.listCommunitiesResponse.data.communities = editCommunity(
+          res.data.community_view,
+          s.listCommunitiesResponse.data.communities
+        );
+      }
+      return s;
+    });
   }
 }