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 />,
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 <h1 className="h4 mb-4">{I18NextService.i18n.t("search")}</h1>
473 {this.displayResults(type)}
474 {this.resultsCount === 0 &&
475 this.state.searchRes.state === "success" && (
476 <span>{I18NextService.i18n.t("no_results")}</span>
478 <Paginator page={page} onChange={this.handlePageChange} />
483 displayResults(type: SearchType) {
488 return this.comments;
493 return this.communities;
504 className="row gx-2 gy-3"
505 onSubmit={linkEvent(this, this.handleSearchSubmit)}
507 <div className="col-auto flex-grow-1 flex-sm-grow-0">
510 className="form-control me-2 mb-2 col-sm-8"
511 value={this.state.searchText}
512 placeholder={`${I18NextService.i18n.t("search")}...`}
513 aria-label={I18NextService.i18n.t("search")}
514 onInput={linkEvent(this, this.handleQChange)}
519 <div className="col-auto">
520 <button type="submit" className="btn btn-secondary mb-2">
521 {this.state.searchRes.state === "loading" ? (
524 <span>{I18NextService.i18n.t("search")}</span>
533 const { type, listingType, sort, communityId, creatorId } =
534 getSearchQueryParams();
536 communitySearchOptions,
537 creatorSearchOptions,
538 searchCommunitiesLoading,
539 searchCreatorLoading,
543 const hasCommunities =
544 communitiesRes.state == "success" &&
545 communitiesRes.data.communities.length > 0;
549 <div className="row row-cols-auto g-2 g-sm-3 mb-2 mb-sm-3">
550 <div className="col">
553 onChange={linkEvent(this, this.handleTypeChange)}
554 className="form-select d-inline-block w-auto"
555 aria-label={I18NextService.i18n.t("type")}
557 <option disabled aria-hidden="true">
558 {I18NextService.i18n.t("type")}
560 {searchTypes.map(option => (
561 <option value={option} key={option}>
562 {I18NextService.i18n.t(
563 option.toString().toLowerCase() as NoOptionI18nKeys
569 <div className="col">
572 showLocal={showLocal(this.isoData)}
574 onChange={this.handleListingTypeChange}
577 <div className="col">
580 onChange={this.handleSortChange}
586 <div className="row gy-2 gx-4 mb-3">
589 filterType="community"
590 onChange={this.handleCommunityFilterChange}
591 onSearch={this.handleCommunitySearch}
592 options={communitySearchOptions}
594 loading={searchCommunitiesLoading}
599 onChange={this.handleCreatorFilterChange}
600 onSearch={this.handleCreatorSearch}
601 options={creatorSearchOptions}
603 loading={searchCreatorLoading}
610 buildCombined(): Combined[] {
611 const combined: Combined[] = [];
613 resolveObjectRes: resolveObjectResponse,
614 searchRes: searchResponse,
617 // Push the possible resolve / federated objects first
618 if (resolveObjectResponse.state == "success") {
619 const { comment, post, community, person } = resolveObjectResponse.data;
622 combined.push(commentViewToCombined(comment));
625 combined.push(postViewToCombined(post));
628 combined.push(communityViewToCombined(community));
631 combined.push(personViewSafeToCombined(person));
635 // Push the search results
636 if (searchResponse.state === "success") {
637 const { comments, posts, communities, users } = searchResponse.data;
641 ...(comments?.map(commentViewToCombined) ?? []),
642 ...(posts?.map(postViewToCombined) ?? []),
643 ...(communities?.map(communityViewToCombined) ?? []),
644 ...(users?.map(personViewSafeToCombined) ?? []),
649 const { sort } = getSearchQueryParams();
652 if (sort === "New") {
653 combined.sort((a, b) => b.published.localeCompare(a.published));
655 combined.sort((a, b) =>
657 ((b.data as CommentView | PostView).counts.score |
658 (b.data as CommunityView).counts.subscribers |
659 (b.data as PersonView).counts.comment_score) -
660 ((a.data as CommentView | PostView).counts.score |
661 (a.data as CommunityView).counts.subscribers |
662 (a.data as PersonView).counts.comment_score)
671 const combined = this.buildCombined();
676 <div key={i.published} className="row">
677 <div className="col-12">
678 {i.type_ === "posts" && (
680 key={(i.data as PostView).post.id}
681 post_view={i.data as PostView}
683 enableDownvotes={enableDownvotes(this.state.siteRes)}
684 enableNsfw={enableNsfw(this.state.siteRes)}
685 allLanguages={this.state.siteRes.all_languages}
686 siteLanguages={this.state.siteRes.discussion_languages}
688 // All of these are unused, since its view only
689 onPostEdit={() => {}}
690 onPostVote={() => {}}
691 onPostReport={() => {}}
692 onBlockPerson={() => {}}
693 onLockPost={() => {}}
694 onDeletePost={() => {}}
695 onRemovePost={() => {}}
696 onSavePost={() => {}}
697 onFeaturePost={() => {}}
698 onPurgePerson={() => {}}
699 onPurgePost={() => {}}
700 onBanPersonFromCommunity={() => {}}
701 onBanPerson={() => {}}
702 onAddModToCommunity={() => {}}
703 onAddAdmin={() => {}}
704 onTransferCommunity={() => {}}
707 {i.type_ === "comments" && (
709 key={(i.data as CommentView).comment.id}
712 comment_view: i.data as CommentView,
717 viewType={CommentViewType.Flat}
721 enableDownvotes={enableDownvotes(this.state.siteRes)}
722 allLanguages={this.state.siteRes.all_languages}
723 siteLanguages={this.state.siteRes.discussion_languages}
724 // All of these are unused, since its viewonly
726 onSaveComment={() => {}}
727 onBlockPerson={() => {}}
728 onDeleteComment={() => {}}
729 onRemoveComment={() => {}}
730 onCommentVote={() => {}}
731 onCommentReport={() => {}}
732 onDistinguishComment={() => {}}
733 onAddModToCommunity={() => {}}
734 onAddAdmin={() => {}}
735 onTransferCommunity={() => {}}
736 onPurgeComment={() => {}}
737 onPurgePerson={() => {}}
738 onCommentReplyRead={() => {}}
739 onPersonMentionRead={() => {}}
740 onBanPersonFromCommunity={() => {}}
741 onBanPerson={() => {}}
742 onCreateComment={() => Promise.resolve({ state: "empty" })}
743 onEditComment={() => Promise.resolve({ state: "empty" })}
746 {i.type_ === "communities" && (
747 <div>{communityListing(i.data as CommunityView)}</div>
749 {i.type_ === "users" && (
750 <div>{personListing(i.data as PersonView)}</div>
761 searchRes: searchResponse,
762 resolveObjectRes: resolveObjectResponse,
766 searchResponse.state === "success" ? searchResponse.data.comments : [];
769 resolveObjectResponse.state === "success" &&
770 resolveObjectResponse.data.comment
772 comments.unshift(resolveObjectResponse.data.comment);
777 nodes={commentsToFlatNodes(comments)}
778 viewType={CommentViewType.Flat}
782 enableDownvotes={enableDownvotes(siteRes)}
783 allLanguages={siteRes.all_languages}
784 siteLanguages={siteRes.discussion_languages}
785 // All of these are unused, since its viewonly
787 onSaveComment={() => {}}
788 onBlockPerson={() => {}}
789 onDeleteComment={() => {}}
790 onRemoveComment={() => {}}
791 onCommentVote={() => {}}
792 onCommentReport={() => {}}
793 onDistinguishComment={() => {}}
794 onAddModToCommunity={() => {}}
795 onAddAdmin={() => {}}
796 onTransferCommunity={() => {}}
797 onPurgeComment={() => {}}
798 onPurgePerson={() => {}}
799 onCommentReplyRead={() => {}}
800 onPersonMentionRead={() => {}}
801 onBanPersonFromCommunity={() => {}}
802 onBanPerson={() => {}}
803 onCreateComment={() => Promise.resolve({ state: "empty" })}
804 onEditComment={() => Promise.resolve({ state: "empty" })}
811 searchRes: searchResponse,
812 resolveObjectRes: resolveObjectResponse,
816 searchResponse.state === "success" ? searchResponse.data.posts : [];
819 resolveObjectResponse.state === "success" &&
820 resolveObjectResponse.data.post
822 posts.unshift(resolveObjectResponse.data.post);
828 <div key={pv.post.id} className="row">
829 <div className="col-12">
833 enableDownvotes={enableDownvotes(siteRes)}
834 enableNsfw={enableNsfw(siteRes)}
835 allLanguages={siteRes.all_languages}
836 siteLanguages={siteRes.discussion_languages}
838 // All of these are unused, since its view only
839 onPostEdit={() => {}}
840 onPostVote={() => {}}
841 onPostReport={() => {}}
842 onBlockPerson={() => {}}
843 onLockPost={() => {}}
844 onDeletePost={() => {}}
845 onRemovePost={() => {}}
846 onSavePost={() => {}}
847 onFeaturePost={() => {}}
848 onPurgePerson={() => {}}
849 onPurgePost={() => {}}
850 onBanPersonFromCommunity={() => {}}
851 onBanPerson={() => {}}
852 onAddModToCommunity={() => {}}
853 onAddAdmin={() => {}}
854 onTransferCommunity={() => {}}
865 searchRes: searchResponse,
866 resolveObjectRes: resolveObjectResponse,
869 searchResponse.state === "success" ? searchResponse.data.communities : [];
872 resolveObjectResponse.state === "success" &&
873 resolveObjectResponse.data.community
875 communities.unshift(resolveObjectResponse.data.community);
880 {communities.map(cv => (
881 <div key={cv.community.id} className="row">
882 <div className="col-12">{communityListing(cv)}</div>
891 searchRes: searchResponse,
892 resolveObjectRes: resolveObjectResponse,
895 searchResponse.state === "success" ? searchResponse.data.users : [];
898 resolveObjectResponse.state === "success" &&
899 resolveObjectResponse.data.person
901 users.unshift(resolveObjectResponse.data.person);
907 <div key={pvs.person.id} className="row">
908 <div className="col-12">{personListing(pvs)}</div>
915 get resultsCount(): number {
916 const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
919 r.state === "success"
920 ? r.data.posts.length +
921 r.data.comments.length +
922 r.data.communities.length +
927 resolveRes.state === "success"
928 ? resolveRes.data.post ||
929 resolveRes.data.person ||
930 resolveRes.data.community ||
931 resolveRes.data.comment
936 return resObjCount + searchCount;
940 const auth = myAuth();
941 const { searchText: q } = this.state;
942 const { communityId, creatorId, type, sort, listingType, page } =
943 getSearchQueryParams();
946 this.setState({ searchRes: { state: "loading" } });
948 searchRes: await HttpService.client.search({
950 community_id: communityId ?? undefined,
951 creator_id: creatorId ?? undefined,
954 listing_type: listingType,
960 window.scrollTo(0, 0);
961 restoreScrollPosition(this.context);
964 this.setState({ resolveObjectRes: { state: "loading" } });
966 resolveObjectRes: await HttpService.silent_client.resolveObject({
975 handleCreatorSearch = debounce(async (text: string) => {
976 const { creatorId } = getSearchQueryParams();
977 const { creatorSearchOptions } = this.state;
978 const newOptions: Choice[] = [];
980 this.setState({ searchCreatorLoading: true });
982 const selectedChoice = creatorSearchOptions.find(
983 choice => getIdFromString(choice.value) === creatorId
986 if (selectedChoice) {
987 newOptions.push(selectedChoice);
990 if (text.length > 0) {
991 newOptions.push(...(await fetchUsers(text)).map(personToChoice));
995 searchCreatorLoading: false,
996 creatorSearchOptions: newOptions,
1000 handleCommunitySearch = debounce(async (text: string) => {
1001 const { communityId } = getSearchQueryParams();
1002 const { communitySearchOptions } = this.state;
1004 searchCommunitiesLoading: true,
1007 const newOptions: Choice[] = [];
1009 const selectedChoice = communitySearchOptions.find(
1010 choice => getIdFromString(choice.value) === communityId
1013 if (selectedChoice) {
1014 newOptions.push(selectedChoice);
1017 if (text.length > 0) {
1018 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
1022 searchCommunitiesLoading: false,
1023 communitySearchOptions: newOptions,
1027 handleSortChange(sort: SortType) {
1028 this.updateUrl({ sort, page: 1 });
1031 handleTypeChange(i: Search, event: any) {
1032 const type = event.target.value as SearchType;
1040 handlePageChange(page: number) {
1041 this.updateUrl({ page });
1044 handleListingTypeChange(listingType: ListingType) {
1051 handleCommunityFilterChange({ value }: Choice) {
1053 communityId: getIdFromString(value) ?? null,
1058 handleCreatorFilterChange({ value }: Choice) {
1060 creatorId: getIdFromString(value) ?? null,
1065 handleSearchSubmit(i: Search, event: any) {
1066 event.preventDefault();
1069 q: i.state.searchText,
1074 handleQChange(i: Search, event: any) {
1075 i.setState({ searchText: event.target.value });
1086 }: Partial<SearchProps>) {
1090 listingType: urlListingType,
1091 communityId: urlCommunityId,
1093 creatorId: urlCreatorId,
1095 } = getSearchQueryParams();
1097 let query = q ?? this.state.searchText ?? urlQ;
1099 if (query && query.length > 0) {
1100 query = encodeURIComponent(query);
1103 const queryParams: QueryParams<SearchProps> = {
1105 type: type ?? urlType,
1106 listingType: listingType ?? urlListingType,
1107 communityId: getUpdatedSearchId(communityId, urlCommunityId),
1108 creatorId: getUpdatedSearchId(creatorId, urlCreatorId),
1109 page: (page ?? urlPage).toString(),
1110 sort: sort ?? urlSort,
1113 this.props.history.push(`/search${getQueryString(queryParams)}`);