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
feat(table): hold several values in a select column
Elian Doranf24a739e7219
diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.tsindex 7b6bc54154..248c6e6ab5 100644--- a/apps/client/src/services/attributes.spec.ts+++ b/apps/client/src/services/attributes.spec.ts@@ -187,6 +187,63 @@ describe("addLabel / setLabel / setRelation", () => {});});+describe("setLabelValues", () => {+ beforeEach(() => vi.clearAllMocks());++ /** A note holding the given values under one name, as several labels of it. */+ function noteHolding(...values: string[]) {+ const note = buildNote({ title: "N" });+ for (const [ index, value ] of values.entries()) {+ note.attributes.push(`attr-${index}`);+ froca.attributes[`attr-${index}`] = {+ attributeId: `attr-${index}`, noteId: note.noteId, type: "label",+ name: "tags", value, position: index, isInheritable: false+ } as never;+ }+ return note;+ }++ it("reuses the labels already there, so the set keeps its order and positions", async () => {+ const note = noteHolding("a", "b");++ await attributeService.setLabelValues(note, "tags", [ "a", "c" ]);++ // "a" is where it was, so only the label that changed is written.+ expect(server.put).toHaveBeenCalledTimes(1);+ expect(server.put).toHaveBeenCalledWith(+ `notes/${note.noteId}/attribute`,+ { attributeId: "attr-1", type: "label", name: "tags", value: "c" },+ undefined+ );+ expect(server.remove).not.toHaveBeenCalled();+ });++ it("creates what the set gained, having no label left to reuse for it", async () => {+ const note = noteHolding("a");++ await attributeService.setLabelValues(note, "tags", [ "a", "b" ], "comp-1");++ expect(server.put).toHaveBeenCalledWith(+ `notes/${note.noteId}/attribute`,+ { attributeId: undefined, type: "label", name: "tags", value: "b" },+ "comp-1"+ );+ });++ it("removes the labels the set no longer fills, emptying included", async () => {+ const note = noteHolding("a", "b", "c");++ await attributeService.setLabelValues(note, "tags", [ "a" ]);++ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/attr-1`, undefined);+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/attr-2`, undefined);++ vi.clearAllMocks();+ await attributeService.setLabelValues(note, "tags", []);+ expect(server.remove).toHaveBeenCalledTimes(3);+ });+});+describe("addSelectOption", () => {beforeEach(() => vi.clearAllMocks());diff --git a/apps/client/src/services/attributes.ts b/apps/client/src/services/attributes.tsindex a358af5025..f35af3f8be 100644--- a/apps/client/src/services/attributes.ts+++ b/apps/client/src/services/attributes.ts@@ -109,6 +109,35 @@ function removeOwnedRelationByName(note: FNote, relationName: string) {return false;}+/**+ * Sets the labels of one name on a note to exactly `values`, for a field holding a set of them.+ *+ * The labels already there are reused in order, so taking a value out of the middle of a set renames+ * the ones after it rather than deleting and recreating the lot — which keeps their positions, and+ * with them the order the set reads in. Only owned labels are touched: an inherited one belongs to+ * the note it is written on.+ */+export async function setLabelValues(note: FNote, name: string, values: string[], componentId?: string) {+ const existing = note.getOwnedLabels(name);++ for (const [ index, value ] of values.entries()) {+ const attributeId = existing[index]?.attributeId;+ if (existing[index]?.value === value) {+ continue;+ }+ await server.put(+ `notes/${note.noteId}/attribute`,+ { attributeId, type: "label", name, value },+ componentId+ );+ }++ // Whatever the new set did not fill is no longer held.+ for (const spare of existing.slice(values.length)) {+ await server.remove(`notes/${note.noteId}/attributes/${spare.attributeId}`, componentId);+ }+}+/*** Adds an option to a `select` definition, for a field offering to create the choice being typed* into it.@@ -292,6 +321,7 @@ export default {setLabel,setRelation,setAttribute,+ setLabelValues,addSelectOption,setBooleanWithInheritance,removeAttributeById,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 34e657e975..fed3a402d3 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1333,7 +1333,9 @@"unknown_attribute_type": "Unknown attribute type '{{type}}'","add_new_attribute": "Add new attribute","remove_this_attribute": "Remove this attribute",- "remove_color": "Remove the color label"+ "remove_color": "Remove the color label",+ "remove_value": "Remove this value",+ "select_values_placeholder": "Select an option or create one"},"script_executor": {"query": "Query",diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.css b/apps/client/src/widgets/attribute_widgets/label_value_input.cssindex 78f571e0f9..7a1f380229 100644--- a/apps/client/src/widgets/attribute_widgets/label_value_input.css+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.css@@ -27,13 +27,3 @@ body[dir=rtl] .label-select-combobox.form-control:hover,body[dir=rtl] .label-select-combobox.form-control:focus {background-position: left calc(0.75rem - var(--input-group-padding-inline-end, 0px)) center;}--/* The "Create" entry of a select combobox, set apart from the options it sits under: it makes a new- choice rather than picking one. Scoped to the dropdown, which is portaled to the body. */-.form-autocomplete-dropdown .label-select-create-option {- font-style: italic;-- > .bx {- color: var(--muted-text-color);- }-}diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsxindex 9db39d84b6..013b12f8a4 100644--- a/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx@@ -268,7 +268,7 @@ describe("LabelValueInput", () => {// than its label: `t()` renders empty under the test environment's uninitialized i18n.const items = await settleDropdown();expect(items).toHaveLength(1);- expect(items[0]?.querySelector(".label-select-create-option")).not.toBeNull();+ expect(items[0]?.querySelector(".select-create-option")).not.toBeNull();await act(async () => (items[0] as HTMLElement | undefined)?.click());expect(onCreateOption).toHaveBeenCalledWith("Blocked");@@ -296,7 +296,7 @@ describe("LabelValueInput", () => {await typeInto(input, "Blo");const items = await settleDropdown();expect(items).toHaveLength(1);- expect(items[0]?.querySelector(".label-select-create-option")).not.toBeNull();+ expect(items[0]?.querySelector(".select-create-option")).not.toBeNull();// The part an entry matched is set in bold.await typeInto(input, "et");diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsxindex 4eab17021d..303f92dd50 100644--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx@@ -3,10 +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 { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { useRef } from "preact/hooks";import { t } from "../../services/i18n";-import FormAutocomplete from "../react/FormAutocomplete";+import { SelectComboBox } from "./select_input";/*** The field a label of each type is edited through, shared so that a promoted field and a system@@ -225,136 +225,6 @@ export default function LabelValueInput({);}-/**- * Marks the "Create" entry apart from the options it sits under. An option can never start with it:- * it cannot be typed, and the definition editor takes what was typed.- */-const CREATE_OPTION_SENTINEL = "\u0000";--/**- * The combobox a select with {@link LabelValueInputProps#onCreateOption} is edited through. The box- * holds a draft of the value: the full list opens on focus, typing filters it, and only picking an- * entry commits — an option by its text, the "Create" entry by first handing the typed text to- * `onCreateOption`. Text that matches nothing reverts on blur, except an emptied box, which commits- * the empty value: clearing is a choice of its own, and cannot pollute the definition.- */-function SelectComboBox({ options, value, onCommit, onCreateOption, inputProps }: {- options: readonly string[];- value: string;- onCommit: (value: string) => void;- onCreateOption: (option: string) => void | Promise<void>;- inputProps?: LabelValueInputProps["inputProps"];-}) {- const [ draft, setDraft ] = useState(value);- // What the note holds is what the box shows, however the value came to change.- useEffect(() => setDraft(value), [ value ]);- // Whether the text is something typed this visit, rather than the value the box opened with.- // Only typed text filters the list and offers creating: comparing the text against the value- // instead would stop filtering whenever typing happens to pass through it (retyping what was- // erased, or reproducing a stale value), which is exactly when the list must keep up.- const typedSinceFocus = useRef(false);-- // Narrowed because Preact types the attribute as possibly signal-backed, while the text box- // underneath takes the plain string.- const { id, ...restInputProps } = inputProps ?? {};-- // What the list is narrowed by: the typed text, or nothing while the box still shows the value- // it opened with — reopening a filled field offers every choice, not the one already made.- const filter = typedSinceFocus.current ? draft.trim() : "";-- const source = useCallback(async (query: string) => {- const trimmed = query.trim();- const typed = typedSinceFocus.current ? trimmed : "";- const items = typed- ? options.filter((option) => option.toLowerCase().includes(typed.toLowerCase()))- : [ ...options ];-- if (typed && !options.some((option) => option.toLowerCase() === typed.toLowerCase())) {- items.push(CREATE_OPTION_SENTINEL + trimmed);- }- return items;- }, [ options ]);-- return (- <FormAutocomplete- {...restInputProps}- id={typeof id === "string" ? id : undefined}- className={clsx(inputProps?.className, "label-select-combobox")}- currentValue={draft}- openOnFocus- // The suggestions are the choices themselves, so the list opens on the option already- // held — Enter then keeps it, as a dropdown's would.- autoActivate- source={source}- renderItem={(item) => item.startsWith(CREATE_OPTION_SENTINEL)- ? <span className="label-select-create-option">- <span className="bx bx-plus" />{" "}- {t("promoted_attributes.create_option", { option: item.substring(CREATE_OPTION_SENTINEL.length) })}- </span>- : highlightMatch(item, filter)}- onChange={(newValue) => {- // Typing only — a made choice arrives through onPick — so the text is never a- // commit, only the filter. Even text spelling an option exactly keeps filtering:- // "bar" typed on the way to "barr" is not yet a decision for either.- typedSinceFocus.current = true;- setDraft(newValue);- }}- onPick={(item) => {- // A made choice resets the box to its opened-with state: the text is the value- // again, so the list is back to offering everything.- typedSinceFocus.current = false;- if (item.startsWith(CREATE_OPTION_SENTINEL)) {- const option = item.substring(CREATE_OPTION_SENTINEL.length);- void onCreateOption(option);- setDraft(option);- onCommit(option);- } else {- setDraft(item);- onCommit(item);- }- }}- onBlur={(leftBehind) => {- typedSinceFocus.current = false;- const trimmed = leftBehind.trim();- if (!trimmed) {- setDraft("");- if (value) {- onCommit("");- }- return;- }-- // Text spelling an option's full name is as good as picking it — leaving the field- // after typing it out must not throw the choice away. The option's own casing wins.- const match = options.find((option) => option.toLowerCase() === trimmed.toLowerCase());- if (match && match !== value) {- setDraft(match);- onCommit(match);- } else if (leftBehind !== value) {- setDraft(value);- }- }}- />- );-}--/**- * An option with the part the typed text matched set in bold, so a filtered list shows why each of- * its entries is still there. Case-insensitive like the filtering, first occurrence only — the same- * match the filter found. Without a filter (or, defensively, without a match) the text is plain.- */-function highlightMatch(text: string, filter: string) {- const index = filter ? text.toLowerCase().indexOf(filter.toLowerCase()) : -1;- if (index < 0) {- return text;- }- return <>- {text.substring(0, index)}- <b>{text.substring(index, index + filter.length)}</b>- {text.substring(index + filter.length)}- </>;-}-/*** The choices a select offers: the unset entry first — a promoted field can always be left blank, and* it wears the host's placeholder so "not set" reads the same as in a text field — then the defineddiff --git a/apps/client/src/widgets/attribute_widgets/select_input.css b/apps/client/src/widgets/attribute_widgets/select_input.cssnew file mode 100644index 0000000000..52e0109a3d--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/select_input.css@@ -0,0 +1,18 @@+/* The "Create" entry of a select's list, set apart from the options it sits under: it makes a new+ option rather than picking one. Scoped to the dropdown, which is portaled to the body. */+.form-autocomplete-dropdown .select-create-option {+ font-style: italic;++ > .bx {+ color: var(--muted-text-color);+ }+}++/*+ * The chips of a multi-valued select. They hold text rather than a box typed into, so they need none+ * of the field styling the shared chip leaves to its contents — only room for the word itself.+ */+.form-autocomplete-field .select-values-chip > span {+ padding-block: 2px;+ white-space: nowrap;+}diff --git a/apps/client/src/widgets/attribute_widgets/select_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/select_input.spec.tsxnew file mode 100644index 0000000000..b7c7d7da90--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/select_input.spec.tsx@@ -0,0 +1,151 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { createdOption, isCreateEntry, selectEntriesFor, SelectValuesInput } from "./select_input";++describe("SelectValuesInput", () => {+ let container: HTMLElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ async function mount(props: Parameters<typeof SelectValuesInput>[0]) {+ await act(async () => render(<SelectValuesInput {...props} />, container));+ return container;+ }++ /** 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(".form-autocomplete-dropdown li") ];+ }++ async function typeInto(input: HTMLInputElement | null, value: string) {+ await act(async () => {+ if (input) {+ input.value = value;+ input.dispatchEvent(new Event("input", { bubbles: true }));+ }+ });+ }++ const options = [ "Todo", "In progress", "Done" ];++ it("shows the values held as chips inside the field, and drops the one pressed", async () => {+ const onCommit = vi.fn();+ await mount({ options, values: [ "Todo", "Done" ], onCommit });++ const chips = [ ...container.querySelectorAll(".select-values-chip") ];+ expect(chips.map((chip) => chip.textContent?.trim())).toEqual([ "Todo", "Done" ]);+ // The chips sit within the field's frame, ahead of the box typed into.+ expect(chips[0]?.closest(".form-autocomplete-field")).not.toBeNull();++ await act(async () => chips[0]?.querySelector<HTMLElement>(".tn-chip-remove")?.click());+ expect(onCommit).toHaveBeenCalledWith([ "Done" ]);+ });++ it("offers only what is not held yet, and adds the entry picked to the set", async () => {+ const onCommit = vi.fn();+ await mount({ options, values: [ "Todo" ], onCommit });++ const input = container.querySelector("input");+ await act(async () => input?.focus());++ // "Todo" is a chip already, so the list is what is left to take.+ const items = await settleDropdown();+ expect(items.map((item) => item.textContent)).toEqual([ "In progress", "Done" ]);++ await act(async () => (items[1] as HTMLElement | undefined)?.click());+ expect(onCommit).toHaveBeenCalledWith([ "Todo", "Done" ]);+ });++ it("creates an option the definition lacks, taking it as a value in the same breath", async () => {+ const onCommit = vi.fn();+ const onCreateOption = vi.fn();+ await mount({ options, values: [], onCommit, onCreateOption });++ const input = container.querySelector("input");+ await act(async () => input?.focus());+ await typeInto(input, "Blocked");++ const items = await settleDropdown();+ expect(items[0]?.querySelector(".select-create-option")).not.toBeNull();++ await act(async () => (items[0] as HTMLElement | undefined)?.click());+ expect(onCreateOption).toHaveBeenCalledWith("Blocked");+ expect(onCommit).toHaveBeenCalledWith([ "Blocked" ]);+ // The box goes back to being empty: what it held was a filter, and the value is a chip now.+ expect(input?.value).toBe("");+ });++ it("drops the last chip on backspace in an empty box, and leaves a filled one alone", async () => {+ const onCommit = vi.fn();+ await mount({ options, values: [ "Todo", "Done" ], onCommit });++ const input = container.querySelector("input");+ await act(async () => {+ input?.dispatchEvent(new KeyboardEvent("keydown", { key: "Backspace", bubbles: true }));+ });+ expect(onCommit).toHaveBeenCalledWith([ "Todo" ]);++ // With something typed, backspace is the box's own to erase with.+ onCommit.mockClear();+ await typeInto(input, "Do");+ await act(async () => {+ input?.dispatchEvent(new KeyboardEvent("keydown", { key: "Backspace", bubbles: true }));+ });+ expect(onCommit).not.toHaveBeenCalled();+ });+});++describe("selectEntriesFor", () => {+ const options = [ "Todo", "In progress", "Done" ];++ it("offers every option unfiltered, and narrows to what the filter matches", () => {+ expect(selectEntriesFor({ options, filter: "" })).toEqual(options);+ // Matched anywhere in the option, ignoring case and surrounding space.+ expect(selectEntriesFor({ options, filter: " o " })).toEqual([ "Todo", "In progress", "Done" ]);+ expect(selectEntriesFor({ options, filter: "do" })).toEqual([ "Todo", "Done" ]);+ expect(selectEntriesFor({ options, filter: "PROG" })).toEqual([ "In progress" ]);+ });++ it("offers to create a filter that names no option, but only when asked", () => {+ const entries = selectEntriesFor({ options, filter: "Blocked", canCreate: true });+ expect(entries).toHaveLength(1);+ expect(isCreateEntry(entries[0])).toBe(true);+ expect(createdOption(entries[0])).toBe("Blocked");++ // Without the offer the list is simply empty, rather than inviting what cannot be done.+ expect(selectEntriesFor({ options, filter: "Blocked" })).toEqual([]);+ // An option named exactly is picked, not created — whatever its casing.+ expect(selectEntriesFor({ options, filter: "done", canCreate: true })).toEqual([ "Done" ]);+ });++ it("leaves out what is spoken for, without offering to create it afresh", () => {+ // The values a multi field holds are shown as chips, so offering them again invites a+ // duplicate it could not tell from the first.+ expect(selectEntriesFor({ options, filter: "", exclude: [ "Todo" ] }))+ .toEqual([ "In progress", "Done" ]);++ // Excluded, "Todo" no longer matches the list — but it is still an option that exists, so+ // typing it out must not offer to make a second one.+ expect(selectEntriesFor({ options, filter: "Todo", exclude: [ "Todo" ], canCreate: true }))+ .toEqual([]);+ });++ it("offers to create a value held but never declared, which is an option nowhere yet", () => {+ // A value left behind by an option since renamed away is held without being offered.+ const entries = selectEntriesFor({ options, filter: "Archived", exclude: [], canCreate: true });+ expect(entries.map(createdOption)).toEqual([ "Archived" ]);+ });+});diff --git a/apps/client/src/widgets/attribute_widgets/select_input.tsx b/apps/client/src/widgets/attribute_widgets/select_input.tsxnew file mode 100644index 0000000000..8babff3eff--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/select_input.tsx@@ -0,0 +1,288 @@+import "./select_input.css";++import clsx from "clsx";+import type { InputHTMLAttributes, TargetedKeyboardEvent } from "preact";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import Chip from "../react/Chip";+import FormAutocomplete from "../react/FormAutocomplete";++/** Merged onto the box, for the id, tab order and data attributes a host needs to attach. */+type SelectInputProps = InputHTMLAttributes<HTMLInputElement>;++interface SelectComboBoxProps {+ /** The options the definition declares. */+ options: readonly string[];+ /** The value held, or the empty string where the field is unset. */+ value: string;+ onCommit(value: string): void;+ /** Adds an option to the definition, for the entry offered on text naming none of them. */+ onCreateOption(option: string): void | Promise<void>;+ inputProps?: SelectInputProps;+}++/**+ * The field a select holding one value is edited through. The box holds a draft of the value: the+ * full list opens on focus, typing filters it, and only picking an entry commits — an option by its+ * text, the "Create" entry by first handing the typed text to `onCreateOption`. Text that matches+ * nothing reverts when the field is left, except an emptied box, which commits the empty value:+ * clearing is a choice of its own, and cannot pollute the definition.+ */+export function SelectComboBox({ options, value, onCommit, onCreateOption, inputProps }: SelectComboBoxProps) {+ const [ draft, setDraft ] = useState(value);+ // What the note holds is what the box shows, however the value came to change.+ useEffect(() => setDraft(value), [ value ]);+ // Whether the text is something typed this visit, rather than the value the box opened with.+ // Only typed text filters the list and offers creating: comparing the text against the value+ // instead would stop filtering whenever typing happens to pass through it (retyping what was+ // erased, or reproducing a stale value), which is exactly when the list must keep up.+ const typedSinceFocus = useRef(false);++ // Narrowed because Preact types the attribute as possibly signal-backed, while the text box+ // underneath takes the plain string.+ const { id, ...restInputProps } = inputProps ?? {};++ // What the list is narrowed by: the typed text, or nothing while the box still shows the value+ // it opened with — reopening a filled field offers every choice, not the one already made.+ const filter = typedSinceFocus.current ? draft.trim() : "";++ const source = useCallback(async (query: string) => selectEntriesFor({+ options,+ filter: typedSinceFocus.current ? query : "",+ canCreate: true+ }), [ options ]);++ return (+ <FormAutocomplete+ {...restInputProps}+ id={typeof id === "string" ? id : undefined}+ className={clsx(inputProps?.className, "label-select-combobox")}+ currentValue={draft}+ openOnFocus+ // The suggestions are the choices themselves, so the list opens on the option already+ // held — Enter then keeps it, as a dropdown's would.+ autoActivate+ source={source}+ renderItem={(item) => renderSelectEntry(item, filter)}+ onChange={(newValue) => {+ // Typing only — a made choice arrives through onPick — so the text is never a+ // commit, only the filter. Even text spelling an option exactly keeps filtering:+ // "bar" typed on the way to "barr" is not yet a decision for either.+ typedSinceFocus.current = true;+ setDraft(newValue);+ }}+ onPick={(item) => {+ // A made choice resets the box to its opened-with state: the text is the value+ // again, so the list is back to offering everything.+ typedSinceFocus.current = false;+ if (isCreateEntry(item)) {+ const option = createdOption(item);+ void onCreateOption(option);+ setDraft(option);+ onCommit(option);+ } else {+ setDraft(item);+ onCommit(item);+ }+ }}+ onBlur={(leftBehind) => {+ typedSinceFocus.current = false;+ const trimmed = leftBehind.trim();+ if (!trimmed) {+ setDraft("");+ if (value) {+ onCommit("");+ }+ return;+ }++ // Text spelling an option's full name is as good as picking it — leaving the field+ // after typing it out must not throw the choice away. The option's own casing wins.+ const match = options.find((option) => option.toLowerCase() === trimmed.toLowerCase());+ if (match && match !== value) {+ setDraft(match);+ onCommit(match);+ } else if (leftBehind !== value) {+ setDraft(value);+ }+ }}+ />+ );+}++interface SelectValuesInputProps {+ /** The options the definition declares. */+ options: readonly string[];+ /** The values held, in the order they are shown. */+ values: readonly string[];+ /** Receives the values as they now stand, whenever one is taken or dropped. */+ onCommit(values: string[]): void;+ /**+ * Adds an option to the definition, for the entry offered on text naming none of them. Left out,+ * the field picks from the options as they stand.+ */+ onCreateOption?(option: string): void | Promise<void>;+ placeholder?: string;+ disabled?: boolean;+}++/**+ * The field a select holding several values is edited through: the values as chips inside the field,+ * and a box after them offering what is left to take.+ *+ * The box holds a filter rather than a value — the chips are what is held — so nothing typed into it+ * is ever kept: an entry has to be picked, and what is left behind is dropped when the field is. The+ * list stays open across picks, since taking one value is rarely the end of it.+ */+export function SelectValuesInput({ options, values, onCommit, onCreateOption, placeholder, disabled }: SelectValuesInputProps) {+ const [ filter, setFilter ] = useState("");++ // Taken values leave the list: what is held is shown as a chip, so offering it again would only+ // invite a duplicate the field cannot show apart from the first.+ const source = useCallback(async (query: string) => selectEntriesFor({+ options,+ filter: query,+ exclude: values,+ canCreate: !!onCreateOption+ }), [ options, values, onCreateOption ]);++ function take(value: string) {+ setFilter("");+ onCommit([ ...values, value ]);+ }++ function drop(value: string) {+ onCommit(values.filter((held) => held !== value));+ }++ function handleKeyDown(e: TargetedKeyboardEvent<HTMLInputElement>) {+ // Backspace on an empty box drops the last chip, the box having nothing of its own to erase.+ if (e.key === "Backspace" && !e.currentTarget.value && values.length) {+ e.preventDefault();+ drop(values[values.length - 1]);+ }+ }++ return (+ <FormAutocomplete+ className="select-values-input"+ currentValue={filter}+ placeholder={values.length ? undefined : placeholder}+ disabled={disabled}+ openOnFocus+ autoActivate+ keepOpenOnPick+ source={source}+ renderItem={(item) => renderSelectEntry(item, filter)}+ leading={values.map((value) => (+ <Chip+ key={value}+ className="select-values-chip"+ removeButtonText={t("promoted_attributes.remove_value")}+ disabled={disabled}+ onRemove={() => drop(value)}+ >+ <span>{value}</span>+ </Chip>+ ))}+ onChange={setFilter}+ onPick={(item) => {+ if (isCreateEntry(item)) {+ const option = createdOption(item);+ void onCreateOption?.(option);+ take(option);+ } else {+ take(item);+ }+ }}+ // Text nobody picked names no value, so it goes with the field rather than being kept.+ onBlur={() => setFilter("")}+ onKeyDown={handleKeyDown}+ />+ );+}++/**+ * Marks the entry offering to make the typed text into an option, apart from the options themselves.+ * An option can never start with it: a control character cannot be typed into either the field or+ * the definition editor.+ */+const CREATE_OPTION_SENTINEL = "\u0000";++interface SelectEntriesArgs {+ /** Every option the definition declares. */+ options: readonly string[];+ /** What was typed into the field; empty offers the options unfiltered. */+ filter: string;+ /** Options to leave out of the list, being spoken for already — the values a multi field holds. */+ exclude?: readonly string[];+ /** Whether an unmatched filter may be offered as an option to create. */+ canCreate?: boolean;+}++/**+ * The entries a select's list offers: the options the filter matches, and — where it names none of+ * them — an entry offering to make it one.+ *+ * The offer is weighed against every option, the excluded ones included: a value the field already+ * holds is a choice that exists, so typing it out again offers nothing rather than a second copy.+ *+ * Exported for its own tests; the fields above are what it is for.+ */+export function selectEntriesFor({ options, filter, exclude = [], canCreate }: SelectEntriesArgs) {+ const trimmed = filter.trim();+ const query = trimmed.toLowerCase();+ const entries = options+ .filter((option) => !exclude.includes(option))+ .filter((option) => !query || option.toLowerCase().includes(query));++ const isKnown = (option: string) => option.toLowerCase() === query;+ if (canCreate && trimmed && !options.some(isKnown) && !exclude.some(isKnown)) {+ entries.push(CREATE_OPTION_SENTINEL + trimmed);+ }+ return entries;+}++/** Whether a picked entry is the offer to create an option rather than one of the options. */+export function isCreateEntry(item: string) {+ return item.startsWith(CREATE_OPTION_SENTINEL);+}++/** The option a create entry would make, i.e. the text that was typed. */+export function createdOption(item: string) {+ return item.substring(CREATE_OPTION_SENTINEL.length);+}++/**+ * One entry of the list: the create entry as the thing it will do, an option with the part the+ * filter matched set in bold so a narrowed list shows why each of its entries is still there.+ */+function renderSelectEntry(item: string, filter: string) {+ if (isCreateEntry(item)) {+ return (+ <span className="select-create-option">+ <span className="bx bx-plus" />{" "}+ {t("promoted_attributes.create_option", { option: createdOption(item) })}+ </span>+ );+ }+ return highlightMatch(item, filter);+}++/**+ * An option with the part the typed text matched set in bold. Case-insensitive like the filtering,+ * first occurrence only — the same match the filter found. Without a filter (or, defensively,+ * without a match) the text is plain.+ */+function highlightMatch(text: string, filter: string) {+ const index = filter ? text.toLowerCase().indexOf(filter.toLowerCase()) : -1;+ if (index < 0) {+ return text;+ }+ return <>+ {text.substring(0, index)}+ <b>{text.substring(index, index + filter.length)}</b>+ {text.substring(index + filter.length)}+ </>;+}diff --git a/apps/client/src/widgets/collections/table/columns.css b/apps/client/src/widgets/collections/table/columns.cssnew file mode 100644index 0000000000..209a391d83--- /dev/null+++ b/apps/client/src/widgets/collections/table/columns.css@@ -0,0 +1,66 @@+/* The chips of a multi-valued select cell, read-only here: the cell shows the set, the editor edits+ it. They wrap rather than being clipped one word in, a row growing to the tallest cell in it. */+.table-select-values {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px;++ > .tn-chip {+ padding-inline: 8px;+ padding-block: 1px;+ }+}++/*+ * The editor opens over its cell rather than inside it. A cell is as tall as one line and as wide as+ * the column was dragged to, which a set of chips and a box to type in outgrows at once — laid out+ * within, the chips would wrap out of sight the moment there were two.+ *+ * The cell it belongs to therefore stops clipping while it is being edited, and comes forward so the+ * editor is drawn over the rows below rather than under them.+ */+.tabulator-row:not(.tabulator-moving) .tabulator-cell.tabulator-editing:has(> .table-select-editor) {+ overflow: visible !important;+ z-index: 10;++ /* The cell also gives up the frame it wears while being edited, the editor standing over it with+ one of its own: two would be one too many, and the cell's would stop short of the editor —+ ending at the column's edge while the editor carried on past it. */+ outline: none;+ border-color: transparent;+ background: transparent;+}++.table-select-editor {+ position: absolute;+ inset-block-start: 0;+ inset-inline-start: 0;+ /* Never narrower than the cell it stands in, and no wider than it needs — up to a ceiling, past+ which the chips wrap instead of the editor running across the table. */+ min-width: 100%;+ width: max-content;+ max-width: 320px;++ /*+ * The editor brings a surface of its own, opaque, because it stands over the table rather than in+ * it. A field's own background is a translucent film — a tint meant to sit on the page behind it,+ * and in some themes nothing at all — through which the row underneath would otherwise be read+ * along with the chips.+ *+ * The surface is inset by the width of the field's focus ring, since an outline is drawn outside+ * the element it belongs to: without the room, the ring — translucent in every theme — would fall+ * past the surface and be tinted by whatever it happened to cross, coming out one colour over the+ * cell and another over the table beside it.+ */+ padding: 2px;+ background-color: var(--main-background-color);+ border-radius: 8px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, var(--dropdown-shadow-opacity, 0.2));++ /* Over that surface the film reads as it does anywhere else: as a field within the thing it+ floats on, rather than as a hole in it. */+ > .form-autocomplete-field {+ background-color: var(--input-background-color);+ }+}diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex 76036ccbfe..0ba163cc0f 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -1,11 +1,15 @@+import "./columns.css";+import { LabelType } from "@triliumnext/commons";import { JSX } from "preact";import { useEffect, useRef, useState } from "preact/hooks";import type { CellComponent, ColumnDefinition, EmptyCallback, FormatterParams, RowComponent, ValueBooleanCallback, ValueVoidCallback } from "tabulator-tables";import froca from "../../../services/froca.js";+import { t } from "../../../services/i18n.js";import { formatDateNumeric } from "../../../utils/formatters.js";import LabelValueInput from "../../attribute_widgets/label_value_input.jsx";+import { SelectValuesInput } from "../../attribute_widgets/select_input.jsx";import Icon from "../../react/Icon.jsx";import NoteAutocomplete from "../../react/NoteAutocomplete.jsx";import { renderReactWidget } from "../../react/react_utils.jsx";@@ -18,6 +22,8 @@ export interface AttributeDefinitionInformation {type?: ColumnType;/** The values a `select` column offers, from the definition that declared it. */options?: string[];+ /** Whether the column holds a set of values rather than one, which only a `select` may. */+ isMulti?: boolean;}const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {@@ -164,7 +170,7 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,];const seenFields = new Set<string>();- for (const { name, title, type, options } of info) {+ for (const { name, title, type, options, isMulti } of info) {const prefix = (type === "relation" ? "relations" : "labels");const field = `${prefix}.${name}`;@@ -183,9 +189,16 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,...(type === "select" && {editorParams: (): Record<string, unknown> => ({options: options ?? [],+ isMulti,onCreateOption: onCreateSelectOption&& ((option: string) => onCreateSelectOption(name, option))} satisfies SelectEditorParams)+ }),+ // A set is shown as the chips it is edited as, and sorted by the values it holds rather+ // than by the array Tabulator would otherwise compare as an object.+ ...(type === "select" && isMulti && {+ formatter: wrapFormatter(SelectValuesFormatter),+ sorter: (a, b) => joinValues(a).localeCompare(joinValues(b))})});seenFields.add(field);@@ -329,29 +342,89 @@ function NoteFormatter({ cell }: FormatterOpts) {* hands no reference to the box it builds; the list then opens as it does for any focused combobox.*/function SelectEditor({ cell, success, editorParams }: EditorOpts) {- const { options, onCreateOption } = editorParams as SelectEditorParams;+ const { options, isMulti, onCreateOption } = editorParams as SelectEditorParams;const containerRef = useRef<HTMLDivElement>(null);useEffect(() => containerRef.current?.querySelector("input")?.focus(), []);+ // The set as it stands while the cell is open. Reporting each chip as it is taken would close the+ // editor on the first one — `success` is Tabulator's "the edit is done" — so the set is held here+ // and handed over once, when the field is left. A ref beside it because the handler below is+ // bound once and would otherwise report the set the editor opened with.+ const [ values, setValues ] = useState<string[]>(() => asValues(cell.getValue()));+ const editedValues = useRef(values);+ editedValues.current = values;++ useEffect(() => {+ const editor = containerRef.current;+ if (!isMulti || !editor) return;++ const onFocusOut = (e: FocusEvent) => {+ // Focus moving within the editor — the box to a chip's remove button, or back — is not+ // leaving it. Picking from the list does not blur at all: the list keeps the focus in+ // the box, which is what lets it stay open across picks.+ if (e.relatedTarget instanceof Node && editor.contains(e.relatedTarget)) return;+ success(editedValues.current);+ };++ editor.addEventListener("focusout", onFocusOut);+ return () => editor.removeEventListener("focusout", onFocusOut);+ }, [ isMulti, success ]);return (<div ref={containerRef} className="table-select-editor">- <LabelValueInput- labelType="select"- value={cell.getValue() ?? ""}- selectOptions={options}- onCommit={success}- onCreateOption={onCreateOption}- />+ {isMulti ? (+ <SelectValuesInput+ options={options}+ values={values}+ placeholder={t("promoted_attributes.select_values_placeholder")}+ onCreateOption={onCreateOption}+ onCommit={setValues}+ />+ ) : (+ <LabelValueInput+ labelType="select"+ value={cell.getValue() ?? ""}+ selectOptions={options}+ onCommit={success}+ onCreateOption={onCreateOption}+ />+ )}</div>);}+/** A multi-valued cell as the chips it is edited as, so reading and editing show the same set. */+function SelectValuesFormatter({ cell }: FormatterOpts) {+ return (+ <span className="table-select-values">+ {asValues(cell.getValue()).map((value) => (+ <span key={value} className="tn-chip">{value}</span>+ ))}+ </span>+ );+}++/**+ * A multi-valued cell's values. Stored as an array, but a cell can hold what an older single-valued+ * definition left behind, or nothing at all, so anything else is read as the set it stands for.+ */+function asValues(value: unknown): string[] {+ if (Array.isArray(value)) return value.filter((item): item is string => typeof item === "string");+ return typeof value === "string" && value ? [ value ] : [];+}++/** The values as one string, for comparing two sets in a sort. */+function joinValues(value: unknown) {+ return asValues(value).join(", ");+}+/**- * What a select column hands its editor: the options it offers, and how to add one to them. A type- * rather than an interface so that it still reads as the loose record Tabulator types params as.+ * What a select column hands its editor: the options it offers, whether it holds a set of them, and+ * how to add one. A type rather than an interface so that it still reads as the loose record+ * Tabulator types params as.*/export type SelectEditorParams = {options: string[];+ isMulti?: boolean;/** Absent where the definition cannot be written to, which leaves the field a plain picker. */onCreateOption?: (option: string) => void | Promise<void>;};diff --git a/apps/client/src/widgets/collections/table/row_editing.ts b/apps/client/src/widgets/collections/table/row_editing.tsindex 03f6b8ff49..57f6598ee5 100644--- a/apps/client/src/widgets/collections/table/row_editing.ts+++ b/apps/client/src/widgets/collections/table/row_editing.ts@@ -3,7 +3,7 @@ import { EventCallBackMethods, RowComponent, Tabulator } from "tabulator-tables"import { CommandListenerData } from "../../../components/app_context";import FNote from "../../../entities/fnote";-import { setAttribute, setLabel } from "../../../services/attributes";+import { setAttribute, setLabel, setLabelValues } from "../../../services/attributes";import branches from "../../../services/branches";import froca from "../../../services/froca";import note_create, { CreateNoteOpts } from "../../../services/note_create";@@ -49,6 +49,16 @@ export default function useRowTableEditing(api: RefObject<Tabulator>, attributeDif (field.includes(".")) {const [ type, name ] = field.split(".", 2);if (type === "labels") {+ // A set of values is written as the several labels it is, rather than as one+ // holding the array stringified.+ if (Array.isArray(newValue)) {+ const note = await froca.getNote(noteId);+ if (note) {+ await setLabelValues(note, name, newValue as string[]);+ }+ return;+ }+if (typeof newValue === "boolean") {newValue = newValue ? "true" : "false";} else if (typeof newValue === "number") {diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.tsindex 8e2de80ab6..54d0324fc0 100644--- a/apps/client/src/widgets/collections/table/rows.ts+++ b/apps/client/src/widgets/collections/table/rows.ts@@ -7,7 +7,7 @@ export type TableData = {iconClass: string;noteId: string;title: string;- labels: Record<string, boolean | string | null>;+ labels: Record<string, boolean | string | string[] | null>;relations: Record<string, boolean | string | null>;branchId: string;colorClass: string | undefined;@@ -33,9 +33,13 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDefconst labels: typeof definitions[0]["labels"] = {};const relations: typeof definitions[0]["relations"] = {};- for (const { name, type } of infos) {+ for (const { name, type, isMulti } of infos) {if (type === "relation") {relations[name] = note.getRelationValue(name);+ } else if (isMulti) {+ // Every label of the name rather than the first, blanks dropped: the cell holds the+ // set, and an empty one is a value the field never offered.+ labels[name] = note.getLabels(name).map((label) => label.value).filter(Boolean);} else {labels[name] = note.getLabelValue(name);}@@ -76,11 +80,6 @@ export default function getAttributeDefinitionInformation(parentNote: FNote) {const attrDefs = parentNote.getAttributeDefinitions();for (const attrDef of attrDefs) {const def = attrDef.getDefinition();- if (def.multiplicity !== "single") {- console.warn("Multiple values are not supported for now");- continue;- }-const [ attrType, name ] = extractAttributeDefinitionTypeAndName(attrDef.name);if (attrDef.type !== "label") {console.warn("Relations are not supported for now");@@ -92,11 +91,21 @@ export default function getAttributeDefinitionInformation(parentNote: FNote) {type = "relation";}+ // A select is the one field a column can show several values in: its values are a set drawn+ // from the options, which chips display and edit as the set it is. Any other type holds free+ // text, for which a column has one cell and no way to tell one value from the next.+ const isMulti = def.multiplicity === "multi";+ if (isMulti && type !== "select") {+ console.warn("Multiple values are not supported for now");+ continue;+ }+info.push({name,title: def.promotedAlias,type,- options: def.selectOptions+ options: def.selectOptions,+ isMulti});}return info;diff --git a/apps/client/src/widgets/react/Chip.css b/apps/client/src/widgets/react/Chip.cssnew file mode 100644index 0000000000..778fc1540c--- /dev/null+++ b/apps/client/src/widgets/react/Chip.css@@ -0,0 +1,54 @@+/*+ * One entry of a set: a rounded chip holding whatever it stands for, and a button removing it. The+ * chip is the surface — its contents give up borders and backgrounds of their own — so that a set+ * being read and a set being edited come out looking alike.+ */+.tn-chip {+ --chip-remove-size: 18px;++ display: flex;+ align-items: center;+ gap: 2px;+ /* Tighter at the trailing edge, where the remove button brings padding of its own. */+ padding-inline: 8px 3px;+ border-radius: var(--badge-radius, 12px);+ background-color: var(--hover-item-background-color);++ /* The chip carries the focus ring, anything typed into it having given up one of its own —+ otherwise a field's outline would be drawn inside a chip that already looks like a box. */+ &:focus-within {+ outline: 2px solid var(--input-focus-outline-color);+ }++ > .tn-chip-remove {+ --icon-button-size: var(--chip-remove-size);+ --icon-button-icon-ratio: 0.9;++ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ width: var(--chip-remove-size);+ height: var(--chip-remove-size);+ padding: 0;+ font-size: calc(var(--chip-remove-size) * 0.9);+ line-height: 1;++ /* Blank until aimed at, where the theme's own hover treatment takes back over — the chip is+ the surface it sits on, not a button plate of its own. */+ &:not(:hover):not(:focus-visible) {+ background: transparent;+ }+ }++ /* Nothing to press where the set is read-only: the chips are then only a display of it, and a+ button offering a removal that is not on the table would say otherwise. */+ > .tn-chip-remove:disabled {+ display: none;+ }++ /* With no button at the trailing edge, the chip pads itself as evenly as it started. */+ &:has(> .tn-chip-remove:disabled) {+ padding-inline-end: 8px;+ }+}diff --git a/apps/client/src/widgets/react/Chip.tsx b/apps/client/src/widgets/react/Chip.tsxnew file mode 100644index 0000000000..06c7bae9c6--- /dev/null+++ b/apps/client/src/widgets/react/Chip.tsx@@ -0,0 +1,35 @@+import "./Chip.css";++import type { ComponentChildren } from "preact";++import ActionButton from "./ActionButton.jsx";++interface ChipProps {+ children: ComponentChildren;+ /** What removing this chip means, in the host's own words (e.g. "Remove this option"). */+ removeButtonText: string;+ onRemove(): void;+ /** Leaves the chips as a display of the set, with nothing to press. */+ disabled?: boolean;+ className?: string;+}++/**+ * One entry of a set, drawn as a rounded chip with a button removing it. Whatever the chip stands+ * for goes inside — the text of a value, or a box the text is typed into — so that a set being read+ * and a set being edited look alike.+ */+export default function Chip({ children, removeButtonText, onRemove, disabled, className }: ChipProps) {+ return (+ <div className={`tn-chip ${className ?? ""}`}>+ {children}+ <ActionButton+ className="tn-chip-remove"+ icon="bx bx-x"+ text={removeButtonText}+ disabled={disabled}+ onClick={onRemove}+ />+ </div>+ );+}diff --git a/apps/client/src/widgets/react/FormAutocomplete.css b/apps/client/src/widgets/react/FormAutocomplete.cssindex 89dfa7ce08..66b7e07cda 100644--- a/apps/client/src/widgets/react/FormAutocomplete.css+++ b/apps/client/src/widgets/react/FormAutocomplete.css@@ -1,3 +1,39 @@+/*+ * A field carrying chips ahead of the box typed into (see the component's `leading`): the two are+ * framed as one, so the chips read as being in the field rather than stacked above it. The box gives+ * up its own frame and takes what room is left on the line, wrapping onto the next once the chips+ * have filled it.+ */+.form-autocomplete-field {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px;+ padding: 3px 6px;+ border: 1px solid var(--main-border-color);+ border-radius: 6px;+ background: var(--input-background-color);++ &:focus-within {+ outline: 2px solid var(--input-focus-outline-color);+ }++ > input.form-control {+ flex: 1;+ min-width: 6ch;+ width: auto;+ padding: 2px 0;+ border: none;+ outline: none;++ &,+ &:hover,+ &:focus {+ background: transparent;+ }+ }+}+/** The suggestion list, dressed as one of the application's menus — the same metrics the mention list* in a text note is given, since both are a list of choices floating over the thing being edited.diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex d5ba9276ce..1c476cfb4b 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -35,12 +35,28 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {* which is the DOM's own text-selection event and reaches the input as such.)*/onPick?(item: string): void;+ /**+ * Leaves the list open once an entry is picked, for a field collecting several — where picking+ * one is rarely the end of it, and closing would ask for the list back each time.+ *+ * The entries are fetched afresh, so a list narrowing as it is picked from (one leaving out what+ * has been taken already) is correct the moment its source says so.+ */+ keepOpenOnPick?: boolean;/*** Renders one suggestion, for lists where the bare text does not tell the whole story. Only the* appearance of the row is affected: what a suggestion means and what selecting it commits stay* the string the source returned. Defaults to showing that string.*/renderItem?(item: string): ComponentChildren;+ /**+ * Rendered inside the field, ahead of the box being typed into — the chips of a field holding+ * several values, which belong within its frame rather than above it.+ *+ * The two are then wrapped together, and the list is measured against that wrapper, so it spans+ * the whole field instead of only the stretch of it left over for typing.+ */+ leading?: ComponentChildren;/*** Opens the list with an entry already picked out — the one the field's text names, or failing* that the first — so that Enter takes it without arrowing down to it first.@@ -58,9 +74,10 @@ 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, onPick, renderItem, autoActivate, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {+export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, onPick, keepOpenOnPick, renderItem, leading, autoActivate, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {const ownInputRef = useRef<HTMLInputElement>(null);const inputEl = inputRef ?? ownInputRef;+ const fieldRef = useRef<HTMLDivElement>(null);const dropdownRef = useRef<HTMLUListElement>(null);const [ isOpen, setIsOpen ] = useState(false);const [ items, setItems ] = useState<string[]>([]);@@ -120,8 +137,10 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO}const reposition = () => {- if (inputEl.current) {- setPosition(computeDropdownPosition(inputEl.current));+ // The wrapper where there is one, so a field carrying chips is spanned whole.+ const anchor = fieldRef.current ?? inputEl.current;+ if (anchor) {+ setPosition(computeDropdownPosition(anchor));}};@@ -137,7 +156,13 @@ export default function FormAutocomplete({ currentValue, onChange, source, openOfunction selectItem(item: string) {(onPick ?? onChange)(item);- close();+ if (keepOpenOnPick) {+ // Nothing is highlighted until the refreshed entries arrive, so Enter cannot take twice+ // what the list is about to stop offering.+ setActiveIndex(-1);+ } else {+ close();+ }inputEl.current?.focus();}@@ -181,29 +206,35 @@ export default function FormAutocomplete({ currentValue, onChange, source, openOonKeyDown?.(e);}+ const field = (+ <FormTextBox+ {...restProps}+ inputRef={inputEl}+ currentValue={currentValue}+ onChange={(newValue) => {+ onChange(newValue);+ if (!isDisabled) {+ setIsOpen(true);+ }+ }}+ onFocus={openOnFocus && !isDisabled ? () => setIsOpen(true) : undefined}+ onBlur={(newValue) => {+ close();+ onBlur?.(newValue);+ }}+ onKeyDown={handleKeyDown}+ role="combobox"+ aria-expanded={isOpen && items.length > 0}+ aria-autocomplete="list"+ aria-activedescendant={activeItemId}+ />+ );+return (<>- <FormTextBox- {...restProps}- inputRef={inputEl}- currentValue={currentValue}- onChange={(newValue) => {- onChange(newValue);- if (!isDisabled) {- setIsOpen(true);- }- }}- onFocus={openOnFocus && !isDisabled ? () => setIsOpen(true) : undefined}- onBlur={(newValue) => {- close();- onBlur?.(newValue);- }}- onKeyDown={handleKeyDown}- role="combobox"- aria-expanded={isOpen && items.length > 0}- aria-autocomplete="list"- aria-activedescendant={activeItemId}- />+ {leading !== undefined+ ? <div ref={fieldRef} className="form-autocomplete-field">{leading}{field}</div>+ : field}{isOpen && items.length > 0 && position && createPortal(<uldiff --git a/apps/client/src/widgets/react/FormTextBoxList.css b/apps/client/src/widgets/react/FormTextBoxList.cssindex 63d267715e..502692a231 100644--- a/apps/client/src/widgets/react/FormTextBoxList.css+++ b/apps/client/src/widgets/react/FormTextBoxList.css@@ -2,82 +2,35 @@* Laid out as chips rather than as a stack of fields: an option is one short word, so a full-width* boxed input per entry spends a whole row of the form on it and lists ten of them down the page.* A wrapping run of chips fits several to a line and shows the set as the set it is.+ *+ * The chip itself is the shared one (see Chip.css); what belongs here is what makes this chip's+ * contents a field one types into rather than text one reads.*/.form-textbox-list {- --textbox-list-remove-size: 18px;-display: flex;flex-wrap: wrap;align-items: center;gap: 4px;- .form-textbox-list-row {- display: flex;- align-items: center;- gap: 2px;- /* Tighter at the trailing edge, where the remove button brings padding of its own. */- padding-inline: 8px 3px;- border-radius: var(--badge-radius, 12px);- background-color: var(--hover-item-background-color);-- /* The chip carries the focus ring, its input having given up one of its own — otherwise a- field's outline would be drawn inside a chip that already looks like a box. */- &:focus-within {- outline: 2px solid var(--input-focus-outline-color);- }-- > input {- /* `form-control` is full-width by default; a chip is as wide as the word it holds. */- width: auto;- field-sizing: content;- /* Also the width where `field-sizing` is not supported, the `size` attribute standing- in for it there — see the component. */- min-width: 4ch;- /* The same ceiling the `size` attribute is capped at, so a long option scrolls inside- its chip either way instead of taking a line to itself. */- max-width: 30ch;- padding: 3px 0;- border: none;- outline: none;- font-size: inherit;-- &,- &:hover,- &:focus {- background: transparent;- }- }-- > .form-textbox-list-remove {- --icon-button-size: var(--textbox-list-remove-size);- --icon-button-icon-ratio: 0.9;-- flex-shrink: 0;- display: flex;- align-items: center;- justify-content: center;- width: var(--textbox-list-remove-size);- height: var(--textbox-list-remove-size);- padding: 0;- font-size: calc(var(--textbox-list-remove-size) * 0.9);- line-height: 1;-- /* Blank until aimed at, where the theme's own hover treatment takes back over — the- chip is the surface it sits on, not a button plate of its own. */- &:not(:hover):not(:focus-visible) {- background: transparent;- }- }-- /* Nothing to press where the list is read-only: the chips are then only a display of the- set, and a button offering a removal that is not on the table would say otherwise. */- > .form-textbox-list-remove:disabled {- display: none;- }-- /* With no button at the trailing edge, the chip pads itself as evenly as it started. */- &:has(> .form-textbox-list-remove:disabled) {- padding-inline-end: 8px;+ .form-textbox-list-row > input {+ /* `form-control` is full-width by default; a chip is as wide as the word it holds. */+ width: auto;+ field-sizing: content;+ /* Also the width where `field-sizing` is not supported, the `size` attribute standing+ in for it there — see the component. */+ min-width: 4ch;+ /* The same ceiling the `size` attribute is capped at, so a long option scrolls inside+ its chip either way instead of taking a line to itself. */+ max-width: 30ch;+ padding: 3px 0;+ border: none;+ outline: none;+ font-size: inherit;++ &,+ &:hover,+ &:focus {+ background: transparent;}}diff --git a/apps/client/src/widgets/react/FormTextBoxList.tsx b/apps/client/src/widgets/react/FormTextBoxList.tsxindex 038606e461..4a3dd01841 100644--- a/apps/client/src/widgets/react/FormTextBoxList.tsx+++ b/apps/client/src/widgets/react/FormTextBoxList.tsx@@ -2,8 +2,8 @@ import "./FormTextBoxList.css";import { useEffect, useRef, useState } from "preact/hooks";-import ActionButton from "./ActionButton.jsx";import Button from "./Button.jsx";+import Chip from "./Chip.jsx";import FormTextBox from "./FormTextBox.jsx";/** Room to start typing an option into an empty chip, and a ceiling so one long one cannot hog a line. */@@ -59,7 +59,13 @@ export default function FormTextBoxList({ initialValues, disabled, onChange, addreturn (<div ref={containerRef} className="form-textbox-list">{rows.map((row) => (- <div key={row.id} className="form-textbox-list-row">+ <Chip+ key={row.id}+ className="form-textbox-list-row"+ removeButtonText={removeButtonText}+ disabled={disabled}+ onRemove={() => commitRows(rows.filter((other) => other.id !== row.id))}+ ><FormTextBoxcurrentValue={row.value}// A chip is as wide as its own word. `field-sizing` does this exactly (see@@ -70,14 +76,7 @@ export default function FormTextBoxList({ initialValues, disabled, onChange, addonChange={(value) => commitRows(rows.map((other) => other.id === row.id ? { ...other, value } : other))}/>- <ActionButton- className="form-textbox-list-remove"- icon="bx bx-x"- text={removeButtonText}- disabled={disabled}- onClick={() => commitRows(rows.filter((other) => other.id !== row.id))}- />- </div>+ </Chip>))}<ButtonclassName="form-textbox-list-add"diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsxindex 47628e9c1c..5eba51da20 100644--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx@@ -251,6 +251,21 @@ describe("AttributeList", () => {expect(put.mock.calls[0][0]).toBe("notes/subject/attributes");});+ it("edits a system attribute that is a closed set as a dropdown of the values it allows", () => {+ renderPanel(buildNote({ id: "subject", title: "Subject", "#sortDirection": "desc" }));++ act(() => firstRow().click());++ const field = document.querySelector<HTMLSelectElement>(".attr-detail .attr-input-value");+ expect(field?.tagName).toBe("SELECT");+ expect([ ...(field?.options ?? []) ].map((option) => option.value)).toEqual([ "", "asc", "desc" ]);+ expect(field?.value).toBe("desc");+ // Not framed by an input group: it has no buttons to be grouped with, and a group blanks the+ // background of the fields inside it — which is the background the themes draw the dropdown's+ // arrow on, leaving nothing to say the field is one.+ expect(field?.closest(".input-group")).toBeNull();+ });+it("saves an attribute left open for editing to the note it belongs to, on reading another", () => {renderPanel(noteWithAttributes());act(() => firstRow().click());