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() {
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 client.resolveObject(resolveObjectForm);
440 creatorDetailsResponse,
441 listCommunitiesResponse,
442 resolveObjectResponse,
447 get documentTitle(): string {
448 const { q } = getSearchQueryParams();
449 const name = this.state.siteRes.site_view.site.name;
450 return `${I18NextService.i18n.t("search")} - ${q ? `${q} - ` : ""}${name}`;
454 const { type, page } = getSearchQueryParams();
457 <div className="search container-lg">
459 title={this.documentTitle}
460 path={this.context.router.route.match.url}
462 <h5>{I18NextService.i18n.t("search")}</h5>
465 {this.displayResults(type)}
466 {this.resultsCount === 0 &&
467 this.state.searchRes.state === "success" && (
468 <span>{I18NextService.i18n.t("no_results")}</span>
470 <Paginator page={page} onChange={this.handlePageChange} />
475 displayResults(type: SearchType) {
480 return this.comments;
485 return this.communities;
495 <form className="row" onSubmit={linkEvent(this, this.handleSearchSubmit)}>
496 <div className="col-auto">
499 className="form-control me-2 mb-2 col-sm-8"
500 value={this.state.searchText}
501 placeholder={`${I18NextService.i18n.t("search")}...`}
502 aria-label={I18NextService.i18n.t("search")}
503 onInput={linkEvent(this, this.handleQChange)}
508 <div className="col-auto">
509 <button type="submit" className="btn btn-secondary mb-2">
510 {this.state.searchRes.state === "loading" ? (
513 <span>{I18NextService.i18n.t("search")}</span>
522 const { type, listingType, sort, communityId, creatorId } =
523 getSearchQueryParams();
525 communitySearchOptions,
526 creatorSearchOptions,
527 searchCommunitiesLoading,
528 searchCreatorLoading,
532 const hasCommunities =
533 communitiesRes.state == "success" &&
534 communitiesRes.data.communities.length > 0;
537 <div className="mb-2">
540 onChange={linkEvent(this, this.handleTypeChange)}
541 className="form-select d-inline-block w-auto mb-2"
542 aria-label={I18NextService.i18n.t("type")}
544 <option disabled aria-hidden="true">
545 {I18NextService.i18n.t("type")}
547 {searchTypes.map(option => (
548 <option value={option} key={option}>
549 {I18NextService.i18n.t(
550 option.toString().toLowerCase() as NoOptionI18nKeys
555 <span className="ms-2">
558 showLocal={showLocal(this.isoData)}
560 onChange={this.handleListingTypeChange}
563 <span className="ms-2">
566 onChange={this.handleSortChange}
571 <div className="row">
574 filterType="community"
575 onChange={this.handleCommunityFilterChange}
576 onSearch={this.handleCommunitySearch}
577 options={communitySearchOptions}
579 loading={searchCommunitiesLoading}
584 onChange={this.handleCreatorFilterChange}
585 onSearch={this.handleCreatorSearch}
586 options={creatorSearchOptions}
588 loading={searchCreatorLoading}
595 buildCombined(): Combined[] {
596 const combined: Combined[] = [];
598 resolveObjectRes: resolveObjectResponse,
599 searchRes: searchResponse,
602 // Push the possible resolve / federated objects first
603 if (resolveObjectResponse.state == "success") {
604 const { comment, post, community, person } = resolveObjectResponse.data;
607 combined.push(commentViewToCombined(comment));
610 combined.push(postViewToCombined(post));
613 combined.push(communityViewToCombined(community));
616 combined.push(personViewSafeToCombined(person));
620 // Push the search results
621 if (searchResponse.state === "success") {
622 const { comments, posts, communities, users } = searchResponse.data;
626 ...(comments?.map(commentViewToCombined) ?? []),
627 ...(posts?.map(postViewToCombined) ?? []),
628 ...(communities?.map(communityViewToCombined) ?? []),
629 ...(users?.map(personViewSafeToCombined) ?? []),
634 const { sort } = getSearchQueryParams();
637 if (sort === "New") {
638 combined.sort((a, b) => b.published.localeCompare(a.published));
640 combined.sort((a, b) =>
642 ((b.data as CommentView | PostView).counts.score |
643 (b.data as CommunityView).counts.subscribers |
644 (b.data as PersonView).counts.comment_score) -
645 ((a.data as CommentView | PostView).counts.score |
646 (a.data as CommunityView).counts.subscribers |
647 (a.data as PersonView).counts.comment_score)
656 const combined = this.buildCombined();
661 <div key={i.published} className="row">
662 <div className="col-12">
663 {i.type_ === "posts" && (
665 key={(i.data as PostView).post.id}
666 post_view={i.data as PostView}
668 enableDownvotes={enableDownvotes(this.state.siteRes)}
669 enableNsfw={enableNsfw(this.state.siteRes)}
670 allLanguages={this.state.siteRes.all_languages}
671 siteLanguages={this.state.siteRes.discussion_languages}
673 // All of these are unused, since its view only
674 onPostEdit={() => {}}
675 onPostVote={() => {}}
676 onPostReport={() => {}}
677 onBlockPerson={() => {}}
678 onLockPost={() => {}}
679 onDeletePost={() => {}}
680 onRemovePost={() => {}}
681 onSavePost={() => {}}
682 onFeaturePost={() => {}}
683 onPurgePerson={() => {}}
684 onPurgePost={() => {}}
685 onBanPersonFromCommunity={() => {}}
686 onBanPerson={() => {}}
687 onAddModToCommunity={() => {}}
688 onAddAdmin={() => {}}
689 onTransferCommunity={() => {}}
692 {i.type_ === "comments" && (
694 key={(i.data as CommentView).comment.id}
697 comment_view: i.data as CommentView,
702 viewType={CommentViewType.Flat}
706 enableDownvotes={enableDownvotes(this.state.siteRes)}
707 allLanguages={this.state.siteRes.all_languages}
708 siteLanguages={this.state.siteRes.discussion_languages}
709 // All of these are unused, since its viewonly
711 onSaveComment={() => {}}
712 onBlockPerson={() => {}}
713 onDeleteComment={() => {}}
714 onRemoveComment={() => {}}
715 onCommentVote={() => {}}
716 onCommentReport={() => {}}
717 onDistinguishComment={() => {}}
718 onAddModToCommunity={() => {}}
719 onAddAdmin={() => {}}
720 onTransferCommunity={() => {}}
721 onPurgeComment={() => {}}
722 onPurgePerson={() => {}}
723 onCommentReplyRead={() => {}}
724 onPersonMentionRead={() => {}}
725 onBanPersonFromCommunity={() => {}}
726 onBanPerson={() => {}}
727 onCreateComment={() => Promise.resolve({ state: "empty" })}
728 onEditComment={() => Promise.resolve({ state: "empty" })}
731 {i.type_ === "communities" && (
732 <div>{communityListing(i.data as CommunityView)}</div>
734 {i.type_ === "users" && (
735 <div>{personListing(i.data as PersonView)}</div>
746 searchRes: searchResponse,
747 resolveObjectRes: resolveObjectResponse,
751 searchResponse.state === "success" ? searchResponse.data.comments : [];
754 resolveObjectResponse.state === "success" &&
755 resolveObjectResponse.data.comment
757 comments.unshift(resolveObjectResponse.data.comment);
762 nodes={commentsToFlatNodes(comments)}
763 viewType={CommentViewType.Flat}
767 enableDownvotes={enableDownvotes(siteRes)}
768 allLanguages={siteRes.all_languages}
769 siteLanguages={siteRes.discussion_languages}
770 // All of these are unused, since its viewonly
772 onSaveComment={() => {}}
773 onBlockPerson={() => {}}
774 onDeleteComment={() => {}}
775 onRemoveComment={() => {}}
776 onCommentVote={() => {}}
777 onCommentReport={() => {}}
778 onDistinguishComment={() => {}}
779 onAddModToCommunity={() => {}}
780 onAddAdmin={() => {}}
781 onTransferCommunity={() => {}}
782 onPurgeComment={() => {}}
783 onPurgePerson={() => {}}
784 onCommentReplyRead={() => {}}
785 onPersonMentionRead={() => {}}
786 onBanPersonFromCommunity={() => {}}
787 onBanPerson={() => {}}
788 onCreateComment={() => Promise.resolve({ state: "empty" })}
789 onEditComment={() => Promise.resolve({ state: "empty" })}
796 searchRes: searchResponse,
797 resolveObjectRes: resolveObjectResponse,
801 searchResponse.state === "success" ? searchResponse.data.posts : [];
804 resolveObjectResponse.state === "success" &&
805 resolveObjectResponse.data.post
807 posts.unshift(resolveObjectResponse.data.post);
813 <div key={pv.post.id} className="row">
814 <div className="col-12">
818 enableDownvotes={enableDownvotes(siteRes)}
819 enableNsfw={enableNsfw(siteRes)}
820 allLanguages={siteRes.all_languages}
821 siteLanguages={siteRes.discussion_languages}
823 // All of these are unused, since its view only
824 onPostEdit={() => {}}
825 onPostVote={() => {}}
826 onPostReport={() => {}}
827 onBlockPerson={() => {}}
828 onLockPost={() => {}}
829 onDeletePost={() => {}}
830 onRemovePost={() => {}}
831 onSavePost={() => {}}
832 onFeaturePost={() => {}}
833 onPurgePerson={() => {}}
834 onPurgePost={() => {}}
835 onBanPersonFromCommunity={() => {}}
836 onBanPerson={() => {}}
837 onAddModToCommunity={() => {}}
838 onAddAdmin={() => {}}
839 onTransferCommunity={() => {}}
850 searchRes: searchResponse,
851 resolveObjectRes: resolveObjectResponse,
854 searchResponse.state === "success" ? searchResponse.data.communities : [];
857 resolveObjectResponse.state === "success" &&
858 resolveObjectResponse.data.community
860 communities.unshift(resolveObjectResponse.data.community);
865 {communities.map(cv => (
866 <div key={cv.community.id} className="row">
867 <div className="col-12">{communityListing(cv)}</div>
876 searchRes: searchResponse,
877 resolveObjectRes: resolveObjectResponse,
880 searchResponse.state === "success" ? searchResponse.data.users : [];
883 resolveObjectResponse.state === "success" &&
884 resolveObjectResponse.data.person
886 users.unshift(resolveObjectResponse.data.person);
892 <div key={pvs.person.id} className="row">
893 <div className="col-12">{personListing(pvs)}</div>
900 get resultsCount(): number {
901 const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
904 r.state === "success"
905 ? r.data.posts.length +
906 r.data.comments.length +
907 r.data.communities.length +
912 resolveRes.state === "success"
913 ? resolveRes.data.post ||
914 resolveRes.data.person ||
915 resolveRes.data.community ||
916 resolveRes.data.comment
921 return resObjCount + searchCount;
925 const auth = myAuth();
926 const { searchText: q } = this.state;
927 const { communityId, creatorId, type, sort, listingType, page } =
928 getSearchQueryParams();
931 this.setState({ searchRes: { state: "loading" } });
933 searchRes: await HttpService.client.search({
935 community_id: communityId ?? undefined,
936 creator_id: creatorId ?? undefined,
939 listing_type: listingType,
945 window.scrollTo(0, 0);
946 restoreScrollPosition(this.context);
949 this.setState({ resolveObjectRes: { state: "loading" } });
951 resolveObjectRes: await HttpService.client.resolveObject({
960 handleCreatorSearch = debounce(async (text: string) => {
961 const { creatorId } = getSearchQueryParams();
962 const { creatorSearchOptions } = this.state;
963 const newOptions: Choice[] = [];
965 this.setState({ searchCreatorLoading: true });
967 const selectedChoice = creatorSearchOptions.find(
968 choice => getIdFromString(choice.value) === creatorId
971 if (selectedChoice) {
972 newOptions.push(selectedChoice);
975 if (text.length > 0) {
976 newOptions.push(...(await fetchUsers(text)).map(personToChoice));
980 searchCreatorLoading: false,
981 creatorSearchOptions: newOptions,
985 handleCommunitySearch = debounce(async (text: string) => {
986 const { communityId } = getSearchQueryParams();
987 const { communitySearchOptions } = this.state;
989 searchCommunitiesLoading: true,
992 const newOptions: Choice[] = [];
994 const selectedChoice = communitySearchOptions.find(
995 choice => getIdFromString(choice.value) === communityId
998 if (selectedChoice) {
999 newOptions.push(selectedChoice);
1002 if (text.length > 0) {
1003 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
1007 searchCommunitiesLoading: false,
1008 communitySearchOptions: newOptions,
1012 handleSortChange(sort: SortType) {
1013 this.updateUrl({ sort, page: 1 });
1016 handleTypeChange(i: Search, event: any) {
1017 const type = event.target.value as SearchType;
1025 handlePageChange(page: number) {
1026 this.updateUrl({ page });
1029 handleListingTypeChange(listingType: ListingType) {
1036 handleCommunityFilterChange({ value }: Choice) {
1038 communityId: getIdFromString(value) ?? null,
1043 handleCreatorFilterChange({ value }: Choice) {
1045 creatorId: getIdFromString(value) ?? null,
1050 handleSearchSubmit(i: Search, event: any) {
1051 event.preventDefault();
1054 q: i.state.searchText,
1059 handleQChange(i: Search, event: any) {
1060 i.setState({ searchText: event.target.value });
1071 }: Partial<SearchProps>) {
1075 listingType: urlListingType,
1076 communityId: urlCommunityId,
1078 creatorId: urlCreatorId,
1080 } = getSearchQueryParams();
1082 let query = q ?? this.state.searchText ?? urlQ;
1084 if (query && query.length > 0) {
1085 query = encodeURIComponent(query);
1088 const queryParams: QueryParams<SearchProps> = {
1090 type: type ?? urlType,
1091 listingType: listingType ?? urlListingType,
1092 communityId: getUpdatedSearchId(communityId, urlCommunityId),
1093 creatorId: getUpdatedSearchId(creatorId, urlCreatorId),
1094 page: (page ?? urlPage).toString(),
1095 sort: sort ?? urlSort,
1098 this.props.history.push(`/search${getQueryString(queryParams)}`);
1100 await this.search();