1 import { Component, linkEvent } from "inferno";
2 import { Subscription } from "rxjs";
18 ListCommunitiesResponse,
21 } from "lemmy-js-client";
22 import { WebSocketService } from "../services";
26 routeSearchTypeToEnum,
30 createPostLikeFindRes,
39 restoreScrollPosition,
40 routeListingTypeToEnum,
49 capitalizeFirstLetter,
53 import { PostListing } from "./post-listing";
54 import { HtmlTags } from "./html-tags";
55 import { Spinner } from "./icon";
56 import { PersonListing } from "./person-listing";
57 import { CommunityLink } from "./community-link";
58 import { SortSelect } from "./sort-select";
59 import { ListingTypeSelect } from "./listing-type-select";
60 import { CommentNodes } from "./comment-nodes";
61 import { i18n } from "../i18next";
62 import { InitialFetchRequest } from "shared/interfaces";
66 Choices = require("choices.js");
69 interface SearchProps {
73 listingType: ListingType;
79 interface SearchState {
83 listingType: ListingType;
87 searchResponse: SearchResponse;
88 communities: CommunityView[];
89 creator?: PersonViewSafe;
99 listingType?: ListingType;
100 communityId?: number;
105 export class Search extends Component<any, SearchState> {
106 private isoData = setIsoData(this.context);
107 private communityChoices: any;
108 private creatorChoices: any;
109 private subscription: Subscription;
110 private emptyState: SearchState = {
111 q: Search.getSearchQueryFromProps(this.props.match.params.q),
112 type_: Search.getSearchTypeFromProps(this.props.match.params.type),
113 sort: Search.getSortTypeFromProps(this.props.match.params.sort),
114 listingType: Search.getListingTypeFromProps(
115 this.props.match.params.listing_type
117 page: Search.getPageFromProps(this.props.match.params.page),
118 searchText: Search.getSearchQueryFromProps(this.props.match.params.q),
119 communityId: Search.getCommunityIdFromProps(
120 this.props.match.params.community_id
122 creatorId: Search.getCreatorIdFromProps(this.props.match.params.creator_id),
131 site: this.isoData.site_res.site_view.site,
135 static getSearchQueryFromProps(q: string): string {
136 return decodeURIComponent(q) || "";
139 static getSearchTypeFromProps(type_: string): SearchType {
140 return type_ ? routeSearchTypeToEnum(type_) : SearchType.All;
143 static getSortTypeFromProps(sort: string): SortType {
144 return sort ? routeSortTypeToEnum(sort) : SortType.TopAll;
147 static getListingTypeFromProps(listingType: string): ListingType {
148 return listingType ? routeListingTypeToEnum(listingType) : ListingType.All;
151 static getCommunityIdFromProps(id: string): number {
152 return id ? Number(id) : 0;
155 static getCreatorIdFromProps(id: string): number {
156 return id ? Number(id) : 0;
159 static getPageFromProps(page: string): number {
160 return page ? Number(page) : 1;
163 constructor(props: any, context: any) {
164 super(props, context);
166 this.state = this.emptyState;
167 this.handleSortChange = this.handleSortChange.bind(this);
168 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
170 this.parseMessage = this.parseMessage.bind(this);
171 this.subscription = wsSubscribe(this.parseMessage);
173 // Only fetch the data if coming from another route
174 if (this.isoData.path == this.context.router.route.match.url) {
175 let singleOrMultipleCommunities = this.isoData.routeData[0];
176 if (singleOrMultipleCommunities.communities) {
177 this.state.communities = this.isoData.routeData[0].communities;
179 this.state.communities = [this.isoData.routeData[0].community_view];
182 let creator = this.isoData.routeData[1];
183 if (creator?.person_view) {
184 this.state.creator = this.isoData.routeData[1].person_view;
186 if (this.state.q != "") {
187 this.state.searchResponse = this.isoData.routeData[2];
188 this.state.loading = false;
193 this.fetchCommunities();
198 componentWillUnmount() {
199 this.subscription.unsubscribe();
200 saveScrollPosition(this.context);
203 componentDidMount() {
204 this.setupCommunityFilter();
205 this.setupCreatorFilter();
208 static getDerivedStateFromProps(props: any): SearchProps {
210 q: Search.getSearchQueryFromProps(props.match.params.q),
211 type_: Search.getSearchTypeFromProps(props.match.params.type),
212 sort: Search.getSortTypeFromProps(props.match.params.sort),
213 listingType: Search.getListingTypeFromProps(
214 props.match.params.listing_type
216 communityId: Search.getCommunityIdFromProps(
217 props.match.params.community_id
219 creatorId: Search.getCreatorIdFromProps(props.match.params.creator_id),
220 page: Search.getPageFromProps(props.match.params.page),
225 let listCommunitiesForm: ListCommunities = {
226 type_: ListingType.All,
227 sort: SortType.TopAll,
229 auth: authField(false),
231 WebSocketService.Instance.send(
232 wsClient.listCommunities(listCommunitiesForm)
236 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
237 let pathSplit = req.path.split("/");
238 let promises: Promise<any>[] = [];
240 let communityId = this.getCommunityIdFromProps(pathSplit[11]);
241 if (communityId !== 0) {
242 let getCommunityForm: GetCommunity = {
245 setOptionalAuth(getCommunityForm, req.auth);
246 promises.push(req.client.getCommunity(getCommunityForm));
248 let listCommunitiesForm: ListCommunities = {
249 type_: ListingType.All,
250 sort: SortType.TopAll,
253 setOptionalAuth(listCommunitiesForm, req.auth);
254 promises.push(req.client.listCommunities(listCommunitiesForm));
257 let creatorId = this.getCreatorIdFromProps(pathSplit[13]);
258 if (creatorId !== 0) {
259 let getCreatorForm: GetPersonDetails = {
260 person_id: creatorId,
262 setOptionalAuth(getCreatorForm, req.auth);
263 promises.push(req.client.getPersonDetails(getCreatorForm));
265 promises.push(Promise.resolve());
268 let form: SearchForm = {
269 q: this.getSearchQueryFromProps(pathSplit[3]),
270 type_: this.getSearchTypeFromProps(pathSplit[5]),
271 sort: this.getSortTypeFromProps(pathSplit[7]),
272 listing_type: this.getListingTypeFromProps(pathSplit[9]),
273 page: this.getPageFromProps(pathSplit[15]),
276 if (communityId !== 0) {
277 form.community_id = communityId;
279 if (creatorId !== 0) {
280 form.creator_id = creatorId;
282 setOptionalAuth(form, req.auth);
285 promises.push(req.client.search(form));
291 componentDidUpdate(_: any, lastState: SearchState) {
293 lastState.q !== this.state.q ||
294 lastState.type_ !== this.state.type_ ||
295 lastState.sort !== this.state.sort ||
296 lastState.listingType !== this.state.listingType ||
297 lastState.communityId !== this.state.communityId ||
298 lastState.creatorId !== this.state.creatorId ||
299 lastState.page !== this.state.page
301 this.setState({ loading: true, searchText: this.state.q });
306 get documentTitle(): string {
308 return `${i18n.t("search")} - ${this.state.q} - ${this.state.site.name}`;
310 return `${i18n.t("search")} - ${this.state.site.name}`;
316 <div class="container">
318 title={this.documentTitle}
319 path={this.context.router.route.match.url}
321 <h5>{i18n.t("search")}</h5>
324 {this.state.type_ == SearchType.All && this.all()}
325 {this.state.type_ == SearchType.Comments && this.comments()}
326 {this.state.type_ == SearchType.Posts && this.posts()}
327 {this.state.type_ == SearchType.Communities && this.communities()}
328 {this.state.type_ == SearchType.Users && this.users()}
329 {this.resultsCount() == 0 && <span>{i18n.t("no_results")}</span>}
339 onSubmit={linkEvent(this, this.handleSearchSubmit)}
343 class="form-control mr-2 mb-2"
344 value={this.state.searchText}
345 placeholder={`${i18n.t("search")}...`}
346 aria-label={i18n.t("search")}
347 onInput={linkEvent(this, this.handleQChange)}
351 <button type="submit" class="btn btn-secondary mr-2 mb-2">
352 {this.state.loading ? <Spinner /> : <span>{i18n.t("search")}</span>}
360 <div className="mb-2">
362 value={this.state.type_}
363 onChange={linkEvent(this, this.handleTypeChange)}
364 class="custom-select w-auto mb-2"
365 aria-label={i18n.t("type")}
367 <option disabled aria-hidden="true">
370 <option value={SearchType.All}>{i18n.t("all")}</option>
371 <option value={SearchType.Comments}>{i18n.t("comments")}</option>
372 <option value={SearchType.Posts}>{i18n.t("posts")}</option>
373 <option value={SearchType.Communities}>
374 {i18n.t("communities")}
376 <option value={SearchType.Users}>{i18n.t("users")}</option>
380 type_={this.state.listingType}
381 showLocal={showLocal(this.isoData)}
382 onChange={this.handleListingTypeChange}
387 sort={this.state.sort}
388 onChange={this.handleSortChange}
393 <div class="form-row">
394 {this.state.communities.length > 0 && this.communityFilter()}
395 {this.creatorFilter()}
404 data: CommentView | PostView | CommunityView | PersonViewSafe;
407 let comments = this.state.searchResponse.comments.map(e => {
408 return { type_: "comments", data: e, published: e.comment.published };
410 let posts = this.state.searchResponse.posts.map(e => {
411 return { type_: "posts", data: e, published: e.post.published };
413 let communities = this.state.searchResponse.communities.map(e => {
415 type_: "communities",
417 published: e.community.published,
420 let users = this.state.searchResponse.users.map(e => {
421 return { type_: "users", data: e, published: e.person.published };
424 combined.push(...comments);
425 combined.push(...posts);
426 combined.push(...communities);
427 combined.push(...users);
430 if (this.state.sort == SortType.New) {
431 combined.sort((a, b) => b.published.localeCompare(a.published));
435 ((b.data as CommentView | PostView).counts.score |
436 (b.data as CommunityView).counts.subscribers |
437 (b.data as PersonViewSafe).counts.comment_score) -
438 ((a.data as CommentView | PostView).counts.score |
439 (a.data as CommunityView).counts.subscribers |
440 (a.data as PersonViewSafe).counts.comment_score)
449 {i.type_ == "posts" && (
451 key={(i.data as PostView).post.id}
452 post_view={i.data as PostView}
454 enableDownvotes={this.state.site.enable_downvotes}
455 enableNsfw={this.state.site.enable_nsfw}
458 {i.type_ == "comments" && (
460 key={(i.data as CommentView).comment.id}
461 nodes={[{ comment_view: i.data as CommentView }]}
464 enableDownvotes={this.state.site.enable_downvotes}
467 {i.type_ == "communities" && (
468 <div>{this.communityListing(i.data as CommunityView)}</div>
470 {i.type_ == "users" && (
471 <div>{this.userListing(i.data as PersonViewSafe)}</div>
483 nodes={commentsToFlatNodes(this.state.searchResponse.comments)}
486 enableDownvotes={this.state.site.enable_downvotes}
494 {this.state.searchResponse.posts.map(post => (
500 enableDownvotes={this.state.site.enable_downvotes}
501 enableNsfw={this.state.site.enable_nsfw}
513 {this.state.searchResponse.communities.map(community => (
515 <div class="col-12">{this.communityListing(community)}</div>
522 communityListing(community_view: CommunityView) {
526 <CommunityLink community={community_view.community} />
529 ${i18n.t("number_of_subscribers", {
530 count: community_view.counts.subscribers,
537 userListing(person_view: PersonViewSafe) {
540 <PersonListing person={person_view.person} showApubName />
542 <span>{` - ${i18n.t("number_of_comments", {
543 count: person_view.counts.comment_count,
551 {this.state.searchResponse.users.map(user => (
553 <div class="col-12">{this.userListing(user)}</div>
562 <div class="form-group col-sm-6">
563 <label class="col-form-label" htmlFor="community-filter">
564 {i18n.t("community")}
569 id="community-filter"
570 value={this.state.communityId}
572 <option value="0">{i18n.t("all")}</option>
573 {this.state.communities.map(cv => (
574 <option value={cv.community.id}>{communitySelectName(cv)}</option>
584 <div class="form-group col-sm-6">
585 <label class="col-form-label" htmlFor="creator-filter">
586 {capitalizeFirstLetter(i18n.t("creator"))}
592 value={this.state.creatorId}
594 <option value="0">{i18n.t("all")}</option>
595 {this.state.creator && (
596 <option value={this.state.creator.person.id}>
597 {personSelectName(this.state.creator)}
609 {this.state.page > 1 && (
611 class="btn btn-secondary mr-1"
612 onClick={linkEvent(this, this.prevPage)}
618 {this.resultsCount() > 0 && (
620 class="btn btn-secondary"
621 onClick={linkEvent(this, this.nextPage)}
630 resultsCount(): number {
631 let res = this.state.searchResponse;
634 res.comments.length +
635 res.communities.length +
640 nextPage(i: Search) {
641 i.updateUrl({ page: i.state.page + 1 });
644 prevPage(i: Search) {
645 i.updateUrl({ page: i.state.page - 1 });
649 let form: SearchForm = {
651 type_: this.state.type_,
652 sort: this.state.sort,
653 listing_type: this.state.listingType,
654 page: this.state.page,
656 auth: authField(false),
658 if (this.state.communityId !== 0) {
659 form.community_id = this.state.communityId;
661 if (this.state.creatorId !== 0) {
662 form.creator_id = this.state.creatorId;
665 if (this.state.q != "") {
666 WebSocketService.Instance.send(wsClient.search(form));
670 setupCommunityFilter() {
672 let selectId: any = document.getElementById("community-filter");
674 this.communityChoices = new Choices(selectId, choicesConfig);
675 this.communityChoices.passedElement.element.addEventListener(
678 this.handleCommunityFilterChange(Number(e.detail.choice.value));
682 this.communityChoices.passedElement.element.addEventListener(
684 debounce(async (e: any) => {
685 let communities = (await fetchCommunities(e.detail.value))
687 let choices = communities.map(cv => communityToChoice(cv));
688 choices.unshift({ value: "0", label: i18n.t("all") });
689 this.communityChoices.setChoices(choices, "value", "label", true);
697 setupCreatorFilter() {
699 let selectId: any = document.getElementById("creator-filter");
701 this.creatorChoices = new Choices(selectId, choicesConfig);
702 this.creatorChoices.passedElement.element.addEventListener(
705 this.handleCreatorFilterChange(Number(e.detail.choice.value));
709 this.creatorChoices.passedElement.element.addEventListener(
711 debounce(async (e: any) => {
712 let creators = (await fetchUsers(e.detail.value)).users;
713 let choices = creators.map(pvs => personToChoice(pvs));
714 choices.unshift({ value: "0", label: i18n.t("all") });
715 this.creatorChoices.setChoices(choices, "value", "label", true);
723 handleSortChange(val: SortType) {
724 this.updateUrl({ sort: val, page: 1 });
727 handleTypeChange(i: Search, event: any) {
729 type_: SearchType[event.target.value],
734 handleListingTypeChange(val: ListingType) {
741 handleCommunityFilterChange(communityId: number) {
748 handleCreatorFilterChange(creatorId: number) {
755 handleSearchSubmit(i: Search, event: any) {
756 event.preventDefault();
758 q: i.state.searchText,
759 type_: i.state.type_,
760 listingType: i.state.listingType,
761 communityId: i.state.communityId,
762 creatorId: i.state.creatorId,
768 handleQChange(i: Search, event: any) {
769 i.setState({ searchText: event.target.value });
772 updateUrl(paramUpdates: UrlParams) {
773 const qStr = paramUpdates.q || this.state.q;
774 const qStrEncoded = encodeURIComponent(qStr);
775 const typeStr = paramUpdates.type_ || this.state.type_;
776 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
777 const sortStr = paramUpdates.sort || this.state.sort;
779 paramUpdates.communityId == 0
781 : paramUpdates.communityId || this.state.communityId;
783 paramUpdates.creatorId == 0
785 : paramUpdates.creatorId || this.state.creatorId;
786 const page = paramUpdates.page || this.state.page;
787 this.props.history.push(
788 `/search/q/${qStrEncoded}/type/${typeStr}/sort/${sortStr}/listing_type/${listingTypeStr}/community_id/${communityId}/creator_id/${creatorId}/page/${page}`
792 parseMessage(msg: any) {
794 let op = wsUserOp(msg);
796 toast(i18n.t(msg.error), "danger");
798 } else if (op == UserOperation.Search) {
799 let data = wsJsonToRes<SearchResponse>(msg).data;
800 this.state.searchResponse = data;
801 this.state.loading = false;
802 window.scrollTo(0, 0);
803 this.setState(this.state);
804 restoreScrollPosition(this.context);
805 } else if (op == UserOperation.CreateCommentLike) {
806 let data = wsJsonToRes<CommentResponse>(msg).data;
807 createCommentLikeRes(
809 this.state.searchResponse.comments
811 this.setState(this.state);
812 } else if (op == UserOperation.CreatePostLike) {
813 let data = wsJsonToRes<PostResponse>(msg).data;
814 createPostLikeFindRes(data.post_view, this.state.searchResponse.posts);
815 this.setState(this.state);
816 } else if (op == UserOperation.ListCommunities) {
817 let data = wsJsonToRes<ListCommunitiesResponse>(msg).data;
818 this.state.communities = data.communities;
819 this.setState(this.state);
820 this.setupCommunityFilter();