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)}
595 {i.type_ == "comments" && (
597 key={(i.data as CommentView).comment.id}
600 comment_view: i.data as CommentView,
605 viewType={CommentViewType.Flat}
609 maxCommentsShown={None}
612 enableDownvotes={enableDownvotes(this.state.siteRes)}
615 {i.type_ == "communities" && (
616 <div>{this.communityListing(i.data as CommunityView)}</div>
618 {i.type_ == "users" && (
619 <div>{this.userListing(i.data as PersonViewSafe)}</div>
629 let comments: CommentView[] = [];
631 this.state.resolveObjectResponse.match({
632 some: res => pushNotNull(comments, res.comment),
635 this.state.searchResponse.match({
636 some: res => pushNotNull(comments, res.comments),
642 nodes={commentsToFlatNodes(comments)}
643 viewType={CommentViewType.Flat}
649 maxCommentsShown={None}
650 enableDownvotes={enableDownvotes(this.state.siteRes)}
656 let posts: PostView[] = [];
658 this.state.resolveObjectResponse.match({
659 some: res => pushNotNull(posts, res.post),
662 this.state.searchResponse.match({
663 some: res => pushNotNull(posts, res.posts),
678 enableDownvotes={enableDownvotes(this.state.siteRes)}
679 enableNsfw={enableNsfw(this.state.siteRes)}
690 let communities: CommunityView[] = [];
692 this.state.resolveObjectResponse.match({
693 some: res => pushNotNull(communities, res.community),
696 this.state.searchResponse.match({
697 some: res => pushNotNull(communities, res.communities),
703 {communities.map(community => (
705 <div class="col-12">{this.communityListing(community)}</div>
713 let users: PersonViewSafe[] = [];
715 this.state.resolveObjectResponse.match({
716 some: res => pushNotNull(users, res.person),
719 this.state.searchResponse.match({
720 some: res => pushNotNull(users, res.users),
728 <div class="col-12">{this.userListing(user)}</div>
735 communityListing(community_view: CommunityView) {
739 <CommunityLink community={community_view.community} />
742 ${i18n.t("number_of_subscribers", {
743 count: community_view.counts.subscribers,
744 formattedCount: numToSI(community_view.counts.subscribers),
751 userListing(person_view: PersonViewSafe) {
754 <PersonListing person={person_view.person} showApubName />
756 <span>{` - ${i18n.t("number_of_comments", {
757 count: person_view.counts.comment_count,
758 formattedCount: numToSI(person_view.counts.comment_count),
765 <div class="form-group col-sm-6">
766 <label class="col-form-label" htmlFor="community-filter">
767 {i18n.t("community")}
772 id="community-filter"
773 value={this.state.communityId}
775 <option value="0">{i18n.t("all")}</option>
776 {this.state.communities.map(cv => (
777 <option value={cv.community.id}>{communitySelectName(cv)}</option>
787 <div class="form-group col-sm-6">
788 <label class="col-form-label" htmlFor="creator-filter">
789 {capitalizeFirstLetter(i18n.t("creator"))}
795 value={this.state.creatorId}
797 <option value="0">{i18n.t("all")}</option>
798 {this.state.creatorDetails.match({
800 <option value={creator.person_view.person.id}>
801 {personSelectName(creator.person_view)}
812 resultsCount(): number {
813 let searchCount = this.state.searchResponse
818 r.communities?.length +
823 let resObjCount = this.state.resolveObjectResponse
824 .map(r => (r.post || r.person || r.community || r.comment ? 1 : 0))
827 return resObjCount + searchCount;
830 handlePageChange(page: number) {
831 this.updateUrl({ page });
835 let community_id: Option<number> =
836 this.state.communityId == 0 ? None : Some(this.state.communityId);
837 let creator_id: Option<number> =
838 this.state.creatorId == 0 ? None : Some(this.state.creatorId);
840 let form = new SearchForm({
843 community_name: None,
845 type_: Some(this.state.type_),
846 sort: Some(this.state.sort),
847 listing_type: Some(this.state.listingType),
848 page: Some(this.state.page),
849 limit: Some(fetchLimit),
850 auth: auth(false).ok(),
853 let resolveObjectForm = new ResolveObject({
855 auth: auth(false).ok(),
858 if (this.state.q != "") {
859 this.state.searchResponse = None;
860 this.state.resolveObjectResponse = None;
861 this.state.loading = true;
862 this.setState(this.state);
863 WebSocketService.Instance.send(wsClient.search(form));
864 WebSocketService.Instance.send(wsClient.resolveObject(resolveObjectForm));
868 setupCommunityFilter() {
870 let selectId: any = document.getElementById("community-filter");
872 this.communityChoices = new Choices(selectId, choicesConfig);
873 this.communityChoices.passedElement.element.addEventListener(
876 this.handleCommunityFilterChange(Number(e.detail.choice.value));
880 this.communityChoices.passedElement.element.addEventListener(
882 debounce(async (e: any) => {
884 let communities = (await fetchCommunities(e.detail.value))
886 let choices = communities.map(cv => communityToChoice(cv));
887 choices.unshift({ value: "0", label: i18n.t("all") });
888 this.communityChoices.setChoices(choices, "value", "label", true);
899 setupCreatorFilter() {
901 let selectId: any = document.getElementById("creator-filter");
903 this.creatorChoices = new Choices(selectId, choicesConfig);
904 this.creatorChoices.passedElement.element.addEventListener(
907 this.handleCreatorFilterChange(Number(e.detail.choice.value));
911 this.creatorChoices.passedElement.element.addEventListener(
913 debounce(async (e: any) => {
915 let creators = (await fetchUsers(e.detail.value)).users;
916 let choices = creators.map(pvs => personToChoice(pvs));
917 choices.unshift({ value: "0", label: i18n.t("all") });
918 this.creatorChoices.setChoices(choices, "value", "label", true);
929 handleSortChange(val: SortType) {
930 this.updateUrl({ sort: val, page: 1 });
933 handleTypeChange(i: Search, event: any) {
935 type_: SearchType[event.target.value],
940 handleListingTypeChange(val: ListingType) {
947 handleCommunityFilterChange(communityId: number) {
954 handleCreatorFilterChange(creatorId: number) {
961 handleSearchSubmit(i: Search, event: any) {
962 event.preventDefault();
964 q: i.state.searchText,
965 type_: i.state.type_,
966 listingType: i.state.listingType,
967 communityId: i.state.communityId,
968 creatorId: i.state.creatorId,
974 handleQChange(i: Search, event: any) {
975 i.setState({ searchText: event.target.value });
978 updateUrl(paramUpdates: UrlParams) {
979 const qStr = paramUpdates.q || this.state.q;
980 const qStrEncoded = encodeURIComponent(qStr);
981 const typeStr = paramUpdates.type_ || this.state.type_;
982 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
983 const sortStr = paramUpdates.sort || this.state.sort;
985 paramUpdates.communityId == 0
987 : paramUpdates.communityId || this.state.communityId;
989 paramUpdates.creatorId == 0
991 : paramUpdates.creatorId || this.state.creatorId;
992 const page = paramUpdates.page || this.state.page;
993 this.props.history.push(
994 `/search/q/${qStrEncoded}/type/${typeStr}/sort/${sortStr}/listing_type/${listingTypeStr}/community_id/${communityId}/creator_id/${creatorId}/page/${page}`
998 parseMessage(msg: any) {
1000 let op = wsUserOp(msg);
1002 if (msg.error == "couldnt_find_object") {
1003 this.state.resolveObjectResponse = Some({
1009 this.checkFinishedLoading();
1011 toast(i18n.t(msg.error), "danger");
1014 } else if (op == UserOperation.Search) {
1015 let data = wsJsonToRes<SearchResponse>(msg, SearchResponse);
1016 this.state.searchResponse = Some(data);
1017 window.scrollTo(0, 0);
1018 this.checkFinishedLoading();
1019 restoreScrollPosition(this.context);
1020 } else if (op == UserOperation.CreateCommentLike) {
1021 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
1022 createCommentLikeRes(
1024 this.state.searchResponse.map(r => r.comments).unwrapOr([])
1026 this.setState(this.state);
1027 } else if (op == UserOperation.CreatePostLike) {
1028 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
1029 createPostLikeFindRes(
1031 this.state.searchResponse.map(r => r.posts).unwrapOr([])
1033 this.setState(this.state);
1034 } else if (op == UserOperation.ListCommunities) {
1035 let data = wsJsonToRes<ListCommunitiesResponse>(
1037 ListCommunitiesResponse
1039 this.state.communities = data.communities;
1040 this.setState(this.state);
1041 this.setupCommunityFilter();
1042 } else if (op == UserOperation.ResolveObject) {
1043 let data = wsJsonToRes<ResolveObjectResponse>(msg, ResolveObjectResponse);
1044 this.state.resolveObjectResponse = Some(data);
1045 this.checkFinishedLoading();
1049 checkFinishedLoading() {
1051 this.state.searchResponse.isSome() &&
1052 this.state.resolveObjectResponse.isSome()
1054 this.state.loading = false;
1055 this.setState(this.state);