]> Untitled Git - lemmy.git/blob - ui/src/components/search.tsx
Merge remote-tracking branch 'weblate/main' into main
[lemmy.git] / ui / src / components / search.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Helmet } from 'inferno-helmet';
3 import { Subscription } from 'rxjs';
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import {
6   UserOperation,
7   Post,
8   Comment,
9   Community,
10   UserView,
11   SortType,
12   SearchForm,
13   SearchResponse,
14   SearchType,
15   PostResponse,
16   CommentResponse,
17   WebSocketJsonResponse,
18   GetSiteResponse,
19   Site,
20 } from '../interfaces';
21 import { WebSocketService } from '../services';
22 import {
23   wsJsonToRes,
24   fetchLimit,
25   routeSearchTypeToEnum,
26   routeSortTypeToEnum,
27   toast,
28   createCommentLikeRes,
29   createPostLikeFindRes,
30   commentsToFlatNodes,
31   getPageFromProps,
32 } from '../utils';
33 import { PostListing } from './post-listing';
34 import { UserListing } from './user-listing';
35 import { CommunityLink } from './community-link';
36 import { SortSelect } from './sort-select';
37 import { CommentNodes } from './comment-nodes';
38 import { i18n } from '../i18next';
39
40 interface SearchState {
41   q: string;
42   type_: SearchType;
43   sort: SortType;
44   page: number;
45   searchResponse: SearchResponse;
46   loading: boolean;
47   site: Site;
48   searchText: string;
49 }
50
51 interface SearchProps {
52   q: string;
53   type_: SearchType;
54   sort: SortType;
55   page: number;
56 }
57
58 interface UrlParams {
59   q?: string;
60   type_?: string;
61   sort?: string;
62   page?: number;
63 }
64
65 export class Search extends Component<any, SearchState> {
66   private subscription: Subscription;
67   private emptyState: SearchState = {
68     q: Search.getSearchQueryFromProps(this.props),
69     type_: Search.getSearchTypeFromProps(this.props),
70     sort: Search.getSortTypeFromProps(this.props),
71     page: getPageFromProps(this.props),
72     searchText: Search.getSearchQueryFromProps(this.props),
73     searchResponse: {
74       type_: null,
75       posts: [],
76       comments: [],
77       communities: [],
78       users: [],
79     },
80     loading: false,
81     site: {
82       id: undefined,
83       name: undefined,
84       creator_id: undefined,
85       published: undefined,
86       creator_name: undefined,
87       number_of_users: undefined,
88       number_of_posts: undefined,
89       number_of_comments: undefined,
90       number_of_communities: undefined,
91       enable_downvotes: undefined,
92       open_registration: undefined,
93       enable_nsfw: undefined,
94     },
95   };
96
97   static getSearchQueryFromProps(props: any): string {
98     return props.match.params.q ? props.match.params.q : '';
99   }
100
101   static getSearchTypeFromProps(props: any): SearchType {
102     return props.match.params.type
103       ? routeSearchTypeToEnum(props.match.params.type)
104       : SearchType.All;
105   }
106
107   static getSortTypeFromProps(props: any): SortType {
108     return props.match.params.sort
109       ? routeSortTypeToEnum(props.match.params.sort)
110       : SortType.TopAll;
111   }
112
113   constructor(props: any, context: any) {
114     super(props, context);
115
116     this.state = this.emptyState;
117     this.handleSortChange = this.handleSortChange.bind(this);
118
119     this.subscription = WebSocketService.Instance.subject
120       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
121       .subscribe(
122         msg => this.parseMessage(msg),
123         err => console.error(err),
124         () => console.log('complete')
125       );
126
127     WebSocketService.Instance.getSite();
128
129     if (this.state.q) {
130       this.search();
131     }
132   }
133
134   componentWillUnmount() {
135     this.subscription.unsubscribe();
136   }
137
138   static getDerivedStateFromProps(props: any): SearchProps {
139     return {
140       q: Search.getSearchQueryFromProps(props),
141       type_: Search.getSearchTypeFromProps(props),
142       sort: Search.getSortTypeFromProps(props),
143       page: getPageFromProps(props),
144     };
145   }
146
147   componentDidUpdate(_: any, lastState: SearchState) {
148     if (
149       lastState.q !== this.state.q ||
150       lastState.type_ !== this.state.type_ ||
151       lastState.sort !== this.state.sort ||
152       lastState.page !== this.state.page
153     ) {
154       this.setState({ loading: true, searchText: this.state.q });
155       this.search();
156     }
157   }
158
159   get documentTitle(): string {
160     if (this.state.site.name) {
161       if (this.state.q) {
162         return `${i18n.t('search')} - ${this.state.q} - ${
163           this.state.site.name
164         }`;
165       } else {
166         return `${i18n.t('search')} - ${this.state.site.name}`;
167       }
168     } else {
169       return 'Lemmy';
170     }
171   }
172
173   render() {
174     return (
175       <div class="container">
176         <Helmet title={this.documentTitle} />
177         <h5>{i18n.t('search')}</h5>
178         {this.selects()}
179         {this.searchForm()}
180         {this.state.type_ == SearchType.All && this.all()}
181         {this.state.type_ == SearchType.Comments && this.comments()}
182         {this.state.type_ == SearchType.Posts && this.posts()}
183         {this.state.type_ == SearchType.Communities && this.communities()}
184         {this.state.type_ == SearchType.Users && this.users()}
185         {this.resultsCount() == 0 && <span>{i18n.t('no_results')}</span>}
186         {this.paginator()}
187       </div>
188     );
189   }
190
191   searchForm() {
192     return (
193       <form
194         class="form-inline"
195         onSubmit={linkEvent(this, this.handleSearchSubmit)}
196       >
197         <input
198           type="text"
199           class="form-control mr-2 mb-2"
200           value={this.state.searchText}
201           placeholder={`${i18n.t('search')}...`}
202           onInput={linkEvent(this, this.handleQChange)}
203           required
204           minLength={3}
205         />
206         <button type="submit" class="btn btn-secondary mr-2 mb-2">
207           {this.state.loading ? (
208             <svg class="icon icon-spinner spin">
209               <use xlinkHref="#icon-spinner"></use>
210             </svg>
211           ) : (
212             <span>{i18n.t('search')}</span>
213           )}
214         </button>
215       </form>
216     );
217   }
218
219   selects() {
220     return (
221       <div className="mb-2">
222         <select
223           value={this.state.type_}
224           onChange={linkEvent(this, this.handleTypeChange)}
225           class="custom-select w-auto mb-2"
226         >
227           <option disabled>{i18n.t('type')}</option>
228           <option value={SearchType.All}>{i18n.t('all')}</option>
229           <option value={SearchType.Comments}>{i18n.t('comments')}</option>
230           <option value={SearchType.Posts}>{i18n.t('posts')}</option>
231           <option value={SearchType.Communities}>
232             {i18n.t('communities')}
233           </option>
234           <option value={SearchType.Users}>{i18n.t('users')}</option>
235         </select>
236         <span class="ml-2">
237           <SortSelect
238             sort={this.state.sort}
239             onChange={this.handleSortChange}
240             hideHot
241           />
242         </span>
243       </div>
244     );
245   }
246
247   all() {
248     let combined: Array<{
249       type_: string;
250       data: Comment | Post | Community | UserView;
251     }> = [];
252     let comments = this.state.searchResponse.comments.map(e => {
253       return { type_: 'comments', data: e };
254     });
255     let posts = this.state.searchResponse.posts.map(e => {
256       return { type_: 'posts', data: e };
257     });
258     let communities = this.state.searchResponse.communities.map(e => {
259       return { type_: 'communities', data: e };
260     });
261     let users = this.state.searchResponse.users.map(e => {
262       return { type_: 'users', data: e };
263     });
264
265     combined.push(...comments);
266     combined.push(...posts);
267     combined.push(...communities);
268     combined.push(...users);
269
270     // Sort it
271     if (this.state.sort == SortType.New) {
272       combined.sort((a, b) => b.data.published.localeCompare(a.data.published));
273     } else {
274       combined.sort(
275         (a, b) =>
276           ((b.data as Comment | Post).score |
277             (b.data as Community).number_of_subscribers |
278             (b.data as UserView).comment_score) -
279           ((a.data as Comment | Post).score |
280             (a.data as Community).number_of_subscribers |
281             (a.data as UserView).comment_score)
282       );
283     }
284
285     return (
286       <div>
287         {combined.map(i => (
288           <div class="row">
289             <div class="col-12">
290               {i.type_ == 'posts' && (
291                 <PostListing
292                   post={i.data as Post}
293                   showCommunity
294                   enableDownvotes={this.state.site.enable_downvotes}
295                   enableNsfw={this.state.site.enable_nsfw}
296                 />
297               )}
298               {i.type_ == 'comments' && (
299                 <CommentNodes
300                   nodes={[{ comment: i.data as Comment }]}
301                   locked
302                   noIndent
303                   enableDownvotes={this.state.site.enable_downvotes}
304                 />
305               )}
306               {i.type_ == 'communities' && (
307                 <div>{this.communityListing(i.data as Community)}</div>
308               )}
309               {i.type_ == 'users' && (
310                 <div>
311                   <span>
312                     @
313                     <UserListing
314                       user={{
315                         name: (i.data as UserView).name,
316                         avatar: (i.data as UserView).avatar,
317                       }}
318                     />
319                   </span>
320                   <span>{` - ${i18n.t('number_of_comments', {
321                     count: (i.data as UserView).number_of_comments,
322                   })}`}</span>
323                 </div>
324               )}
325             </div>
326           </div>
327         ))}
328       </div>
329     );
330   }
331
332   comments() {
333     return (
334       <CommentNodes
335         nodes={commentsToFlatNodes(this.state.searchResponse.comments)}
336         locked
337         noIndent
338         enableDownvotes={this.state.site.enable_downvotes}
339       />
340     );
341   }
342
343   posts() {
344     return (
345       <>
346         {this.state.searchResponse.posts.map(post => (
347           <div class="row">
348             <div class="col-12">
349               <PostListing
350                 post={post}
351                 showCommunity
352                 enableDownvotes={this.state.site.enable_downvotes}
353                 enableNsfw={this.state.site.enable_nsfw}
354               />
355             </div>
356           </div>
357         ))}
358       </>
359     );
360   }
361
362   // Todo possibly create UserListing and CommunityListing
363   communities() {
364     return (
365       <>
366         {this.state.searchResponse.communities.map(community => (
367           <div class="row">
368             <div class="col-12">{this.communityListing(community)}</div>
369           </div>
370         ))}
371       </>
372     );
373   }
374
375   communityListing(community: Community) {
376     return (
377       <>
378         <span>
379           <CommunityLink community={community} />
380         </span>
381         <span>{` - ${community.title} - 
382         ${i18n.t('number_of_subscribers', {
383           count: community.number_of_subscribers,
384         })}
385       `}</span>
386       </>
387     );
388   }
389
390   users() {
391     return (
392       <>
393         {this.state.searchResponse.users.map(user => (
394           <div class="row">
395             <div class="col-12">
396               <span>
397                 @
398                 <UserListing
399                   user={{
400                     name: user.name,
401                     avatar: user.avatar,
402                   }}
403                 />
404               </span>
405               <span>{` - ${i18n.t('number_of_comments', {
406                 count: user.number_of_comments,
407               })}`}</span>
408             </div>
409           </div>
410         ))}
411       </>
412     );
413   }
414
415   paginator() {
416     return (
417       <div class="mt-2">
418         {this.state.page > 1 && (
419           <button
420             class="btn btn-secondary mr-1"
421             onClick={linkEvent(this, this.prevPage)}
422           >
423             {i18n.t('prev')}
424           </button>
425         )}
426
427         {this.resultsCount() > 0 && (
428           <button
429             class="btn btn-secondary"
430             onClick={linkEvent(this, this.nextPage)}
431           >
432             {i18n.t('next')}
433           </button>
434         )}
435       </div>
436     );
437   }
438
439   resultsCount(): number {
440     let res = this.state.searchResponse;
441     return (
442       res.posts.length +
443       res.comments.length +
444       res.communities.length +
445       res.users.length
446     );
447   }
448
449   nextPage(i: Search) {
450     i.updateUrl({ page: i.state.page + 1 });
451   }
452
453   prevPage(i: Search) {
454     i.updateUrl({ page: i.state.page - 1 });
455   }
456
457   search() {
458     let form: SearchForm = {
459       q: this.state.q,
460       type_: SearchType[this.state.type_],
461       sort: SortType[this.state.sort],
462       page: this.state.page,
463       limit: fetchLimit,
464     };
465
466     if (this.state.q != '') {
467       WebSocketService.Instance.search(form);
468     }
469   }
470
471   handleSortChange(val: SortType) {
472     this.updateUrl({ sort: SortType[val].toLowerCase(), page: 1 });
473   }
474
475   handleTypeChange(i: Search, event: any) {
476     i.updateUrl({
477       type_: SearchType[Number(event.target.value)].toLowerCase(),
478       page: 1,
479     });
480   }
481
482   handleSearchSubmit(i: Search, event: any) {
483     event.preventDefault();
484     i.updateUrl({
485       q: i.state.searchText,
486       type_: SearchType[i.state.type_].toLowerCase(),
487       sort: SortType[i.state.sort].toLowerCase(),
488       page: i.state.page,
489     });
490   }
491
492   handleQChange(i: Search, event: any) {
493     i.setState({ searchText: event.target.value });
494   }
495
496   updateUrl(paramUpdates: UrlParams) {
497     const qStr = paramUpdates.q || this.state.q;
498     const typeStr =
499       paramUpdates.type_ || SearchType[this.state.type_].toLowerCase();
500     const sortStr =
501       paramUpdates.sort || SortType[this.state.sort].toLowerCase();
502     const page = paramUpdates.page || this.state.page;
503     this.props.history.push(
504       `/search/q/${qStr}/type/${typeStr}/sort/${sortStr}/page/${page}`
505     );
506   }
507
508   parseMessage(msg: WebSocketJsonResponse) {
509     console.log(msg);
510     let res = wsJsonToRes(msg);
511     if (msg.error) {
512       toast(i18n.t(msg.error), 'danger');
513       return;
514     } else if (res.op == UserOperation.Search) {
515       let data = res.data as SearchResponse;
516       this.state.searchResponse = data;
517       this.state.loading = false;
518       window.scrollTo(0, 0);
519       this.setState(this.state);
520     } else if (res.op == UserOperation.CreateCommentLike) {
521       let data = res.data as CommentResponse;
522       createCommentLikeRes(data, this.state.searchResponse.comments);
523       this.setState(this.state);
524     } else if (res.op == UserOperation.CreatePostLike) {
525       let data = res.data as PostResponse;
526       createPostLikeFindRes(data, this.state.searchResponse.posts);
527       this.setState(this.state);
528     } else if (res.op == UserOperation.GetSite) {
529       let data = res.data as GetSiteResponse;
530       this.state.site = data.site;
531       this.setState(this.state);
532     }
533   }
534 }