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 { InitialFetchRequest } from "shared/interfaces";
30 import { i18n } from "../i18next";
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 this.state.communities = communitiesRes
204 .map(c => c.communities)
205 .unwrapOr([communityRes.map(c => c.community_view).unwrap()]);
207 this.state.creatorDetails = Some(
208 this.isoData.routeData[2] as GetPersonDetailsResponse
211 if (this.state.q != "") {
212 this.state.searchResponse = Some(
213 this.isoData.routeData[3] as SearchResponse
215 this.state.resolveObjectResponse = Some(
216 this.isoData.routeData[4] as ResolveObjectResponse
218 this.state.loading = false;
223 this.fetchCommunities();
228 componentWillUnmount() {
229 this.subscription.unsubscribe();
230 saveScrollPosition(this.context);
233 componentDidMount() {
234 this.setupCommunityFilter();
235 this.setupCreatorFilter();
238 static getDerivedStateFromProps(props: any): SearchProps {
240 q: Search.getSearchQueryFromProps(props.match.params.q),
241 type_: Search.getSearchTypeFromProps(props.match.params.type),
242 sort: Search.getSortTypeFromProps(props.match.params.sort),
243 listingType: Search.getListingTypeFromProps(
244 props.match.params.listing_type
246 communityId: Search.getCommunityIdFromProps(
247 props.match.params.community_id
249 creatorId: Search.getCreatorIdFromProps(props.match.params.creator_id),
250 page: Search.getPageFromProps(props.match.params.page),
255 let listCommunitiesForm = new ListCommunities({
256 type_: Some(ListingType.All),
257 sort: Some(SortType.TopAll),
258 limit: Some(fetchLimit),
260 auth: auth(false).ok(),
262 WebSocketService.Instance.send(
263 wsClient.listCommunities(listCommunitiesForm)
267 static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
268 let pathSplit = req.path.split("/");
269 let promises: Promise<any>[] = [];
271 let communityId = this.getCommunityIdFromProps(pathSplit[11]);
272 let community_id: Option<number> =
273 communityId == 0 ? None : Some(communityId);
276 let getCommunityForm = new GetCommunity({
281 promises.push(req.client.getCommunity(getCommunityForm));
282 promises.push(Promise.resolve());
285 let listCommunitiesForm = new ListCommunities({
286 type_: Some(ListingType.All),
287 sort: Some(SortType.TopAll),
288 limit: Some(fetchLimit),
292 promises.push(Promise.resolve());
293 promises.push(req.client.listCommunities(listCommunitiesForm));
297 let creatorId = this.getCreatorIdFromProps(pathSplit[13]);
298 let creator_id: Option<number> = creatorId == 0 ? None : Some(creatorId);
301 let getCreatorForm = new GetPersonDetails({
311 promises.push(req.client.getPersonDetails(getCreatorForm));
314 promises.push(Promise.resolve());
318 let form = new SearchForm({
319 q: this.getSearchQueryFromProps(pathSplit[3]),
321 community_name: None,
323 type_: Some(this.getSearchTypeFromProps(pathSplit[5])),
324 sort: Some(this.getSortTypeFromProps(pathSplit[7])),
325 listing_type: Some(this.getListingTypeFromProps(pathSplit[9])),
326 page: Some(this.getPageFromProps(pathSplit[15])),
327 limit: Some(fetchLimit),
331 let resolveObjectForm = new ResolveObject({
332 q: this.getSearchQueryFromProps(pathSplit[3]),
337 promises.push(req.client.search(form));
338 promises.push(req.client.resolveObject(resolveObjectForm));
340 promises.push(Promise.resolve());
341 promises.push(Promise.resolve());
347 componentDidUpdate(_: any, lastState: SearchState) {
349 lastState.q !== this.state.q ||
350 lastState.type_ !== this.state.type_ ||
351 lastState.sort !== this.state.sort ||
352 lastState.listingType !== this.state.listingType ||
353 lastState.communityId !== this.state.communityId ||
354 lastState.creatorId !== this.state.creatorId ||
355 lastState.page !== this.state.page
359 searchText: this.state.q,
360 searchResponse: None,
361 resolveObjectResponse: None,
367 get documentTitle(): string {
368 return this.state.siteRes.site_view.match({
371 ? `${i18n.t("search")} - ${this.state.q} - ${siteView.site.name}`
372 : `${i18n.t("search")} - ${siteView.site.name}`,
379 <div class="container">
381 title={this.documentTitle}
382 path={this.context.router.route.match.url}
386 <h5>{i18n.t("search")}</h5>
389 {this.state.type_ == SearchType.All && this.all()}
390 {this.state.type_ == SearchType.Comments && this.comments()}
391 {this.state.type_ == SearchType.Posts && this.posts()}
392 {this.state.type_ == SearchType.Communities && this.communities()}
393 {this.state.type_ == SearchType.Users && this.users()}
394 {this.state.type_ == SearchType.Url && this.posts()}
395 {this.resultsCount() == 0 && <span>{i18n.t("no_results")}</span>}
396 <Paginator page={this.state.page} onChange={this.handlePageChange} />
405 onSubmit={linkEvent(this, this.handleSearchSubmit)}
409 class="form-control mr-2 mb-2"
410 value={this.state.searchText}
411 placeholder={`${i18n.t("search")}...`}
412 aria-label={i18n.t("search")}
413 onInput={linkEvent(this, this.handleQChange)}
417 <button type="submit" class="btn btn-secondary mr-2 mb-2">
418 {this.state.loading ? <Spinner /> : <span>{i18n.t("search")}</span>}
426 <div className="mb-2">
428 value={this.state.type_}
429 onChange={linkEvent(this, this.handleTypeChange)}
430 class="custom-select w-auto mb-2"
431 aria-label={i18n.t("type")}
433 <option disabled aria-hidden="true">
436 <option value={SearchType.All}>{i18n.t("all")}</option>
437 <option value={SearchType.Comments}>{i18n.t("comments")}</option>
438 <option value={SearchType.Posts}>{i18n.t("posts")}</option>
439 <option value={SearchType.Communities}>
440 {i18n.t("communities")}
442 <option value={SearchType.Users}>{i18n.t("users")}</option>
443 <option value={SearchType.Url}>{i18n.t("url")}</option>
447 type_={this.state.listingType}
448 showLocal={showLocal(this.isoData)}
450 onChange={this.handleListingTypeChange}
455 sort={this.state.sort}
456 onChange={this.handleSortChange}
461 <div class="form-row">
462 {this.state.communities.length > 0 && this.communityFilter()}
463 {this.creatorFilter()}
469 postViewToCombined(postView: PostView): Combined {
473 published: postView.post.published,
477 commentViewToCombined(commentView: CommentView): Combined {
481 published: commentView.comment.published,
485 communityViewToCombined(communityView: CommunityView): Combined {
487 type_: "communities",
489 published: communityView.community.published,
493 personViewSafeToCombined(personViewSafe: PersonViewSafe): Combined {
496 data: personViewSafe,
497 published: personViewSafe.person.published,
501 buildCombined(): Combined[] {
502 let combined: Combined[] = [];
504 // Push the possible resolve / federated objects first
505 this.state.resolveObjectResponse.match({
507 let resolveComment = res.comment;
508 if (resolveComment.isSome()) {
509 combined.push(this.commentViewToCombined(resolveComment.unwrap()));
511 let resolvePost = res.post;
512 if (resolvePost.isSome()) {
513 combined.push(this.postViewToCombined(resolvePost.unwrap()));
515 let resolveCommunity = res.community;
516 if (resolveCommunity.isSome()) {
518 this.communityViewToCombined(resolveCommunity.unwrap())
521 let resolveUser = res.person;
522 if (resolveUser.isSome()) {
523 combined.push(this.personViewSafeToCombined(resolveUser.unwrap()));
529 // Push the search results
530 this.state.searchResponse.match({
534 res.comments?.map(e => this.commentViewToCombined(e))
538 res.posts?.map(e => this.postViewToCombined(e))
542 res.communities?.map(e => this.communityViewToCombined(e))
546 res.users?.map(e => this.personViewSafeToCombined(e))
553 if (this.state.sort == SortType.New) {
554 combined.sort((a, b) => b.published.localeCompare(a.published));
558 ((b.data as CommentView | PostView).counts.score |
559 (b.data as CommunityView).counts.subscribers |
560 (b.data as PersonViewSafe).counts.comment_score) -
561 ((a.data as CommentView | PostView).counts.score |
562 (a.data as CommunityView).counts.subscribers |
563 (a.data as PersonViewSafe).counts.comment_score)
570 let combined = this.buildCombined();
576 {i.type_ == "posts" && (
578 key={(i.data as PostView).post.id}
579 post_view={i.data as PostView}
584 enableDownvotes={enableDownvotes(this.state.siteRes)}
585 enableNsfw={enableNsfw(this.state.siteRes)}
588 {i.type_ == "comments" && (
590 key={(i.data as CommentView).comment.id}
591 nodes={[{ comment_view: i.data as CommentView }]}
594 maxCommentsShown={None}
597 enableDownvotes={enableDownvotes(this.state.siteRes)}
600 {i.type_ == "communities" && (
601 <div>{this.communityListing(i.data as CommunityView)}</div>
603 {i.type_ == "users" && (
604 <div>{this.userListing(i.data as PersonViewSafe)}</div>
614 let comments: CommentView[] = [];
616 this.state.resolveObjectResponse.match({
617 some: res => pushNotNull(comments, res.comment),
620 this.state.searchResponse.match({
621 some: res => pushNotNull(comments, res.comments),
627 nodes={commentsToFlatNodes(comments)}
632 maxCommentsShown={None}
633 enableDownvotes={enableDownvotes(this.state.siteRes)}
639 let posts: PostView[] = [];
641 this.state.resolveObjectResponse.match({
642 some: res => pushNotNull(posts, res.post),
645 this.state.searchResponse.match({
646 some: res => pushNotNull(posts, res.posts),
661 enableDownvotes={enableDownvotes(this.state.siteRes)}
662 enableNsfw={enableNsfw(this.state.siteRes)}
672 let communities: CommunityView[] = [];
674 this.state.resolveObjectResponse.match({
675 some: res => pushNotNull(communities, res.community),
678 this.state.searchResponse.match({
679 some: res => pushNotNull(communities, res.communities),
685 {communities.map(community => (
687 <div class="col-12">{this.communityListing(community)}</div>
695 let users: PersonViewSafe[] = [];
697 this.state.resolveObjectResponse.match({
698 some: res => pushNotNull(users, res.person),
701 this.state.searchResponse.match({
702 some: res => pushNotNull(users, res.users),
710 <div class="col-12">{this.userListing(user)}</div>
717 communityListing(community_view: CommunityView) {
721 <CommunityLink community={community_view.community} />
724 ${i18n.t("number_of_subscribers", {
725 count: community_view.counts.subscribers,
726 formattedCount: numToSI(community_view.counts.subscribers),
733 userListing(person_view: PersonViewSafe) {
736 <PersonListing person={person_view.person} showApubName />
738 <span>{` - ${i18n.t("number_of_comments", {
739 count: person_view.counts.comment_count,
740 formattedCount: numToSI(person_view.counts.comment_count),
747 <div class="form-group col-sm-6">
748 <label class="col-form-label" htmlFor="community-filter">
749 {i18n.t("community")}
754 id="community-filter"
755 value={this.state.communityId}
757 <option value="0">{i18n.t("all")}</option>
758 {this.state.communities.map(cv => (
759 <option value={cv.community.id}>{communitySelectName(cv)}</option>
769 <div class="form-group col-sm-6">
770 <label class="col-form-label" htmlFor="creator-filter">
771 {capitalizeFirstLetter(i18n.t("creator"))}
777 value={this.state.creatorId}
779 <option value="0">{i18n.t("all")}</option>
780 {this.state.creatorDetails.match({
782 <option value={creator.person_view.person.id}>
783 {personSelectName(creator.person_view)}
794 resultsCount(): number {
795 let searchCount = this.state.searchResponse
800 r.communities?.length +
805 let resObjCount = this.state.resolveObjectResponse
806 .map(r => (r.post || r.person || r.community || r.comment ? 1 : 0))
809 return resObjCount + searchCount;
812 handlePageChange(page: number) {
813 this.updateUrl({ page });
817 let community_id: Option<number> =
818 this.state.communityId == 0 ? None : Some(this.state.communityId);
819 let creator_id: Option<number> =
820 this.state.creatorId == 0 ? None : Some(this.state.creatorId);
822 console.log(community_id.unwrapOr(-22));
824 let form = new SearchForm({
827 community_name: None,
829 type_: Some(this.state.type_),
830 sort: Some(this.state.sort),
831 listing_type: Some(this.state.listingType),
832 page: Some(this.state.page),
833 limit: Some(fetchLimit),
834 auth: auth(false).ok(),
837 let resolveObjectForm = new ResolveObject({
839 auth: auth(false).ok(),
842 if (this.state.q != "") {
843 this.state.searchResponse = None;
844 this.state.resolveObjectResponse = None;
845 this.state.loading = true;
846 this.setState(this.state);
847 WebSocketService.Instance.send(wsClient.search(form));
848 WebSocketService.Instance.send(wsClient.resolveObject(resolveObjectForm));
852 setupCommunityFilter() {
854 let selectId: any = document.getElementById("community-filter");
856 this.communityChoices = new Choices(selectId, choicesConfig);
857 this.communityChoices.passedElement.element.addEventListener(
860 this.handleCommunityFilterChange(Number(e.detail.choice.value));
864 this.communityChoices.passedElement.element.addEventListener(
866 debounce(async (e: any) => {
868 let communities = (await fetchCommunities(e.detail.value))
870 let choices = communities.map(cv => communityToChoice(cv));
871 choices.unshift({ value: "0", label: i18n.t("all") });
872 this.communityChoices.setChoices(choices, "value", "label", true);
883 setupCreatorFilter() {
885 let selectId: any = document.getElementById("creator-filter");
887 this.creatorChoices = new Choices(selectId, choicesConfig);
888 this.creatorChoices.passedElement.element.addEventListener(
891 this.handleCreatorFilterChange(Number(e.detail.choice.value));
895 this.creatorChoices.passedElement.element.addEventListener(
897 debounce(async (e: any) => {
899 let creators = (await fetchUsers(e.detail.value)).users;
900 let choices = creators.map(pvs => personToChoice(pvs));
901 choices.unshift({ value: "0", label: i18n.t("all") });
902 this.creatorChoices.setChoices(choices, "value", "label", true);
913 handleSortChange(val: SortType) {
914 this.updateUrl({ sort: val, page: 1 });
917 handleTypeChange(i: Search, event: any) {
919 type_: SearchType[event.target.value],
924 handleListingTypeChange(val: ListingType) {
931 handleCommunityFilterChange(communityId: number) {
938 handleCreatorFilterChange(creatorId: number) {
945 handleSearchSubmit(i: Search, event: any) {
946 event.preventDefault();
948 q: i.state.searchText,
949 type_: i.state.type_,
950 listingType: i.state.listingType,
951 communityId: i.state.communityId,
952 creatorId: i.state.creatorId,
958 handleQChange(i: Search, event: any) {
959 i.setState({ searchText: event.target.value });
962 updateUrl(paramUpdates: UrlParams) {
963 const qStr = paramUpdates.q || this.state.q;
964 const qStrEncoded = encodeURIComponent(qStr);
965 const typeStr = paramUpdates.type_ || this.state.type_;
966 const listingTypeStr = paramUpdates.listingType || this.state.listingType;
967 const sortStr = paramUpdates.sort || this.state.sort;
969 paramUpdates.communityId == 0
971 : paramUpdates.communityId || this.state.communityId;
973 paramUpdates.creatorId == 0
975 : paramUpdates.creatorId || this.state.creatorId;
976 const page = paramUpdates.page || this.state.page;
977 this.props.history.push(
978 `/search/q/${qStrEncoded}/type/${typeStr}/sort/${sortStr}/listing_type/${listingTypeStr}/community_id/${communityId}/creator_id/${creatorId}/page/${page}`
982 parseMessage(msg: any) {
984 let op = wsUserOp(msg);
986 if (msg.error == "couldnt_find_object") {
987 this.state.resolveObjectResponse = Some({
993 this.checkFinishedLoading();
995 toast(i18n.t(msg.error), "danger");
998 } else if (op == UserOperation.Search) {
999 let data = wsJsonToRes<SearchResponse>(msg, SearchResponse);
1000 this.state.searchResponse = Some(data);
1001 window.scrollTo(0, 0);
1002 this.checkFinishedLoading();
1003 restoreScrollPosition(this.context);
1004 } else if (op == UserOperation.CreateCommentLike) {
1005 let data = wsJsonToRes<CommentResponse>(msg, CommentResponse);
1006 createCommentLikeRes(
1008 this.state.searchResponse.map(r => r.comments).unwrapOr([])
1010 this.setState(this.state);
1011 } else if (op == UserOperation.CreatePostLike) {
1012 let data = wsJsonToRes<PostResponse>(msg, PostResponse);
1013 createPostLikeFindRes(
1015 this.state.searchResponse.map(r => r.posts).unwrapOr([])
1017 this.setState(this.state);
1018 } else if (op == UserOperation.ListCommunities) {
1019 let data = wsJsonToRes<ListCommunitiesResponse>(
1021 ListCommunitiesResponse
1023 this.state.communities = data.communities;
1024 this.setState(this.state);
1025 this.setupCommunityFilter();
1026 } else if (op == UserOperation.ResolveObject) {
1027 let data = wsJsonToRes<ResolveObjectResponse>(msg, ResolveObjectResponse);
1028 this.state.resolveObjectResponse = Some(data);
1029 this.checkFinishedLoading();
1033 checkFinishedLoading() {
1035 this.state.searchResponse.isSome() &&
1036 this.state.resolveObjectResponse.isSome()
1038 this.state.loading = false;
1039 this.setState(this.state);