]> Untitled Git - lemmy-ui.git/blobdiff - src/shared/components/search.tsx
Use canonical URLs (#1883)
[lemmy-ui.git] / src / shared / components / search.tsx
index c62c7a98413542d7220ee7c875579927bb5ad332..99b180356b87c5ab89f789a795c49c81f9ef8645 100644 (file)
@@ -1,7 +1,31 @@
+import {
+  commentsToFlatNodes,
+  communityToChoice,
+  enableDownvotes,
+  enableNsfw,
+  fetchCommunities,
+  fetchUsers,
+  getUpdatedSearchId,
+  myAuth,
+  personToChoice,
+  setIsoData,
+  showLocal,
+} from "@utils/app";
+import { restoreScrollPosition, saveScrollPosition } from "@utils/browser";
+import {
+  capitalizeFirstLetter,
+  debounce,
+  getIdFromString,
+  getPageFromString,
+  getQueryParams,
+  getQueryString,
+  numToSI,
+} from "@utils/helpers";
+import type { QueryParams } from "@utils/types";
+import { Choice, RouteDataResponse } from "@utils/types";
 import type { NoOptionI18nKeys } from "i18next";
 import { Component, linkEvent } from "inferno";
 import {
-  CommentResponse,
   CommentView,
   CommunityView,
   GetCommunity,
@@ -13,7 +37,6 @@ import {
   ListCommunitiesResponse,
   ListingType,
   PersonView,
-  PostResponse,
   PostView,
   ResolveObject,
   ResolveObjectResponse,
@@ -21,45 +44,11 @@ import {
   SearchResponse,
   SearchType,
   SortType,
-  UserOperation,
-  wsJsonToRes,
-  wsUserOp,
 } from "lemmy-js-client";
-import { Subscription } from "rxjs";
-import { i18n } from "../i18next";
+import { fetchLimit } from "../config";
 import { CommentViewType, InitialFetchRequest } from "../interfaces";
-import { WebSocketService } from "../services";
-import {
-  Choice,
-  QueryParams,
-  WithPromiseKeys,
-  capitalizeFirstLetter,
-  commentsToFlatNodes,
-  communityToChoice,
-  createCommentLikeRes,
-  createPostLikeFindRes,
-  debounce,
-  enableDownvotes,
-  enableNsfw,
-  fetchCommunities,
-  fetchLimit,
-  fetchUsers,
-  getIdFromString,
-  getPageFromString,
-  getQueryParams,
-  getQueryString,
-  getUpdatedSearchId,
-  myAuth,
-  numToSI,
-  personToChoice,
-  restoreScrollPosition,
-  saveScrollPosition,
-  setIsoData,
-  showLocal,
-  toast,
-  wsClient,
-  wsSubscribe,
-} from "../utils";
+import { FirstLoadService, I18NextService } from "../services";
+import { HttpService, RequestState } from "../services/HttpService";
 import { CommentNodes } from "./comment/comment-nodes";
 import { HtmlTags } from "./common/html-tags";
 import { Spinner } from "./common/icon";
@@ -81,28 +70,29 @@ interface SearchProps {
   page: number;
 }
 
-interface SearchData {
-  communityResponse?: GetCommunityResponse;
-  listCommunitiesResponse?: ListCommunitiesResponse;
-  creatorDetailsResponse?: GetPersonDetailsResponse;
-  searchResponse?: SearchResponse;
-  resolveObjectResponse?: ResolveObjectResponse;
-}
+type SearchData = RouteDataResponse<{
+  communityResponse: GetCommunityResponse;
+  listCommunitiesResponse: ListCommunitiesResponse;
+  creatorDetailsResponse: GetPersonDetailsResponse;
+  searchResponse: SearchResponse;
+  resolveObjectResponse: ResolveObjectResponse;
+}>;
 
 type FilterType = "creator" | "community";
 
 interface SearchState {
-  searchResponse?: SearchResponse;
-  communities: CommunityView[];
-  creatorDetails?: GetPersonDetailsResponse;
-  searchLoading: boolean;
-  searchCommunitiesLoading: boolean;
-  searchCreatorLoading: boolean;
+  searchRes: RequestState<SearchResponse>;
+  resolveObjectRes: RequestState<ResolveObjectResponse>;
+  creatorDetailsRes: RequestState<GetPersonDetailsResponse>;
+  communitiesRes: RequestState<ListCommunitiesResponse>;
+  communityRes: RequestState<GetCommunityResponse>;
   siteRes: GetSiteResponse;
   searchText?: string;
-  resolveObjectResponse?: ResolveObjectResponse;
   communitySearchOptions: Choice[];
   creatorSearchOptions: Choice[];
+  searchCreatorLoading: boolean;
+  searchCommunitiesLoading: boolean;
+  isIsomorphic: boolean;
 }
 
 interface Combined {
@@ -191,15 +181,15 @@ const Filter = ({
   loading: boolean;
 }) => {
   return (
-    <div className="form-group col-sm-6">
-      <label className="col-form-label" htmlFor={`${filterType}-filter`}>
-        {capitalizeFirstLetter(i18n.t(filterType))}
+    <div className="col-sm-6">
+      <label className="mb-1" htmlFor={`${filterType}-filter`}>
+        {capitalizeFirstLetter(I18NextService.i18n.t(filterType))}
       </label>
       <SearchableSelect
         id={`${filterType}-filter`}
         options={[
           {
-            label: i18n.t("all"),
+            label: I18NextService.i18n.t("all"),
             value: "0",
           },
         ].concat(options)}
@@ -237,7 +227,7 @@ function getListing(
   return (
     <>
       <span>{listing}</span>
-      <span>{` - ${i18n.t(translationKey, {
+      <span>{` - ${I18NextService.i18n.t(translationKey, {
         count: Number(count),
         formattedCount: numToSI(count),
       })}`}</span>
@@ -247,15 +237,19 @@ function getListing(
 
 export class Search extends Component<any, SearchState> {
   private isoData = setIsoData<SearchData>(this.context);
-  private subscription?: Subscription;
+
   state: SearchState = {
-    searchLoading: false,
+    resolveObjectRes: { state: "empty" },
+    creatorDetailsRes: { state: "empty" },
+    communitiesRes: { state: "empty" },
+    communityRes: { state: "empty" },
     siteRes: this.isoData.site_res,
-    communities: [],
-    searchCommunitiesLoading: false,
-    searchCreatorLoading: false,
     creatorSearchOptions: [],
     communitySearchOptions: [],
+    searchRes: { state: "empty" },
+    searchCreatorLoading: false,
+    searchCommunitiesLoading: false,
+    isIsomorphic: false,
   };
 
   constructor(props: any, context: any) {
@@ -268,9 +262,6 @@ export class Search extends Component<any, SearchState> {
       this.handleCommunityFilterChange.bind(this);
     this.handleCreatorFilterChange = this.handleCreatorFilterChange.bind(this);
 
-    this.parseMessage = this.parseMessage.bind(this);
-    this.subscription = wsSubscribe(this.parseMessage);
-
     const { q } = getSearchQueryParams();
 
     this.state = {
@@ -279,92 +270,113 @@ export class Search extends Component<any, SearchState> {
     };
 
     // Only fetch the data if coming from another route
-    if (this.isoData.path === this.context.router.route.match.url) {
+    if (FirstLoadService.isFirstLoad) {
       const {
-        communityResponse,
-        creatorDetailsResponse,
-        listCommunitiesResponse,
-        resolveObjectResponse,
-        searchResponse,
+        communityResponse: communityRes,
+        creatorDetailsResponse: creatorDetailsRes,
+        listCommunitiesResponse: communitiesRes,
+        resolveObjectResponse: resolveObjectRes,
+        searchResponse: searchRes,
       } = this.isoData.routeData;
 
-      // This can be single or multiple communities given
-      if (listCommunitiesResponse) {
+      this.state = {
+        ...this.state,
+        isIsomorphic: true,
+      };
+
+      if (creatorDetailsRes?.state === "success") {
         this.state = {
           ...this.state,
-          communities: listCommunitiesResponse.communities,
+          creatorSearchOptions:
+            creatorDetailsRes?.state === "success"
+              ? [personToChoice(creatorDetailsRes.data.person_view)]
+              : [],
+          creatorDetailsRes,
         };
       }
-      if (communityResponse) {
+
+      if (communitiesRes?.state === "success") {
         this.state = {
           ...this.state,
-          communities: [communityResponse.community_view],
-          communitySearchOptions: [
-            communityToChoice(communityResponse.community_view),
-          ],
+          communitiesRes,
         };
       }
 
-      this.state = {
-        ...this.state,
-        creatorDetails: creatorDetailsResponse,
-        creatorSearchOptions: creatorDetailsResponse
-          ? [personToChoice(creatorDetailsResponse.person_view)]
-          : [],
-      };
+      if (communityRes?.state === "success") {
+        this.state = {
+          ...this.state,
+          communityRes,
+        };
+      }
 
       if (q !== "") {
         this.state = {
           ...this.state,
-          searchResponse,
-          resolveObjectResponse,
-          searchLoading: false,
         };
-      } else {
-        this.search();
-      }
-    } else {
-      const listCommunitiesForm: ListCommunities = {
-        type_: defaultListingType,
-        sort: defaultSortType,
-        limit: fetchLimit,
-        auth: myAuth(false),
-      };
 
-      WebSocketService.Instance.send(
-        wsClient.listCommunities(listCommunitiesForm)
-      );
+        if (searchRes?.state === "success") {
+          this.state = {
+            ...this.state,
+            searchRes,
+          };
+        }
+
+        if (resolveObjectRes?.state === "success") {
+          this.state = {
+            ...this.state,
+            resolveObjectRes,
+          };
+        }
+      }
+    }
+  }
 
-      if (q) {
-        this.search();
+  async componentDidMount() {
+    if (!this.state.isIsomorphic) {
+      const promises = [this.fetchCommunities()];
+      if (this.state.searchText) {
+        promises.push(this.search());
       }
+
+      await Promise.all(promises);
     }
   }
 
+  async fetchCommunities() {
+    this.setState({ communitiesRes: { state: "loading" } });
+    this.setState({
+      communitiesRes: await HttpService.client.listCommunities({
+        type_: defaultListingType,
+        sort: defaultSortType,
+        limit: fetchLimit,
+        auth: myAuth(),
+      }),
+    });
+  }
+
   componentWillUnmount() {
-    this.subscription?.unsubscribe();
     saveScrollPosition(this.context);
   }
 
-  static fetchInitialData({
+  static async fetchInitialData({
     client,
     auth,
     query: { communityId, creatorId, q, type, sort, listingType, page },
-  }: InitialFetchRequest<
-    QueryParams<SearchProps>
-  >): WithPromiseKeys<SearchData> {
+  }: InitialFetchRequest<QueryParams<SearchProps>>): Promise<SearchData> {
     const community_id = getIdFromString(communityId);
-    let communityResponse: Promise<GetCommunityResponse> | undefined =
-      undefined;
-    let listCommunitiesResponse: Promise<ListCommunitiesResponse> | undefined =
-      undefined;
+    let communityResponse: RequestState<GetCommunityResponse> = {
+      state: "empty",
+    };
+    let listCommunitiesResponse: RequestState<ListCommunitiesResponse> = {
+      state: "empty",
+    };
     if (community_id) {
       const getCommunityForm: GetCommunity = {
         id: community_id,
         auth,
       };
 
-      communityResponse = client.getCommunity(getCommunityForm);
+      communityResponse = await client.getCommunity(getCommunityForm);
     } else {
       const listCommunitiesForm: ListCommunities = {
         type_: defaultListingType,
@@ -373,27 +385,30 @@ export class Search extends Component<any, SearchState> {
         auth,
       };
 
-      listCommunitiesResponse = client.listCommunities(listCommunitiesForm);
+      listCommunitiesResponse = await client.listCommunities(
+        listCommunitiesForm
+      );
     }
 
     const creator_id = getIdFromString(creatorId);
-    let creatorDetailsResponse: Promise<GetPersonDetailsResponse> | undefined =
-      undefined;
+    let creatorDetailsResponse: RequestState<GetPersonDetailsResponse> = {
+      state: "empty",
+    };
     if (creator_id) {
       const getCreatorForm: GetPersonDetails = {
         person_id: creator_id,
         auth,
       };
 
-      creatorDetailsResponse = client.getPersonDetails(getCreatorForm);
+      creatorDetailsResponse = await client.getPersonDetails(getCreatorForm);
     }
 
     const query = getSearchQueryFromQuery(q);
 
-    let searchResponse: Promise<SearchResponse> | undefined = undefined;
-    let resolveObjectResponse:
-      | Promise<ResolveObjectResponse | undefined>
-      | undefined = undefined;
+    let searchResponse: RequestState<SearchResponse> = { state: "empty" };
+    let resolveObjectResponse: RequestState<ResolveObjectResponse> = {
+      state: "empty",
+    };
 
     if (query) {
       const form: SearchForm = {
@@ -409,15 +424,21 @@ export class Search extends Component<any, SearchState> {
       };
 
       if (query !== "") {
-        searchResponse = client.search(form);
+        searchResponse = await client.search(form);
         if (auth) {
           const resolveObjectForm: ResolveObject = {
             q: query,
             auth,
           };
-          resolveObjectResponse = client
-            .resolveObject(resolveObjectForm)
-            .catch(() => undefined);
+          resolveObjectResponse = await HttpService.silent_client.resolveObject(
+            resolveObjectForm
+          );
+
+          // If we return this object with a state of failed, the catch-all-handler will redirect
+          // to an error page, so we ignore it by covering up the error with the empty state.
+          if (resolveObjectResponse.state === "failed") {
+            resolveObjectResponse = { state: "empty" };
+          }
         }
       }
     }
@@ -434,25 +455,30 @@ export class Search extends Component<any, SearchState> {
   get documentTitle(): string {
     const { q } = getSearchQueryParams();
     const name = this.state.siteRes.site_view.site.name;
-    return `${i18n.t("search")} - ${q ? `${q} - ` : ""}${name}`;
+    return `${I18NextService.i18n.t("search")} - ${q ? `${q} - ` : ""}${name}`;
   }
 
   render() {
     const { type, page } = getSearchQueryParams();
 
     return (
-      <div className="container-lg">
+      <div className="search container-lg">
         <HtmlTags
           title={this.documentTitle}
           path={this.context.router.route.match.url}
+          canonicalPath={
+            this.context.router.route.match.url +
+            this.context.router.route.location.search
+          }
         />
-        <h5>{i18n.t("search")}</h5>
+        <h1 className="h4 mb-4">{I18NextService.i18n.t("search")}</h1>
         {this.selects}
         {this.searchForm}
         {this.displayResults(type)}
-        {this.resultsCount === 0 && !this.state.searchLoading && (
-          <span>{i18n.t("no_results")}</span>
-        )}
+        {this.resultsCount === 0 &&
+          this.state.searchRes.state === "success" && (
+            <span>{I18NextService.i18n.t("no_results")}</span>
+          )}
         <Paginator page={page} onChange={this.handlePageChange} />
       </div>
     );
@@ -479,26 +505,30 @@ export class Search extends Component<any, SearchState> {
   get searchForm() {
     return (
       <form
-        className="form-inline"
+        className="row gx-2 gy-3"
         onSubmit={linkEvent(this, this.handleSearchSubmit)}
       >
-        <input
-          type="text"
-          className="form-control mr-2 mb-2"
-          value={this.state.searchText}
-          placeholder={`${i18n.t("search")}...`}
-          aria-label={i18n.t("search")}
-          onInput={linkEvent(this, this.handleQChange)}
-          required
-          minLength={1}
-        />
-        <button type="submit" className="btn btn-secondary mr-2 mb-2">
-          {this.state.searchLoading ? (
-            <Spinner />
-          ) : (
-            <span>{i18n.t("search")}</span>
-          )}
-        </button>
+        <div className="col-auto flex-grow-1 flex-sm-grow-0">
+          <input
+            type="text"
+            className="form-control me-2 mb-2 col-sm-8"
+            value={this.state.searchText}
+            placeholder={`${I18NextService.i18n.t("search")}...`}
+            aria-label={I18NextService.i18n.t("search")}
+            onInput={linkEvent(this, this.handleQChange)}
+            required
+            minLength={1}
+          />
+        </div>
+        <div className="col-auto">
+          <button type="submit" className="btn btn-secondary mb-2">
+            {this.state.searchRes.state === "loading" ? (
+              <Spinner />
+            ) : (
+              <span>{I18NextService.i18n.t("search")}</span>
+            )}
+          </button>
+        </div>
       </form>
     );
   }
@@ -511,50 +541,61 @@ export class Search extends Component<any, SearchState> {
       creatorSearchOptions,
       searchCommunitiesLoading,
       searchCreatorLoading,
+      communitiesRes,
     } = this.state;
 
+    const hasCommunities =
+      communitiesRes.state == "success" &&
+      communitiesRes.data.communities.length > 0;
+
     return (
-      <div className="mb-2">
-        <select
-          value={type}
-          onChange={linkEvent(this, this.handleTypeChange)}
-          className="custom-select w-auto mb-2"
-          aria-label={i18n.t("type")}
-        >
-          <option disabled aria-hidden="true">
-            {i18n.t("type")}
-          </option>
-          {searchTypes.map(option => (
-            <option value={option} key={option}>
-              {i18n.t(option.toString().toLowerCase() as NoOptionI18nKeys)}
-            </option>
-          ))}
-        </select>
-        <span className="ml-2">
-          <ListingTypeSelect
-            type_={listingType}
-            showLocal={showLocal(this.isoData)}
-            showSubscribed
-            onChange={this.handleListingTypeChange}
-          />
-        </span>
-        <span className="ml-2">
-          <SortSelect
-            sort={sort}
-            onChange={this.handleSortChange}
-            hideHot
-            hideMostComments
-          />
-        </span>
-        <div className="form-row">
-          {this.state.communities.length > 0 && (
+      <>
+        <div className="row row-cols-auto g-2 g-sm-3 mb-2 mb-sm-3">
+          <div className="col">
+            <select
+              value={type}
+              onChange={linkEvent(this, this.handleTypeChange)}
+              className="form-select d-inline-block w-auto"
+              aria-label={I18NextService.i18n.t("type")}
+            >
+              <option disabled aria-hidden="true">
+                {I18NextService.i18n.t("type")}
+              </option>
+              {searchTypes.map(option => (
+                <option value={option} key={option}>
+                  {I18NextService.i18n.t(
+                    option.toString().toLowerCase() as NoOptionI18nKeys
+                  )}
+                </option>
+              ))}
+            </select>
+          </div>
+          <div className="col">
+            <ListingTypeSelect
+              type_={listingType}
+              showLocal={showLocal(this.isoData)}
+              showSubscribed
+              onChange={this.handleListingTypeChange}
+            />
+          </div>
+          <div className="col">
+            <SortSelect
+              sort={sort}
+              onChange={this.handleSortChange}
+              hideHot
+              hideMostComments
+            />
+          </div>
+        </div>
+        <div className="row gy-2 gx-4 mb-3">
+          {hasCommunities && (
             <Filter
               filterType="community"
               onChange={this.handleCommunityFilterChange}
               onSearch={this.handleCommunitySearch}
               options={communitySearchOptions}
-              loading={searchCommunitiesLoading}
               value={communityId}
+              loading={searchCommunitiesLoading}
             />
           )}
           <Filter
@@ -562,21 +603,24 @@ export class Search extends Component<any, SearchState> {
             onChange={this.handleCreatorFilterChange}
             onSearch={this.handleCreatorSearch}
             options={creatorSearchOptions}
-            loading={searchCreatorLoading}
             value={creatorId}
+            loading={searchCreatorLoading}
           />
         </div>
-      </div>
+      </>
     );
   }
 
   buildCombined(): Combined[] {
     const combined: Combined[] = [];
-    const { resolveObjectResponse, searchResponse } = this.state;
+    const {
+      resolveObjectRes: resolveObjectResponse,
+      searchRes: searchResponse,
+    } = this.state;
 
     // Push the possible resolve / federated objects first
-    if (resolveObjectResponse) {
-      const { comment, post, community, person } = resolveObjectResponse;
+    if (resolveObjectResponse.state == "success") {
+      const { comment, post, community, person } = resolveObjectResponse.data;
 
       if (comment) {
         combined.push(commentViewToCombined(comment));
@@ -593,8 +637,8 @@ export class Search extends Component<any, SearchState> {
     }
 
     // Push the search results
-    if (searchResponse) {
-      const { comments, posts, communities, users } = searchResponse;
+    if (searchResponse.state === "success") {
+      const { comments, posts, communities, users } = searchResponse.data;
 
       combined.push(
         ...[
@@ -645,6 +689,23 @@ export class Search extends Component<any, SearchState> {
                   allLanguages={this.state.siteRes.all_languages}
                   siteLanguages={this.state.siteRes.discussion_languages}
                   viewOnly
+                  // All of these are unused, since its view only
+                  onPostEdit={() => {}}
+                  onPostVote={() => {}}
+                  onPostReport={() => {}}
+                  onBlockPerson={() => {}}
+                  onLockPost={() => {}}
+                  onDeletePost={() => {}}
+                  onRemovePost={() => {}}
+                  onSavePost={() => {}}
+                  onFeaturePost={() => {}}
+                  onPurgePerson={() => {}}
+                  onPurgePost={() => {}}
+                  onBanPersonFromCommunity={() => {}}
+                  onBanPerson={() => {}}
+                  onAddModToCommunity={() => {}}
+                  onAddAdmin={() => {}}
+                  onTransferCommunity={() => {}}
                 />
               )}
               {i.type_ === "comments" && (
@@ -664,6 +725,26 @@ export class Search extends Component<any, SearchState> {
                   enableDownvotes={enableDownvotes(this.state.siteRes)}
                   allLanguages={this.state.siteRes.all_languages}
                   siteLanguages={this.state.siteRes.discussion_languages}
+                  // All of these are unused, since its viewonly
+                  finished={new Map()}
+                  onSaveComment={() => {}}
+                  onBlockPerson={() => {}}
+                  onDeleteComment={() => {}}
+                  onRemoveComment={() => {}}
+                  onCommentVote={() => {}}
+                  onCommentReport={() => {}}
+                  onDistinguishComment={() => {}}
+                  onAddModToCommunity={() => {}}
+                  onAddAdmin={() => {}}
+                  onTransferCommunity={() => {}}
+                  onPurgeComment={() => {}}
+                  onPurgePerson={() => {}}
+                  onCommentReplyRead={() => {}}
+                  onPersonMentionRead={() => {}}
+                  onBanPersonFromCommunity={() => {}}
+                  onBanPerson={() => {}}
+                  onCreateComment={() => Promise.resolve({ state: "empty" })}
+                  onEditComment={() => Promise.resolve({ state: "empty" })}
                 />
               )}
               {i.type_ === "communities" && (
@@ -680,11 +761,19 @@ export class Search extends Component<any, SearchState> {
   }
 
   get comments() {
-    const { searchResponse, resolveObjectResponse, siteRes } = this.state;
-    const comments = searchResponse?.comments ?? [];
-
-    if (resolveObjectResponse?.comment) {
-      comments.unshift(resolveObjectResponse?.comment);
+    const {
+      searchRes: searchResponse,
+      resolveObjectRes: resolveObjectResponse,
+      siteRes,
+    } = this.state;
+    const comments =
+      searchResponse.state === "success" ? searchResponse.data.comments : [];
+
+    if (
+      resolveObjectResponse.state === "success" &&
+      resolveObjectResponse.data.comment
+    ) {
+      comments.unshift(resolveObjectResponse.data.comment);
     }
 
     return (
@@ -697,16 +786,44 @@ export class Search extends Component<any, SearchState> {
         enableDownvotes={enableDownvotes(siteRes)}
         allLanguages={siteRes.all_languages}
         siteLanguages={siteRes.discussion_languages}
+        // All of these are unused, since its viewonly
+        finished={new Map()}
+        onSaveComment={() => {}}
+        onBlockPerson={() => {}}
+        onDeleteComment={() => {}}
+        onRemoveComment={() => {}}
+        onCommentVote={() => {}}
+        onCommentReport={() => {}}
+        onDistinguishComment={() => {}}
+        onAddModToCommunity={() => {}}
+        onAddAdmin={() => {}}
+        onTransferCommunity={() => {}}
+        onPurgeComment={() => {}}
+        onPurgePerson={() => {}}
+        onCommentReplyRead={() => {}}
+        onPersonMentionRead={() => {}}
+        onBanPersonFromCommunity={() => {}}
+        onBanPerson={() => {}}
+        onCreateComment={() => Promise.resolve({ state: "empty" })}
+        onEditComment={() => Promise.resolve({ state: "empty" })}
       />
     );
   }
 
   get posts() {
-    const { searchResponse, resolveObjectResponse, siteRes } = this.state;
-    const posts = searchResponse?.posts ?? [];
-
-    if (resolveObjectResponse?.post) {
-      posts.unshift(resolveObjectResponse.post);
+    const {
+      searchRes: searchResponse,
+      resolveObjectRes: resolveObjectResponse,
+      siteRes,
+    } = this.state;
+    const posts =
+      searchResponse.state === "success" ? searchResponse.data.posts : [];
+
+    if (
+      resolveObjectResponse.state === "success" &&
+      resolveObjectResponse.data.post
+    ) {
+      posts.unshift(resolveObjectResponse.data.post);
     }
 
     return (
@@ -722,6 +839,23 @@ export class Search extends Component<any, SearchState> {
                 allLanguages={siteRes.all_languages}
                 siteLanguages={siteRes.discussion_languages}
                 viewOnly
+                // All of these are unused, since its view only
+                onPostEdit={() => {}}
+                onPostVote={() => {}}
+                onPostReport={() => {}}
+                onBlockPerson={() => {}}
+                onLockPost={() => {}}
+                onDeletePost={() => {}}
+                onRemovePost={() => {}}
+                onSavePost={() => {}}
+                onFeaturePost={() => {}}
+                onPurgePerson={() => {}}
+                onPurgePost={() => {}}
+                onBanPersonFromCommunity={() => {}}
+                onBanPerson={() => {}}
+                onAddModToCommunity={() => {}}
+                onAddAdmin={() => {}}
+                onTransferCommunity={() => {}}
               />
             </div>
           </div>
@@ -731,11 +865,18 @@ export class Search extends Component<any, SearchState> {
   }
 
   get communities() {
-    const { searchResponse, resolveObjectResponse } = this.state;
-    const communities = searchResponse?.communities ?? [];
-
-    if (resolveObjectResponse?.community) {
-      communities.unshift(resolveObjectResponse.community);
+    const {
+      searchRes: searchResponse,
+      resolveObjectRes: resolveObjectResponse,
+    } = this.state;
+    const communities =
+      searchResponse.state === "success" ? searchResponse.data.communities : [];
+
+    if (
+      resolveObjectResponse.state === "success" &&
+      resolveObjectResponse.data.community
+    ) {
+      communities.unshift(resolveObjectResponse.data.community);
     }
 
     return (
@@ -750,11 +891,18 @@ export class Search extends Component<any, SearchState> {
   }
 
   get users() {
-    const { searchResponse, resolveObjectResponse } = this.state;
-    const users = searchResponse?.users ?? [];
-
-    if (resolveObjectResponse?.person) {
-      users.unshift(resolveObjectResponse.person);
+    const {
+      searchRes: searchResponse,
+      resolveObjectRes: resolveObjectResponse,
+    } = this.state;
+    const users =
+      searchResponse.state === "success" ? searchResponse.data.users : [];
+
+    if (
+      resolveObjectResponse.state === "success" &&
+      resolveObjectResponse.data.person
+    ) {
+      users.unshift(resolveObjectResponse.data.person);
     }
 
     return (
@@ -769,75 +917,72 @@ export class Search extends Component<any, SearchState> {
   }
 
   get resultsCount(): number {
-    const { searchResponse: r, resolveObjectResponse: resolveRes } = this.state;
-
-    const searchCount = r
-      ? r.posts.length +
-        r.comments.length +
-        r.communities.length +
-        r.users.length
-      : 0;
-
-    const resObjCount = resolveRes
-      ? resolveRes.post ||
-        resolveRes.person ||
-        resolveRes.community ||
-        resolveRes.comment
-        ? 1
-        : 0
-      : 0;
+    const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
+
+    const searchCount =
+      r.state === "success"
+        ? r.data.posts.length +
+          r.data.comments.length +
+          r.data.communities.length +
+          r.data.users.length
+        : 0;
+
+    const resObjCount =
+      resolveRes.state === "success"
+        ? resolveRes.data.post ||
+          resolveRes.data.person ||
+          resolveRes.data.community ||
+          resolveRes.data.comment
+          ? 1
+          : 0
+        : 0;
 
     return resObjCount + searchCount;
   }
 
-  search() {
-    const auth = myAuth(false);
+  async search() {
+    const auth = myAuth();
     const { searchText: q } = this.state;
     const { communityId, creatorId, type, sort, listingType, page } =
       getSearchQueryParams();
 
-    if (q && q !== "") {
-      const form: SearchForm = {
-        q,
-        community_id: communityId ?? undefined,
-        creator_id: creatorId ?? undefined,
-        type_: type,
-        sort,
-        listing_type: listingType,
-        page,
-        limit: fetchLimit,
-        auth,
-      };
-
-      if (auth) {
-        const resolveObjectForm: ResolveObject = {
+    if (q) {
+      this.setState({ searchRes: { state: "loading" } });
+      this.setState({
+        searchRes: await HttpService.client.search({
           q,
+          community_id: communityId ?? undefined,
+          creator_id: creatorId ?? undefined,
+          type_: type,
+          sort,
+          listing_type: listingType,
+          page,
+          limit: fetchLimit,
           auth,
-        };
-        WebSocketService.Instance.send(
-          wsClient.resolveObject(resolveObjectForm)
-        );
-      }
-
-      this.setState({
-        searchResponse: undefined,
-        resolveObjectResponse: undefined,
-        searchLoading: true,
+        }),
       });
+      window.scrollTo(0, 0);
+      restoreScrollPosition(this.context);
 
-      WebSocketService.Instance.send(wsClient.search(form));
+      if (auth) {
+        this.setState({ resolveObjectRes: { state: "loading" } });
+        this.setState({
+          resolveObjectRes: await HttpService.silent_client.resolveObject({
+            q,
+            auth,
+          }),
+        });
+      }
     }
   }
 
   handleCreatorSearch = debounce(async (text: string) => {
     const { creatorId } = getSearchQueryParams();
     const { creatorSearchOptions } = this.state;
-    this.setState({
-      searchCreatorLoading: true,
-    });
-
     const newOptions: Choice[] = [];
 
+    this.setState({ searchCreatorLoading: true });
+
     const selectedChoice = creatorSearchOptions.find(
       choice => getIdFromString(choice.value) === creatorId
     );
@@ -847,7 +992,7 @@ export class Search extends Component<any, SearchState> {
     }
 
     if (text.length > 0) {
-      newOptions.push(...(await fetchUsers(text)).users.map(personToChoice));
+      newOptions.push(...(await fetchUsers(text)).map(personToChoice));
     }
 
     this.setState({
@@ -874,9 +1019,7 @@ export class Search extends Component<any, SearchState> {
     }
 
     if (text.length > 0) {
-      newOptions.push(
-        ...(await fetchCommunities(text)).communities.map(communityToChoice)
-      );
+      newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
     }
 
     this.setState({
@@ -936,7 +1079,7 @@ export class Search extends Component<any, SearchState> {
     i.setState({ searchText: event.target.value });
   }
 
-  updateUrl({
+  async updateUrl({
     q,
     type,
     listingType,
@@ -972,72 +1115,5 @@ export class Search extends Component<any, SearchState> {
     };
 
     this.props.history.push(`/search${getQueryString(queryParams)}`);
-
-    this.search();
-  }
-
-  parseMessage(msg: any) {
-    console.log(msg);
-    const op = wsUserOp(msg);
-    if (msg.error) {
-      if (msg.error === "couldnt_find_object") {
-        this.setState({
-          resolveObjectResponse: {},
-        });
-        this.checkFinishedLoading();
-      } else {
-        toast(i18n.t(msg.error), "danger");
-      }
-    } else {
-      switch (op) {
-        case UserOperation.Search: {
-          const searchResponse = wsJsonToRes<SearchResponse>(msg);
-          this.setState({ searchResponse });
-          window.scrollTo(0, 0);
-          this.checkFinishedLoading();
-          restoreScrollPosition(this.context);
-
-          break;
-        }
-
-        case UserOperation.CreateCommentLike: {
-          const { comment_view } = wsJsonToRes<CommentResponse>(msg);
-          createCommentLikeRes(
-            comment_view,
-            this.state.searchResponse?.comments
-          );
-
-          break;
-        }
-
-        case UserOperation.CreatePostLike: {
-          const { post_view } = wsJsonToRes<PostResponse>(msg);
-          createPostLikeFindRes(post_view, this.state.searchResponse?.posts);
-
-          break;
-        }
-
-        case UserOperation.ListCommunities: {
-          const { communities } = wsJsonToRes<ListCommunitiesResponse>(msg);
-          this.setState({ communities });
-
-          break;
-        }
-
-        case UserOperation.ResolveObject: {
-          const resolveObjectResponse = wsJsonToRes<ResolveObjectResponse>(msg);
-          this.setState({ resolveObjectResponse });
-          this.checkFinishedLoading();
-
-          break;
-        }
-      }
-    }
-  }
-
-  checkFinishedLoading() {
-    if (this.state.searchResponse || this.state.resolveObjectResponse) {
-      this.setState({ searchLoading: false });
-    }
   }
 }