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="col-sm-6">
185 <label className="mb-1" 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 />,
219 "number_of_comments",
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() {
335 if (!this.state.isIsomorphic) {
336 const promises = [this.fetchCommunities()];
337 if (this.state.searchText) {
338 promises.push(this.search());
341 await Promise.all(promises);
345 async fetchCommunities() {
346 this.setState({ communitiesRes: { state: "loading" } });
348 communitiesRes: await HttpService.client.listCommunities({
349 type_: defaultListingType,
350 sort: defaultSortType,
357 componentWillUnmount() {
358 saveScrollPosition(this.context);
361 static async fetchInitialData({
364 query: { communityId, creatorId, q, type, sort, listingType, page },
365 }: InitialFetchRequest<QueryParams<SearchProps>>): Promise<SearchData> {
366 const community_id = getIdFromString(communityId);
367 let communityResponse: RequestState<GetCommunityResponse> = {
370 let listCommunitiesResponse: RequestState<ListCommunitiesResponse> = {
374 const getCommunityForm: GetCommunity = {
379 communityResponse = await client.getCommunity(getCommunityForm);
381 const listCommunitiesForm: ListCommunities = {
382 type_: defaultListingType,
383 sort: defaultSortType,
388 listCommunitiesResponse = await client.listCommunities(
393 const creator_id = getIdFromString(creatorId);
394 let creatorDetailsResponse: RequestState<GetPersonDetailsResponse> = {
398 const getCreatorForm: GetPersonDetails = {
399 person_id: creator_id,
403 creatorDetailsResponse = await client.getPersonDetails(getCreatorForm);
406 const query = getSearchQueryFromQuery(q);
408 let searchResponse: RequestState<SearchResponse> = { state: "empty" };
409 let resolveObjectResponse: RequestState<ResolveObjectResponse> = {
414 const form: SearchForm = {
418 type_: getSearchTypeFromQuery(type),
419 sort: getSortTypeFromQuery(sort),
420 listing_type: getListingTypeFromQuery(listingType),
421 page: getPageFromString(page),
427 searchResponse = await client.search(form);
429 const resolveObjectForm: ResolveObject = {
433 resolveObjectResponse = await HttpService.silent_client.resolveObject(
437 // If we return this object with a state of failed, the catch-all-handler will redirect
438 // to an error page, so we ignore it by covering up the error with the empty state.
439 if (resolveObjectResponse.state === "failed") {
440 resolveObjectResponse = { state: "empty" };
448 creatorDetailsResponse,
449 listCommunitiesResponse,
450 resolveObjectResponse,
455 get documentTitle(): string {
456 const { q } = getSearchQueryParams();
457 const name = this.state.siteRes.site_view.site.name;
458 return `${I18NextService.i18n.t("search")} - ${q ? `${q} - ` : ""}${name}`;
462 const { type, page } = getSearchQueryParams();
465 <div className="search container-lg">
467 title={this.documentTitle}
468 path={this.context.router.route.match.url}
470 this.context.router.route.match.url +
471 this.context.router.route.location.search
474 <h1 className="h4 mb-4">{I18NextService.i18n.t("search")}</h1>
477 {this.displayResults(type)}
478 {this.resultsCount === 0 &&
479 this.state.searchRes.state === "success" && (
480 <span>{I18NextService.i18n.t("no_results")}</span>
482 <Paginator page={page} onChange={this.handlePageChange} />
487 displayResults(type: SearchType) {
492 return this.comments;
497 return this.communities;
508 className="row gx-2 gy-3"
509 onSubmit={linkEvent(this, this.handleSearchSubmit)}
511 <div className="col-auto flex-grow-1 flex-sm-grow-0">
514 className="form-control me-2 mb-2 col-sm-8"
515 value={this.state.searchText}
516 placeholder={`${I18NextService.i18n.t("search")}...`}
517 aria-label={I18NextService.i18n.t("search")}
518 onInput={linkEvent(this, this.handleQChange)}
523 <div className="col-auto">
524 <button type="submit" className="btn btn-secondary mb-2">
525 {this.state.searchRes.state === "loading" ? (
528 <span>{I18NextService.i18n.t("search")}</span>
537 const { type, listingType, sort, communityId, creatorId } =
538 getSearchQueryParams();
540 communitySearchOptions,
541 creatorSearchOptions,
542 searchCommunitiesLoading,
543 searchCreatorLoading,
547 const hasCommunities =
548 communitiesRes.state === "success" &&
549 communitiesRes.data.communities.length > 0;
553 <div className="row row-cols-auto g-2 g-sm-3 mb-2 mb-sm-3">
554 <div className="col">
557 onChange={linkEvent(this, this.handleTypeChange)}
558 className="form-select d-inline-block w-auto"
559 aria-label={I18NextService.i18n.t("type")}
561 <option disabled aria-hidden="true">
562 {I18NextService.i18n.t("type")}
564 {searchTypes.map(option => (
565 <option value={option} key={option}>
566 {I18NextService.i18n.t(
567 option.toString().toLowerCase() as NoOptionI18nKeys,
573 <div className="col">
576 showLocal={showLocal(this.isoData)}
578 onChange={this.handleListingTypeChange}
581 <div className="col">
584 onChange={this.handleSortChange}
590 <div className="row gy-2 gx-4 mb-3">
593 filterType="community"
594 onChange={this.handleCommunityFilterChange}
595 onSearch={this.handleCommunitySearch}
596 options={communitySearchOptions}
598 loading={searchCommunitiesLoading}
603 onChange={this.handleCreatorFilterChange}
604 onSearch={this.handleCreatorSearch}
605 options={creatorSearchOptions}
607 loading={searchCreatorLoading}
614 buildCombined(): Combined[] {
615 const combined: Combined[] = [];
617 resolveObjectRes: resolveObjectResponse,
618 searchRes: searchResponse,
621 // Push the possible resolve / federated objects first
622 if (resolveObjectResponse.state === "success") {
623 const { comment, post, community, person } = resolveObjectResponse.data;
626 combined.push(commentViewToCombined(comment));
629 combined.push(postViewToCombined(post));
632 combined.push(communityViewToCombined(community));
635 combined.push(personViewSafeToCombined(person));
639 // Push the search results
640 if (searchResponse.state === "success") {
641 const { comments, posts, communities, users } = searchResponse.data;
645 ...(comments?.map(commentViewToCombined) ?? []),
646 ...(posts?.map(postViewToCombined) ?? []),
647 ...(communities?.map(communityViewToCombined) ?? []),
648 ...(users?.map(personViewSafeToCombined) ?? []),
653 const { sort } = getSearchQueryParams();
656 if (sort === "New") {
657 combined.sort((a, b) => b.published.localeCompare(a.published));
659 combined.sort((a, b) =>
661 ((b.data as CommentView | PostView).counts.score |
662 (b.data as CommunityView).counts.subscribers |
663 (b.data as PersonView).counts.comment_score) -
664 ((a.data as CommentView | PostView).counts.score |
665 (a.data as CommunityView).counts.subscribers |
666 (a.data as PersonView).counts.comment_score),
675 const combined = this.buildCombined();
680 <div key={i.published} className="row">
681 <div className="col-12">
682 {i.type_ === "posts" && (
684 key={(i.data as PostView).post.id}
685 post_view={i.data as PostView}
687 enableDownvotes={enableDownvotes(this.state.siteRes)}
688 enableNsfw={enableNsfw(this.state.siteRes)}
689 allLanguages={this.state.siteRes.all_languages}
690 siteLanguages={this.state.siteRes.discussion_languages}
692 // All of these are unused, since its view only
693 onPostEdit={() => {}}
694 onPostVote={() => {}}
695 onPostReport={() => {}}
696 onBlockPerson={() => {}}
697 onLockPost={() => {}}
698 onDeletePost={() => {}}
699 onRemovePost={() => {}}
700 onSavePost={() => {}}
701 onFeaturePost={() => {}}
702 onPurgePerson={() => {}}
703 onPurgePost={() => {}}
704 onBanPersonFromCommunity={() => {}}
705 onBanPerson={() => {}}
706 onAddModToCommunity={() => {}}
707 onAddAdmin={() => {}}
708 onTransferCommunity={() => {}}
709 onMarkPostAsRead={() => {}}
712 {i.type_ === "comments" && (
714 key={(i.data as CommentView).comment.id}
717 comment_view: i.data as CommentView,
722 viewType={CommentViewType.Flat}
726 enableDownvotes={enableDownvotes(this.state.siteRes)}
727 allLanguages={this.state.siteRes.all_languages}
728 siteLanguages={this.state.siteRes.discussion_languages}
729 // All of these are unused, since its viewonly
731 onSaveComment={() => {}}
732 onBlockPerson={() => {}}
733 onDeleteComment={() => {}}
734 onRemoveComment={() => {}}
735 onCommentVote={() => {}}
736 onCommentReport={() => {}}
737 onDistinguishComment={() => {}}
738 onAddModToCommunity={() => {}}
739 onAddAdmin={() => {}}
740 onTransferCommunity={() => {}}
741 onPurgeComment={() => {}}
742 onPurgePerson={() => {}}
743 onCommentReplyRead={() => {}}
744 onPersonMentionRead={() => {}}
745 onBanPersonFromCommunity={() => {}}
746 onBanPerson={() => {}}
747 onCreateComment={() => Promise.resolve({ state: "empty" })}
748 onEditComment={() => Promise.resolve({ state: "empty" })}
751 {i.type_ === "communities" && (
752 <div>{communityListing(i.data as CommunityView)}</div>
754 {i.type_ === "users" && (
755 <div>{personListing(i.data as PersonView)}</div>
766 searchRes: searchResponse,
767 resolveObjectRes: resolveObjectResponse,
771 searchResponse.state === "success" ? searchResponse.data.comments : [];
774 resolveObjectResponse.state === "success" &&
775 resolveObjectResponse.data.comment
777 comments.unshift(resolveObjectResponse.data.comment);
782 nodes={commentsToFlatNodes(comments)}
783 viewType={CommentViewType.Flat}
787 enableDownvotes={enableDownvotes(siteRes)}
788 allLanguages={siteRes.all_languages}
789 siteLanguages={siteRes.discussion_languages}
790 // All of these are unused, since its viewonly
792 onSaveComment={() => {}}
793 onBlockPerson={() => {}}
794 onDeleteComment={() => {}}
795 onRemoveComment={() => {}}
796 onCommentVote={() => {}}
797 onCommentReport={() => {}}
798 onDistinguishComment={() => {}}
799 onAddModToCommunity={() => {}}
800 onAddAdmin={() => {}}
801 onTransferCommunity={() => {}}
802 onPurgeComment={() => {}}
803 onPurgePerson={() => {}}
804 onCommentReplyRead={() => {}}
805 onPersonMentionRead={() => {}}
806 onBanPersonFromCommunity={() => {}}
807 onBanPerson={() => {}}
808 onCreateComment={() => Promise.resolve({ state: "empty" })}
809 onEditComment={() => Promise.resolve({ state: "empty" })}
816 searchRes: searchResponse,
817 resolveObjectRes: resolveObjectResponse,
821 searchResponse.state === "success" ? searchResponse.data.posts : [];
824 resolveObjectResponse.state === "success" &&
825 resolveObjectResponse.data.post
827 posts.unshift(resolveObjectResponse.data.post);
833 <div key={pv.post.id} className="row">
834 <div className="col-12">
838 enableDownvotes={enableDownvotes(siteRes)}
839 enableNsfw={enableNsfw(siteRes)}
840 allLanguages={siteRes.all_languages}
841 siteLanguages={siteRes.discussion_languages}
843 // All of these are unused, since its view only
844 onPostEdit={() => {}}
845 onPostVote={() => {}}
846 onPostReport={() => {}}
847 onBlockPerson={() => {}}
848 onLockPost={() => {}}
849 onDeletePost={() => {}}
850 onRemovePost={() => {}}
851 onSavePost={() => {}}
852 onFeaturePost={() => {}}
853 onPurgePerson={() => {}}
854 onPurgePost={() => {}}
855 onBanPersonFromCommunity={() => {}}
856 onBanPerson={() => {}}
857 onAddModToCommunity={() => {}}
858 onAddAdmin={() => {}}
859 onTransferCommunity={() => {}}
860 onMarkPostAsRead={() => {}}
871 searchRes: searchResponse,
872 resolveObjectRes: resolveObjectResponse,
875 searchResponse.state === "success" ? searchResponse.data.communities : [];
878 resolveObjectResponse.state === "success" &&
879 resolveObjectResponse.data.community
881 communities.unshift(resolveObjectResponse.data.community);
886 {communities.map(cv => (
887 <div key={cv.community.id} className="row">
888 <div className="col-12">{communityListing(cv)}</div>
897 searchRes: searchResponse,
898 resolveObjectRes: resolveObjectResponse,
901 searchResponse.state === "success" ? searchResponse.data.users : [];
904 resolveObjectResponse.state === "success" &&
905 resolveObjectResponse.data.person
907 users.unshift(resolveObjectResponse.data.person);
913 <div key={pvs.person.id} className="row">
914 <div className="col-12">{personListing(pvs)}</div>
921 get resultsCount(): number {
922 const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
925 r.state === "success"
926 ? r.data.posts.length +
927 r.data.comments.length +
928 r.data.communities.length +
933 resolveRes.state === "success"
934 ? resolveRes.data.post ||
935 resolveRes.data.person ||
936 resolveRes.data.community ||
937 resolveRes.data.comment
942 return resObjCount + searchCount;
946 const auth = myAuth();
947 const { searchText: q } = this.state;
948 const { communityId, creatorId, type, sort, listingType, page } =
949 getSearchQueryParams();
952 this.setState({ searchRes: { state: "loading" } });
954 searchRes: await HttpService.client.search({
956 community_id: communityId ?? undefined,
957 creator_id: creatorId ?? undefined,
960 listing_type: listingType,
966 window.scrollTo(0, 0);
967 restoreScrollPosition(this.context);
970 this.setState({ resolveObjectRes: { state: "loading" } });
972 resolveObjectRes: await HttpService.silent_client.resolveObject({
981 handleCreatorSearch = debounce(async (text: string) => {
982 const { creatorId } = getSearchQueryParams();
983 const { creatorSearchOptions } = this.state;
984 const newOptions: Choice[] = [];
986 this.setState({ searchCreatorLoading: true });
988 const selectedChoice = creatorSearchOptions.find(
989 choice => getIdFromString(choice.value) === creatorId,
992 if (selectedChoice) {
993 newOptions.push(selectedChoice);
996 if (text.length > 0) {
997 newOptions.push(...(await fetchUsers(text)).map(personToChoice));
1001 searchCreatorLoading: false,
1002 creatorSearchOptions: newOptions,
1006 handleCommunitySearch = debounce(async (text: string) => {
1007 const { communityId } = getSearchQueryParams();
1008 const { communitySearchOptions } = this.state;
1010 searchCommunitiesLoading: true,
1013 const newOptions: Choice[] = [];
1015 const selectedChoice = communitySearchOptions.find(
1016 choice => getIdFromString(choice.value) === communityId,
1019 if (selectedChoice) {
1020 newOptions.push(selectedChoice);
1023 if (text.length > 0) {
1024 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
1028 searchCommunitiesLoading: false,
1029 communitySearchOptions: newOptions,
1033 handleSortChange(sort: SortType) {
1034 this.updateUrl({ sort, page: 1 });
1037 handleTypeChange(i: Search, event: any) {
1038 const type = event.target.value as SearchType;
1046 handlePageChange(page: number) {
1047 this.updateUrl({ page });
1050 handleListingTypeChange(listingType: ListingType) {
1057 handleCommunityFilterChange({ value }: Choice) {
1059 communityId: getIdFromString(value) ?? null,
1064 handleCreatorFilterChange({ value }: Choice) {
1066 creatorId: getIdFromString(value) ?? null,
1071 handleSearchSubmit(i: Search, event: any) {
1072 event.preventDefault();
1075 q: i.state.searchText,
1080 handleQChange(i: Search, event: any) {
1081 i.setState({ searchText: event.target.value });
1092 }: Partial<SearchProps>) {
1096 listingType: urlListingType,
1097 communityId: urlCommunityId,
1099 creatorId: urlCreatorId,
1101 } = getSearchQueryParams();
1103 let query = q ?? this.state.searchText ?? urlQ;
1105 if (query && query.length > 0) {
1106 query = encodeURIComponent(query);
1109 const queryParams: QueryParams<SearchProps> = {
1111 type: type ?? urlType,
1112 listingType: listingType ?? urlListingType,
1113 communityId: getUpdatedSearchId(communityId, urlCommunityId),
1114 creatorId: getUpdatedSearchId(creatorId, urlCreatorId),
1115 page: (page ?? urlPage).toString(),
1116 sort: sort ?? urlSort,
1119 this.props.history.push(`/search${getQueryString(queryParams)}`);