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={() => {}}
711 {i.type_ === "comments" && (
713 key={(i.data as CommentView).comment.id}
716 comment_view: i.data as CommentView,
721 viewType={CommentViewType.Flat}
725 enableDownvotes={enableDownvotes(this.state.siteRes)}
726 allLanguages={this.state.siteRes.all_languages}
727 siteLanguages={this.state.siteRes.discussion_languages}
728 // All of these are unused, since its viewonly
730 onSaveComment={() => {}}
731 onBlockPerson={() => {}}
732 onDeleteComment={() => {}}
733 onRemoveComment={() => {}}
734 onCommentVote={() => {}}
735 onCommentReport={() => {}}
736 onDistinguishComment={() => {}}
737 onAddModToCommunity={() => {}}
738 onAddAdmin={() => {}}
739 onTransferCommunity={() => {}}
740 onPurgeComment={() => {}}
741 onPurgePerson={() => {}}
742 onCommentReplyRead={() => {}}
743 onPersonMentionRead={() => {}}
744 onBanPersonFromCommunity={() => {}}
745 onBanPerson={() => {}}
746 onCreateComment={() => Promise.resolve({ state: "empty" })}
747 onEditComment={() => Promise.resolve({ state: "empty" })}
750 {i.type_ === "communities" && (
751 <div>{communityListing(i.data as CommunityView)}</div>
753 {i.type_ === "users" && (
754 <div>{personListing(i.data as PersonView)}</div>
765 searchRes: searchResponse,
766 resolveObjectRes: resolveObjectResponse,
770 searchResponse.state === "success" ? searchResponse.data.comments : [];
773 resolveObjectResponse.state === "success" &&
774 resolveObjectResponse.data.comment
776 comments.unshift(resolveObjectResponse.data.comment);
781 nodes={commentsToFlatNodes(comments)}
782 viewType={CommentViewType.Flat}
786 enableDownvotes={enableDownvotes(siteRes)}
787 allLanguages={siteRes.all_languages}
788 siteLanguages={siteRes.discussion_languages}
789 // All of these are unused, since its viewonly
791 onSaveComment={() => {}}
792 onBlockPerson={() => {}}
793 onDeleteComment={() => {}}
794 onRemoveComment={() => {}}
795 onCommentVote={() => {}}
796 onCommentReport={() => {}}
797 onDistinguishComment={() => {}}
798 onAddModToCommunity={() => {}}
799 onAddAdmin={() => {}}
800 onTransferCommunity={() => {}}
801 onPurgeComment={() => {}}
802 onPurgePerson={() => {}}
803 onCommentReplyRead={() => {}}
804 onPersonMentionRead={() => {}}
805 onBanPersonFromCommunity={() => {}}
806 onBanPerson={() => {}}
807 onCreateComment={() => Promise.resolve({ state: "empty" })}
808 onEditComment={() => Promise.resolve({ state: "empty" })}
815 searchRes: searchResponse,
816 resolveObjectRes: resolveObjectResponse,
820 searchResponse.state === "success" ? searchResponse.data.posts : [];
823 resolveObjectResponse.state === "success" &&
824 resolveObjectResponse.data.post
826 posts.unshift(resolveObjectResponse.data.post);
832 <div key={pv.post.id} className="row">
833 <div className="col-12">
837 enableDownvotes={enableDownvotes(siteRes)}
838 enableNsfw={enableNsfw(siteRes)}
839 allLanguages={siteRes.all_languages}
840 siteLanguages={siteRes.discussion_languages}
842 // All of these are unused, since its view only
843 onPostEdit={() => {}}
844 onPostVote={() => {}}
845 onPostReport={() => {}}
846 onBlockPerson={() => {}}
847 onLockPost={() => {}}
848 onDeletePost={() => {}}
849 onRemovePost={() => {}}
850 onSavePost={() => {}}
851 onFeaturePost={() => {}}
852 onPurgePerson={() => {}}
853 onPurgePost={() => {}}
854 onBanPersonFromCommunity={() => {}}
855 onBanPerson={() => {}}
856 onAddModToCommunity={() => {}}
857 onAddAdmin={() => {}}
858 onTransferCommunity={() => {}}
869 searchRes: searchResponse,
870 resolveObjectRes: resolveObjectResponse,
873 searchResponse.state === "success" ? searchResponse.data.communities : [];
876 resolveObjectResponse.state === "success" &&
877 resolveObjectResponse.data.community
879 communities.unshift(resolveObjectResponse.data.community);
884 {communities.map(cv => (
885 <div key={cv.community.id} className="row">
886 <div className="col-12">{communityListing(cv)}</div>
895 searchRes: searchResponse,
896 resolveObjectRes: resolveObjectResponse,
899 searchResponse.state === "success" ? searchResponse.data.users : [];
902 resolveObjectResponse.state === "success" &&
903 resolveObjectResponse.data.person
905 users.unshift(resolveObjectResponse.data.person);
911 <div key={pvs.person.id} className="row">
912 <div className="col-12">{personListing(pvs)}</div>
919 get resultsCount(): number {
920 const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
923 r.state === "success"
924 ? r.data.posts.length +
925 r.data.comments.length +
926 r.data.communities.length +
931 resolveRes.state === "success"
932 ? resolveRes.data.post ||
933 resolveRes.data.person ||
934 resolveRes.data.community ||
935 resolveRes.data.comment
940 return resObjCount + searchCount;
944 const auth = myAuth();
945 const { searchText: q } = this.state;
946 const { communityId, creatorId, type, sort, listingType, page } =
947 getSearchQueryParams();
950 this.setState({ searchRes: { state: "loading" } });
952 searchRes: await HttpService.client.search({
954 community_id: communityId ?? undefined,
955 creator_id: creatorId ?? undefined,
958 listing_type: listingType,
964 window.scrollTo(0, 0);
965 restoreScrollPosition(this.context);
968 this.setState({ resolveObjectRes: { state: "loading" } });
970 resolveObjectRes: await HttpService.silent_client.resolveObject({
979 handleCreatorSearch = debounce(async (text: string) => {
980 const { creatorId } = getSearchQueryParams();
981 const { creatorSearchOptions } = this.state;
982 const newOptions: Choice[] = [];
984 this.setState({ searchCreatorLoading: true });
986 const selectedChoice = creatorSearchOptions.find(
987 choice => getIdFromString(choice.value) === creatorId,
990 if (selectedChoice) {
991 newOptions.push(selectedChoice);
994 if (text.length > 0) {
995 newOptions.push(...(await fetchUsers(text)).map(personToChoice));
999 searchCreatorLoading: false,
1000 creatorSearchOptions: newOptions,
1004 handleCommunitySearch = debounce(async (text: string) => {
1005 const { communityId } = getSearchQueryParams();
1006 const { communitySearchOptions } = this.state;
1008 searchCommunitiesLoading: true,
1011 const newOptions: Choice[] = [];
1013 const selectedChoice = communitySearchOptions.find(
1014 choice => getIdFromString(choice.value) === communityId,
1017 if (selectedChoice) {
1018 newOptions.push(selectedChoice);
1021 if (text.length > 0) {
1022 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
1026 searchCommunitiesLoading: false,
1027 communitySearchOptions: newOptions,
1031 handleSortChange(sort: SortType) {
1032 this.updateUrl({ sort, page: 1 });
1035 handleTypeChange(i: Search, event: any) {
1036 const type = event.target.value as SearchType;
1044 handlePageChange(page: number) {
1045 this.updateUrl({ page });
1048 handleListingTypeChange(listingType: ListingType) {
1055 handleCommunityFilterChange({ value }: Choice) {
1057 communityId: getIdFromString(value) ?? null,
1062 handleCreatorFilterChange({ value }: Choice) {
1064 creatorId: getIdFromString(value) ?? null,
1069 handleSearchSubmit(i: Search, event: any) {
1070 event.preventDefault();
1073 q: i.state.searchText,
1078 handleQChange(i: Search, event: any) {
1079 i.setState({ searchText: event.target.value });
1090 }: Partial<SearchProps>) {
1094 listingType: urlListingType,
1095 communityId: urlCommunityId,
1097 creatorId: urlCreatorId,
1099 } = getSearchQueryParams();
1101 let query = q ?? this.state.searchText ?? urlQ;
1103 if (query && query.length > 0) {
1104 query = encodeURIComponent(query);
1107 const queryParams: QueryParams<SearchProps> = {
1109 type: type ?? urlType,
1110 listingType: listingType ?? urlListingType,
1111 communityId: getUpdatedSearchId(communityId, urlCommunityId),
1112 creatorId: getUpdatedSearchId(creatorId, urlCreatorId),
1113 page: (page ?? urlPage).toString(),
1114 sort: sort ?? urlSort,
1117 this.props.history.push(`/search${getQueryString(queryParams)}`);