1 import { Component, linkEvent } from 'inferno';
2 import { Subscription } from 'rxjs';
16 } from 'lemmy-js-client';
17 import { WebSocketService } from '../services';
21 routeSearchTypeToEnum,
25 createPostLikeFindRes,
34 import { PostListing } from './post-listing';
35 import { HtmlTags } from './html-tags';
36 import { UserListing } from './user-listing';
37 import { CommunityLink } from './community-link';
38 import { SortSelect } from './sort-select';
39 import { CommentNodes } from './comment-nodes';
40 import { i18n } from '../i18next';
41 import { InitialFetchRequest } from 'shared/interfaces';
43 interface SearchProps {
50 interface SearchState {
55 searchResponse: SearchResponse;
68 export class Search extends Component<any, SearchState> {
69 private isoData = setIsoData(this.context);
70 private subscription: Subscription;
71 private emptyState: SearchState = {
72 q: Search.getSearchQueryFromProps(this.props.match.params.q),
73 type_: Search.getSearchTypeFromProps(this.props.match.params.type),
74 sort: Search.getSortTypeFromProps(this.props.match.params.sort),
75 page: Search.getPageFromProps(this.props.match.params.page),
76 searchText: Search.getSearchQueryFromProps(this.props.match.params.q),
85 site: this.isoData.site_res.site_view.site,
88 static getSearchQueryFromProps(q: string): string {
89 return decodeURIComponent(q) || '';
92 static getSearchTypeFromProps(type_: string): SearchType {
93 return type_ ? routeSearchTypeToEnum(type_) : SearchType.All;
96 static getSortTypeFromProps(sort: string): SortType {
97 return sort ? routeSortTypeToEnum(sort) : SortType.TopAll;
100 static getPageFromProps(page: string): number {
101 return page ? Number(page) : 1;
104 constructor(props: any, context: any) {
105 super(props, context);
107 this.state = this.emptyState;
108 this.handleSortChange = this.handleSortChange.bind(this);
110 this.parseMessage = this.parseMessage.bind(this);
111 this.subscription = wsSubscribe(this.parseMessage);
113 // Only fetch the data if coming from another route
114 if (this.state.q != '') {
115 if (this.isoData.path == this.context.router.route.match.url) {
116 this.state.searchResponse = this.isoData.routeData[0];
117 this.state.loading = false;
124 componentWillUnmount() {
125 this.subscription.unsubscribe();
128 static getDerivedStateFromProps(props: any): SearchProps {
130 q: Search.getSearchQueryFromProps(props.match.params.q),
131 type_: Search.getSearchTypeFromProps(props.match.params.type),
132 sort: Search.getSortTypeFromProps(props.match.params.sort),
133 page: Search.getPageFromProps(props.match.params.page),
137 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
138 let pathSplit = req.path.split('/');
139 let promises: Promise<any>[] = [];
141 let form: SearchForm = {
142 q: this.getSearchQueryFromProps(pathSplit[3]),
143 type_: this.getSearchTypeFromProps(pathSplit[5]),
144 sort: this.getSortTypeFromProps(pathSplit[7]),
145 page: this.getPageFromProps(pathSplit[9]),
148 setOptionalAuth(form, req.auth);
151 promises.push(req.client.search(form));
157 componentDidUpdate(_: any, lastState: SearchState) {
159 lastState.q !== this.state.q ||
160 lastState.type_ !== this.state.type_ ||
161 lastState.sort !== this.state.sort ||
162 lastState.page !== this.state.page
164 this.setState({ loading: true, searchText: this.state.q });
169 get documentTitle(): string {
171 return `${i18n.t('search')} - ${this.state.q} - ${this.state.site.name}`;
173 return `${i18n.t('search')} - ${this.state.site.name}`;
179 <div class="container">
181 title={this.documentTitle}
182 path={this.context.router.route.match.url}
184 <h5>{i18n.t('search')}</h5>
187 {this.state.type_ == SearchType.All && this.all()}
188 {this.state.type_ == SearchType.Comments && this.comments()}
189 {this.state.type_ == SearchType.Posts && this.posts()}
190 {this.state.type_ == SearchType.Communities && this.communities()}
191 {this.state.type_ == SearchType.Users && this.users()}
192 {this.resultsCount() == 0 && <span>{i18n.t('no_results')}</span>}
202 onSubmit={linkEvent(this, this.handleSearchSubmit)}
206 class="form-control mr-2 mb-2"
207 value={this.state.searchText}
208 placeholder={`${i18n.t('search')}...`}
209 onInput={linkEvent(this, this.handleQChange)}
213 <button type="submit" class="btn btn-secondary mr-2 mb-2">
214 {this.state.loading ? (
215 <svg class="icon icon-spinner spin">
216 <use xlinkHref="#icon-spinner"></use>
219 <span>{i18n.t('search')}</span>
228 <div className="mb-2">
230 value={this.state.type_}
231 onChange={linkEvent(this, this.handleTypeChange)}
232 class="custom-select w-auto mb-2"
234 <option disabled>{i18n.t('type')}</option>
235 <option value={SearchType.All}>{i18n.t('all')}</option>
236 <option value={SearchType.Comments}>{i18n.t('comments')}</option>
237 <option value={SearchType.Posts}>{i18n.t('posts')}</option>
238 <option value={SearchType.Communities}>
239 {i18n.t('communities')}
241 <option value={SearchType.Users}>{i18n.t('users')}</option>
245 sort={this.state.sort}
246 onChange={this.handleSortChange}
258 data: CommentView | PostView | CommunityView | UserViewSafe;
261 let comments = this.state.searchResponse.comments.map(e => {
262 return { type_: 'comments', data: e, published: e.comment.published };
264 let posts = this.state.searchResponse.posts.map(e => {
265 return { type_: 'posts', data: e, published: e.post.published };
267 let communities = this.state.searchResponse.communities.map(e => {
269 type_: 'communities',
271 published: e.community.published,
274 let users = this.state.searchResponse.users.map(e => {
275 return { type_: 'users', data: e, published: e.user.published };
278 combined.push(...comments);
279 combined.push(...posts);
280 combined.push(...communities);
281 combined.push(...users);
284 if (this.state.sort == SortType.New) {
285 combined.sort((a, b) => b.published.localeCompare(a.published));
289 ((b.data as CommentView | PostView).counts.score |
290 (b.data as CommunityView).counts.subscribers |
291 (b.data as UserViewSafe).counts.comment_score) -
292 ((a.data as CommentView | PostView).counts.score |
293 (a.data as CommunityView).counts.subscribers |
294 (a.data as UserViewSafe).counts.comment_score)
303 {i.type_ == 'posts' && (
305 key={(i.data as PostView).post.id}
306 post_view={i.data as PostView}
308 enableDownvotes={this.state.site.enable_downvotes}
309 enableNsfw={this.state.site.enable_nsfw}
312 {i.type_ == 'comments' && (
314 key={(i.data as CommentView).comment.id}
315 nodes={[{ comment_view: i.data as CommentView }]}
318 enableDownvotes={this.state.site.enable_downvotes}
321 {i.type_ == 'communities' && (
322 <div>{this.communityListing(i.data as CommunityView)}</div>
324 {i.type_ == 'users' && (
325 <div>{this.userListing(i.data as UserViewSafe)}</div>
337 nodes={commentsToFlatNodes(this.state.searchResponse.comments)}
340 enableDownvotes={this.state.site.enable_downvotes}
348 {this.state.searchResponse.posts.map(post => (
354 enableDownvotes={this.state.site.enable_downvotes}
355 enableNsfw={this.state.site.enable_nsfw}
367 {this.state.searchResponse.communities.map(community => (
369 <div class="col-12">{this.communityListing(community)}</div>
376 communityListing(community_view: CommunityView) {
380 <CommunityLink community={community_view.community} />
383 ${i18n.t('number_of_subscribers', {
384 count: community_view.counts.subscribers,
391 userListing(user_view: UserViewSafe) {
394 <UserListing user={user_view.user} showApubName />
396 <span>{` - ${i18n.t('number_of_comments', {
397 count: user_view.counts.comment_count,
405 {this.state.searchResponse.users.map(user => (
407 <div class="col-12">{this.userListing(user)}</div>
417 {this.state.page > 1 && (
419 class="btn btn-secondary mr-1"
420 onClick={linkEvent(this, this.prevPage)}
426 {this.resultsCount() > 0 && (
428 class="btn btn-secondary"
429 onClick={linkEvent(this, this.nextPage)}
438 resultsCount(): number {
439 let res = this.state.searchResponse;
442 res.comments.length +
443 res.communities.length +
448 nextPage(i: Search) {
449 i.updateUrl({ page: i.state.page + 1 });
452 prevPage(i: Search) {
453 i.updateUrl({ page: i.state.page - 1 });
457 let form: SearchForm = {
459 type_: this.state.type_,
460 sort: this.state.sort,
461 page: this.state.page,
463 auth: authField(false),
466 if (this.state.q != '') {
467 WebSocketService.Instance.send(wsClient.search(form));
471 handleSortChange(val: SortType) {
472 this.updateUrl({ sort: val, page: 1 });
475 handleTypeChange(i: Search, event: any) {
477 type_: SearchType[event.target.value],
482 handleSearchSubmit(i: Search, event: any) {
483 event.preventDefault();
485 q: i.state.searchText,
486 type_: i.state.type_,
492 handleQChange(i: Search, event: any) {
493 i.setState({ searchText: event.target.value });
496 updateUrl(paramUpdates: UrlParams) {
497 const qStr = paramUpdates.q || this.state.q;
498 const qStrEncoded = encodeURIComponent(qStr);
499 const typeStr = paramUpdates.type_ || this.state.type_;
500 const sortStr = paramUpdates.sort || this.state.sort;
501 const page = paramUpdates.page || this.state.page;
502 this.props.history.push(
503 `/search/q/${qStrEncoded}/type/${typeStr}/sort/${sortStr}/page/${page}`
507 parseMessage(msg: any) {
509 let op = wsUserOp(msg);
511 toast(i18n.t(msg.error), 'danger');
513 } else if (op == UserOperation.Search) {
514 let data = wsJsonToRes<SearchResponse>(msg).data;
515 this.state.searchResponse = data;
516 this.state.loading = false;
517 window.scrollTo(0, 0);
518 this.setState(this.state);
519 } else if (op == UserOperation.CreateCommentLike) {
520 let data = wsJsonToRes<CommentResponse>(msg).data;
521 createCommentLikeRes(
523 this.state.searchResponse.comments
525 this.setState(this.state);
526 } else if (op == UserOperation.CreatePostLike) {
527 let data = wsJsonToRes<PostResponse>(msg).data;
528 createPostLikeFindRes(data.post_view, this.state.searchResponse.posts);
529 this.setState(this.state);