1 import type { NoOptionI18nKeys } from "i18next";
2 import { Component, linkEvent } from "inferno";
9 GetPersonDetailsResponse,
12 ListCommunitiesResponse,
17 ResolveObjectResponse,
22 } from "lemmy-js-client";
23 import { i18n } from "../i18next";
24 import { CommentViewType, InitialFetchRequest } from "../interfaces";
25 import { FirstLoadService } from "../services/FirstLoadService";
26 import { HttpService, RequestState } from "../services/HttpService";
31 capitalizeFirstLetter,
48 restoreScrollPosition,
53 import { CommentNodes } from "./comment/comment-nodes";
54 import { HtmlTags } from "./common/html-tags";
55 import { Spinner } from "./common/icon";
56 import { ListingTypeSelect } from "./common/listing-type-select";
57 import { Paginator } from "./common/paginator";
58 import { SearchableSelect } from "./common/searchable-select";
59 import { SortSelect } from "./common/sort-select";
60 import { CommunityLink } from "./community/community-link";
61 import { PersonListing } from "./person/person-listing";
62 import { PostListing } from "./post/post-listing";
64 interface SearchProps {
68 listingType: ListingType;
69 communityId?: number | null;
70 creatorId?: number | null;
74 type SearchData = RouteDataResponse<{
75 communityResponse: GetCommunityResponse;
76 listCommunitiesResponse: ListCommunitiesResponse;
77 creatorDetailsResponse: GetPersonDetailsResponse;
78 searchResponse: SearchResponse;
79 resolveObjectResponse: ResolveObjectResponse;
82 type FilterType = "creator" | "community";
84 interface SearchState {
85 searchRes: RequestState<SearchResponse>;
86 resolveObjectRes: RequestState<ResolveObjectResponse>;
87 creatorDetailsRes: RequestState<GetPersonDetailsResponse>;
88 communitiesRes: RequestState<ListCommunitiesResponse>;
89 communityRes: RequestState<GetCommunityResponse>;
90 siteRes: GetSiteResponse;
92 communitySearchOptions: Choice[];
93 creatorSearchOptions: Choice[];
94 searchCreatorLoading: boolean;
95 searchCommunitiesLoading: boolean;
96 isIsomorphic: boolean;
101 data: CommentView | PostView | CommunityView | PersonView;
105 const defaultSearchType = "All";
106 const defaultSortType = "TopAll";
107 const defaultListingType = "All";
109 const searchTypes = ["All", "Comments", "Posts", "Communities", "Users", "Url"];
111 const getSearchQueryParams = () =>
112 getQueryParams<SearchProps>({
113 q: getSearchQueryFromQuery,
114 type: getSearchTypeFromQuery,
115 sort: getSortTypeFromQuery,
116 listingType: getListingTypeFromQuery,
117 communityId: getIdFromString,
118 creatorId: getIdFromString,
119 page: getPageFromString,
122 const getSearchQueryFromQuery = (q?: string): string | undefined =>
123 q ? decodeURIComponent(q) : undefined;
125 function getSearchTypeFromQuery(type_?: string): SearchType {
126 return type_ ? (type_ as SearchType) : defaultSearchType;
129 function getSortTypeFromQuery(sort?: string): SortType {
130 return sort ? (sort as SortType) : defaultSortType;
133 function getListingTypeFromQuery(listingType?: string): ListingType {
134 return listingType ? (listingType as ListingType) : defaultListingType;
137 function postViewToCombined(data: PostView): Combined {
141 published: data.post.published,
145 function commentViewToCombined(data: CommentView): Combined {
149 published: data.comment.published,
153 function communityViewToCombined(data: CommunityView): Combined {
155 type_: "communities",
157 published: data.community.published,
161 function personViewSafeToCombined(data: PersonView): Combined {
165 published: data.person.published,
177 filterType: FilterType;
179 onSearch: (text: string) => void;
180 onChange: (choice: Choice) => void;
181 value?: number | null;
185 <div className="mb-3 col-sm-6">
186 <label className="col-form-label me-2" htmlFor={`${filterType}-filter`}>
187 {capitalizeFirstLetter(i18n.t(filterType))}
190 id={`${filterType}-filter`}
193 label: i18n.t("all"),
206 const communityListing = ({
208 counts: { subscribers },
211 <CommunityLink community={community} />,
213 "number_of_subscribers"
216 const personListing = ({ person, counts: { comment_count } }: PersonView) =>
218 <PersonListing person={person} showApubName />,
224 listing: JSX.ElementClass,
226 translationKey: "number_of_comments" | "number_of_subscribers"
230 <span>{listing}</span>
231 <span>{` - ${i18n.t(translationKey, {
232 count: Number(count),
233 formattedCount: numToSI(count),
239 export class Search extends Component<any, SearchState> {
240 private isoData = setIsoData<SearchData>(this.context);
242 state: SearchState = {
243 resolveObjectRes: { state: "empty" },
244 creatorDetailsRes: { state: "empty" },
245 communitiesRes: { state: "empty" },
246 communityRes: { state: "empty" },
247 siteRes: this.isoData.site_res,
248 creatorSearchOptions: [],
249 communitySearchOptions: [],
250 searchRes: { state: "empty" },
251 searchCreatorLoading: false,
252 searchCommunitiesLoading: false,
256 constructor(props: any, context: any) {
257 super(props, context);
259 this.handleSortChange = this.handleSortChange.bind(this);
260 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
261 this.handlePageChange = this.handlePageChange.bind(this);
262 this.handleCommunityFilterChange =
263 this.handleCommunityFilterChange.bind(this);
264 this.handleCreatorFilterChange = this.handleCreatorFilterChange.bind(this);
266 const { q } = getSearchQueryParams();
273 // Only fetch the data if coming from another route
274 if (FirstLoadService.isFirstLoad) {
276 communityResponse: communityRes,
277 creatorDetailsResponse: creatorDetailsRes,
278 listCommunitiesResponse: communitiesRes,
279 resolveObjectResponse: resolveObjectRes,
280 searchResponse: searchRes,
281 } = this.isoData.routeData;
288 if (creatorDetailsRes?.state === "success") {
291 creatorSearchOptions:
292 creatorDetailsRes?.state === "success"
293 ? [personToChoice(creatorDetailsRes.data.person_view)]
299 if (communitiesRes?.state === "success") {
306 if (communityRes?.state === "success") {
318 if (searchRes?.state === "success") {
325 if (resolveObjectRes?.state === "success") {
335 async componentDidMount() {
336 if (!this.state.isIsomorphic) {
337 const promises = [this.fetchCommunities()];
338 if (this.state.searchText) {
339 promises.push(this.search());
342 await Promise.all(promises);
346 async fetchCommunities() {
347 this.setState({ communitiesRes: { state: "loading" } });
349 communitiesRes: await HttpService.client.listCommunities({
350 type_: defaultListingType,
351 sort: defaultSortType,
358 componentWillUnmount() {
359 saveScrollPosition(this.context);
362 static async fetchInitialData({
365 query: { communityId, creatorId, q, type, sort, listingType, page },
366 }: InitialFetchRequest<QueryParams<SearchProps>>): Promise<SearchData> {
367 const community_id = getIdFromString(communityId);
368 let communityResponse: RequestState<GetCommunityResponse> = {
371 let listCommunitiesResponse: RequestState<ListCommunitiesResponse> = {
375 const getCommunityForm: GetCommunity = {
380 communityResponse = await client.getCommunity(getCommunityForm);
382 const listCommunitiesForm: ListCommunities = {
383 type_: defaultListingType,
384 sort: defaultSortType,
389 listCommunitiesResponse = await client.listCommunities(
394 const creator_id = getIdFromString(creatorId);
395 let creatorDetailsResponse: RequestState<GetPersonDetailsResponse> = {
399 const getCreatorForm: GetPersonDetails = {
400 person_id: creator_id,
404 creatorDetailsResponse = await client.getPersonDetails(getCreatorForm);
407 const query = getSearchQueryFromQuery(q);
409 let searchResponse: RequestState<SearchResponse> = { state: "empty" };
410 let resolveObjectResponse: RequestState<ResolveObjectResponse> = {
415 const form: SearchForm = {
419 type_: getSearchTypeFromQuery(type),
420 sort: getSortTypeFromQuery(sort),
421 listing_type: getListingTypeFromQuery(listingType),
422 page: getPageFromString(page),
428 searchResponse = await client.search(form);
430 const resolveObjectForm: ResolveObject = {
434 resolveObjectResponse = await client.resolveObject(resolveObjectForm);
441 creatorDetailsResponse,
442 listCommunitiesResponse,
443 resolveObjectResponse,
448 get documentTitle(): string {
449 const { q } = getSearchQueryParams();
450 const name = this.state.siteRes.site_view.site.name;
451 return `${i18n.t("search")} - ${q ? `${q} - ` : ""}${name}`;
455 const { type, page } = getSearchQueryParams();
458 <div className="search container-lg">
460 title={this.documentTitle}
461 path={this.context.router.route.match.url}
463 <h5>{i18n.t("search")}</h5>
466 {this.displayResults(type)}
467 {this.resultsCount === 0 &&
468 this.state.searchRes.state === "success" && (
469 <span>{i18n.t("no_results")}</span>
471 <Paginator page={page} onChange={this.handlePageChange} />
476 displayResults(type: SearchType) {
481 return this.comments;
486 return this.communities;
496 <form className="row" onSubmit={linkEvent(this, this.handleSearchSubmit)}>
497 <div className="col-auto">
500 className="form-control me-2 mb-2 col-sm-8"
501 value={this.state.searchText}
502 placeholder={`${i18n.t("search")}...`}
503 aria-label={i18n.t("search")}
504 onInput={linkEvent(this, this.handleQChange)}
509 <div className="col-auto">
510 <button type="submit" className="btn btn-secondary mb-2">
511 {this.state.searchRes.state === "loading" ? (
514 <span>{i18n.t("search")}</span>
523 const { type, listingType, sort, communityId, creatorId } =
524 getSearchQueryParams();
526 communitySearchOptions,
527 creatorSearchOptions,
528 searchCommunitiesLoading,
529 searchCreatorLoading,
533 const hasCommunities =
534 communitiesRes.state == "success" &&
535 communitiesRes.data.communities.length > 0;
538 <div className="mb-2">
541 onChange={linkEvent(this, this.handleTypeChange)}
542 className="form-select d-inline-block w-auto mb-2"
543 aria-label={i18n.t("type")}
545 <option disabled aria-hidden="true">
548 {searchTypes.map(option => (
549 <option value={option} key={option}>
550 {i18n.t(option.toString().toLowerCase() as NoOptionI18nKeys)}
554 <span className="ms-2">
557 showLocal={showLocal(this.isoData)}
559 onChange={this.handleListingTypeChange}
562 <span className="ms-2">
565 onChange={this.handleSortChange}
570 <div className="row">
573 filterType="community"
574 onChange={this.handleCommunityFilterChange}
575 onSearch={this.handleCommunitySearch}
576 options={communitySearchOptions}
578 loading={searchCommunitiesLoading}
583 onChange={this.handleCreatorFilterChange}
584 onSearch={this.handleCreatorSearch}
585 options={creatorSearchOptions}
587 loading={searchCreatorLoading}
594 buildCombined(): Combined[] {
595 const combined: Combined[] = [];
597 resolveObjectRes: resolveObjectResponse,
598 searchRes: searchResponse,
601 // Push the possible resolve / federated objects first
602 if (resolveObjectResponse.state == "success") {
603 const { comment, post, community, person } = resolveObjectResponse.data;
606 combined.push(commentViewToCombined(comment));
609 combined.push(postViewToCombined(post));
612 combined.push(communityViewToCombined(community));
615 combined.push(personViewSafeToCombined(person));
619 // Push the search results
620 if (searchResponse.state === "success") {
621 const { comments, posts, communities, users } = searchResponse.data;
625 ...(comments?.map(commentViewToCombined) ?? []),
626 ...(posts?.map(postViewToCombined) ?? []),
627 ...(communities?.map(communityViewToCombined) ?? []),
628 ...(users?.map(personViewSafeToCombined) ?? []),
633 const { sort } = getSearchQueryParams();
636 if (sort === "New") {
637 combined.sort((a, b) => b.published.localeCompare(a.published));
639 combined.sort((a, b) =>
641 ((b.data as CommentView | PostView).counts.score |
642 (b.data as CommunityView).counts.subscribers |
643 (b.data as PersonView).counts.comment_score) -
644 ((a.data as CommentView | PostView).counts.score |
645 (a.data as CommunityView).counts.subscribers |
646 (a.data as PersonView).counts.comment_score)
655 const combined = this.buildCombined();
660 <div key={i.published} className="row">
661 <div className="col-12">
662 {i.type_ === "posts" && (
664 key={(i.data as PostView).post.id}
665 post_view={i.data as PostView}
667 enableDownvotes={enableDownvotes(this.state.siteRes)}
668 enableNsfw={enableNsfw(this.state.siteRes)}
669 allLanguages={this.state.siteRes.all_languages}
670 siteLanguages={this.state.siteRes.discussion_languages}
672 // All of these are unused, since its view only
673 onPostEdit={() => {}}
674 onPostVote={() => {}}
675 onPostReport={() => {}}
676 onBlockPerson={() => {}}
677 onLockPost={() => {}}
678 onDeletePost={() => {}}
679 onRemovePost={() => {}}
680 onSavePost={() => {}}
681 onFeaturePost={() => {}}
682 onPurgePerson={() => {}}
683 onPurgePost={() => {}}
684 onBanPersonFromCommunity={() => {}}
685 onBanPerson={() => {}}
686 onAddModToCommunity={() => {}}
687 onAddAdmin={() => {}}
688 onTransferCommunity={() => {}}
691 {i.type_ === "comments" && (
693 key={(i.data as CommentView).comment.id}
696 comment_view: i.data as CommentView,
701 viewType={CommentViewType.Flat}
705 enableDownvotes={enableDownvotes(this.state.siteRes)}
706 allLanguages={this.state.siteRes.all_languages}
707 siteLanguages={this.state.siteRes.discussion_languages}
708 // All of these are unused, since its viewonly
710 onSaveComment={() => {}}
711 onBlockPerson={() => {}}
712 onDeleteComment={() => {}}
713 onRemoveComment={() => {}}
714 onCommentVote={() => {}}
715 onCommentReport={() => {}}
716 onDistinguishComment={() => {}}
717 onAddModToCommunity={() => {}}
718 onAddAdmin={() => {}}
719 onTransferCommunity={() => {}}
720 onPurgeComment={() => {}}
721 onPurgePerson={() => {}}
722 onCommentReplyRead={() => {}}
723 onPersonMentionRead={() => {}}
724 onBanPersonFromCommunity={() => {}}
725 onBanPerson={() => {}}
726 onCreateComment={() => Promise.resolve({ state: "empty" })}
727 onEditComment={() => Promise.resolve({ state: "empty" })}
730 {i.type_ === "communities" && (
731 <div>{communityListing(i.data as CommunityView)}</div>
733 {i.type_ === "users" && (
734 <div>{personListing(i.data as PersonView)}</div>
745 searchRes: searchResponse,
746 resolveObjectRes: resolveObjectResponse,
750 searchResponse.state === "success" ? searchResponse.data.comments : [];
753 resolveObjectResponse.state === "success" &&
754 resolveObjectResponse.data.comment
756 comments.unshift(resolveObjectResponse.data.comment);
761 nodes={commentsToFlatNodes(comments)}
762 viewType={CommentViewType.Flat}
766 enableDownvotes={enableDownvotes(siteRes)}
767 allLanguages={siteRes.all_languages}
768 siteLanguages={siteRes.discussion_languages}
769 // All of these are unused, since its viewonly
771 onSaveComment={() => {}}
772 onBlockPerson={() => {}}
773 onDeleteComment={() => {}}
774 onRemoveComment={() => {}}
775 onCommentVote={() => {}}
776 onCommentReport={() => {}}
777 onDistinguishComment={() => {}}
778 onAddModToCommunity={() => {}}
779 onAddAdmin={() => {}}
780 onTransferCommunity={() => {}}
781 onPurgeComment={() => {}}
782 onPurgePerson={() => {}}
783 onCommentReplyRead={() => {}}
784 onPersonMentionRead={() => {}}
785 onBanPersonFromCommunity={() => {}}
786 onBanPerson={() => {}}
787 onCreateComment={() => Promise.resolve({ state: "empty" })}
788 onEditComment={() => Promise.resolve({ state: "empty" })}
795 searchRes: searchResponse,
796 resolveObjectRes: resolveObjectResponse,
800 searchResponse.state === "success" ? searchResponse.data.posts : [];
803 resolveObjectResponse.state === "success" &&
804 resolveObjectResponse.data.post
806 posts.unshift(resolveObjectResponse.data.post);
812 <div key={pv.post.id} className="row">
813 <div className="col-12">
817 enableDownvotes={enableDownvotes(siteRes)}
818 enableNsfw={enableNsfw(siteRes)}
819 allLanguages={siteRes.all_languages}
820 siteLanguages={siteRes.discussion_languages}
822 // All of these are unused, since its view only
823 onPostEdit={() => {}}
824 onPostVote={() => {}}
825 onPostReport={() => {}}
826 onBlockPerson={() => {}}
827 onLockPost={() => {}}
828 onDeletePost={() => {}}
829 onRemovePost={() => {}}
830 onSavePost={() => {}}
831 onFeaturePost={() => {}}
832 onPurgePerson={() => {}}
833 onPurgePost={() => {}}
834 onBanPersonFromCommunity={() => {}}
835 onBanPerson={() => {}}
836 onAddModToCommunity={() => {}}
837 onAddAdmin={() => {}}
838 onTransferCommunity={() => {}}
849 searchRes: searchResponse,
850 resolveObjectRes: resolveObjectResponse,
853 searchResponse.state === "success" ? searchResponse.data.communities : [];
856 resolveObjectResponse.state === "success" &&
857 resolveObjectResponse.data.community
859 communities.unshift(resolveObjectResponse.data.community);
864 {communities.map(cv => (
865 <div key={cv.community.id} className="row">
866 <div className="col-12">{communityListing(cv)}</div>
875 searchRes: searchResponse,
876 resolveObjectRes: resolveObjectResponse,
879 searchResponse.state === "success" ? searchResponse.data.users : [];
882 resolveObjectResponse.state === "success" &&
883 resolveObjectResponse.data.person
885 users.unshift(resolveObjectResponse.data.person);
891 <div key={pvs.person.id} className="row">
892 <div className="col-12">{personListing(pvs)}</div>
899 get resultsCount(): number {
900 const { searchRes: r, resolveObjectRes: resolveRes } = this.state;
903 r.state === "success"
904 ? r.data.posts.length +
905 r.data.comments.length +
906 r.data.communities.length +
911 resolveRes.state === "success"
912 ? resolveRes.data.post ||
913 resolveRes.data.person ||
914 resolveRes.data.community ||
915 resolveRes.data.comment
920 return resObjCount + searchCount;
924 const auth = myAuth();
925 const { searchText: q } = this.state;
926 const { communityId, creatorId, type, sort, listingType, page } =
927 getSearchQueryParams();
930 this.setState({ searchRes: { state: "loading" } });
932 searchRes: await HttpService.client.search({
934 community_id: communityId ?? undefined,
935 creator_id: creatorId ?? undefined,
938 listing_type: listingType,
944 window.scrollTo(0, 0);
945 restoreScrollPosition(this.context);
948 this.setState({ resolveObjectRes: { state: "loading" } });
950 resolveObjectRes: await HttpService.client.resolveObject({
959 handleCreatorSearch = debounce(async (text: string) => {
960 const { creatorId } = getSearchQueryParams();
961 const { creatorSearchOptions } = this.state;
962 const newOptions: Choice[] = [];
964 this.setState({ searchCreatorLoading: true });
966 const selectedChoice = creatorSearchOptions.find(
967 choice => getIdFromString(choice.value) === creatorId
970 if (selectedChoice) {
971 newOptions.push(selectedChoice);
974 if (text.length > 0) {
975 newOptions.push(...(await fetchUsers(text)).map(personToChoice));
979 searchCreatorLoading: false,
980 creatorSearchOptions: newOptions,
984 handleCommunitySearch = debounce(async (text: string) => {
985 const { communityId } = getSearchQueryParams();
986 const { communitySearchOptions } = this.state;
988 searchCommunitiesLoading: true,
991 const newOptions: Choice[] = [];
993 const selectedChoice = communitySearchOptions.find(
994 choice => getIdFromString(choice.value) === communityId
997 if (selectedChoice) {
998 newOptions.push(selectedChoice);
1001 if (text.length > 0) {
1002 newOptions.push(...(await fetchCommunities(text)).map(communityToChoice));
1006 searchCommunitiesLoading: false,
1007 communitySearchOptions: newOptions,
1011 handleSortChange(sort: SortType) {
1012 this.updateUrl({ sort, page: 1 });
1015 handleTypeChange(i: Search, event: any) {
1016 const type = event.target.value as SearchType;
1024 handlePageChange(page: number) {
1025 this.updateUrl({ page });
1028 handleListingTypeChange(listingType: ListingType) {
1035 handleCommunityFilterChange({ value }: Choice) {
1037 communityId: getIdFromString(value) ?? null,
1042 handleCreatorFilterChange({ value }: Choice) {
1044 creatorId: getIdFromString(value) ?? null,
1049 handleSearchSubmit(i: Search, event: any) {
1050 event.preventDefault();
1053 q: i.state.searchText,
1058 handleQChange(i: Search, event: any) {
1059 i.setState({ searchText: event.target.value });
1070 }: Partial<SearchProps>) {
1074 listingType: urlListingType,
1075 communityId: urlCommunityId,
1077 creatorId: urlCreatorId,
1079 } = getSearchQueryParams();
1081 let query = q ?? this.state.searchText ?? urlQ;
1083 if (query && query.length > 0) {
1084 query = encodeURIComponent(query);
1087 const queryParams: QueryParams<SearchProps> = {
1089 type: type ?? urlType,
1090 listingType: listingType ?? urlListingType,
1091 communityId: getUpdatedSearchId(communityId, urlCommunityId),
1092 creatorId: getUpdatedSearchId(creatorId, urlCreatorId),
1093 page: (page ?? urlPage).toString(),
1094 sort: sort ?? urlSort,
1097 this.props.history.push(`/search${getQueryString(queryParams)}`);
1099 await this.search();