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