import { LitElement, html, TemplateResult, nothing, type PropertyValueMap } from "lit"; import { customElement } from "../utils/decorators/custom-element"; import { property, state } from "lit/decorators.js"; import { consume } from "@lit/context"; import { type WeavyType, WeavyContext } from "../contexts/weavy-context"; import { Ref, createRef, ref } from "lit/directives/ref.js"; import type { MemberType } from "../types/members.types"; import { getInfiniteSearchMemberOptions } from "../data/members"; import { getBlockedUserIdsOptions } from "../data/blocks"; import { localized, msg } from "@lit/localize"; import { InfiniteQueryController } from "../controllers/infinite-query-controller"; import { QueryController } from "../controllers/query-controller"; import { InfiniteScrollController } from "../controllers/infinite-scroll-controller"; import { clickOnEnterAndConsumeOnSpace } from "../utils/keyboard"; import { ShadowPartsController } from "../controllers/shadow-parts-controller"; import { InfiniteQueryResultType } from "../types/query.types"; import { getFlatInfiniteResultData } from "../utils/query-cache"; import type { MemberSearchSubmitEventType } from "../types/members.events"; import type { NamedEvent } from "../types/generic.types"; import type { SearchEventType } from "../types/search.events"; import type { WySearch } from "./ui/wy-search"; import { partMap } from "../utils/directives/shadow-part-map"; import paneCss from "../scss/components/pane.scss"; import footerbarCss from "../scss/components/footerbar.scss"; import inputCss from "../scss/components/input.scss"; import scrollCss from "../scss/scroll.scss"; import pagerCss from "../scss/components/pager.scss"; import hostContentsCss from "../scss/host-contents.scss"; import "./ui/wy-button"; import "./ui/wy-icon"; import "./ui/wy-item"; import "./ui/wy-avatar"; import "./ui/wy-progress-circular"; import "./ui/wy-search"; declare global { interface HTMLElementTagNameMap { "wy-users-search": WyUsersSearch; } } /** * User search UI used to find and pick members for apps. * * **Used sub components:** * * - [``](./ui/wy-search.ts) * - [``](./ui/wy-item.ts) * - [``](./ui/wy-avatar.ts) * - [``](./ui/wy-button.ts) * - [``](./ui/wy-icon.ts) * - [``](./ui/wy-progress-circular.ts) * * @csspart wy-pane - Root pane container. * @csspart wy-pane-body - Body area for content. * @csspart wy-pane-group - Group wrapper inside pane. * @csspart wy-no-result - Message shown when there are no results. * @csspart wy-users-search-blocked - A result row for a user the authenticated user has blocked. * @csspart wy-footerbar - Footer bar container. * @csspart wy-footerbar-sticky - Sticky footer modifier. * @csspart wy-pager - Pager container. * @csspart wy-pager-bottom - Pager bottom modifier. * * @fires {MemberSearchSubmitEventType} submit - Emitted when the selected members are submitted. */ @customElement("wy-users-search") @localized() export class WyUsersSearch extends LitElement { static override styles = [scrollCss, footerbarCss, inputCss, pagerCss, hostContentsCss, paneCss]; protected exportParts = new ShadowPartsController(this); /** * Consumed Weavy client used for querying members. * * @internal */ @consume({ context: WeavyContext, subscribe: true }) @state() weavy?: WeavyType; /** * App identifier used to scope member searches. */ @property({ attribute: false }) appId?: number; /** * Label for the submit button. */ @property({ attribute: false }) buttonTitle?: string; /** * Whether blocking is available in the host component. * * Governs whether the block list is tracked at all. With the feature off there is no way to block or unblock anyone * from here, so the list would only ever be an empty answer to a question nobody asked. */ @property({ attribute: false }) canBlock: boolean = false; /** * Filters search results to agents, non-agents, or all members. * * @internal */ @state() agentFilter?: boolean = false; /** * Members already chosen prior to the current selection. * * @internal */ @state() private selected: MemberType[] = []; /** * Members marked during the current selection session. * * @internal */ @state() private select: MemberType[] = []; /** * Current search query text. * * @internal */ @state() text: string = ""; /** * Infinite query controller handling member search responses. * * @internal */ peopleQuery = new InfiniteQueryController>(this); /** * Query controller for the ids of the users the viewer has blocked. * * Searching without an `appId` goes to `/api/users`, which maps users in summary form and carries no * `is_blocked` -- that flag is answered per user only by the detailed representation. The list is what fills the gap. * * @internal */ private blockedUsersQuery = new QueryController(this); /** * Reference to the search input instance. * * @internal */ private searchRef: Ref = createRef(); /** * Controls incremental loading when scrolling. * * @internal */ private infiniteScroll = new InfiniteScrollController(this); /** * Pager sentinel element reference for infinite scroll. * * @internal */ private pagerRef: Ref = createRef(); /** * Emits the selected members via the `submit` event. * * @internal * @returns {boolean} `true` if the event was not canceled. */ private dispatchSubmit() { // Carry the resolved flag out with the selection rather than leaving it to the consumer: the new-conversation // picker acts on `is_blocked`, and a search outside an app returns users in summary form, which does not carry it. const blockedUserIds = this.blockedUsersQuery.result?.data; this.selected = [...this.selected, ...this.select].map((member) => blockedUserIds?.includes(member.id) ? { ...member, is_blocked: true } : member ); const event: MemberSearchSubmitEventType = new (CustomEvent as NamedEvent)("submit", { detail: { members: this.selected }, }); return this.dispatchEvent(event); } /** * Checks whether a member is currently selected. * * @internal */ private isChecked(memberId: number): boolean { return ( this.select.find((m) => { return m.id === memberId; }) != null ); } /** * Toggles selection state for the provided member. * * @internal */ private handleSelected(member: MemberType, checked: boolean) { if (checked) { this.select = [...this.select, member]; } else { this.select = this.select.filter((m) => { return m.id !== member.id; }); this.selected = this.selected.filter((m) => { return m.id !== member.id; }); } } /** * Renders the list of currently selected members. * * @internal */ getSelected() { if (this.selected.length > 0) { return html` ${this.selected.map((member: MemberType) => { return html` this.handleSelected(member, false)} @keydown=${clickOnEnterAndConsumeOnSpace} @keyup=${clickOnEnterAndConsumeOnSpace} > ${member.name} `; })} `; } else { return nothing; } } /** * Renders search results for the current query and filter. * * @internal */ getSearchResult() { const { data: peopleData, hasNextPage, isPending } = this.peopleQuery.result ?? { data: [], isPending: true }; const blockedUserIds = this.blockedUsersQuery.result?.data; const flattenedPages = getFlatInfiniteResultData(peopleData); const hasResult = Boolean(flattenedPages.length); const templateResults: TemplateResult[] = []; if (isPending) { templateResults.push(html``); } else if (!hasResult) { templateResults.push(html`
${this.text ? msg("Your search did not match any people.") : msg("No more users found.")}
`); } if (hasResult) { templateResults.push( html` ${flattenedPages .filter((m: MemberType) => this.selected.find((s) => s.id === m.id) === undefined) .map((member: MemberType) => { // Blocked users stay selectable and are only marked: group participation is unrestricted, so the icon is // informational. It is the new-conversation picker that treats the selection differently. // // Either source answers: a search scoped to an app returns members, which carry the flag, while an // unscoped search returns users in summary form, which do not -- there the block list is all there is. const isBlocked = Boolean(member.is_blocked || blockedUserIds?.includes(member.id)); return html` this.handleSelected(member, !this.isChecked(member.id))} @keydown=${clickOnEnterAndConsumeOnSpace} @keyup=${clickOnEnterAndConsumeOnSpace} > ${member.name} ${isBlocked ? html`` : nothing} `; }) ?? nothing}` ); } if (hasNextPage) { templateResults.push(html`
`); } return templateResults; } override render() { return html`
(this.text = e.detail.query)}>
(this.agentFilter = false)} kind="tab" small >${msg("People")} (this.agentFilter = true)} kind="tab" small >${msg("Agents")} (this.agentFilter = undefined)} kind="tab" small >${msg("All")}
${this.getSelected()} ${this.getSearchResult()}
this.dispatchSubmit()} ?disabled=${this.selected.length === 0 && this.select.length === 0 ? true : undefined} >${this.buttonTitle ?? msg("Create")}
`; } protected override async willUpdate(changedProperties: PropertyValueMap): Promise { super.willUpdate(changedProperties); if (changedProperties.has("weavy") && this.weavy) { await this.peopleQuery.trackInfiniteQuery( getInfiniteSearchMemberOptions( this.weavy, () => this.text, this.appId, () => this.agentFilter ) ); } if ((changedProperties.has("weavy") || changedProperties.has("canBlock")) && this.weavy) { if (this.canBlock) { await this.blockedUsersQuery.trackQuery(getBlockedUserIdsOptions(this.weavy)); } else { this.blockedUsersQuery.untrackQuery(); } } } protected override async updated(changedProperties: PropertyValueMap): Promise { this.infiniteScroll.observe(this.peopleQuery.result, this.pagerRef.value); if (changedProperties.has("text") || changedProperties.has("agentFilter")) { if (this.select.length > 0) { this.selected = [...this.selected, ...this.select]; this.select = []; } await this.peopleQuery.result?.refetch?.(); this.searchRef.value?.focusInput(); } } }