Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/ui: implement an item picker dialog
Adorian Doran122262c3007f
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex 9c75346b8c..7dc33f55e4 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -27,6 +27,7 @@ import type { MarkdownImportOpts } from "../widgets/dialogs/markdown_import.jsx"import { ChooseNoteTypeCallback } from "../widgets/dialogs/note_type_chooser.jsx";import type { PrintPreviewData } from "../widgets/dialogs/print_preview.jsx";import type { NotePickerDialogOptions } from "../widgets/dialogs/note_picker.js";+import type { ItemPickerDialogOptions } from "../widgets/dialogs/item_picker.js";import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";import type NoteTreeWidget from "../widgets/note_tree.js";import type { RightPaneTabId } from "../widgets/sidebar/RightPaneTabs.jsx";@@ -151,6 +152,7 @@ export type CommandMappings = {isNewNote?: boolean;};showPromptDialog: PromptDialogOptions;+ showItemPickerDialog: ItemPickerDialogOptions;showNotePickerDialog: NotePickerDialogOptions;showInfoDialog: InfoProps;showConfirmDialog: ConfirmWithMessageOptions;diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsxindex efa949cbcd..2394e17a4b 100644--- a/apps/client/src/layouts/layout_commons.tsx+++ b/apps/client/src/layouts/layout_commons.tsx@@ -35,6 +35,7 @@ export function applyModals(rootContainer: RootContainer) {.child(<LazyDialog triggerEvents={["showInfoDialog"]} loader={() => import("../widgets/dialogs/info.js")} />).child(<LazyDialog triggerEvents={["showConfirmDialog", "showConfirmDeleteNoteBoxWithNoteDialog"]} loader={() => import("../widgets/dialogs/confirm.js")} />).child(<LazyDialog triggerEvents={["showPromptDialog"]} loader={() => import("../widgets/dialogs/prompt.js")} />)+ .child(<LazyDialog triggerEvents={["showItemPickerDialog"]} loader={() => import("../widgets/dialogs/item_picker.js")} />).child(<LazyDialog triggerEvents={["showCpuArchWarning"]} loader={() => import("../widgets/dialogs/incorrect_cpu_arch.js")} />).child(<LazyDialog triggerEvents={["showOptions"]} loader={() => import("../widgets/dialogs/OptionsDialog.jsx")} />).child(<LazyDialog triggerEvents={["showContentLanguagesDialog"]} loader={() => import("../widgets/dialogs/content_languages.js")} />)diff --git a/apps/client/src/services/dialog.ts b/apps/client/src/services/dialog.tsindex bb24dbfea3..9eb6385ab0 100644--- a/apps/client/src/services/dialog.ts+++ b/apps/client/src/services/dialog.ts@@ -4,6 +4,7 @@ import { Modal } from "bootstrap";import appContext from "../components/app_context.js";import type { ConfirmDeleteNoteBoxOptions, ConfirmDialogOptions, ConfirmDialogResult, ConfirmWithMessageOptions, MessageType } from "../widgets/dialogs/confirm.js";import { InfoExtraProps } from "../widgets/dialogs/info.jsx";+import type { ItemPickerDialogOptions, PickerItem } from "../widgets/dialogs/item_picker.js";import type { PromptDialogOptions } from "../widgets/dialogs/prompt.js";import { focusSavedElement, saveFocusedElement } from "./focus.js";import keyboardActionsService from "./keyboard_actions.js";@@ -229,6 +230,19 @@ export async function chooseNote(props: Omit<NotePickerDialogOptions, "callback"appContext.triggerCommand("showNotePickerDialog", { ...props, callback: res }));}+/**+ * Picks one item out of many, grouped and searchable.+ *+ * Named for the one thing it does now: picking several at once is the same dialog with a different+ * answer, and will be a method of its own beside this.+ *+ * @returns what was picked, or nothing where the reader backed out.+ */+export async function pickSingleItem(props: Omit<ItemPickerDialogOptions, "callback">) {+ return new Promise<PickerItem | null>((res) =>+ appContext.triggerCommand("showItemPickerDialog", { ...props, callback: res }));+}+export async function prompt(props: PromptDialogOptions) {return new Promise<string | null>((res) => appContext.triggerCommand("showPromptDialog", { ...props, callback: res }));}@@ -238,5 +252,6 @@ export default {chooseNote,confirm,confirmDeleteNoteBoxWithNote,+ pickSingleItem,prompt};diff --git a/apps/client/src/services/frontend_script_api.ts b/apps/client/src/services/frontend_script_api.tsindex cc9f9c8d44..169449abd9 100644--- a/apps/client/src/services/frontend_script_api.ts+++ b/apps/client/src/services/frontend_script_api.ts@@ -287,6 +287,7 @@ export interface Api {* @returns promise resolving to the answer provided by the user*/showPromptDialog: typeof dialogService.prompt;+ pickSingleItem: typeof dialogService.pickSingleItem;/*** Trigger command. This is a very low-level API which should be avoided if possible.@@ -687,6 +688,7 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, origthis.showConfirmDialog = dialogService.confirm;this.showPromptDialog = dialogService.prompt;+ this.pickSingleItem = dialogService.pickSingleItem;this.triggerCommand = (name, data) => appContext.triggerCommand(name, data);this.triggerEvent = (name, data) => appContext.triggerEvent(name, data);diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b1b05a25b3..aa57aa965b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2523,6 +2523,11 @@"built-in-templates": "Built-in templates","selector-save": "Save"},+ "item_picker": {+ "title": "Pick an item",+ "search": "Search…",+ "nothing-found": "Nothing matches what you typed."+ },"sortable_card": {"reorder": "Drag to reorder"},diff --git a/apps/client/src/widgets/dialogs/item_picker.css b/apps/client/src/widgets/dialogs/item_picker.cssnew file mode 100644index 0000000000..782e58cb5d--- /dev/null+++ b/apps/client/src/widgets/dialogs/item_picker.css@@ -0,0 +1,211 @@+:where(:root) {+ /* The colour the quick search marks its terms in, which is what a marked term reads as here. */+ --item-picker-mark-color: var(--quick-search-result-highlight-color);+ --item-picker-inline-padding: 40px;+ /* One line of caption in the card's own padding: an exact height, which is what lets an item+ fold and unfold rather than jumping once a max-height has come down to meet it. */+ --item-picker-item-height: calc(1.4em + 2 * var(--card-padding-block));+ --item-picker-fold-duration: 0.15s;+}++.modal.item-picker-dialog {+ .modal-body {+ /* A column, so that what stands where the list was can take the room the list is not using. */+ display: flex;+ flex-direction: column;+ padding-inline: var(--item-picker-inline-padding);+ }++ /* The room the list stands in, which is also what the placeholder is laid over. */+ .item-picker-results {+ position: relative;+ flex: 1 0 auto;+ }++ .modal-dialog {+ /* Half again as wide as a small dialog, which is narrow but not cramped by the padding. */+ max-width: 405px;+ }++ .settings-search {+ margin-bottom: 20px;+ }++ .item-picker-groups {+ display: flex;+ flex-direction: column;+ }++ /* The room between groups is each card's own, so it closes with the card rather than holding a+ stripe open where one used to stand. */+ .item-picker-groups > .tn-card {+ margin-block-end: 1em;+ transition: margin var(--item-picker-fold-duration) ease;+ }++ .item-picker-groups > .tn-card:last-child {+ margin-block-end: 0;+ }++ /*+ * A group whose items have all folded goes as well, but by folding: the heading closes over the+ * same moment the items do.+ *+ * The filter's own rule takes an empty group away outright, which would cut the folding short.+ * Answered in kind, since that rule is `!important` for reasons of its own.+ */+ .tn-card.tn-filter-scope:not(:has(.tn-filter-match)) {+ display: block !important;+ }++ .tn-card:not(:has(.item-picker-item:not(.item-picker-folded))) {+ margin-block-end: 0;+ pointer-events: none;++ & .tn-card-heading {+ height: 0;+ margin: 0;+ opacity: 0;+ overflow: hidden;+ }+ }++ .tn-card-heading {+ height: 1.4em;+ transition: height var(--item-picker-fold-duration) ease,+ margin var(--item-picker-fold-duration) ease,+ opacity calc(var(--item-picker-fold-duration) * 0.7) ease;+ }++ .item-picker-item {+ display: flex;+ align-items: center;+ gap: 0.4em;+ /* Folding: what the item takes up, and what it is painted with, both go to nothing. Its own+ height rather than a ceiling to come down from, so the whole of the transition is spent+ moving: a max-height above the real one is over before it has visibly begun. */+ height: var(--item-picker-item-height);+ /* The gap between segments is the item's own, so it folds away with the item. A card's flex+ gap would hold a stripe open for every item the filter took out. */+ margin-block-end: var(--card-section-gap);+ transition: height var(--item-picker-fold-duration) ease,+ margin var(--item-picker-fold-duration) ease,+ padding var(--item-picker-fold-duration) ease,+ border-width var(--item-picker-fold-duration) ease,+ opacity calc(var(--item-picker-fold-duration) * 0.7) ease;+ overflow: hidden;+ cursor: pointer;+ }++ .item-picker-item:last-of-type {+ margin-block-end: 0;+ }++ .item-picker-folded {+ height: 0;+ margin-block: 0;+ padding-block: 0;+ border-width: 0;+ opacity: 0;+ }++ /* Marked by its colour alone, as the quick search marks what it found. */+ .item-picker-caption {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ /* Bootstrap gives a mark padding of its own, which would part the term from the rest of the+ caption it stands in the middle of. */+ .item-picker-caption mark {+ margin: 0;+ padding: 0;+ background: none;+ color: var(--item-picker-mark-color);+ font-weight: 600;+ }++ /*+ * Laid over the room the list stands in rather than following it, so it holds still while the+ * list folds away under it. Out of the way of the field above and of what is still standing:+ * it is faded rather than taken down, and takes no presses meant for either.+ */+ .item-picker-empty {+ position: absolute;+ inset: 0;+ opacity: 0;+ visibility: hidden;+ pointer-events: none;+ transition: opacity var(--item-picker-fold-duration) ease,+ visibility 0s linear var(--item-picker-fold-duration);+ }++ /* Nothing left standing anywhere, which is the only time there is anything to say. */+ .item-picker-groups:not(:has(.item-picker-item:not(.item-picker-folded))) + .item-picker-empty {+ opacity: 1;+ visibility: visible;+ transition: opacity var(--item-picker-fold-duration) ease;+ }++ /* The groups arrive with the dialog rather than into it: one rise as it opens, which is also+ one animation however many items are being shown. */+ .item-picker-groups {+ /* Long enough to be read as its own: the dialog's opening covers the first moments of it. */+ animation: item-picker-rise 0.4s ease-out;+ }+}++.tn-card-body > .item-picker-item {+ /* The card lays its own segments out with a gap; these carry their own so they can fold. */+ margin-block-start: 0;+}++.modal.item-picker-dialog .tn-card-body {+ gap: 0;+}++/*+ * One height whatever it holds, so a list of three opens the same box as a list of a hundred and+ * the list scrolls inside it.+ *+ * The height is the content box's rather than the dialog's: a scrollable modal only caps that box,+ * which is otherwise sized by what it holds and closes over the list as the filter narrows it. The+ * dialog is then given the whole screen and centres the box in it, which is how Bootstrap centres+ * one of its own; a margin of half the room left over would rest on that room being what it looks.+ */+body:not(.mobile) .modal.item-picker-dialog {+ .modal-dialog {+ display: flex;+ align-items: center;+ height: 100%;+ margin-block: 0;+ }++ .modal-content {+ height: 60vh;+ max-height: 100%;+ }+}++/* A phone fills the screen instead, which `isFullPageOnMobile` answers for. */+body.mobile .modal.item-picker-dialog .modal-content {+ height: 100%;+}++@keyframes item-picker-rise {+ from { opacity: 0; transform: translateY(50px); }+ to { opacity: 1; transform: translateY(0); }+}++@media (prefers-reduced-motion: reduce) {+ .modal.item-picker-dialog {+ .item-picker-groups {+ animation: none;+ }++ .item-picker-item {+ transition: none;+ }+ }+}diff --git a/apps/client/src/widgets/dialogs/item_picker.spec.tsx b/apps/client/src/widgets/dialogs/item_picker.spec.tsxnew file mode 100644index 0000000000..682f3422a3--- /dev/null+++ b/apps/client/src/widgets/dialogs/item_picker.spec.tsx@@ -0,0 +1,248 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Component from "../../components/component";+import { ParentComponent } from "../react/react_utils";+import ItemPickerDialog, { type ItemPickerDialogOptions, type PickerItem } from "./item_picker";++// i18next is never initialised under test, so the stock title and placeholder would be undefined.+vi.mock("../../services/i18n", () => ({+ t: (key: string) => key+}));++const GROUPS = [+ {+ key: "fruit",+ groupHeader: "Fruit",+ items: [+ { key: "apple", caption: "Apple", icon: "bx bx-leaf" },+ { key: "apricot", caption: "Apricot" }+ ]+ },+ {+ key: "tools",+ groupHeader: "Tools",+ items: [+ { key: "hammer", caption: "Hammer" },+ { key: "plane", caption: "Plane" }+ ]+ }+];++describe("ItemPickerDialog", () => {+ let container: HTMLElement;+ let host: Component;+ let picked: (PickerItem | null)[];++ beforeEach(() => {+ vi.useFakeTimers();+ picked = [];+ container = document.createElement("div");+ document.body.appendChild(container);+ host = new Component();++ act(() => {+ render(+ <ParentComponent.Provider value={host}>+ <ItemPickerDialog />+ </ParentComponent.Provider>,+ container);+ });+ });++ afterEach(() => {+ vi.useRealTimers();+ render(null, container);+ container.remove();+ });++ it("draws a card for each group, with an item for each of its entries", async () => {+ await open({ title: "Pick one", items: GROUPS });++ expect(headings()).toEqual([ "Fruit", "Tools" ]);+ expect(captions()).toEqual([ "Apple", "Apricot", "Hammer", "Plane" ]);+ expect(dialog()?.querySelector(".modal-title")?.textContent).toContain("Pick one");+ // The icon an entry carries, for the entries that carry one.+ expect(item("Apple")?.querySelector(".bx-leaf")).not.toBeNull();+ });++ /** A plain list is one group with nothing written above it. */+ it("takes a list of items as readily as groups of them", async () => {+ await open({ items: [ { key: "one", caption: "One" }, { key: "two", caption: "Two" } ] });++ expect(captions()).toEqual([ "One", "Two" ]);+ expect(headings()).toEqual([]);+ });++ it("answers with what was picked, and closes", async () => {+ await open({ items: GROUPS });++ await act(async () => { item("Hammer")?.click(); });+ await close();++ expect(picked).toEqual([ GROUPS[1].items[0] ]);+ });++ it("answers with nothing where the reader backed out", async () => {+ await open({ items: GROUPS });+ await close();++ expect(picked).toEqual([ null ]);+ });++ it("picks with the keyboard as well as with a press", async () => {+ await open({ items: GROUPS });++ await act(async () => {+ item("Plane")?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));+ });+ await close();++ expect(picked).toEqual([ GROUPS[1].items[1] ]);+ });++ describe("searching", () => {+ /**+ * Folded away rather than taken down, so the list closes over what was filtered out. What+ * is left standing is what a press can still reach.+ */+ it("folds away everything that does not match", async () => {+ await open({ items: GROUPS });++ await type("app");++ expect(standing()).toEqual([ "Apple" ]);+ expect(item("Hammer")?.className).toContain("item-picker-folded");+ // Still drawn, so the folding can be drawn as well.+ expect(captions()).toEqual([ "Apple", "Apricot", "Hammer", "Plane" ]);+ });++ it("marks what was typed wherever it stands in the caption", async () => {+ await open({ items: GROUPS });++ await type("mm");++ const marked = item("Hammer")?.querySelectorAll("mark");+ expect([ ...marked ?? [] ].map((mark) => mark.textContent)).toEqual([ "mm" ]);+ // What was not typed is left as it was.+ expect(item("Hammer")?.textContent).toBe("Hammer");+ });++ it("shows a whole group asked for by its own name", async () => {+ await open({ items: GROUPS });++ await type("tools");++ expect(standing()).toEqual([ "Hammer", "Plane" ]);+ });++ it("leaves everything standing once the field is emptied again", async () => {+ await open({ items: GROUPS });++ await type("app");+ expect(standing()).toEqual([ "Apple" ]);++ await type("");+ expect(standing()).toEqual([ "Apple", "Apricot", "Hammer", "Plane" ]);+ expect(item("Apple")?.querySelectorAll("mark").length).toBe(0);+ });++ /** The field the settings are looked through, clear button and all. */+ it("is searched through the app's own search field", async () => {+ await open({ items: GROUPS });++ expect(dialog()?.querySelector(".settings-search-icon")).not.toBeNull();+ expect(dialog()?.querySelector(".settings-search-clear")).toBeNull();++ await type("app");+ expect(standing()).toEqual([ "Apple" ]);++ const clear = dialog()?.querySelector<HTMLElement>(".settings-search-clear");+ expect(clear).not.toBeNull();+ await act(async () => { clear?.click(); await Promise.resolve(); });+ await act(async () => { vi.advanceTimersByTime(300); await Promise.resolve(); });++ expect(standing()).toEqual([ "Apple", "Apricot", "Hammer", "Plane" ]);+ });++ /**+ * Nothing left standing is what shows the placeholder, which is laid over the list rather+ * than following it: whether it is painted is CSS's to say from the same condition.+ */+ it("leaves nothing standing when nothing matches at all", async () => {+ await open({ items: GROUPS });++ await type("zzz");++ expect(standing()).toEqual([]);+ const empty = dialog()?.querySelector(".item-picker-empty");+ expect(empty?.previousElementSibling?.className).toContain("item-picker-groups");+ });+ });++ // #region The dialog, and what the test does to it++ async function open(options: Omit<ItemPickerDialogOptions, "callback">) {+ await act(async () => {+ await host.handleEvent("showItemPickerDialog", {+ ...options,+ callback: (item: PickerItem | null) => picked.push(item)+ } as never);+ await Promise.resolve();+ });+ }++ /** Bootstrap tells the dialog it has gone; under test the event is the test's to send. */+ async function close() {+ await act(async () => {+ dialog()?.dispatchEvent(new Event("hidden.bs.modal", { bubbles: true }));+ await Promise.resolve();+ });+ }++ async function type(query: string) {+ const field = dialog()?.querySelector<HTMLInputElement>(".settings-search-input");+ await act(async () => {+ if (field) {+ field.value = query;+ field.dispatchEvent(new Event("input", { bubbles: true }));+ }+ await Promise.resolve();+ });++ // The typing settles before the list answers it.+ await act(async () => { vi.advanceTimersByTime(300); await Promise.resolve(); });+ }++ function dialog() {+ return document.querySelector<HTMLElement>(".modal.item-picker-dialog");+ }++ function items() {+ return [ ...(dialog()?.querySelectorAll<HTMLElement>(".item-picker-item") ?? []) ];+ }++ function captions() {+ return items().map((element) => element.textContent);+ }++ /** What is left standing, which is what the reader can still pick. */+ function standing() {+ return items()+ .filter((element) => !element.className.includes("item-picker-folded"))+ .map((element) => element.textContent);+ }++ function item(caption: string) {+ return items().find((element) => element.textContent === caption);+ }++ function headings() {+ return [ ...(dialog()?.querySelectorAll(".tn-card-heading") ?? []) ]+ .map((element) => element.textContent);+ }++ // #endregion+});diff --git a/apps/client/src/widgets/dialogs/item_picker.tsx b/apps/client/src/widgets/dialogs/item_picker.tsxnew file mode 100644index 0000000000..d9177e7acb--- /dev/null+++ b/apps/client/src/widgets/dialogs/item_picker.tsx@@ -0,0 +1,217 @@+import "./item_picker.css";++import clsx from "clsx";+import { useMemo, useRef, useState } from "preact/hooks";++import { escapeRegExp } from "../../services/utils";+import { t } from "../../services/i18n";+import { Card } from "../react/Card";+import { FilterProvider, filterRoleClass, useFilterMatch, useFilterState } from "../react/filter";+import SettingsSearch from "../type_widgets/options/components/SettingsSearch";+import { useDebouncedValue, useTriliumEvent } from "../react/hooks";+import Icon from "../react/Icon";+import Modal from "../react/Modal";+import NoItems from "../react/NoItems";++/** One thing that can be picked. */+export interface PickerItem {+ key: string;+ caption: string;+ /** An icon class, `bx` prefix included. */+ icon?: string;+}++/** A run of items under a heading of their own. */+export interface PickerItemGroup {+ key: string;+ groupHeader: string;+ items: PickerItem[];+}++export interface ItemPickerDialogOptions {+ title?: string;+ /**+ * What can be picked: either the items themselves or groups of them, never the two mixed.+ *+ * They are read as they are given, so whatever it takes to work them out is done before the+ * dialog is opened rather than while the reader waits.+ */+ items: PickerItem[] | PickerItemGroup[];+ /** What the search field reads while it is empty. */+ placeholder?: string;+ /** Said with what was picked, or with nothing where the reader backed out. */+ callback?: (item: PickerItem | null) => void;+}++/** How long the typing settles before the list answers it. Matches the settings search. */+const DEBOUNCE_MS = 150;++/**+ * Picks one thing out of many, grouped, searchable, and closed by the picking.+ *+ * The list is narrowed by {@link FilterProvider}, the same filter the settings search runs on: each+ * item asks whether it matches and is left standing or folded away, so nothing is mounted or torn+ * down as the query changes and the folding can be drawn.+ *+ * Summoned through `dialog.pickSingleItem()`, which is named for the one thing it does now: picking+ * several at once is the same dialog with a different answer.+ */+export default function ItemPickerDialog() {+ const opts = useRef<ItemPickerDialogOptions>();+ /** What was picked, said once the dialog has closed rather than while it is closing. */+ const picked = useRef<PickerItem | null>(null);+ const searchRef = useRef<HTMLInputElement>(null);+ const [ shown, setShown ] = useState(false);+ const [ query, setQuery ] = useState("");++ useTriliumEvent("showItemPickerDialog", (options) => {+ opts.current = options;+ picked.current = null;+ setQuery("");+ setShown(true);+ });++ const groups = useMemo(() => asGroups(opts.current?.items ?? []), [ opts.current?.items ]);+ const settled = useDebouncedValue(query.trim(), DEBOUNCE_MS);++ function pick(item: PickerItem) {+ picked.current = item;+ setShown(false);+ }++ return (+ <Modal+ className="item-picker-dialog"+ title={opts.current?.title ?? t("item_picker.title")}+ size="sm"+ scrollable+ isFullPageOnMobile+ zIndex={2000}+ show={shown}+ stackable+ onShown={() => searchRef.current?.focus()}+ onHidden={() => {+ setShown(false);+ opts.current?.callback?.(picked.current);+ opts.current = undefined;+ }}+ >+ {/* The field the settings are looked through, which stands over the lists of the+ dialogs they open as well. */}+ <SettingsSearch+ inputRef={searchRef}+ query={query}+ onChange={setQuery}+ placeholder={opts.current?.placeholder ?? t("item_picker.search")}+ />++ <FilterProvider query={settled}>+ {/* What stands where the list was is laid over this rather than after it, so it+ holds still while the list folds away under it. */}+ <div className="item-picker-results">+ {/* Drawn once the dialog has opened, which is what the rise comes from: the+ items are the dialog's content rather than something arriving into it. */}+ <div className="item-picker-groups">+ {groups.map((group) => (+ <Card key={group.key} heading={group.groupHeader || undefined}>+ {group.items.map((item) => (+ <PickerRow key={item.key} item={item} onPick={pick} />+ ))}+ </Card>+ ))}+ </div>++ <NoItems+ className="item-picker-empty"+ icon="bx bx-search"+ text={t("item_picker.nothing-found")}+ />+ </div>+ </FilterProvider>+ </Modal>+ );+}++/**+ * One item, standing whether or not it matches: folded away rather than taken down, so the list+ * closes over what was filtered out instead of blinking from one set to the next.+ */+function PickerRow({ item, onPick }: { item: PickerItem, onPick: (item: PickerItem) => void }) {+ const matched = useFilterMatch(item.caption);++ return (+ <section+ // Marked as a match for the card holding it, which is what keeps a group standing+ // while anything in it is still being shown.+ className={clsx("tn-card-section tn-card-highlight-on-hover item-picker-item",+ filterRoleClass(matched ? "match" : undefined),+ { "item-picker-folded": !matched })}+ tabIndex={matched ? 0 : -1}+ aria-hidden={!matched}+ onClick={() => onPick(item)}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onPick(item);+ }+ }}+ >+ {item.icon && <Icon icon={item.icon} />}+ <Marked text={item.caption} />+ </section>+ );+}++/** What the reader typed, marked wherever it stands in the caption. */+function Marked({ text }: { text: string }) {+ const filter = useFilterState();+ const parts = useMemo(() => split(text, filter?.tokens), [ text, filter ]);++ return (+ <span className="item-picker-caption">+ {parts.map((part, index) => part.marked+ ? <mark key={index}>{part.text}</mark>+ : part.text)}+ </span>+ );+}++/** Whether what was given is groups of items rather than the items themselves. */+function isGroup(entry: PickerItem | PickerItemGroup): entry is PickerItemGroup {+ return "items" in entry;+}++/**+ * The items as groups, whichever of the two the caller gave.+ *+ * A plain list becomes one group with no heading, so the dialog draws one shape rather than two.+ */+function asGroups(items: PickerItem[] | PickerItemGroup[]): PickerItemGroup[] {+ const [ first ] = items;+ if (!first) {+ return [];+ }++ return isGroup(first)+ ? items as PickerItemGroup[]+ : [ { key: "", groupHeader: "", items: items as PickerItem[] } ];+}++/**+ * The caption cut into the parts that were typed and the parts that were not.+ *+ * Marked against the text as it stands, so a term matched by its shape alone, an accent dropped for+ * instance, is left unmarked rather than marked in the wrong place.+ */+function split(text: string, tokens?: string[]) {+ if (!tokens?.length) {+ return [ { text, marked: false } ];+ }++ // Split on a capturing group, so what was typed comes back among the parts: at the odd+ // places, whatever the terms matched.+ const terms = new RegExp(`(${tokens.map(escapeRegExp).join("|")})`, "gi");+ return text.split(terms)+ .map((part, index) => ({ text: part, marked: index % 2 === 1 }))+ .filter((part) => part.text !== "");+}diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.tsindex 7c5dae7296..93d9544afa 100644--- a/packages/commons/src/lib/script_api.ts+++ b/packages/commons/src/lib/script_api.ts@@ -17,6 +17,21 @@*//** A label or relation attached to a note. */+/** One thing a picker offers, as `pickSingleItem` takes and answers with. */+export interface PickerItem {+ key: string;+ caption: string;+ /** An icon class, `bx` prefix included. */+ icon?: string;+}++/** A run of picker items under a heading of their own. */+export interface PickerItemGroup {+ key: string;+ groupHeader: string;+ items: PickerItem[];+}+export interface ScriptAttribute {attributeId: string;type: "label" | "relation";@@ -576,6 +591,20 @@ export interface FrontendApi {*/showPromptDialog(props: { title?: string; message?: string; defaultValue?: string }): Promise<string | null>;+ /**+ * Show a dialog for picking one item out of many, grouped and searchable.+ *+ * `items` are either the items themselves or groups of them, never the two mixed. Named for the+ * one thing it does now: picking several at once will be a method of its own beside this.+ *+ * @returns promise resolving to the item picked, or null where the user backed out.+ */+ pickSingleItem(props: {+ title?: string;+ items: PickerItem[] | PickerItemGroup[];+ placeholder?: string;+ }): Promise<PickerItem | null>;+/*** Create a note link (jQuery object) for given note.*