1 import { None, Option, Some } from "@sniptt/monads";
2 import { Component, linkEvent } from "inferno";
10 GetPersonDetailsResponse,
13 ListCommunitiesResponse,
19 ResolveObjectResponse,
27 } from "lemmy-js-client";
28 import { Subscription } from "rxjs";
29 import { i18n } from "../i18next";
30 import { CommentViewType, InitialFetchRequest } from "../interfaces";
31 import { WebSocketService } from "../services";
34 capitalizeFirstLetter,
40 createPostLikeFindRes,
52 restoreScrollPosition,
53 routeListingTypeToEnum,
54 routeSearchTypeToEnum,
63 import { CommentNodes } from "./comment/comment-nodes";
64 import { HtmlTags } from "./common/html-tags";
65 import { Spinner } from "./common/icon";
66 import { ListingTypeSelect } from "./common/listing-type-select";
67 import { Paginator } from "./common/paginator";
68 import { SortSelect } from "./common/sort-select";
69 import { CommunityLink } from "./community/community-link";
70 import { PersonListing } from "./person/person-listing";
71 import { PostListing } from "./post/post-listing";
75 Choices = require("choices.js");
78 interface SearchProps {
82 listingType: ListingType;
88 interface SearchState {
92 listingType: ListingType;
96 searchResponse: Option<SearchResponse>;
97 communities: CommunityView[];
98 creatorDetails: Option<GetPersonDetailsResponse>;
100 siteRes: GetSiteResponse;
102 resolveObjectResponse: Option<ResolveObjectResponse>;
105 interface UrlParams {
109 listingType?: ListingType;
110 communityId?: number;
117 data: CommentView | PostView | CommunityView | PersonViewSafe;
121 export class Search extends Component<any, SearchState> {
122 private isoData = setIsoData(
124 GetCommunityResponse,
125 ListCommunitiesResponse,
126 GetPersonDetailsResponse,
128 ResolveObjectResponse
130 private communityChoices: any;
131 private creatorChoices: any;
132 private subscription: Subscription;
133 private emptyState: SearchState = {
134 q: Search.getSearchQueryFromProps(this.props.match.params.q),
135 type_: Search.getSearchTypeFromProps(this.props.match.params.type),
136 sort: Search.getSortTypeFromProps(this.props.match.params.sort),
137 listingType: Search.getListingTypeFromProps(
138 this.props.match.params.listing_type
140 page: Search.getPageFromProps(this.props.match.params.page),
141 searchText: Search.getSearchQueryFromProps(this.props.match.params.q),
142 communityId: Search.getCommunityIdFromProps(
143 this.props.match.params.community_id
145 creatorId: Search.getCreatorIdFromProps(this.props.match.params.creator_id),
146 searchResponse: None,
147 resolveObjectResponse: None,
148 creatorDetails: None,
150 siteRes: this.isoData.site_res,
154 static getSearchQueryFromProps(q: string): string {
155 return decodeURIComponent(q) || "";
158 static getSearchTypeFromProps(type_: string): SearchType {
159 return type_ ? routeSearchTypeToEnum(type_) : SearchType.All;
162 static getSortTypeFromProps(sort: string): SortType {
163 return sort ? routeSortTypeToEnum(sort) : SortType.TopAll;
166 static getListingTypeFromProps(listingType: string): ListingType {
167 return listingType ? routeListingTypeToEnum(listingType) : ListingType.All;
170 static getCommunityIdFromProps(id: string): number {
171 return id ? Number(id) : 0;
174 static getCreatorIdFromProps(id: string): number {
175 return id ? Number(id) : 0;
178 static getPageFromProps(page: string): number {
179 return page ? Number(page) : 1;
182 constructor(props: any, context: any) {
183 super(props, context);
185 this.state = this.emptyState;
186 this.handleSortChange = this.handleSortChange.bind(this);
187 this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
188 this.handlePageChange = this.handlePageChange.bind(this);
190 this.parseMessage = this.parseMessage.bind(this);
191 this.subscription = wsSubscribe(this.parseMessage);
193 // Only fetch the data if coming from another route
194 if (this.isoData.path == this.context.router.route.match.url) {
195 let communityRes = Some(
196 this.isoData.routeData[0] as GetCommunityResponse
198 let communitiesRes = Some(
199 this.isoData.routeData[1] as ListCommunitiesResponse
202 // This can be single or multiple communities given
203 communitiesRes.match({
204 some: res => (this.state.communities = res.communities),
209 some: res => (this.state.communities = [res.community_view]),
213 this.state.creatorDetails = Some(
214 this.isoData.routeData[2] as GetPersonDetailsResponse
217 if (this.state.q != "") {
218 this.state.searchResponse = Some(
219 this.isoData.routeData[3] as SearchResponse
221 this.state.resolveObjectResponse = Some(
222 this.isoData.routeData[4] as ResolveObjectResponse
224 this.state.loading = false;
229 this.fetchCommunities();
234 componentWillUnmount() {
235 this.subscription.unsubscribe();
236 saveScrollPosition(this.context);
239 componentDidMount() {
240 this.setupCommunityFilter();
241 this.setupCreatorFilter();
244 static getDerivedStateFromProps(props: any): SearchProps {
246 q: Search.getSearchQueryFromProps(props.match.params.q),
247 type_: Search.getSearchTypeFromProps(props.match.params.type),
248 sort: Search.getSortTypeFromProps(props.match.params.sort),
249 listingType: Search.getListingTypeFromProps(
250 props.match.params.listing_type
252 communityId: Search.getCommunityIdFromProps(
253 props.match.params.community_id
255 creatorId: Search.getCreatorIdFromProps(props.match.params.creator_id),
256 page: Search.getPageFromProps(props.match.params.page),
261 let listCommunitiesForm = new ListCommunities({
262 type_: Some(ListingType.All),
263 sort: Some(SortType.TopAll),
264 limit: Some(fetchLimit),
266 auth: auth(false).ok(),
268 WebSocketService.Instance.send(
269 wsClient.listCommunities(listCommunitiesForm)
273 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
274 let pathSplit = req.path.split("/");
275 let promises: Promise<any>[] = [];
277 let communityId = this.getCommunityIdFromProps(pathSplit[11]);
278 let community_id: Option<number> =
279 communityId == 0 ? None : Some(communityId);
282 let getCommunityForm = new GetCommunity({
287 promises.push(req.client.getCommunity(getCommunityForm));
288 promises.push(Promise.resolve());
291 let listCommunitiesForm = new ListCommunities({
292 type_: Some(ListingType.All),
293 sort: Some(SortType.TopAll),
294 limit: Some(fetchLimit),
298 promises.push(Promise.resolve());
299 promises.push(req.client.listCommunities(listCommunitiesForm));
303 let creatorId = this.getCreatorIdFromProps(pathSplit[13]);
304 let creator_id: Option<number> = creatorId == 0 ? None : Some(creatorId);
307 let getCreatorForm = new GetPersonDetails({
317 promises.push(req.client.getPersonDetails(getCreatorForm));
320 promises.push(Promise.resolve());
324 let form = new SearchForm({
325 q: this.getSearchQueryFromProps(pathSplit[3]),
327 community_name: None,
329 type_: Some(this.getSearchTypeFromProps(pathSplit[5])),
330 sort: Some(this.getSortTypeFromProps(pathSplit[7])),
331 listing_type: Some(this.getListingTypeFromProps(pathSplit[9])),
332 page: Some(this.getPageFromProps(pathSplit[15])),
333 limit: Some(fetchLimit),
337 let resolveObjectForm = new ResolveObject({
338 q: this.getSearchQueryFromProps(pathSplit[3]),
343 promises.push(req.client.search(form));
344 promises.push(req.client.resolveObject(resolveObjectForm));
346 promises.push(Promise.resolve());
347 promises.push(Promise.resolve());
353 componentDidUpdate(_: any, lastState: SearchState) {
355 lastState.q !== this.state.q ||
356 lastState.type_ !== this.state.type_ ||
357 lastState.sort !== this.state.sort ||
358 lastState.listingType !== this.state.listingType ||
359 lastState.communityId !== this.state.communityId ||
360 lastState.creatorId !== this.state.creatorId ||
361 lastState.page !== this.state.page
365 searchText: this.state.q,
366 searchResponse: None,
367 resolveObjectResponse: None,
373 get documentTitle(): string {
374 return this.state.siteRes.site_view.match({
377 ? `${i18n.t("search")} - ${this.state.q} - ${siteView.site.name}`
378 : `${i18n.t("search")} - ${siteView.site.name}`,
385 <div class="container">
387 title={this.documentTitle}
388 path={this.context.router.route.match.url}
392 <h5>{i18n.t("search")}</h5>
395 {this.state.type_ == SearchType.All && this.all()}
396 {this.state.type_ == SearchType.Comments && this.comments()}
397 {this.state.type_ == SearchType.Posts && this.posts()}
398 {this.state.type_ == SearchType.Communities && this.communities()}
399 {this.state.type_ == SearchType.Users && this.users()}
400 {this.state.type_ == SearchType.Url && this.posts()}
401 {this.resultsCount() == 0 && <span>{i18n.t("no_results")}</span>}
402 <Paginator page={this.state.page} onChange={this.handlePageChange} />
411 onSubmit={linkEvent(this, this.handleSearchSubmit)}
415 class="form-control mr-2 mb-2"
416 value={this.state.searchText}
417 placeholder={`${i18n.t("search")}...`}
418 aria-label={i18n.t("search")}
419 onInput={linkEvent(this, this.handleQChange)}
423 <button type="submit" class="btn btn-secondary mr-2 mb-2">
424 {this.state.loading ? <Spinner /> : <span>{i18n.t("search")}</span>}
432 <div className="mb-2">
434 value={this.state.type_}
435 onChange={linkEvent(this, this.handleTypeChange)}
436 class="custom-select w-auto mb-2"
437 aria-label={i18n.t("type")}
439 <option disabled aria-hidden="true">
442 <option value={SearchType.All}>{i18n.t("all")}</option>
443 <option value={SearchType.Comments}>{i18n.t("comments")}</option>
444 <option value={SearchType.Posts}>{i18n.t("posts")}</option>
445 <option value={SearchType.Communities}>
446 {i18n.t("communities")}
448 <option value={SearchType.Users}>{i18n.t("users")}</option>
449 <option value={SearchType.Url}>{i18n.t("url")}</option>
453 type_={this.state.listingType}
454 showLocal={showLocal(this.isoData)}
456 onChange={this.handleListingTypeChange}
461 sort={this.state.sort}
462 onChange={this.handleSortChange}
467 <div class="form-row">
468 {this.state.communities.length > 0 && this.communityFilter()}
469 {this.creatorFilter()}
475 postViewToCombined(postView: PostView): Combined {
479 published: postView.post.published,
483 commentViewToCombined(commentView: CommentView): Combined {
487 published: commentView.comment.published,
491 communityViewToCombined(communityView: CommunityView): Combined {
493 type_: "communities",
495 published: communityView.community.published,
499 personViewSafeToCombined(personViewSafe: PersonViewSafe): Combined {
502 data: personViewSafe,
503 published: personViewSafe.person.published,
507 buildCombined(): Combined[] {
508 let combined: Combined[] = [];
510 // Push the possible resolve / federated objects first
511 this.state.resolveObjectResponse.match({
513 let resolveComment = res.comment;
514 if (resolveComment.isSome()) {
515 combined.push(this.commentViewToCombined(resolveComment.unwrap()));
517 let resolvePost = res.post;
518 if (resolvePost.isSome()) {
519 combined.push(this.postViewToCombined(resolvePost.unwrap()));
521 let resolveCommunity = res.community;
522 if (resolveCommunity.isSome()) {
524 this.communityViewToCombined(resolveCommunity.unwrap())
527 let resolveUser = res.person;
528 if (resolveUser.isSome()) {
529 combined.push(this.personViewSafeToCombined(resolveUser.unwrap()));
535 // Push the search results
536 this.state.searchResponse.match({
540 res.comments?.map(e => this.commentViewToCombined(e))
544 res.posts?.map(e => this.postViewToCombined(e))
548 res.communities?.map(e => this.communityViewToCombined(e))
552 res.users?.map(e => this.personViewSafeToCombined(e))
559 if (this.state.sort == SortType.New) {
560 combined.sort((a, b) => b.published.localeCompare(a.published));
564 ((b.data as CommentView | PostView).counts.score |
565 (b.data as CommunityView).counts.subscribers |
566 (b.data as PersonViewSafe).counts.comment_score) -
567 ((a.data as CommentView | PostView).counts.score |
568 (a.data as CommunityView).counts.subscribers |
569 (a.data as PersonViewSafe).counts.comment_score)
576 let combined = this.buildCombined();
582 {i.type_ == "posts" && (
584 key={(i.data as PostView).post.id}
585 post_view={i.data as PostView}
590 enableDownvotes={enableDownvotes(this.state.siteRes)}
591 enableNsfw={enableNsfw(this.state.siteRes)}
594 {i.type_ == "comments" && (
596 key={(i.data as CommentView).comment.id}
599 comment_view: i.data as CommentView,
604 viewType={CommentViewType.Flat}
607 maxCommentsShown={None}
610 enableDownvotes={enableDownvotes(this.state.siteRes)}
613 {i.type_ == "communities" && (
614 <div>{this.communityListing(i.data as CommunityView)}</div>
616 {i.type_ == "users" && (
617 <div>{this.userListing(i.data as PersonViewSafe)}</div>
627 let comments: CommentView[] = [];
629 this.state.resolveObjectResponse.match({
630 some: res => pushNotNull(comments, res.comment),
633 this.state.searchResponse.match({
634 some: res => pushNotNull(comments, res.comments),
640 nodes={commentsToFlatNodes(comments)}
641 viewType={CommentViewType.Flat}
646 maxCommentsShown={None}
647 enableDownvotes={enableDownvotes(this.state.siteRes)}
653 let posts: PostView[] = [];
655 this.state.resolveObjectResponse.match({
656 some: res => pushNotNull(posts, res.post),
659 this.state.searchResponse.match({
660 some: res => pushNotNull(posts, res.posts),
675 enableDownvotes={enableDownvotes(this.state.siteRes)}
676 enableNsfw={enableNsfw(this.state.siteRes)}
686 let communities: CommunityView[] = [];
688 this.state.resolveObjectResponse.match({
689 some: res => pushNotNull(communities, res.community),
692 this.state.searchResponse.match({
693 some: res => pushNotNull(communities, res.communities),
699 {communities.map(community => (
701 <div class="col-12">{this.communityListing(community)}</div>
709 let users: PersonViewSafe[] = [];
711 this.state.resolveObjectResponse.match({
712 some: res => pushNotNull(users, res.person),
715 this.state.searchResponse.match({
716 some: res => pushNotNull(users, res.users),
724 <div class="col-12">{this.userListing(user)}</div>
731 communityListing(community_view: CommunityView) {
735 <CommunityLink community={community_view.community} />
738 ${i18n.t("number_of_subscribers", {
739 count: community_view.counts.subscribers,
740 formattedCount: numToSI(community_view.counts.subscribers),
747 userListing(person_view: PersonViewSafe) {
750 <PersonListing person={person_view.person} showApubName />
752 <span>{` - ${i18n.t("number_of_comments", {
753 count: person_view.counts.comment_count,
754 formattedCount: numToSI(person_view.counts.comment_count),
761 <div class="form-group col-sm-6">
762 <label class="col-form-label" htmlFor="community-filter">
763 {i18n.t("community")}
768 id="community-filter"
769 value={this.state.communityId}
771 <option value="0">{i18n.t("all")}</option>
772 {this.state.communities.map(cv => (
773 <option value={cv.community.id}>{communitySelectName(cv)}</option>
783 <div class="form-group col-sm-6">
784 <label class="col-form-label" htmlFor="creator-filter">
785 {capitalizeFirstLetter(i18n.t("creator"))}
791 value={this.state.creatorId}
793 <option value="0">{i18n.t("all")}</option>
794 {this.state.creatorDetails.match({
796 <option value={creator.person_view.person.id}>
797 {personSelectName(creator.person_view)}
808 resultsCount(): number {
809 let searchCount = this.state.searchResponse
814 r.communities?.length +
819 let resObjCount = this.state.resolveObjectResponse
820 .map(r => (r.post || r.person || r.community || r.comment ? 1 : 0))
823 return resObjCount + searchCount;
826 handlePageChange(page: number) {
827 this.updateUrl({ page });
831 let community_id: Option<number> =
832 this.state.communityId == 0 ? None : Some(this.state.communityId);
833 let creator_id: Option<number> =
834 this.state.creatorId == 0 ? None : Some(this.state.creatorId);
836 let form = new SearchForm({
839 community_name: None,
841 type_: Some(this.state.type_),
842 sort: Some(this.state.sort),
843 listing_type: Some(this.state.listingType),
844 page: Some(this.state.page),
845 limit: Some(fetchLimit),
846 auth: auth(false).ok(),
849 let resolveObjectForm = new ResolveObject({
851 auth: auth(false).ok(),
854 if (this.state.q != "") {
855 this.state.searchResponse = None;
856 this.state.resolveObjectResponse = None;
857 this.state.loading = true;
858 this.setState(this.state);
859 WebSocketService.Instance.send(wsClient.search(form));
860 WebSocketService.Instance.send(wsClient.resolveObject(resolveObjectForm));
864 setupCommunityFilter() {
866 let selectId: any = document.getElementById("community-filter");
868 this.communityChoices = new Choices(selectId, choicesConfig);
869 this.communityChoices.passedElement.element.addEventListener(
872 this.handleCommunityFilterChange(Number(e.detail.choice.value));
876 this.communityChoices.passedElement.element.addEventListener(
878 debounce(async (e: any) => {
880 let communities = (await fetchCommunities(e.detail.value))
882 let choices = communities.map(cv => communityToChoice(cv));
883 choices.unshift({ value: "0", label: i18n.t("all") });
884 this.communityChoices.setChoices(choices, "value", "label", true);
895 setupCreatorFilter() {
897 let selectId: any = document.getElementById("creator-filter");
899 this.creatorChoices = new Choices(selectId, choicesConfig);
900 this.creatorChoices.passedElement.element.addEventListener(
903 this.handleCreatorFilterChange(Number(e.detail.choice.value));
907 this.creatorChoices.passedElement.element.addEventListener(
909 debounce(async (e: any) => {
911 let creators = (await fetchUsers(e.detail.value)).users;
912 let choices = creators.map(pvs => personToChoice(pvs));
913 choices.unshift({ value: "0", label: i18n.t("all") });
914 this.creatorChoices.setChoices(choices, "value", "label", true);
925 handleSortChange(val: SortType) {
926 this.updateUrl({ sort: val, page: 1 });
929 handleTypeChange(i: Search, event: any) {
931 type_: SearchType[event.target.value],
936 handleListingTypeChange(val: ListingType) {
943 handleCommunityFilterChange(communityId: number) {
950 handleCreatorFilterChange(creatorId: number) {
957 handleSearchSubmit(i: Search, event: any) {
958 event.preventDefault();
960 q: i.state.searchText,
961 type_: i.state.type_,
962 listingType: i.state.listingType,
963 communityId: i.state.communityId,
964 creatorId: i.state.creatorId,
970 handleQChange(i: Search, event: any) {
971 i.setState({ searchText: event.target.value });
974 updateUrl(paramUpdates: UrlParams) {
975 const qStr = paramUpdates.q || this.state.q;
976 const qStrEncoded = encodeURIComponent(qStr);
977 const typeStr = paramUpdates.type_ || this.state.type_;
978 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
979 const sortStr = paramUpdates.sort || this.state.sort;
981 paramUpdates.communityId == 0
983 : paramUpdates.communityId || this.state.communityId;
985 paramUpdates.creatorId == 0
987 : paramUpdates.creatorId || this.state.creatorId;
988 const page = paramUpdates.page || this.state.page;
989 this.props.history.push(
990 `/search/q/${qStrEncoded}/type/${typeStr}/sort/${sortStr}/listing_type/${listingTypeStr}/community_id/${communityId}/creator_id/${creatorId}/page/${page}`
994 parseMessage(msg: any) {
996 let op = wsUserOp(msg);
998 if (msg.error == "couldnt_find_object") {
999 this.state.resolveObjectResponse = Some({
1005 this.checkFinishedLoading();
1007 toast(i18n.t(msg.error), "danger");
1010 } else if (op == UserOperation.Search) {
1011 let data = wsJsonToRes<SearchResponse>(msg, SearchResponse);
1012 this.state.searchResponse = Some(data);
1013 window.scrollTo(0, 0);
1014 this.checkFinishedLoading();
1015 restoreScrollPosition(this.context);
1016 } else if (op == UserOperation.CreateCommentLike) {
1017 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
1018 createCommentLikeRes(
1020 this.state.searchResponse.map(r => r.comments).unwrapOr([])
1022 this.setState(this.state);
1023 } else if (op == UserOperation.CreatePostLike) {
1024 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
1025 createPostLikeFindRes(
1027 this.state.searchResponse.map(r => r.posts).unwrapOr([])
1029 this.setState(this.state);
1030 } else if (op == UserOperation.ListCommunities) {
1031 let data = wsJsonToRes<ListCommunitiesResponse>(
1033 ListCommunitiesResponse
1035 this.state.communities = data.communities;
1036 this.setState(this.state);
1037 this.setupCommunityFilter();
1038 } else if (op == UserOperation.ResolveObject) {
1039 let data = wsJsonToRes<ResolveObjectResponse>(msg, ResolveObjectResponse);
1040 this.state.resolveObjectResponse = Some(data);
1041 this.checkFinishedLoading();
1045 checkFinishedLoading() {
1047 this.state.searchResponse.isSome() &&
1048 this.state.resolveObjectResponse.isSome()
1050 this.state.loading = false;
1051 this.setState(this.state);