14 import { restoreScrollPosition, saveScrollPosition } from "@utils/browser";
16 capitalizeFirstLetter,
23 } from "@utils/helpers";
24 import type { QueryParams } from "@utils/types";
25 import { Choice, RouteDataResponse } from "@utils/types";
26 import type { NoOptionI18nKeys } from "i18next";
27 import { Component, linkEvent } from "inferno";
34 GetPersonDetailsResponse,
37 ListCommunitiesResponse,
42 ResolveObjectResponse,
47 } from "lemmy-js-client";
48 import { fetchLimit } from "../config";
49 import { CommentViewType, InitialFetchRequest } from "../interfaces";
50 import { FirstLoadService, I18NextService } from "../services";
51 import { HttpService, RequestState } from "../services/HttpService";
52 import { CommentNodes } from "./comment/comment-nodes";
53 import { HtmlTags } from "./common/html-tags";
54 import { Spinner } from "./common/icon";
55 import { ListingTypeSelect } from "./common/listing-type-select";
56 import { Paginator } from "./common/paginator";
57 import { SearchableSelect } from "./common/searchable-select";
58 import { SortSelect } from "./common/sort-select";
59 import { CommunityLink } from "./community/community-link";
60 import { PersonListing } from "./person/person-listing";
61 import { PostListing } from "./post/post-listing";
63 interface SearchProps {
67 listingType: ListingType;
68 communityId?: number | null;
69 creatorId?: number | null;
73 type SearchData = RouteDataResponse<{
74 communityResponse: GetCommunityResponse;
75 listCommunitiesResponse: ListCommunitiesResponse;
76 creatorDetailsResponse: GetPersonDetailsResponse;
77 searchResponse: SearchResponse;
78 resolveObjectResponse: ResolveObjectResponse;
81 type FilterType = "creator" | "community";
83 interface SearchState {
84 searchRes: RequestState<SearchResponse>;
85 resolveObjectRes: RequestState<ResolveObjectResponse>;
86 creatorDetailsRes: RequestState<GetPersonDetailsResponse>;
87 communitiesRes: RequestState<ListCommunitiesResponse>;
88 communityRes: RequestState<GetCommunityResponse>;
89 siteRes: GetSiteResponse;
91 communitySearchOptions: Choice[];
92 creatorSearchOptions: Choice[];
93 searchCreatorLoading: boolean;
94 searchCommunitiesLoading: boolean;
95 isIsomorphic: boolean;
100 data: CommentView | PostView | CommunityView | PersonView;
104 const defaultSearchType = "All";
105 const defaultSortType = "TopAll";
106 const defaultListingType = "All";
108 const searchTypes = ["All", "Comments", "Posts", "Communities", "Users", "Url"];
110 const getSearchQueryParams = () =>
111 getQueryParams<SearchProps>({
112 q: getSearchQueryFromQuery,
113 type: getSearchTypeFromQuery,
114 sort: getSortTypeFromQuery,
115 listingType: getListingTypeFromQuery,
116 communityId: getIdFromString,
117 creatorId: getIdFromString,
118 page: getPageFromString,
121 const getSearchQueryFromQuery = (q?: string): string | undefined =>
122 q ? decodeURIComponent(q) : undefined;
124 function getSearchTypeFromQuery(type_?: string): SearchType {
125 return type_ ? (type_ as SearchType) : defaultSearchType;
128 function getSortTypeFromQuery(sort?: string): SortType {
129 return sort ? (sort as SortType) : defaultSortType;
132 function getListingTypeFromQuery(listingType?: string): ListingType {
133 return listingType ? (listingType as ListingType) : defaultListingType;
136 function postViewToCombined(data: PostView): Combined {
140 published: data.post.published,
144 function commentViewToCombined(data: CommentView): Combined {
148 published: data.comment.published,
152 function communityViewToCombined(data: CommunityView): Combined {
154 type_: "communities",
156 published: data.community.published,
160 function personViewSafeToCombined(data: PersonView): Combined {
164 published: data.person.published,
176 filterType: FilterType;
178 onSearch: (text: string) => void;
179 onChange: (choice: Choice) => void;
180 value?: number | null;
184 <div className="mb-3 col-sm-6">
185 <label className="col-form-label me-2" htmlFor={`${filterType}-filter`}>
186 {capitalizeFirstLetter(I18NextService.i18n.t(filterType))}
189 id={`${filterType}-filter`}
192 label: I18NextService.i18n.t("all"),
205 const communityListing = ({
207 counts: { subscribers },
210 <CommunityLink community={community} />,
212 "number_of_subscribers"
215 const personListing = ({ person, counts: { comment_count } }: PersonView) =>
217 <PersonListing person={person} showApubName />,
223 listing: JSX.ElementClass,
225 translationKey: "number_of_comments" | "number_of_subscribers"
229 <span>{listing}</span>
230 <span>{` - ${I18NextService.i18n.t(translationKey, {
231 count: Number(count),
232 formattedCount: numToSI(count),
238 export class Search extends Component<any, SearchState> {
239 private isoData = setIsoData<SearchData>(this.context);
241 state: SearchState = {
242 resolveObjectRes: { state: "empty" },
243 creatorDetailsRes: { state: "empty" },
244 communitiesRes: { state: "empty" },
245 communityRes: { state: "empty" },
246 siteRes: this.isoData.site_res,
247 creatorSearchOptions: [],
248 communitySearchOptions: [],
249 searchRes: { state: "empty" },
250 searchCreatorLoading: false,
251 searchCommunitiesLoading: false,
255 constructor(props: any, context: any) {
256 super(props, context);
258 this.handleSortChange = this.handleSortChange.bind(this);
259 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
260 this.handlePageChange = this.handlePageChange.bind(this);
261 this.handleCommunityFilterChange =
262 this.handleCommunityFilterChange.bind(this);
263 this.handleCreatorFilterChange = this.handleCreatorFilterChange.bind(this);
265 const { q } = getSearchQueryParams();
272 // Only fetch the data if coming from another route
273 if (FirstLoadService.isFirstLoad) {
275 communityResponse: communityRes,
276 creatorDetailsResponse: creatorDetailsRes,
277 listCommunitiesResponse: communitiesRes,
278 resolveObjectResponse: resolveObjectRes,
279 searchResponse: searchRes,
280 } = this.isoData.routeData;
287 if (creatorDetailsRes?.state === "success") {
290 creatorSearchOptions:
291 creatorDetailsRes?.state === "success"
292 ? [personToChoice(creatorDetailsRes.data.person_view)]
298 if (communitiesRes?.state === "success") {
305 if (communityRes?.state === "success") {
317 if (searchRes?.state === "success") {
324 if (resolveObjectRes?.state === "success") {
334 async componentDidMount() {
336 !(this.state.isIsomorphic || this.props.history.location.state?.searched)
338 const promises = [this.fetchCommunities()];
339 if (this.state.searchText) {
340 promises.push(this.search());
343 await Promise.all(promises);
347 async fetchCommunities() {
348 this.setState({ communitiesRes: { state: "loading" } });
350 communitiesRes: await HttpService.client.listCommunities({
351 type_: defaultListingType,
352 sort: defaultSortType,
359 componentWillUnmount() {
360 saveScrollPosition(this.context);
363 static async fetchInitialData({
366 query: { communityId, creatorId, q, type, sort, listingType, page },
367 }: InitialFetchRequest<QueryParams<SearchProps>>): Promise<SearchData> {
368 const community_id = getIdFromString(communityId);
369 let communityResponse: RequestState<GetCommunityResponse> = {
372 let listCommunitiesResponse: RequestState<ListCommunitiesResponse> = {
376 const getCommunityForm: GetCommunity = {
381 communityResponse = await client.getCommunity(getCommunityForm);
383 const listCommunitiesForm: ListCommunities = {
384 type_: defaultListingType,
385 sort: defaultSortType,
390 listCommunitiesResponse = await client.listCommunities(
395 const creator_id = getIdFromString(creatorId);
396 let creatorDetailsResponse: RequestState<GetPersonDetailsResponse> = {
400 const getCreatorForm: GetPersonDetails = {
401 person_id: creator_id,
405 creatorDetailsResponse = await client.getPersonDetails(getCreatorForm);
408 const query = getSearchQueryFromQuery(q);
410 let searchResponse: RequestState<SearchResponse> = { state: "empty" };
411 let resolveObjectResponse: RequestState<ResolveObjectResponse> = {
416 const form: SearchForm = {
420 type_: getSearchTypeFromQuery(type),
421 sort: getSortTypeFromQuery(sort),
422 listing_type: getListingTypeFromQuery(listingType),
423 page: getPageFromString(page),
429 searchResponse = await client.search(form);
431 const resolveObjectForm: ResolveObject = {
435 resolveObjectResponse = await client.resolveObject(resolveObjectForm);
442 creatorDetailsResponse,
443 listCommunitiesResponse,
444 resolveObjectResponse,
449 get documentTitle(): string {
450 const { q } = getSearchQueryParams();
451 const name = this.state.siteRes.site_view.site.name;
452 return `${I18NextService.i18n.t("search")} - ${q ? `${q} - ` : ""}${name}`;
456 const { type, page } = getSearchQueryParams();
459 <div className="search container-lg">
461 title={this.documentTitle}
462 path={this.context.router.route.match.url}
464 <h5>{I18NextService.i18n.t("search")}</h5>
467 {this.displayResults(type)}
468 {this.resultsCount === 0 &&
469 this.state.searchRes.state === "success" && (
470 <span>{I18NextService.i18n.t("no_results")}</span>
472 <Paginator page={page} onChange={this.handlePageChange} />
477 displayResults(type: SearchType) {
482 return this.comments;
487 return this.communities;
497 <form className="row" onSubmit={linkEvent(this, this.handleSearchSubmit)}>
498 <div className="col-auto">
501 className="form-control me-2 mb-2 col-sm-8"
502 value={this.state.searchText}
503 placeholder={`${I18NextService.i18n.t("search")}...`}
504 aria-label={I18NextService.i18n.t("search")}
505 onInput={linkEvent(this, this.handleQChange)}
510 <div className="col-auto">
511 <button type="submit" className="btn btn-secondary mb-2">
512 {this.state.searchRes.state === "loading" ? (
515 <span>{I18NextService.i18n.t("search")}</span>
524 const { type, listingType, sort, communityId, creatorId } =
525 getSearchQueryParams();
527 communitySearchOptions,
528 creatorSearchOptions,
529 searchCommunitiesLoading,
530 searchCreatorLoading,
534 const hasCommunities =
535 communitiesRes.state == "success" &&
536 communitiesRes.data.communities.length > 0;
539 <div className="mb-2">
542 onChange={linkEvent(this, this.handleTypeChange)}
543 className="form-select d-inline-block w-auto mb-2"
544 aria-label={I18NextService.i18n.t("type")}
546 <option disabled aria-hidden="true">
547 {I18NextService.i18n.t("type")}
549 {searchTypes.map(option => (
550 <option value={option} key={option}>
551 {I18NextService.i18n.t(
552 option.toString().toLowerCase() as NoOptionI18nKeys
557 <span className="ms-2">
560 showLocal={showLocal(this.isoData)}
562 onChange={this.handleListingTypeChange}
565 <span className="ms-2">
568 onChange={this.handleSortChange}
573 <div className="row">
576 filterType="community"
577 onChange={this.handleCommunityFilterChange}
578 onSearch={this.handleCommunitySearch}
579 options={communitySearchOptions}
581 loading={searchCommunitiesLoading}
586 onChange={this.handleCreatorFilterChange}
587 onSearch={this.handleCreatorSearch}
588 options={creatorSearchOptions}
590 loading={searchCreatorLoading}
597 buildCombined(): Combined[] {
598 const combined: Combined[] = [];
600 resolveObjectRes: resolveObjectResponse,
601 searchRes: searchResponse,
604 // Push the possible resolve / federated objects first
605 if (resolveObjectResponse.state == "success") {
606 const { comment, post, community, person } = resolveObjectResponse.data;
609 combined.push(commentViewToCombined(comment));
612 combined.push(postViewToCombined(post));
615 combined.push(communityViewToCombined(community));
618 combined.push(personViewSafeToCombined(person));
622 // Push the search results
623 if (searchResponse.state === "success") {
624 const { comments, posts, communities, users } = searchResponse.data;
628 ...(comments?.map(commentViewToCombined) ?? []),
629 ...(posts?.map(postViewToCombined) ?? []),
630 ...(communities?.map(communityViewToCombined) ?? []),
631 ...(users?.map(personViewSafeToCombined) ?? []),
636 const { sort } = getSearchQueryParams();
639 if (sort === "New") {
640 combined.sort((a, b) => b.published.localeCompare(a.published));
642 combined.sort((a, b) =>
644 ((b.data as CommentView | PostView).counts.score |
645 (b.data as CommunityView).counts.subscribers |
646 (b.data as PersonView).counts.comment_score) -
647 ((a.data as CommentView | PostView).counts.score |
648 (a.data as CommunityView).counts.subscribers |
649 (a.data as PersonView).counts.comment_score)
658 const combined = this.buildCombined();
663 <div key={i.published} className="row">
664 <div className="col-12">
665 {i.type_ === "posts" && (
667 key={(i.data as PostView).post.id}
668 post_view={i.data as PostView}
670 enableDownvotes={enableDownvotes(this.state.siteRes)}
671 enableNsfw={enableNsfw(this.state.siteRes)}
672 allLanguages={this.state.siteRes.all_languages}
673 siteLanguages={this.state.siteRes.discussion_languages}
675 // All of these are unused, since its view only
676 onPostEdit={() => {}}
677 onPostVote={() => {}}
678 onPostReport={() => {}}
679 onBlockPerson={() => {}}
680 onLockPost={() => {}}
681 onDeletePost={() => {}}
682 onRemovePost={() => {}}
683 onSavePost={() => {}}
684 onFeaturePost={() => {}}
685 onPurgePerson={() => {}}
686 onPurgePost={() => {}}
687 onBanPersonFromCommunity={() => {}}
688 onBanPerson={() => {}}
689 onAddModToCommunity={() => {}}
690 onAddAdmin={() => {}}
691 onTransferCommunity={() => {}}
694 {i.type_ === "comments" && (
696 key={(i.data as CommentView).comment.id}
699 comment_view: i.data as CommentView,
704 viewType={CommentViewType.Flat}
708 enableDownvotes={enableDownvotes(this.state.siteRes)}
709 allLanguages={this.state.siteRes.all_languages}
710 siteLanguages={this.state.siteRes.discussion_languages}
711 // All of these are unused, since its viewonly
713 onSaveComment={() => {}}
714 onBlockPerson={() => {}}
715 onDeleteComment={() => {}}
716 onRemoveComment={() => {}}
717 onCommentVote={() => {}}
718 onCommentReport={() => {}}
719 onDistinguishComment={() => {}}
720 onAddModToCommunity={() => {}}
721 onAddAdmin={() => {}}
722 onTransferCommunity={() => {}}
723 onPurgeComment={() => {}}
724 onPurgePerson={() => {}}
725 onCommentReplyRead={() => {}}
726 onPersonMentionRead={() => {}}
727 onBanPersonFromCommunity={() => {}}
728 onBanPerson={() => {}}
729 onCreateComment={() => Promise.resolve({ state: "empty" })}
730 onEditComment={() => Promise.resolve({ state: "empty" })}
733 {i.type_ === "communities" && (
734 <div>{communityListing(i.data as CommunityView)}</div>
736 {i.type_ === "users" && (
737 <div>{personListing(i.data as PersonView)}</div>
748 searchRes: searchResponse,
749 resolveObjectRes: resolveObjectResponse,
753 searchResponse.state === "success" ? searchResponse.data.comments : [];
756 resolveObjectResponse.state === "success" &&
757 resolveObjectResponse.data.comment
759 comments.unshift(resolveObjectResponse.data.comment);
764 nodes={commentsToFlatNodes(comments)}
765 viewType={CommentViewType.Flat}
769 enableDownvotes={enableDownvotes(siteRes)}
770 allLanguages={siteRes.all_languages}
771 siteLanguages={siteRes.discussion_languages}
772 // All of these are unused, since its viewonly
774 onSaveComment={() => {}}
775 onBlockPerson={() => {}}
776 onDeleteComment={() => {}}
777 onRemoveComment={() => {}}
778 onCommentVote={() => {}}
779 onCommentReport={() => {}}
780 onDistinguishComment={() => {}}
781 onAddModToCommunity={() => {}}
782 onAddAdmin={() => {}}
783 onTransferCommunity={() => {}}
784 onPurgeComment={() => {}}
785 onPurgePerson={() => {}}
786 onCommentReplyRead={() => {}}
787 onPersonMentionRead={() => {}}
788 onBanPersonFromCommunity={() => {}}
789 onBanPerson={() => {}}
790 onCreateComment={() => Promise.resolve({ state: "empty" })}
791 onEditComment={() => Promise.resolve({ state: "empty" })}
798 searchRes: searchResponse,
799 resolveObjectRes: resolveObjectResponse,
803 searchResponse.state === "success" ? searchResponse.data.posts : [];
806 resolveObjectResponse.state === "success" &&
807 resolveObjectResponse.data.post
809 posts.unshift(resolveObjectResponse.data.post);
815 <div key={pv.post.id} className="row">
816 <div className="col-12">
820 enableDownvotes={enableDownvotes(siteRes)}
821 enableNsfw={enableNsfw(siteRes)}
822 allLanguages={siteRes.all_languages}
823 siteLanguages={siteRes.discussion_languages}
825 // All of these are unused, since its view only
826 onPostEdit={() => {}}
827 onPostVote={() => {}}
828 onPostReport={() => {}}
829 onBlockPerson={() => {}}
830 onLockPost={() => {}}
831 onDeletePost={() => {}}
832 onRemovePost={() => {}}
833 onSavePost={() => {}}
834 onFeaturePost={() => {}}
835 onPurgePerson={() => {}}
836 onPurgePost={() => {}}
837 onBanPersonFromCommunity={() => {}}
838 onBanPerson={() => {}}
839 onAddModToCommunity={() => {}}
840 onAddAdmin={() => {}}
841 onTransferCommunity={() => {}}
852 searchRes: searchResponse,
853 resolveObjectRes: resolveObjectResponse,
856 searchResponse.state === "success" ? searchResponse.data.communities : [];
859 resolveObjectResponse.state === "success" &&
860 resolveObjectResponse.data.community
862 communities.unshift(resolveObjectResponse.data.community);
867 {communities.map(cv => (
868 <div key={cv.community.id} className="row">
869 <div className="col-12">{communityListing(cv)}</div>
878 searchRes: searchResponse,
879 resolveObjectRes: resolveObjectResponse,
882 searchResponse.state === "success" ? searchResponse.data.users : [];
885 resolveObjectResponse.state === "success" &&
886 resolveObjectResponse.data.person
888 users.unshift(resolveObjectResponse.data.person);
894 <div key={pvs.person.id} className="row">
895 <div className="col-12">{personListing(pvs)}</div>
902 get resultsCount(): number {
903 const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
906 r.state === "success"
907 ? r.data.posts.length +
908 r.data.comments.length +
909 r.data.communities.length +
914 resolveRes.state === "success"
915 ? resolveRes.data.post ||
916 resolveRes.data.person ||
917 resolveRes.data.community ||
918 resolveRes.data.comment
923 return resObjCount + searchCount;
927 const auth = myAuth();
928 const { searchText: q } = this.state;
929 const { communityId, creatorId, type, sort, listingType, page } =
930 getSearchQueryParams();
933 this.setState({ searchRes: { state: "loading" } });
935 searchRes: await HttpService.client.search({
937 community_id: communityId ?? undefined,
938 creator_id: creatorId ?? undefined,
941 listing_type: listingType,
947 window.scrollTo(0, 0);
948 restoreScrollPosition(this.context);
951 this.setState({ resolveObjectRes: { state: "loading" } });
953 resolveObjectRes: await HttpService.client.resolveObject({
962 handleCreatorSearch = debounce(async (text: string) => {
963 const { creatorId } = getSearchQueryParams();
964 const { creatorSearchOptions } = this.state;
965 const newOptions: Choice[] = [];
967 this.setState({ searchCreatorLoading: true });
969 const selectedChoice = creatorSearchOptions.find(
970 choice => getIdFromString(choice.value) === creatorId
973 if (selectedChoice) {
974 newOptions.push(selectedChoice);
977 if (text.length > 0) {
978 newOptions.push(...(await fetchUsers(text)).map(personToChoice));
982 searchCreatorLoading: false,
983 creatorSearchOptions: newOptions,
987 handleCommunitySearch = debounce(async (text: string) => {
988 const { communityId } = getSearchQueryParams();
989 const { communitySearchOptions } = this.state;
991 searchCommunitiesLoading: true,
994 const newOptions: Choice[] = [];
996 const selectedChoice = communitySearchOptions.find(
997 choice => getIdFromString(choice.value) === communityId
1000 if (selectedChoice) {
1001 newOptions.push(selectedChoice);
1004 if (text.length > 0) {
1005 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
1009 searchCommunitiesLoading: false,
1010 communitySearchOptions: newOptions,
1014 handleSortChange(sort: SortType) {
1015 this.updateUrl({ sort, page: 1 });
1018 handleTypeChange(i: Search, event: any) {
1019 const type = event.target.value as SearchType;
1027 handlePageChange(page: number) {
1028 this.updateUrl({ page });
1031 handleListingTypeChange(listingType: ListingType) {
1038 handleCommunityFilterChange({ value }: Choice) {
1040 communityId: getIdFromString(value) ?? null,
1045 handleCreatorFilterChange({ value }: Choice) {
1047 creatorId: getIdFromString(value) ?? null,
1052 handleSearchSubmit(i: Search, event: any) {
1053 event.preventDefault();
1056 q: i.state.searchText,
1061 handleQChange(i: Search, event: any) {
1062 i.setState({ searchText: event.target.value });
1073 }: Partial<SearchProps>) {
1077 listingType: urlListingType,
1078 communityId: urlCommunityId,
1080 creatorId: urlCreatorId,
1082 } = getSearchQueryParams();
1084 let query = q ?? this.state.searchText ?? urlQ;
1086 if (query && query.length > 0) {
1087 query = encodeURIComponent(query);
1090 const queryParams: QueryParams<SearchProps> = {
1092 type: type ?? urlType,
1093 listingType: listingType ?? urlListingType,
1094 communityId: getUpdatedSearchId(communityId, urlCommunityId),
1095 creatorId: getUpdatedSearchId(creatorId, urlCreatorId),
1096 page: (page ?? urlPage).toString(),
1097 sort: sort ?? urlSort,
1100 this.props.history.push(`/search${getQueryString(queryParams)}`, {
1104 await this.search();