]> Untitled Git - lemmy.git/blob - ui/src/components/search.tsx
Adding emoji support.
[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 { UserOperation, Post, Comment, Community, UserView, SortType, SearchForm, SearchResponse, SearchType } from '../interfaces';
6 import { WebSocketService } from '../services';
7 import { msgOp, fetchLimit } from '../utils';
8 import { PostListing } from './post-listing';
9 import { CommentNodes } from './comment-nodes';
10 import { i18n } from '../i18next';
11 import { T } from 'inferno-i18next';
12
13 interface SearchState {
14   q: string,
15   type_: SearchType,
16   sort: SortType,
17   page: number,
18   searchResponse: SearchResponse;
19   loading: boolean;
20 }
21
22 export class Search extends Component<any, SearchState> {
23
24   private subscription: Subscription;
25   private emptyState: SearchState = {
26     q: undefined,
27     type_: SearchType.All,
28     sort: SortType.TopAll,
29     page: 1,
30     searchResponse: {
31       op: null,
32       type_: null,
33       posts: [],
34       comments: [],
35       communities: [],
36       users: [],
37     },
38     loading: false,
39   }
40
41   constructor(props: any, context: any) {
42     super(props, context);
43
44     this.state = this.emptyState;
45
46     this.subscription = WebSocketService.Instance.subject
47     .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
48     .subscribe(
49       (msg) => this.parseMessage(msg),
50         (err) => console.error(err),
51         () => console.log('complete')
52     );
53
54   }
55
56   componentWillUnmount() {
57     this.subscription.unsubscribe();
58   }
59
60   componentDidMount() {
61     document.title = `${i18n.t('search')} - ${WebSocketService.Instance.site.name}`;
62   }
63
64   render() {
65     return (
66       <div class="container">
67         <div class="row">
68           <div class="col-12">
69             <h5><T i18nKey="search">#</T></h5>
70             {this.selects()}
71             {this.searchForm()}
72             {this.state.type_ == SearchType.All &&
73               this.all()
74             }
75             {this.state.type_ == SearchType.Comments &&
76               this.comments()
77             }
78             {this.state.type_ == SearchType.Posts &&
79               this.posts()
80             }
81             {this.state.type_ == SearchType.Communities &&
82               this.communities()
83             }
84             {this.state.type_ == SearchType.Users &&
85               this.users()
86             }
87             {this.noResults()}
88             {this.paginator()}
89           </div>
90         </div>
91       </div>
92     )
93   }
94
95   searchForm() {
96     return (
97       <form class="form-inline" onSubmit={linkEvent(this, this.handleSearchSubmit)}>
98         <input type="text" class="form-control mr-2" value={this.state.q} placeholder={`${i18n.t('search')}...`} onInput={linkEvent(this, this.handleQChange)} required minLength={3} />
99         <button type="submit" class="btn btn-secondary mr-2">
100           {this.state.loading ?
101           <svg class="icon icon-spinner spin"><use xlinkHref="#icon-spinner"></use></svg> :
102           <span><T i18nKey="search">#</T></span>
103           }
104         </button>
105       </form>
106     )
107   }
108
109   selects() {
110     return (
111       <div className="mb-2">
112         <select value={this.state.type_} onChange={linkEvent(this, this.handleTypeChange)} class="custom-select custom-select-sm w-auto">
113           <option disabled><T i18nKey="type">#</T></option>
114           <option value={SearchType.All}><T i18nKey="all">#</T></option>
115           <option value={SearchType.Comments}><T i18nKey="comments">#</T></option>
116           <option value={SearchType.Posts}><T i18nKey="posts">#</T></option>
117           <option value={SearchType.Communities}><T i18nKey="communities">#</T></option>
118           <option value={SearchType.Users}><T i18nKey="users">#</T></option>
119         </select>
120         <select value={this.state.sort} onChange={linkEvent(this, this.handleSortChange)} class="custom-select custom-select-sm w-auto ml-2">
121           <option disabled><T i18nKey="sort_type">#</T></option>
122           <option value={SortType.New}><T i18nKey="new">#</T></option>
123           <option value={SortType.TopDay}><T i18nKey="top_day">#</T></option>
124           <option value={SortType.TopWeek}><T i18nKey="week">#</T></option>
125           <option value={SortType.TopMonth}><T i18nKey="month">#</T></option>
126           <option value={SortType.TopYear}><T i18nKey="year">#</T></option>
127           <option value={SortType.TopAll}><T i18nKey="all">#</T></option>
128         </select>
129       </div>
130     )
131
132   }
133
134   all() {
135     let combined: Array<{type_: string, data: Comment | Post | Community | UserView}> = [];
136     let comments = this.state.searchResponse.comments.map(e => {return {type_: "comments", data: e}});
137     let posts = this.state.searchResponse.posts.map(e => {return {type_: "posts", data: e}});
138     let communities = this.state.searchResponse.communities.map(e => {return {type_: "communities", data: e}});
139     let users = this.state.searchResponse.users.map(e => {return {type_: "users", data: e}});
140
141     combined.push(...comments);
142     combined.push(...posts);
143     combined.push(...communities);
144     combined.push(...users);
145
146     // Sort it
147     if (this.state.sort == SortType.New) {
148       combined.sort((a, b) => b.data.published.localeCompare(a.data.published));
149     } else {
150       combined.sort((a, b) => ((b.data as Comment | Post).score 
151         | (b.data as Community).number_of_subscribers
152           | (b.data as UserView).comment_score) 
153           - ((a.data as Comment | Post).score 
154             | (a.data as Community).number_of_subscribers 
155               | (a.data as UserView).comment_score));
156     }
157
158     return (
159       <div>
160         {combined.map(i =>
161           <div>
162             {i.type_ == "posts" &&
163               <PostListing post={i.data as Post} showCommunity viewOnly />
164             }
165             {i.type_ == "comments" && 
166               <CommentNodes nodes={[{comment: i.data as Comment}]} viewOnly noIndent />
167             }
168             {i.type_ == "communities" && 
169               <div>
170                 <span><Link to={`/c/${(i.data as Community).name}`}>{`/c/${(i.data as Community).name}`}</Link></span>
171                 <span>{` - ${(i.data as Community).title} - ${(i.data as Community).number_of_subscribers} subscribers`}</span>
172               </div>
173             }
174             {i.type_ == "users" && 
175               <div>
176                 <span><Link className="text-info" to={`/u/${(i.data as UserView).name}`}>{`/u/${(i.data as UserView).name}`}</Link></span>
177                 <span>{` - ${(i.data as UserView).comment_score} comment karma`}</span>
178               </div>
179             }
180           </div>
181                      )
182         }
183       </div>
184     )
185   }
186
187   comments() {
188     return (
189       <div>
190         {this.state.searchResponse.comments.map(comment => 
191           <CommentNodes nodes={[{comment: comment}]} noIndent viewOnly />
192         )}
193       </div>
194     );
195   }
196
197   posts() {
198     return (
199       <div>
200         {this.state.searchResponse.posts.map(post => 
201           <PostListing post={post} showCommunity viewOnly />
202         )}
203       </div>
204     );
205   }
206
207   // Todo possibly create UserListing and CommunityListing
208   communities() {
209     return (
210       <div>
211         {this.state.searchResponse.communities.map(community => 
212           <div>
213             <span><Link to={`/c/${community.name}`}>{`/c/${community.name}`}</Link></span>
214             <span>{` - ${community.title} - ${community.number_of_subscribers} subscribers`}</span>
215           </div>
216         )}
217       </div>
218     );
219   }
220
221   users() {
222     return (
223       <div>
224         {this.state.searchResponse.users.map(user => 
225           <div>
226             <span><Link className="text-info" to={`/u/${user.name}`}>{`/u/${user.name}`}</Link></span>
227             <span>{` - ${user.comment_score} comment karma`}</span>
228           </div>
229         )}
230       </div>
231     );
232   }
233
234   paginator() {
235     return (
236       <div class="mt-2">
237         {this.state.page > 1 && 
238           <button class="btn btn-sm btn-secondary mr-1" onClick={linkEvent(this, this.prevPage)}><T i18nKey="prev">#</T></button>
239         }
240         <button class="btn btn-sm btn-secondary" onClick={linkEvent(this, this.nextPage)}><T i18nKey="next">#</T></button>
241       </div>
242     );
243   }
244
245   noResults() {
246     let res = this.state.searchResponse;
247     return (
248       <div>
249         {res && res.op && res.posts.length == 0 && res.comments.length == 0 && 
250           <span><T i18nKey="no_results">#</T></span>
251         }
252       </div>
253     )
254   }
255
256   nextPage(i: Search) { 
257     i.state.page++;
258     i.setState(i.state);
259     i.search();
260   }
261
262   prevPage(i: Search) { 
263     i.state.page--;
264     i.setState(i.state);
265     i.search();
266   }
267
268   search() {
269     // TODO community
270     let form: SearchForm = {
271       q: this.state.q,
272       type_: SearchType[this.state.type_],
273       sort: SortType[this.state.sort],
274       page: this.state.page,
275       limit: fetchLimit,
276     };
277
278     WebSocketService.Instance.search(form);
279   }
280
281   handleSortChange(i: Search, event: any) {
282     i.state.sort = Number(event.target.value);
283     i.state.page = 1;
284     i.setState(i.state);
285   }
286
287   handleTypeChange(i: Search, event: any) {
288     i.state.type_ = Number(event.target.value);
289     i.state.page = 1;
290     i.setState(i.state);
291   }
292
293   handleSearchSubmit(i: Search, event: any) {
294     event.preventDefault();
295     i.state.loading = true;
296     i.search();
297     i.setState(i.state);
298   }
299
300   handleQChange(i: Search, event: any) {
301     i.state.q = event.target.value;
302     i.setState(i.state);
303   }
304
305   parseMessage(msg: any) {
306     console.log(msg);
307     let op: UserOperation = msgOp(msg);
308     if (msg.error) {
309       alert(i18n.t(msg.error));
310       return;
311     } else if (op == UserOperation.Search) {
312       let res: SearchResponse = msg;
313       this.state.searchResponse = res;
314       this.state.loading = false;
315       document.title = `${i18n.t('search')} - ${this.state.q} - ${WebSocketService.Instance.site.name}`;
316       window.scrollTo(0,0);
317       this.setState(this.state);
318     }
319   }
320 }
321