]> Untitled Git - lemmy.git/blob - ui/src/components/search.tsx
Fix federated community link on search page.
[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 = this.emptyState;
113       this.state.q = this.getSearchQueryFromProps(nextProps);
114       this.state.type_ = this.getSearchTypeFromProps(nextProps);
115       this.state.sort = this.getSortTypeFromProps(nextProps);
116       this.state.page = this.getPageFromProps(nextProps);
117       this.setState(this.state);
118       this.search();
119     }
120   }
121
122   componentDidMount() {
123     document.title = `${i18n.t('search')} - ${
124       WebSocketService.Instance.site.name
125     }`;
126   }
127
128   render() {
129     return (
130       <div class="container">
131         <h5>{i18n.t('search')}</h5>
132         {this.selects()}
133         {this.searchForm()}
134         {this.state.type_ == SearchType.All && this.all()}
135         {this.state.type_ == SearchType.Comments && this.comments()}
136         {this.state.type_ == SearchType.Posts && this.posts()}
137         {this.state.type_ == SearchType.Communities && this.communities()}
138         {this.state.type_ == SearchType.Users && this.users()}
139         {this.noResults()}
140         {this.paginator()}
141       </div>
142     );
143   }
144
145   searchForm() {
146     return (
147       <form
148         class="form-inline"
149         onSubmit={linkEvent(this, this.handleSearchSubmit)}
150       >
151         <input
152           type="text"
153           class="form-control mr-2"
154           value={this.state.q}
155           placeholder={`${i18n.t('search')}...`}
156           onInput={linkEvent(this, this.handleQChange)}
157           required
158           minLength={3}
159         />
160         <button type="submit" class="btn btn-secondary mr-2">
161           {this.state.loading ? (
162             <svg class="icon icon-spinner spin">
163               <use xlinkHref="#icon-spinner"></use>
164             </svg>
165           ) : (
166             <span>{i18n.t('search')}</span>
167           )}
168         </button>
169       </form>
170     );
171   }
172
173   selects() {
174     return (
175       <div className="mb-2">
176         <select
177           value={this.state.type_}
178           onChange={linkEvent(this, this.handleTypeChange)}
179           class="custom-select custom-select-sm w-auto"
180         >
181           <option disabled>{i18n.t('type')}</option>
182           <option value={SearchType.All}>{i18n.t('all')}</option>
183           <option value={SearchType.Comments}>{i18n.t('comments')}</option>
184           <option value={SearchType.Posts}>{i18n.t('posts')}</option>
185           <option value={SearchType.Communities}>
186             {i18n.t('communities')}
187           </option>
188           <option value={SearchType.Users}>{i18n.t('users')}</option>
189         </select>
190         <span class="ml-2">
191           <SortSelect
192             sort={this.state.sort}
193             onChange={this.handleSortChange}
194             hideHot
195           />
196         </span>
197       </div>
198     );
199   }
200
201   all() {
202     let combined: Array<{
203       type_: string;
204       data: Comment | Post | Community | UserView;
205     }> = [];
206     let comments = this.state.searchResponse.comments.map(e => {
207       return { type_: 'comments', data: e };
208     });
209     let posts = this.state.searchResponse.posts.map(e => {
210       return { type_: 'posts', data: e };
211     });
212     let communities = this.state.searchResponse.communities.map(e => {
213       return { type_: 'communities', data: e };
214     });
215     let users = this.state.searchResponse.users.map(e => {
216       return { type_: 'users', data: e };
217     });
218
219     combined.push(...comments);
220     combined.push(...posts);
221     combined.push(...communities);
222     combined.push(...users);
223
224     // Sort it
225     if (this.state.sort == SortType.New) {
226       combined.sort((a, b) => b.data.published.localeCompare(a.data.published));
227     } else {
228       combined.sort(
229         (a, b) =>
230           ((b.data as Comment | Post).score |
231             (b.data as Community).number_of_subscribers |
232             (b.data as UserView).comment_score) -
233           ((a.data as Comment | Post).score |
234             (a.data as Community).number_of_subscribers |
235             (a.data as UserView).comment_score)
236       );
237     }
238
239     return (
240       <div>
241         {combined.map(i => (
242           <div class="row">
243             <div class="col-12">
244               {i.type_ == 'posts' && (
245                 <PostListing post={i.data as Post} showCommunity />
246               )}
247               {i.type_ == 'comments' && (
248                 <CommentNodes
249                   nodes={[{ comment: i.data as Comment }]}
250                   locked
251                   noIndent
252                 />
253               )}
254               {i.type_ == 'communities' && (
255                 <div>{this.communityListing(i.data as Community)}</div>
256               )}
257               {i.type_ == 'users' && (
258                 <div>
259                   <span>
260                     <UserListing
261                       user={{
262                         name: (i.data as UserView).name,
263                         avatar: (i.data as UserView).avatar,
264                       }}
265                     />
266                   </span>
267                   <span>{` - ${
268                     (i.data as UserView).comment_score
269                   } comment karma`}</span>
270                 </div>
271               )}
272             </div>
273           </div>
274         ))}
275       </div>
276     );
277   }
278
279   comments() {
280     return (
281       <CommentNodes
282         nodes={commentsToFlatNodes(this.state.searchResponse.comments)}
283         locked
284         noIndent
285       />
286     );
287   }
288
289   posts() {
290     return (
291       <>
292         {this.state.searchResponse.posts.map(post => (
293           <div class="row">
294             <div class="col-12">
295               <PostListing post={post} showCommunity />
296             </div>
297           </div>
298         ))}
299       </>
300     );
301   }
302
303   // Todo possibly create UserListing and CommunityListing
304   communities() {
305     return (
306       <>
307         {this.state.searchResponse.communities.map(community => (
308           <div class="row">
309             <div class="col-12">{this.communityListing(community)}</div>
310           </div>
311         ))}
312       </>
313     );
314   }
315
316   communityListing(community: Community) {
317     return (
318       <>
319         <span>
320           <CommunityLink community={community} />
321         </span>
322         <span>{` - ${community.title} - 
323         ${i18n.t('number_of_subscribers', {
324           count: community.number_of_subscribers,
325         })}
326       `}</span>
327       </>
328     );
329   }
330
331   users() {
332     return (
333       <>
334         {this.state.searchResponse.users.map(user => (
335           <div class="row">
336             <div class="col-12">
337               <span>
338                 <Link
339                   className="text-info"
340                   to={`/u/${user.name}`}
341                 >{`/u/${user.name}`}</Link>
342               </span>
343               <span>{` - ${user.comment_score} comment karma`}</span>
344             </div>
345           </div>
346         ))}
347       </>
348     );
349   }
350
351   paginator() {
352     return (
353       <div class="mt-2">
354         {this.state.page > 1 && (
355           <button
356             class="btn btn-sm btn-secondary mr-1"
357             onClick={linkEvent(this, this.prevPage)}
358           >
359             {i18n.t('prev')}
360           </button>
361         )}
362         <button
363           class="btn btn-sm btn-secondary"
364           onClick={linkEvent(this, this.nextPage)}
365         >
366           {i18n.t('next')}
367         </button>
368       </div>
369     );
370   }
371
372   noResults() {
373     let res = this.state.searchResponse;
374     return (
375       <div>
376         {res &&
377           res.posts.length == 0 &&
378           res.comments.length == 0 &&
379           res.communities.length == 0 &&
380           res.users.length == 0 && <span>{i18n.t('no_results')}</span>}
381       </div>
382     );
383   }
384
385   nextPage(i: Search) {
386     i.state.page++;
387     i.setState(i.state);
388     i.updateUrl();
389     i.search();
390   }
391
392   prevPage(i: Search) {
393     i.state.page--;
394     i.setState(i.state);
395     i.updateUrl();
396     i.search();
397   }
398
399   search() {
400     let form: SearchForm = {
401       q: this.state.q,
402       type_: SearchType[this.state.type_],
403       sort: SortType[this.state.sort],
404       page: this.state.page,
405       limit: fetchLimit,
406     };
407
408     if (this.state.q != '') {
409       WebSocketService.Instance.search(form);
410     }
411   }
412
413   handleSortChange(val: SortType) {
414     this.state.sort = val;
415     this.state.page = 1;
416     this.setState(this.state);
417     this.updateUrl();
418   }
419
420   handleTypeChange(i: Search, event: any) {
421     i.state.type_ = Number(event.target.value);
422     i.state.page = 1;
423     i.setState(i.state);
424     i.updateUrl();
425   }
426
427   handleSearchSubmit(i: Search, event: any) {
428     event.preventDefault();
429     i.state.loading = true;
430     i.search();
431     i.setState(i.state);
432     i.updateUrl();
433   }
434
435   handleQChange(i: Search, event: any) {
436     i.state.q = event.target.value;
437     i.setState(i.state);
438   }
439
440   updateUrl() {
441     let typeStr = SearchType[this.state.type_].toLowerCase();
442     let sortStr = SortType[this.state.sort].toLowerCase();
443     this.props.history.push(
444       `/search/q/${this.state.q}/type/${typeStr}/sort/${sortStr}/page/${this.state.page}`
445     );
446   }
447
448   parseMessage(msg: WebSocketJsonResponse) {
449     console.log(msg);
450     let res = wsJsonToRes(msg);
451     if (msg.error) {
452       toast(i18n.t(msg.error), 'danger');
453       return;
454     } else if (res.op == UserOperation.Search) {
455       let data = res.data as SearchResponse;
456       this.state.searchResponse = data;
457       this.state.loading = false;
458       document.title = `${i18n.t('search')} - ${this.state.q} - ${
459         WebSocketService.Instance.site.name
460       }`;
461       window.scrollTo(0, 0);
462       this.setState(this.state);
463     } else if (res.op == UserOperation.CreateCommentLike) {
464       let data = res.data as CommentResponse;
465       createCommentLikeRes(data, this.state.searchResponse.comments);
466       this.setState(this.state);
467     } else if (res.op == UserOperation.CreatePostLike) {
468       let data = res.data as PostResponse;
469       createPostLikeFindRes(data, this.state.searchResponse.posts);
470       this.setState(this.state);
471     }
472   }
473 }