1 import { Component, linkEvent } from 'inferno';
2 import { Helmet } from 'inferno-helmet';
3 import { Subscription } from 'rxjs';
16 WebSocketJsonResponse,
18 } from 'lemmy-js-client';
19 import { WebSocketService } from '../services';
23 routeSearchTypeToEnum,
27 createPostLikeFindRes,
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';
41 interface SearchProps {
48 interface SearchState {
53 searchResponse: SearchResponse;
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),
83 site: this.isoData.site.site,
86 static getSearchQueryFromProps(q: string): string {
90 static getSearchTypeFromProps(type_: string): SearchType {
91 return type_ ? routeSearchTypeToEnum(type_) : SearchType.All;
94 static getSortTypeFromProps(sort: string): SortType {
95 return sort ? routeSortTypeToEnum(sort) : SortType.TopAll;
98 static getPageFromProps(page: string): number {
99 return page ? Number(page) : 1;
102 constructor(props: any, context: any) {
103 super(props, context);
105 this.state = this.emptyState;
106 this.handleSortChange = this.handleSortChange.bind(this);
108 this.parseMessage = this.parseMessage.bind(this);
109 this.subscription = wsSubscribe(this.parseMessage);
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;
122 componentWillUnmount() {
123 this.subscription.unsubscribe();
126 static getDerivedStateFromProps(props: any): SearchProps {
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),
135 static fetchInitialData(auth: string, path: string): Promise<any>[] {
136 let pathSplit = path.split('/');
137 let promises: Promise<any>[] = [];
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]),
149 promises.push(lemmyHttp.search(form));
155 componentDidUpdate(_: any, lastState: SearchState) {
157 lastState.q !== this.state.q ||
158 lastState.type_ !== this.state.type_ ||
159 lastState.sort !== this.state.sort ||
160 lastState.page !== this.state.page
162 this.setState({ loading: true, searchText: this.state.q });
167 get documentTitle(): string {
168 if (this.state.site.name) {
170 return `${i18n.t('search')} - ${this.state.q} - ${
174 return `${i18n.t('search')} - ${this.state.site.name}`;
183 <div class="container">
184 <Helmet title={this.documentTitle} />
185 <h5>{i18n.t('search')}</h5>
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>}
203 onSubmit={linkEvent(this, this.handleSearchSubmit)}
207 class="form-control mr-2 mb-2"
208 value={this.state.searchText}
209 placeholder={`${i18n.t('search')}...`}
210 onInput={linkEvent(this, this.handleQChange)}
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>
220 <span>{i18n.t('search')}</span>
229 <div className="mb-2">
231 value={this.state.type_}
232 onChange={linkEvent(this, this.handleTypeChange)}
233 class="custom-select w-auto mb-2"
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')}
242 <option value={SearchType.Users}>{i18n.t('users')}</option>
246 sort={this.state.sort}
247 onChange={this.handleSortChange}
258 data: Comment | Post | Community | UserView;
260 let comments = this.state.searchResponse.comments.map(e => {
261 return { type_: 'comments', data: e };
263 let posts = this.state.searchResponse.posts.map(e => {
264 return { type_: 'posts', data: e };
266 let communities = this.state.searchResponse.communities.map(e => {
267 return { type_: 'communities', data: e };
269 let users = this.state.searchResponse.users.map(e => {
270 return { type_: 'users', data: e };
273 combined.push(...comments);
274 combined.push(...posts);
275 combined.push(...communities);
276 combined.push(...users);
279 if (this.state.sort == SortType.New) {
280 combined.sort((a, b) => b.data.published.localeCompare(a.data.published));
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)
298 {i.type_ == 'posts' && (
300 key={(i.data as Post).id}
301 post={i.data as Post}
303 enableDownvotes={this.state.site.enable_downvotes}
304 enableNsfw={this.state.site.enable_nsfw}
307 {i.type_ == 'comments' && (
309 key={(i.data as Comment).id}
310 nodes={[{ comment: i.data as Comment }]}
313 enableDownvotes={this.state.site.enable_downvotes}
316 {i.type_ == 'communities' && (
317 <div>{this.communityListing(i.data as Community)}</div>
319 {i.type_ == 'users' && (
325 name: (i.data as UserView).name,
326 preferred_username: (i.data as UserView)
328 avatar: (i.data as UserView).avatar,
332 <span>{` - ${i18n.t('number_of_comments', {
333 count: (i.data as UserView).number_of_comments,
347 nodes={commentsToFlatNodes(this.state.searchResponse.comments)}
350 enableDownvotes={this.state.site.enable_downvotes}
358 {this.state.searchResponse.posts.map(post => (
364 enableDownvotes={this.state.site.enable_downvotes}
365 enableNsfw={this.state.site.enable_nsfw}
374 // Todo possibly create UserListing and CommunityListing
378 {this.state.searchResponse.communities.map(community => (
380 <div class="col-12">{this.communityListing(community)}</div>
387 communityListing(community: Community) {
391 <CommunityLink community={community} />
393 <span>{` - ${community.title} -
394 ${i18n.t('number_of_subscribers', {
395 count: community.number_of_subscribers,
405 {this.state.searchResponse.users.map(user => (
417 <span>{` - ${i18n.t('number_of_comments', {
418 count: user.number_of_comments,
430 {this.state.page > 1 && (
432 class="btn btn-secondary mr-1"
433 onClick={linkEvent(this, this.prevPage)}
439 {this.resultsCount() > 0 && (
441 class="btn btn-secondary"
442 onClick={linkEvent(this, this.nextPage)}
451 resultsCount(): number {
452 let res = this.state.searchResponse;
455 res.comments.length +
456 res.communities.length +
461 nextPage(i: Search) {
462 i.updateUrl({ page: i.state.page + 1 });
465 prevPage(i: Search) {
466 i.updateUrl({ page: i.state.page - 1 });
470 let form: SearchForm = {
472 type_: this.state.type_,
473 sort: this.state.sort,
474 page: this.state.page,
478 if (this.state.q != '') {
479 WebSocketService.Instance.search(form);
483 handleSortChange(val: SortType) {
484 this.updateUrl({ sort: val, page: 1 });
487 handleTypeChange(i: Search, event: any) {
489 type_: SearchType[event.target.value],
494 handleSearchSubmit(i: Search, event: any) {
495 event.preventDefault();
497 q: i.state.searchText,
498 type_: i.state.type_,
504 handleQChange(i: Search, event: any) {
505 i.setState({ searchText: event.target.value });
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}`
518 parseMessage(msg: WebSocketJsonResponse) {
520 let res = wsJsonToRes(msg);
522 toast(i18n.t(msg.error), 'danger');
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);