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
fix(attributes): suggest known values in a multi-valued field (closes #11558)
Elian Dorand9877c20e9af
diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsxindex b356640305..bce14961f2 100644--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx@@ -595,6 +595,27 @@ describe("PromotedAttributesContent rendering", () => {await renderCells(note, [ buildCell(note, { name: "fresh", definition: { labelType: "text" }, uniqueId: "fresh" }) ]);expect(autocompleteMock).not.toHaveBeenCalled();});++ it("hands a multi text field the values the name holds, and the other kinds none", async () => {+ serverGetMock.mockResolvedValue([ "alpha", "beta" ]);+ const held = (definition: DefinitionObject, name: string) =>+ [ { ...buildCell(note, { name, definition, uniqueId: name }), values: [] } ];++ await renderCells(note, held({ labelType: "text" }, "tags"));+ const source = multiInput.current?.source as (query: string) => Promise<string[]>;+ // useLabelValueSuggestions requests the values on the first query, not when the grid+ // renders.+ expect(serverGetMock).not.toHaveBeenCalledWith("attribute-values/tags");+ expect(await source("al")).toEqual([ "alpha" ]);+ expect(serverGetMock).toHaveBeenCalledWith("attribute-values/tags");++ // MultiLabelInput passes the source for `text` alone; a select offers its declared+ // options instead.+ await renderCells(note, held({ labelType: "number" }, "size"));+ expect(multiInput.current?.source).toBeUndefined();+ await renderCells(note, held({ labelType: "select", selectOptions: [ "Todo" ] }, "status"));+ expect(multiInput.current?.source).toBeUndefined();+ });});describe("usePromotedAttributeData", () => {diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex 7cee7cab02..4cfc999f68 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -14,7 +14,7 @@ import { t } from "../services/i18n";import server from "../services/server";import { randomString } from "../services/utils";import ws from "../services/ws";-import LabelValueInput from "./attribute_widgets/label_value_input";+import LabelValueInput, { useLabelValueSuggestions } from "./attribute_widgets/label_value_input";import MultiValueInput from "./attribute_widgets/multi_value_input";import RelationValuesInput from "./attribute_widgets/relation_values_input";import ColorPicker from "./react/ColorPicker";@@ -294,6 +294,7 @@ function MultiLabelInput({ inputId, note, cell, componentId, setCells }: CellProconst { valueName, definition, definitionAttr, values, uniqueId } = cell;const labelType = definition.labelType ?? "text";const createOption = useCreateSelectOption(definitionAttr, componentId, setCells);+ const suggestValues = useLabelValueSuggestions(valueName);const commit = useCallback(async (edited: string[]) => {await attributes.setLabelValues(note, valueName, edited, componentId);@@ -308,6 +309,9 @@ function MultiLabelInput({ inputId, note, cell, componentId, setCells }: CellPro<MultiValueInputlabelType={labelType}values={values ?? []}+ // Matches the single-value field, which useTextLabelAutocomplete limits to+ // `text`.+ source={labelType === "text" ? suggestValues : undefined}options={definition.selectOptions}onCreateOption={labelType === "select" ? createOption : undefined}inputId={inputId}diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex 9d2e0b87ab..728e38ea21 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -33,7 +33,7 @@ import { disposeReactWidget, ParentComponent, renderReactWidgetAtElement } fromimport OptionsRow, { OptionsRowWithToggle } from "../type_widgets/options/components/OptionsRow.jsx";import { ATTR_HELP, AttrHelpEntry } from "./attr_help.js";import { DEFINITION_TYPE_ICONS, RELATION_DEFINITION_TYPE } from "./attribute_types.js";-import LabelValueInput, { getTypedInputForLabel } from "./label_value_input.js";+import LabelValueInput, { getTypedInputForLabel, useLabelValueSuggestions } from "./label_value_input.js";import ValuesInput from "./values_input.jsx";export interface AttributeDetailOpts {@@ -411,24 +411,7 @@ export function AttributeForm({ opts, attrType: initialAttrType, currentNoteId,// same place the type came from rather than passed in.return labelType && { labelType, selectOptions: getBuiltinLabelSelectOptions(name) };}, [ attrType, name ]);- // The values known for a label name never change while the popup is open, so they are fetched- // once per name and filtered locally afterwards.- const knownValues = useRef<{ name: string; values: string[] }>();- const suggestLabelValues = useCallback(async (query: string) => {- if (!name.trim()) {- return [];- }-- if (knownValues.current?.name !== name) {- knownValues.current = {- name,- values: await server.get<string[]>(`attribute-values/${encodeURIComponent(name)}`)- };- }-- const term = query.toLowerCase();- return knownValues.current.values.filter((value) => value.toLowerCase().includes(term));- }, [ name ]);+ const suggestLabelValues = useLabelValueSuggestions(name);// Committing mid-composition makes the spawning editor re-render and swallow the// characters being composed: https://github.com/zadam/trilium/pull/3812const isComposing = useRef(false);diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsxindex 794226e07e..63281bb244 100644--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx@@ -3,9 +3,10 @@ import "./label_value_input.css";import { type LabelType } from "@triliumnext/commons";import clsx from "clsx";import { createElement, type HTMLInputTypeAttribute, type InputHTMLAttributes, type MouseEventHandler } from "preact";-import { useRef } from "preact/hooks";+import { useCallback, useRef } from "preact/hooks";import { t } from "../../services/i18n";+import server from "../../services/server";import { normalizeExternalUrl } from "../../utils/url";import { SelectComboBox } from "./select_input";@@ -287,3 +288,30 @@ export function getTypedInputForLabel(labelType: LabelType | undefined): LabelTyreturn labelType;}++/**+ * Returns a suggestion source for a free-text label value: the values `name` already has across+ * the database, filtered by the query.+ *+ * `attribute-values/<name>` is requested on the first query and cached per name, then filtered in+ * memory. An empty `name` returns no suggestions, since `attribute-values/` matches no route.+ */+export function useLabelValueSuggestions(name: string) {+ const known = useRef<{ name: string; values: string[] }>();++ return useCallback(async (query: string) => {+ if (!name.trim()) {+ return [];+ }++ if (known.current?.name !== name) {+ known.current = {+ name,+ values: await server.get<string[]>(`attribute-values/${encodeURIComponent(name)}`)+ };+ }++ const term = query.toLowerCase();+ return known.current.values.filter((value) => value.toLowerCase().includes(term));+ }, [ name ]);+}diff --git a/apps/client/src/widgets/attribute_widgets/multi_value_input.tsx b/apps/client/src/widgets/attribute_widgets/multi_value_input.tsxindex ae8a62647f..a4a458cd2a 100644--- a/apps/client/src/widgets/attribute_widgets/multi_value_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/multi_value_input.tsx@@ -12,6 +12,11 @@ interface MultiValueInputProps {values: readonly string[];/** Receives the values as they now stand, whenever one is taken or dropped. */onCommit(values: string[]): void;+ /**+ * Returns the values to suggest for the current query, forwarded to {@link ValuesInput}.+ * `select` and `boolean` ignore it and offer their declared options instead.+ */+ source?(query: string): Promise<string[]>;/** The options a `select` holds, from the definition that declared it. Ignored by other types. */options?: readonly string[];/**@@ -37,7 +42,7 @@ interface MultiValueInputProps {* Shared by the promoted-attribute grid and the table's own cells, so that the same definition is* edited the same way wherever the note is opened.*/-export default function MultiValueInput({ labelType, values, onCommit, options, onCreateOption, inputId, tabIndex, disabled }: MultiValueInputProps) {+export default function MultiValueInput({ labelType, values, onCommit, source, options, onCreateOption, inputId, tabIndex, disabled }: MultiValueInputProps) {if (labelType === "select" || labelType === "boolean") {return (<SelectValuesInput@@ -59,6 +64,7 @@ export default function MultiValueInput({ labelType, values, onCommit, options,<ValuesInputlabelType={labelType}values={values}+ source={source}placeholder={t("promoted_attributes.values_placeholder")}inputId={inputId}tabIndex={tabIndex}diff --git a/apps/client/src/widgets/attribute_widgets/values_input.css b/apps/client/src/widgets/attribute_widgets/values_input.cssindex 2b4ebd6a54..836af53ffa 100644--- a/apps/client/src/widgets/attribute_widgets/values_input.css+++ b/apps/client/src/widgets/attribute_widgets/values_input.css@@ -9,7 +9,7 @@* Only the mind map's node panel shows the growth: the promoted-attribute row and the table's* editor each give the field a height to sit against, which swallows it.*/-.values-input .values-input-add {+.values-input-add {--values-input-add-size: 20px;/* Read by the themes that size an icon button through it; the rest is for those that don't. */--icon-button-size: var(--values-input-add-size);diff --git a/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/values_input.spec.tsxindex 1a45b3faaa..1089573c59 100644--- a/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx+++ b/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx@@ -33,10 +33,21 @@ describe("ValuesInput", () => {async function press(input: HTMLInputElement | null, key: string) {await act(async () => {- input?.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));+ // Cancelable, so FormAutocomplete consuming a key sets defaultPrevented, as it does+ // in a browser.+ input?.dispatchEvent(+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));});}+ /** Lets the debounced fetch run; the list is portaled to the body. */+ async function settleDropdown() {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 200));+ });+ return [ ...document.querySelectorAll<HTMLElement>(".form-autocomplete-dropdown li") ];+ }+it("commits nothing while disabled, whatever reaches it", async () => {// The box and the buttons are out of reach on the page, but a host may disable the field// while something is typed into it, and leaving the box hands over what it holds.@@ -192,6 +203,57 @@ describe("ValuesInput", () => {};}+ it("offers the values the name already holds, and takes the one picked as a chip", async () => {+ const onCommit = vi.fn();+ const source = vi.fn(async () => [ "alpha", "beta", "one" ]);+ const input = await mount({ labelType: "text", values: [ "one" ], onCommit, source });++ await act(async () => input?.focus());+ // "one" is already a chip, so the list offers only the remaining values.+ const items = await settleDropdown();+ expect(items.map((item) => item.textContent)).toEqual([ "alpha", "beta" ]);+ // The chips render inside the field, before the input, so the dropdown spans the field.+ const chip = container.querySelector(".tn-chip");+ expect(chip?.closest(".form-autocomplete-field")).not.toBeNull();++ await act(async () => items[1]?.click());+ expect(onCommit).toHaveBeenCalledWith([ "one", "beta" ]);+ });++ it("keeps Enter for what was typed, the list taking only what was arrowed to", async () => {+ // The typed text is the value, so Enter commits it. Without autoActivate the list+ // highlights nothing until the user arrows to an entry.+ const onCommit = vi.fn();+ const source = vi.fn(async () => [ "alpha", "beta" ]);+ const input = await mount({ labelType: "text", values: [], onCommit, source });++ await typeInto(input, "al");+ await settleDropdown();+ await press(input, "Enter");+ expect(onCommit.mock.calls).toEqual([ [ [ "al" ] ] ]);++ // With an entry highlighted the list commits that entry, and only that entry: the key it+ // consumed no longer reaches handleKeyDown.+ onCommit.mockClear();+ await typeInto(input, "al");+ await settleDropdown();+ await press(input, "ArrowDown");+ await press(input, "Enter");+ expect(onCommit.mock.calls).toEqual([ [ [ "alpha" ] ] ]);+ });++ it("offers nothing where the value comes from a widget of the browser's own", async () => {+ // A colour and a date come from a browser widget rather than from typing, so there is+ // nothing to complete.+ const source = vi.fn(async () => [ "#ff0000" ]);+ const input = await mount({ labelType: "color", values: [], onCommit: vi.fn(), source });++ await act(async () => input?.focus());+ expect(await settleDropdown()).toEqual([]);+ expect(source).not.toHaveBeenCalled();+ expect(container.querySelector(".values-input")).not.toBeNull();+ });+it("drops the last chip on backspace in an empty box, and leaves a filled one alone", async () => {const onCommit = vi.fn();const input = await mount({ labelType: "text", values: [ "one", "two" ], onCommit });diff --git a/apps/client/src/widgets/attribute_widgets/values_input.tsx b/apps/client/src/widgets/attribute_widgets/values_input.tsxindex 79d4ffdeac..72f609cc46 100644--- a/apps/client/src/widgets/attribute_widgets/values_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/values_input.tsx@@ -3,11 +3,12 @@ import "./values_input.css";import { type LabelType } from "@triliumnext/commons";import clsx from "clsx";import type { ComponentChildren, TargetedKeyboardEvent } from "preact";-import { useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../services/i18n";import ActionButton from "../react/ActionButton";import Chip from "../react/Chip";+import FormAutocomplete from "../react/FormAutocomplete";import FormTextBox from "../react/FormTextBox";import { ColorSwatch } from "./label_value_display";import { DEFAULT_COLOR, LABEL_MAPPINGS } from "./label_value_input";@@ -19,6 +20,14 @@ interface ValuesInputProps {values: readonly string[];/** Receives the values as they now stand, whenever one is taken or dropped. */onCommit(values: string[]): void;+ /**+ * Returns the values to suggest for the current query, normally the values the label's name+ * already has on other notes. Without it the input offers no suggestions.+ *+ * Ignored for a {@link PICKED_TYPES} value, which comes from a browser widget rather than+ * from typing.+ */+ source?(query: string): Promise<string[]>;/** What removing a chip means, in the host's own words. Left out, a chip holds "a value". */removeButtonText?: string;/** What taking the box's content means, in the host's own words. Left out, it adds "a value". */@@ -40,7 +49,7 @@ interface ValuesInputProps {* rather than quietly dropped. A value already held is not taken a second time: the chips are a set,* and two alike could not be told apart.*/-export default function ValuesInput({ labelType, values, onCommit, removeButtonText, addButtonText, inputId, tabIndex, placeholder, disabled }: ValuesInputProps) {+export default function ValuesInput({ labelType, values, onCommit, source, removeButtonText, addButtonText, inputId, tabIndex, placeholder, disabled }: ValuesInputProps) {const [ draft, setDraft ] = useState("");const inputRef = useRef<HTMLInputElement>(null);const isColor = labelType === "color";@@ -51,6 +60,16 @@ export default function ValuesInput({ labelType, values, onCommit, removeButtonT// to take, the same button offers the confirming where it can be seen. Not before: empty, it// would have nothing to add, and sit there asking to be explained.const showAdd = needsAsking || (!isColor && draft.trim().length > 0);+ // A PICKED_TYPES value comes from a browser widget, so there is nothing to complete.+ const suggest = PICKED_TYPES.has(labelType) ? undefined : source;+ // take() refuses a value the field already holds, so the list leaves those out, as+ // SelectValuesInput does.+ const suggestUnheld = useCallback(async (query: string) => {+ if (!suggest) return [];++ const suggestions = await suggest(query);+ return suggestions.filter((value) => !values.includes(value));+ }, [ suggest, values ]);// A colour picker holds its own value and is never told one: it is set at birth and only read// from after that. Anything written into it can reach a dialog that is still open — it reports@@ -98,6 +117,10 @@ export default function ValuesInput({ labelType, values, onCommit, removeButtonT}function handleKeyDown(e: TargetedKeyboardEvent<HTMLInputElement>) {+ // FormAutocomplete consumes Enter when it commits the highlighted entry. Handling the key+ // here as well would take the typed text alongside that entry.+ if (e.defaultPrevented) return;+if (e.key === "Enter") {// Consumed, so that it does not also reach whatever the field sits in — a table cell// takes Enter as "done here", which would end the edit at the first value.@@ -112,24 +135,73 @@ export default function ValuesInput({ labelType, values, onCommit, removeButtonT}}+ const chips = values.map((value) => (+ <Chip+ key={value}+ removeButtonText={removeButtonText ?? t("promoted_attributes.remove_value")}+ disabled={disabled}+ onRemove={() => drop(value)}+ >+ {/* A colour reads as its swatch even while being edited, `#3d5a80` naming nothing to+ the eye. A swatch rather than the chip's own ground, as the read-only chips wear+ it: this chip also holds the button removing it, which no ground a user may pick+ can be trusted to keep visible. */}+ <span>{isColor ? <ColorSwatch color={value} /> : value}</span>+ </Chip>+ ));++ // A widget says nothing useful about when it is done — a date reports a change per part of it —+ // so a field entered through one is asked rather than watched. Enter does as much for the+ // keyboard; this is the same thing where it can be seen.+ const addButton = showAdd && (+ <ActionButton+ key="add"+ className="values-input-add"+ icon="bx bx-plus"+ text={addButtonText ?? t("promoted_attributes.add_value")}+ disabled={disabled}+ // The value is read from the field rather than from the draft: leaving the field to+ // press this takes it already, and the draft is empty by the time this runs. For a+ // typed box that leaving is also the whole of the press — the take empties the box and+ // the button goes with it, before the click lands on anything.+ onClick={() => take(inputRef.current?.value ?? "")}+ />+ );++ // FormAutocomplete measures the dropdown against the element wrapping `leading` and+ // `trailing`, so passing the chips and the button through them draws the list at the full+ // field width rather than at the width left over for typing.+ if (suggest) {+ return (+ <FormAutocomplete+ id={inputId}+ tabIndex={tabIndex}+ type={LABEL_MAPPINGS[labelType] ?? "text"}+ inputRef={inputRef}+ currentValue={draft}+ // Only while the field is empty: beside chips it would read as one of them.+ placeholder={values.length ? undefined : placeholder}+ disabled={disabled}+ openOnFocus+ // The field collects several values, so the list stays open. suggestUnheld drops+ // the value just taken from the next fetch.+ keepOpenOnPick+ source={suggestUnheld}+ leading={chips}+ trailing={addButton}+ onChange={setDraft}+ onPick={take}+ onBlur={take}+ onKeyDown={handleKeyDown}+ />+ );+ }+return (// Values and the box they are entered in share the one wrapping line, the box after them,// however they are entered — a widget of the browser's own only dresses the box differently.<div className={clsx("tn-field values-input", PICKED_TYPES.has(labelType) && "widget-entry")}>- {values.map((value) => (- <Chip- key={value}- removeButtonText={removeButtonText ?? t("promoted_attributes.remove_value")}- disabled={disabled}- onRemove={() => drop(value)}- >- {/* A colour reads as its swatch even while being edited, `#3d5a80` naming- nothing to the eye. A swatch rather than the chip's own ground, as the- read-only chips wear it: this chip also holds the button removing it,- which no ground a user may pick can be trusted to keep visible. */}- <span>{isColor ? <ColorSwatch color={value} /> : value}</span>- </Chip>- ))}+ {chips}{/* The box and the button that asks for what it holds are one thing on the page, so theyare wrapped as one: whatever wraps or is ordered, they go together, and the buttonnever ends up on a line without the box it belongs to.@@ -164,24 +236,7 @@ export default function ValuesInput({ labelType, values, onCommit, removeButtonTonKeyDown={handleKeyDown}/>)}-- {/* A widget says nothing useful about when it is done — a date reports a change per part- of it — so a field entered through one is asked rather than watched. Enter does as- much for the keyboard; this is the same thing where it can be seen. */}- {showAdd && (- <ActionButton- key="add"- className="values-input-add"- icon="bx bx-plus"- text={addButtonText ?? t("promoted_attributes.add_value")}- disabled={disabled}- // The value is read from the field rather than from the draft: leaving the field- // to press this takes it already, and the draft is empty by the time this runs.- // For a typed box that leaving is also the whole of the press — the take empties- // the box and the button goes with it, before the click lands on anything.- onClick={() => take(inputRef.current?.value ?? "")}- />- )}+ {addButton}</Entry></div>);diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex ca54ed52c0..28698efe00 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -66,6 +66,14 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {* the whole field instead of only the stretch of it left over for typing.*/leading?: ComponentChildren;+ /**+ * Content rendered inside the field, after the input. Use it for a button that commits what the+ * input holds, as {@link FormAutocompleteProps.leading} carries the chips that precede it.+ *+ * Passing either prop wraps the input in a `tn-field` element, which+ * {@link computeDropdownPosition} then measures the dropdown against.+ */+ trailing?: ComponentChildren;/*** Marks an entry as a heading over the ones below it rather than a choice of its own: it takes no* click, is stepped over on the way through the list, and is never what Enter takes.@@ -94,7 +102,7 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {* The dropdown is portalled to the body and positioned over everything else, so it is not clipped* by scrolling ancestors. Selecting a suggestion reports it through `onChange`, exactly like typing.*/-export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, openOnEnter, onPick, keepOpenOnPick, renderItem, leading, autoActivate, isHeading, dropdownMinWidth, inputRef, onFocus, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {+export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, openOnEnter, onPick, keepOpenOnPick, renderItem, leading, trailing, autoActivate, isHeading, dropdownMinWidth, inputRef, onFocus, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {const ownInputRef = useRef<HTMLInputElement>(null);const inputEl = inputRef ?? ownInputRef;const fieldRef = useRef<HTMLDivElement>(null);@@ -267,8 +275,8 @@ export default function FormAutocomplete({ currentValue, onChange, source, openOreturn (<>- {leading !== undefined- ? <div ref={fieldRef} className="tn-field form-autocomplete-field">{leading}{field}</div>+ {leading !== undefined || trailing !== undefined+ ? <div ref={fieldRef} className="tn-field form-autocomplete-field">{leading}{field}{trailing}</div>: field}{isOpen && items.length > 0 && position && createPortal(