]> Untitled Git - lemmy-ui.git/blob - src/shared/components/search.tsx
Hide create community (#787)
[lemmy-ui.git] / src / shared / components / search.tsx
1 import { None, Option, Some } from "@sniptt/monads";
2 import { Component, linkEvent } from "inferno";
3 import {
4   CommentResponse,
5   CommentView,
6   CommunityView,
7   GetCommunity,
8   GetCommunityResponse,
9   GetPersonDetails,
10   GetPersonDetailsResponse,
11   GetSiteResponse,
12   ListCommunities,
13   ListCommunitiesResponse,
14   ListingType,
15   PersonViewSafe,
16   PostResponse,
17   PostView,
18   ResolveObject,
19   ResolveObjectResponse,
20   Search as SearchForm,
21   SearchResponse,
22   SearchType,
23   SortType,
24   UserOperation,
25   wsJsonToRes,
26   wsUserOp,
27 } from "lemmy-js-client";
28 import { Subscription } from "rxjs";
29 import { i18n } from "../i18next";
30 import { CommentViewType, InitialFetchRequest } from "../interfaces";
31 import { WebSocketService } from "../services";
32 import {
33   auth,
34   capitalizeFirstLetter,
35   choicesConfig,
36   commentsToFlatNodes,
37   communitySelectName,
38   communityToChoice,
39   createCommentLikeRes,
40   createPostLikeFindRes,
41   debounce,
42   enableDownvotes,
43   enableNsfw,
44   fetchCommunities,
45   fetchLimit,
46   fetchUsers,
47   isBrowser,
48   numToSI,
49   personSelectName,
50   personToChoice,
51   pushNotNull,
52   restoreScrollPosition,
53   routeListingTypeToEnum,
54   routeSearchTypeToEnum,
55   routeSortTypeToEnum,
56   saveScrollPosition,
57   setIsoData,
58   showLocal,
59   toast,
60   wsClient,
61   wsSubscribe,
62 } from "../utils";
63 import { CommentNodes } from "./comment/comment-nodes";
64 import { HtmlTags } from "./common/html-tags";
65 import { Spinner } from "./common/icon";
66 import { ListingTypeSelect } from "./common/listing-type-select";
67 import { Paginator } from "./common/paginator";
68 import { SortSelect } from "./common/sort-select";
69 import { CommunityLink } from "./community/community-link";
70 import { PersonListing } from "./person/person-listing";
71 import { PostListing } from "./post/post-listing";
72
73 var Choices: any;
74 if (isBrowser()) {
75   Choices = require("choices.js");
76 }
77
78 interface SearchProps {
79   q: string;
80   type_: SearchType;
81   sort: SortType;
82   listingType: ListingType;
83   communityId: number;
84   creatorId: number;
85   page: number;
86 }
87
88 interface SearchState {
89   q: string;
90   type_: SearchType;
91   sort: SortType;
92   listingType: ListingType;
93   communityId: number;
94   creatorId: number;
95   page: number;
96   searchResponse: Option<SearchResponse>;
97   communities: CommunityView[];
98   creatorDetails: Option<GetPersonDetailsResponse>;
99   loading: boolean;
100   siteRes: GetSiteResponse;
101   searchText: string;
102   resolveObjectResponse: Option<ResolveObjectResponse>;
103 }
104
105 interface UrlParams {
106   q?: string;
107   type_?: SearchType;
108   sort?: SortType;
109   listingType?: ListingType;
110   communityId?: number;
111   creatorId?: number;
112   page?: number;
113 }
114
115 interface Combined {
116   type_: string;
117   data: CommentView | PostView | CommunityView | PersonViewSafe;
118   published: string;
119 }
120
121 export class Search extends Component<any, SearchState> {
122   private isoData = setIsoData(
123     this.context,
124     GetCommunityResponse,
125     ListCommunitiesResponse,
126     GetPersonDetailsResponse,
127     SearchResponse,
128     ResolveObjectResponse
129   );
130   private communityChoices: any;
131   private creatorChoices: any;
132   private subscription: Subscription;
133   private emptyState: SearchState = {
134     q: Search.getSearchQueryFromProps(this.props.match.params.q),
135     type_: Search.getSearchTypeFromProps(this.props.match.params.type),
136     sort: Search.getSortTypeFromProps(this.props.match.params.sort),
137     listingType: Search.getListingTypeFromProps(
138       this.props.match.params.listing_type
139     ),
140     page: Search.getPageFromProps(this.props.match.params.page),
141     searchText: Search.getSearchQueryFromProps(this.props.match.params.q),
142     communityId: Search.getCommunityIdFromProps(
143       this.props.match.params.community_id
144     ),
145     creatorId: Search.getCreatorIdFromProps(this.props.match.params.creator_id),
146     searchResponse: None,
147     resolveObjectResponse: None,
148     creatorDetails: None,
149     loading: true,
150     siteRes: this.isoData.site_res,
151     communities: [],
152   };
153
154   static getSearchQueryFromProps(q: string): string {
155     return decodeURIComponent(q) || "";
156   }
157
158   static getSearchTypeFromProps(type_: string): SearchType {
159     return type_ ? routeSearchTypeToEnum(type_) : SearchType.All;
160   }
161
162   static getSortTypeFromProps(sort: string): SortType {
163     return sort ? routeSortTypeToEnum(sort) : SortType.TopAll;
164   }
165
166   static getListingTypeFromProps(listingType: string): ListingType {
167     return listingType ? routeListingTypeToEnum(listingType) : ListingType.All;
168   }
169
170   static getCommunityIdFromProps(id: string): number {
171     return id ? Number(id) : 0;
172   }
173
174   static getCreatorIdFromProps(id: string): number {
175     return id ? Number(id) : 0;
176   }
177
178   static getPageFromProps(page: string): number {
179     return page ? Number(page) : 1;
180   }
181
182   constructor(props: any, context: any) {
183     super(props, context);
184
185     this.state = this.emptyState;
186     this.handleSortChange = this.handleSortChange.bind(this);
187     this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
188     this.handlePageChange = this.handlePageChange.bind(this);
189
190     this.parseMessage = this.parseMessage.bind(this);
191     this.subscription = wsSubscribe(this.parseMessage);
192
193     // Only fetch the data if coming from another route
194     if (this.isoData.path == this.context.router.route.match.url) {
195       let communityRes = Some(
196         this.isoData.routeData[0] as GetCommunityResponse
197       );
198       let communitiesRes = Some(
199         this.isoData.routeData[1] as ListCommunitiesResponse
200       );
201
202       // This can be single or multiple communities given
203       if (communitiesRes.isSome()) {
204         this.state = {
205           ...this.state,
206           communities: communitiesRes.unwrap().communities,
207         };
208       }
209
210       if (communityRes.isSome()) {
211         this.state = {
212           ...this.state,
213           communities: [communityRes.unwrap().community_view],
214         };
215       }
216
217       this.state = {
218         ...this.state,
219         creatorDetails: Some(
220           this.isoData.routeData[2] as GetPersonDetailsResponse
221         ),
222       };
223
224       if (this.state.q != "") {
225         this.state = {
226           ...this.state,
227           searchResponse: Some(this.isoData.routeData[3] as SearchResponse),
228           resolveObjectResponse: Some(
229             this.isoData.routeData[4] as ResolveObjectResponse
230           ),
231           loading: false,
232         };
233       } else {
234         this.search();
235       }
236     } else {
237       this.fetchCommunities();
238       this.search();
239     }
240   }
241
242   componentWillUnmount() {
243     this.subscription.unsubscribe();
244     saveScrollPosition(this.context);
245   }
246
247   componentDidMount() {
248     this.setupCommunityFilter();
249     this.setupCreatorFilter();
250   }
251
252   static getDerivedStateFromProps(props: any): SearchProps {
253     return {
254       q: Search.getSearchQueryFromProps(props.match.params.q),
255       type_: Search.getSearchTypeFromProps(props.match.params.type),
256       sort: Search.getSortTypeFromProps(props.match.params.sort),
257       listingType: Search.getListingTypeFromProps(
258         props.match.params.listing_type
259       ),
260       communityId: Search.getCommunityIdFromProps(
261         props.match.params.community_id
262       ),
263       creatorId: Search.getCreatorIdFromProps(props.match.params.creator_id),
264       page: Search.getPageFromProps(props.match.params.page),
265     };
266   }
267
268   fetchCommunities() {
269     let listCommunitiesForm = new ListCommunities({
270       type_: Some(ListingType.All),
271       sort: Some(SortType.TopAll),
272       limit: Some(fetchLimit),
273       page: None,
274       auth: auth(false).ok(),
275     });
276     WebSocketService.Instance.send(
277       wsClient.listCommunities(listCommunitiesForm)
278     );
279   }
280
281   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
282     let pathSplit = req.path.split("/");
283     let promises: Promise<any>[] = [];
284
285     let communityId = this.getCommunityIdFromProps(pathSplit[11]);
286     let community_id: Option<number> =
287       communityId == 0 ? None : Some(communityId);
288     community_id.match({
289       some: id => {
290         let getCommunityForm = new GetCommunity({
291           id: Some(id),
292           name: None,
293           auth: req.auth,
294         });
295         promises.push(req.client.getCommunity(getCommunityForm));
296         promises.push(Promise.resolve());
297       },
298       none: () => {
299         let listCommunitiesForm = new ListCommunities({
300           type_: Some(ListingType.All),
301           sort: Some(SortType.TopAll),
302           limit: Some(fetchLimit),
303           page: None,
304           auth: req.auth,
305         });
306         promises.push(Promise.resolve());
307         promises.push(req.client.listCommunities(listCommunitiesForm));
308       },
309     });
310
311     let creatorId = this.getCreatorIdFromProps(pathSplit[13]);
312     let creator_id: Option<number> = creatorId == 0 ? None : Some(creatorId);
313     creator_id.match({
314       some: id => {
315         let getCreatorForm = new GetPersonDetails({
316           person_id: Some(id),
317           username: None,
318           sort: None,
319           page: None,
320           limit: None,
321           community_id: None,
322           saved_only: None,
323           auth: req.auth,
324         });
325         promises.push(req.client.getPersonDetails(getCreatorForm));
326       },
327       none: () => {
328         promises.push(Promise.resolve());
329       },
330     });
331
332     let form = new SearchForm({
333       q: this.getSearchQueryFromProps(pathSplit[3]),
334       community_id,
335       community_name: None,
336       creator_id,
337       type_: Some(this.getSearchTypeFromProps(pathSplit[5])),
338       sort: Some(this.getSortTypeFromProps(pathSplit[7])),
339       listing_type: Some(this.getListingTypeFromProps(pathSplit[9])),
340       page: Some(this.getPageFromProps(pathSplit[15])),
341       limit: Some(fetchLimit),
342       auth: req.auth,
343     });
344
345     let resolveObjectForm = new ResolveObject({
346       q: this.getSearchQueryFromProps(pathSplit[3]),
347       auth: req.auth,
348     });
349
350     if (form.q != "") {
351       promises.push(req.client.search(form));
352       promises.push(req.client.resolveObject(resolveObjectForm));
353     } else {
354       promises.push(Promise.resolve());
355       promises.push(Promise.resolve());
356     }
357
358     return promises;
359   }
360
361   componentDidUpdate(_: any, lastState: SearchState) {
362     if (
363       lastState.q !== this.state.q ||
364       lastState.type_ !== this.state.type_ ||
365       lastState.sort !== this.state.sort ||
366       lastState.listingType !== this.state.listingType ||
367       lastState.communityId !== this.state.communityId ||
368       lastState.creatorId !== this.state.creatorId ||
369       lastState.page !== this.state.page
370     ) {
371       this.setState({
372         loading: true,
373         searchText: this.state.q,
374         searchResponse: None,
375         resolveObjectResponse: None,
376       });
377       this.search();
378     }
379   }
380
381   get documentTitle(): string {
382     return this.state.siteRes.site_view.match({
383       some: siteView =>
384         this.state.q
385           ? `${i18n.t("search")} - ${this.state.q} - ${siteView.site.name}`
386           : `${i18n.t("search")} - ${siteView.site.name}`,
387       none: "",
388     });
389   }
390
391   render() {
392     return (
393       <div className="container">
394         <HtmlTags
395           title={this.documentTitle}
396           path={this.context.router.route.match.url}
397           description={None}
398           image={None}
399         />
400         <h5>{i18n.t("search")}</h5>
401         {this.selects()}
402         {this.searchForm()}
403         {this.state.type_ == SearchType.All && this.all()}
404         {this.state.type_ == SearchType.Comments && this.comments()}
405         {this.state.type_ == SearchType.Posts && this.posts()}
406         {this.state.type_ == SearchType.Communities && this.communities()}
407         {this.state.type_ == SearchType.Users && this.users()}
408         {this.state.type_ == SearchType.Url && this.posts()}
409         {this.resultsCount() == 0 && <span>{i18n.t("no_results")}</span>}
410         <Paginator page={this.state.page} onChange={this.handlePageChange} />
411       </div>
412     );
413   }
414
415   searchForm() {
416     return (
417       <form
418         className="form-inline"
419         onSubmit={linkEvent(this, this.handleSearchSubmit)}
420       >
421         <input
422           type="text"
423           className="form-control mr-2 mb-2"
424           value={this.state.searchText}
425           placeholder={`${i18n.t("search")}...`}
426           aria-label={i18n.t("search")}
427           onInput={linkEvent(this, this.handleQChange)}
428           required
429           minLength={1}
430         />
431         <button type="submit" className="btn btn-secondary mr-2 mb-2">
432           {this.state.loading ? <Spinner /> : <span>{i18n.t("search")}</span>}
433         </button>
434       </form>
435     );
436   }
437
438   selects() {
439     return (
440       <div className="mb-2">
441         <select
442           value={this.state.type_}
443           onChange={linkEvent(this, this.handleTypeChange)}
444           className="custom-select w-auto mb-2"
445           aria-label={i18n.t("type")}
446         >
447           <option disabled aria-hidden="true">
448             {i18n.t("type")}
449           </option>
450           <option value={SearchType.All}>{i18n.t("all")}</option>
451           <option value={SearchType.Comments}>{i18n.t("comments")}</option>
452           <option value={SearchType.Posts}>{i18n.t("posts")}</option>
453           <option value={SearchType.Communities}>
454             {i18n.t("communities")}
455           </option>
456           <option value={SearchType.Users}>{i18n.t("users")}</option>
457           <option value={SearchType.Url}>{i18n.t("url")}</option>
458         </select>
459         <span className="ml-2">
460           <ListingTypeSelect
461             type_={this.state.listingType}
462             showLocal={showLocal(this.isoData)}
463             showSubscribed
464             onChange={this.handleListingTypeChange}
465           />
466         </span>
467         <span className="ml-2">
468           <SortSelect
469             sort={this.state.sort}
470             onChange={this.handleSortChange}
471             hideHot
472             hideMostComments
473           />
474         </span>
475         <div className="form-row">
476           {this.state.communities.length > 0 && this.communityFilter()}
477           {this.creatorFilter()}
478         </div>
479       </div>
480     );
481   }
482
483   postViewToCombined(postView: PostView): Combined {
484     return {
485       type_: "posts",
486       data: postView,
487       published: postView.post.published,
488     };
489   }
490
491   commentViewToCombined(commentView: CommentView): Combined {
492     return {
493       type_: "comments",
494       data: commentView,
495       published: commentView.comment.published,
496     };
497   }
498
499   communityViewToCombined(communityView: CommunityView): Combined {
500     return {
501       type_: "communities",
502       data: communityView,
503       published: communityView.community.published,
504     };
505   }
506
507   personViewSafeToCombined(personViewSafe: PersonViewSafe): Combined {
508     return {
509       type_: "users",
510       data: personViewSafe,
511       published: personViewSafe.person.published,
512     };
513   }
514
515   buildCombined(): Combined[] {
516     let combined: Combined[] = [];
517
518     // Push the possible resolve / federated objects first
519     this.state.resolveObjectResponse.match({
520       some: res => {
521         let resolveComment = res.comment;
522         if (resolveComment.isSome()) {
523           combined.push(this.commentViewToCombined(resolveComment.unwrap()));
524         }
525         let resolvePost = res.post;
526         if (resolvePost.isSome()) {
527           combined.push(this.postViewToCombined(resolvePost.unwrap()));
528         }
529         let resolveCommunity = res.community;
530         if (resolveCommunity.isSome()) {
531           combined.push(
532             this.communityViewToCombined(resolveCommunity.unwrap())
533           );
534         }
535         let resolveUser = res.person;
536         if (resolveUser.isSome()) {
537           combined.push(this.personViewSafeToCombined(resolveUser.unwrap()));
538         }
539       },
540       none: void 0,
541     });
542
543     // Push the search results
544     this.state.searchResponse.match({
545       some: res => {
546         pushNotNull(
547           combined,
548           res.comments?.map(e => this.commentViewToCombined(e))
549         );
550         pushNotNull(
551           combined,
552           res.posts?.map(e => this.postViewToCombined(e))
553         );
554         pushNotNull(
555           combined,
556           res.communities?.map(e => this.communityViewToCombined(e))
557         );
558         pushNotNull(
559           combined,
560           res.users?.map(e => this.personViewSafeToCombined(e))
561         );
562       },
563       none: void 0,
564     });
565
566     // Sort it
567     if (this.state.sort == SortType.New) {
568       combined.sort((a, b) => b.published.localeCompare(a.published));
569     } else {
570       combined.sort(
571         (a, b) =>
572           ((b.data as CommentView | PostView).counts.score |
573             (b.data as CommunityView).counts.subscribers |
574             (b.data as PersonViewSafe).counts.comment_score) -
575           ((a.data as CommentView | PostView).counts.score |
576             (a.data as CommunityView).counts.subscribers |
577             (a.data as PersonViewSafe).counts.comment_score)
578       );
579     }
580     return combined;
581   }
582
583   all() {
584     let combined = this.buildCombined();
585     return (
586       <div>
587         {combined.map(i => (
588           <div key={i.published} className="row">
589             <div className="col-12">
590               {i.type_ == "posts" && (
591                 <PostListing
592                   key={(i.data as PostView).post.id}
593                   post_view={i.data as PostView}
594                   duplicates={None}
595                   moderators={None}
596                   admins={None}
597                   showCommunity
598                   enableDownvotes={enableDownvotes(this.state.siteRes)}
599                   enableNsfw={enableNsfw(this.state.siteRes)}
600                   allLanguages={this.state.siteRes.all_languages}
601                   viewOnly
602                 />
603               )}
604               {i.type_ == "comments" && (
605                 <CommentNodes
606                   key={(i.data as CommentView).comment.id}
607                   nodes={[
608                     {
609                       comment_view: i.data as CommentView,
610                       children: [],
611                       depth: 0,
612                     },
613                   ]}
614                   viewType={CommentViewType.Flat}
615                   viewOnly
616                   moderators={None}
617                   admins={None}
618                   maxCommentsShown={None}
619                   locked
620                   noIndent
621                   enableDownvotes={enableDownvotes(this.state.siteRes)}
622                   allLanguages={this.state.siteRes.all_languages}
623                 />
624               )}
625               {i.type_ == "communities" && (
626                 <div>{this.communityListing(i.data as CommunityView)}</div>
627               )}
628               {i.type_ == "users" && (
629                 <div>{this.personListing(i.data as PersonViewSafe)}</div>
630               )}
631             </div>
632           </div>
633         ))}
634       </div>
635     );
636   }
637
638   comments() {
639     let comments: CommentView[] = [];
640
641     this.state.resolveObjectResponse.match({
642       some: res => pushNotNull(comments, res.comment),
643       none: void 0,
644     });
645     this.state.searchResponse.match({
646       some: res => pushNotNull(comments, res.comments),
647       none: void 0,
648     });
649
650     return (
651       <CommentNodes
652         nodes={commentsToFlatNodes(comments)}
653         viewType={CommentViewType.Flat}
654         viewOnly
655         locked
656         noIndent
657         moderators={None}
658         admins={None}
659         maxCommentsShown={None}
660         enableDownvotes={enableDownvotes(this.state.siteRes)}
661         allLanguages={this.state.siteRes.all_languages}
662       />
663     );
664   }
665
666   posts() {
667     let posts: PostView[] = [];
668
669     this.state.resolveObjectResponse.match({
670       some: res => pushNotNull(posts, res.post),
671       none: void 0,
672     });
673     this.state.searchResponse.match({
674       some: res => pushNotNull(posts, res.posts),
675       none: void 0,
676     });
677
678     return (
679       <>
680         {posts.map(pv => (
681           <div key={pv.post.id} className="row">
682             <div className="col-12">
683               <PostListing
684                 post_view={pv}
685                 showCommunity
686                 duplicates={None}
687                 moderators={None}
688                 admins={None}
689                 enableDownvotes={enableDownvotes(this.state.siteRes)}
690                 enableNsfw={enableNsfw(this.state.siteRes)}
691                 allLanguages={this.state.siteRes.all_languages}
692                 viewOnly
693               />
694             </div>
695           </div>
696         ))}
697       </>
698     );
699   }
700
701   communities() {
702     let communities: CommunityView[] = [];
703
704     this.state.resolveObjectResponse.match({
705       some: res => pushNotNull(communities, res.community),
706       none: void 0,
707     });
708     this.state.searchResponse.match({
709       some: res => pushNotNull(communities, res.communities),
710       none: void 0,
711     });
712
713     return (
714       <>
715         {communities.map(cv => (
716           <div key={cv.community.id} className="row">
717             <div className="col-12">{this.communityListing(cv)}</div>
718           </div>
719         ))}
720       </>
721     );
722   }
723
724   users() {
725     let users: PersonViewSafe[] = [];
726
727     this.state.resolveObjectResponse.match({
728       some: res => pushNotNull(users, res.person),
729       none: void 0,
730     });
731     this.state.searchResponse.match({
732       some: res => pushNotNull(users, res.users),
733       none: void 0,
734     });
735
736     return (
737       <>
738         {users.map(pvs => (
739           <div key={pvs.person.id} className="row">
740             <div className="col-12">{this.personListing(pvs)}</div>
741           </div>
742         ))}
743       </>
744     );
745   }
746
747   communityListing(community_view: CommunityView) {
748     return (
749       <>
750         <span>
751           <CommunityLink community={community_view.community} />
752         </span>
753         <span>{` -
754         ${i18n.t("number_of_subscribers", {
755           count: community_view.counts.subscribers,
756           formattedCount: numToSI(community_view.counts.subscribers),
757         })}
758       `}</span>
759       </>
760     );
761   }
762
763   personListing(person_view: PersonViewSafe) {
764     return (
765       <>
766         <span>
767           <PersonListing person={person_view.person} showApubName />
768         </span>
769         <span>{` - ${i18n.t("number_of_comments", {
770           count: person_view.counts.comment_count,
771           formattedCount: numToSI(person_view.counts.comment_count),
772         })}`}</span>
773       </>
774     );
775   }
776
777   communityFilter() {
778     return (
779       <div className="form-group col-sm-6">
780         <label className="col-form-label" htmlFor="community-filter">
781           {i18n.t("community")}
782         </label>
783         <div>
784           <select
785             className="form-control"
786             id="community-filter"
787             value={this.state.communityId}
788           >
789             <option value="0">{i18n.t("all")}</option>
790             {this.state.communities.map(cv => (
791               <option key={cv.community.id} value={cv.community.id}>
792                 {communitySelectName(cv)}
793               </option>
794             ))}
795           </select>
796         </div>
797       </div>
798     );
799   }
800
801   creatorFilter() {
802     return (
803       <div className="form-group col-sm-6">
804         <label className="col-form-label" htmlFor="creator-filter">
805           {capitalizeFirstLetter(i18n.t("creator"))}
806         </label>
807         <div>
808           <select
809             className="form-control"
810             id="creator-filter"
811             value={this.state.creatorId}
812           >
813             <option value="0">{i18n.t("all")}</option>
814             {this.state.creatorDetails.match({
815               some: creator => (
816                 <option value={creator.person_view.person.id}>
817                   {personSelectName(creator.person_view)}
818                 </option>
819               ),
820               none: <></>,
821             })}
822           </select>
823         </div>
824       </div>
825     );
826   }
827
828   resultsCount(): number {
829     let searchCount = this.state.searchResponse
830       .map(
831         r =>
832           r.posts?.length +
833           r.comments?.length +
834           r.communities?.length +
835           r.users?.length
836       )
837       .unwrapOr(0);
838
839     let resObjCount = this.state.resolveObjectResponse
840       .map(r => (r.post || r.person || r.community || r.comment ? 1 : 0))
841       .unwrapOr(0);
842
843     return resObjCount + searchCount;
844   }
845
846   handlePageChange(page: number) {
847     this.updateUrl({ page });
848   }
849
850   search() {
851     let community_id: Option<number> =
852       this.state.communityId == 0 ? None : Some(this.state.communityId);
853     let creator_id: Option<number> =
854       this.state.creatorId == 0 ? None : Some(this.state.creatorId);
855
856     let form = new SearchForm({
857       q: this.state.q,
858       community_id,
859       community_name: None,
860       creator_id,
861       type_: Some(this.state.type_),
862       sort: Some(this.state.sort),
863       listing_type: Some(this.state.listingType),
864       page: Some(this.state.page),
865       limit: Some(fetchLimit),
866       auth: auth(false).ok(),
867     });
868
869     let resolveObjectForm = new ResolveObject({
870       q: this.state.q,
871       auth: auth(false).ok(),
872     });
873
874     if (this.state.q != "") {
875       this.setState({
876         searchResponse: None,
877         resolveObjectResponse: None,
878         loading: true,
879       });
880       WebSocketService.Instance.send(wsClient.search(form));
881       WebSocketService.Instance.send(wsClient.resolveObject(resolveObjectForm));
882     }
883   }
884
885   setupCommunityFilter() {
886     if (isBrowser()) {
887       let selectId: any = document.getElementById("community-filter");
888       if (selectId) {
889         this.communityChoices = new Choices(selectId, choicesConfig);
890         this.communityChoices.passedElement.element.addEventListener(
891           "choice",
892           (e: any) => {
893             this.handleCommunityFilterChange(Number(e.detail.choice.value));
894           },
895           false
896         );
897         this.communityChoices.passedElement.element.addEventListener(
898           "search",
899           debounce(async (e: any) => {
900             try {
901               let communities = (await fetchCommunities(e.detail.value))
902                 .communities;
903               let choices = communities.map(cv => communityToChoice(cv));
904               choices.unshift({ value: "0", label: i18n.t("all") });
905               this.communityChoices.setChoices(choices, "value", "label", true);
906             } catch (err) {
907               console.error(err);
908             }
909           }),
910           false
911         );
912       }
913     }
914   }
915
916   setupCreatorFilter() {
917     if (isBrowser()) {
918       let selectId: any = document.getElementById("creator-filter");
919       if (selectId) {
920         this.creatorChoices = new Choices(selectId, choicesConfig);
921         this.creatorChoices.passedElement.element.addEventListener(
922           "choice",
923           (e: any) => {
924             this.handleCreatorFilterChange(Number(e.detail.choice.value));
925           },
926           false
927         );
928         this.creatorChoices.passedElement.element.addEventListener(
929           "search",
930           debounce(async (e: any) => {
931             try {
932               let creators = (await fetchUsers(e.detail.value)).users;
933               let choices = creators.map(pvs => personToChoice(pvs));
934               choices.unshift({ value: "0", label: i18n.t("all") });
935               this.creatorChoices.setChoices(choices, "value", "label", true);
936             } catch (err) {
937               console.log(err);
938             }
939           }),
940           false
941         );
942       }
943     }
944   }
945
946   handleSortChange(val: SortType) {
947     this.updateUrl({ sort: val, page: 1 });
948   }
949
950   handleTypeChange(i: Search, event: any) {
951     i.updateUrl({
952       type_: SearchType[event.target.value],
953       page: 1,
954     });
955   }
956
957   handleListingTypeChange(val: ListingType) {
958     this.updateUrl({
959       listingType: val,
960       page: 1,
961     });
962   }
963
964   handleCommunityFilterChange(communityId: number) {
965     this.updateUrl({
966       communityId,
967       page: 1,
968     });
969   }
970
971   handleCreatorFilterChange(creatorId: number) {
972     this.updateUrl({
973       creatorId,
974       page: 1,
975     });
976   }
977
978   handleSearchSubmit(i: Search, event: any) {
979     event.preventDefault();
980     i.updateUrl({
981       q: i.state.searchText,
982       type_: i.state.type_,
983       listingType: i.state.listingType,
984       communityId: i.state.communityId,
985       creatorId: i.state.creatorId,
986       sort: i.state.sort,
987       page: i.state.page,
988     });
989   }
990
991   handleQChange(i: Search, event: any) {
992     i.setState({ searchText: event.target.value });
993   }
994
995   updateUrl(paramUpdates: UrlParams) {
996     const qStr = paramUpdates.q || this.state.q;
997     const qStrEncoded = encodeURIComponent(qStr);
998     const typeStr = paramUpdates.type_ || this.state.type_;
999     const listingTypeStr = paramUpdates.listingType || this.state.listingType;
1000     const sortStr = paramUpdates.sort || this.state.sort;
1001     const communityId =
1002       paramUpdates.communityId == 0
1003         ? 0
1004         : paramUpdates.communityId || this.state.communityId;
1005     const creatorId =
1006       paramUpdates.creatorId == 0
1007         ? 0
1008         : paramUpdates.creatorId || this.state.creatorId;
1009     const page = paramUpdates.page || this.state.page;
1010     this.props.history.push(
1011       `/search/q/${qStrEncoded}/type/${typeStr}/sort/${sortStr}/listing_type/${listingTypeStr}/community_id/${communityId}/creator_id/${creatorId}/page/${page}`
1012     );
1013   }
1014
1015   parseMessage(msg: any) {
1016     console.log(msg);
1017     let op = wsUserOp(msg);
1018     if (msg.error) {
1019       if (msg.error == "couldnt_find_object") {
1020         this.setState({
1021           resolveObjectResponse: Some({
1022             comment: None,
1023             post: None,
1024             community: None,
1025             person: None,
1026           }),
1027         });
1028         this.checkFinishedLoading();
1029       } else {
1030         toast(i18n.t(msg.error), "danger");
1031         return;
1032       }
1033     } else if (op == UserOperation.Search) {
1034       let data = wsJsonToRes<SearchResponse>(msg, SearchResponse);
1035       this.setState({ searchResponse: Some(data) });
1036       window.scrollTo(0, 0);
1037       this.checkFinishedLoading();
1038       restoreScrollPosition(this.context);
1039     } else if (op == UserOperation.CreateCommentLike) {
1040       let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
1041       createCommentLikeRes(
1042         data.comment_view,
1043         this.state.searchResponse.map(r => r.comments).unwrapOr([])
1044       );
1045       this.setState(this.state);
1046     } else if (op == UserOperation.CreatePostLike) {
1047       let data = wsJsonToRes<PostResponse>(msg, PostResponse);
1048       createPostLikeFindRes(
1049         data.post_view,
1050         this.state.searchResponse.map(r => r.posts).unwrapOr([])
1051       );
1052       this.setState(this.state);
1053     } else if (op == UserOperation.ListCommunities) {
1054       let data = wsJsonToRes<ListCommunitiesResponse>(
1055         msg,
1056         ListCommunitiesResponse
1057       );
1058       this.setState({ communities: data.communities });
1059       this.setupCommunityFilter();
1060     } else if (op == UserOperation.ResolveObject) {
1061       let data = wsJsonToRes<ResolveObjectResponse>(msg, ResolveObjectResponse);
1062       this.setState({ resolveObjectResponse: Some(data) });
1063       this.checkFinishedLoading();
1064     }
1065   }
1066
1067   checkFinishedLoading() {
1068     if (
1069       this.state.searchResponse.isSome() &&
1070       this.state.resolveObjectResponse.isSome()
1071     ) {
1072       this.setState({ loading: false });
1073     }
1074   }
1075 }