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