Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): show how a typed value is confirmed

Elian Doran7fefef80539e
diff --git a/CLAUDE.md b/CLAUDE.md
index 967c918c88..6c14ee2f50 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -125,7 +125,6 @@ Common UI components are available in `apps/client/src/widgets/react/` — **alw
- `NoItems` - Empty state placeholder with icon and message (use for "no results", "too many items", error states)
- `ActionButton` - Consistent button styling with icon support
- `FormTextBox` - Text input with validation and controlled input handling; `FormTextBoxWithUnit` for inputs with a unit suffix (e.g. "mm", "px")
-- `FormTextBoxList` - Ordered list of short texts edited as one box per entry with add/remove buttons (e.g. a select definition's options); seeds from `initialValues` (remount to reseed) and reports only filled rows
- `FormSelect` - Dropdown/combobox taking an object array as data
- `Slider` - Range slider with label
- `Checkbox`, `RadioButton` - Form controls
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 2876249908..8b03deaf7d 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -549,6 +549,8 @@
"select_type": "Select",
"select_options": "Options",
"select_options_title": "The options the field offers, in this order.",
+ "select_options_placeholder": "Type an option and press Enter",
+ "add_option": "Add this option",
"remove_option": "Remove this option",
"precision_title": "Max number of decimal places.",
"precision": "Precision",
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index 28b8d03de3..a86b96adf9 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -640,6 +640,8 @@ export function AttributeForm({ opts, attrType: initialAttrType, currentNoteId,
labelType="text"
values={definition.selectOptions ?? []}
disabled={!isOwned}
+ placeholder={t("attribute_detail.select_options_placeholder")}
+ addButtonText={t("attribute_detail.add_option")}
removeButtonText={t("attribute_detail.remove_option")}
onCommit={(selectOptions) => commitDefinition({ selectOptions })}
/>
diff --git a/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx
index 7e41284478..335a9bf0e7 100644
--- a/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx
+++ b/apps/client/src/widgets/attribute_widgets/values_input.spec.tsx
@@ -85,10 +85,18 @@ describe("ValuesInput", () => {
expect(input?.value).toBe("");
});
- it("offers that button only where a value is entered through a widget of the browser's own", async () => {
- // Text is confirmed by the Enter it is already typed with; a button beside it would be a
- // second way of saying the same thing.
- await mount({ labelType: "text", values: [], onCommit: vi.fn() });
+ it("offers the button for a typed box only once it holds something to take", async () => {
+ // Text is confirmed by the Enter it is already typed with — but nothing on the page says
+ // so, so once there is something to take, the button shows the confirming instead of
+ // standing empty-handed from the start.
+ const onCommit = vi.fn();
+ const input = await mount({ labelType: "text", values: [], onCommit });
+ expect(container.querySelector(".values-input-add")).toBeNull();
+
+ await typeInto(input, "one");
+ await act(async () => container.querySelector<HTMLElement>(".values-input-add")?.click());
+ expect(onCommit).toHaveBeenCalledWith([ "one" ]);
+ // Taken and emptied, the box has nothing left to offer, and the button goes with it.
expect(container.querySelector(".values-input-add")).toBeNull();
// A colour settles in one gesture — a dialog opened, a colour chosen, the dialog gone — so
diff --git a/apps/client/src/widgets/attribute_widgets/values_input.tsx b/apps/client/src/widgets/attribute_widgets/values_input.tsx
index 3f21590f97..572ff45fed 100644
--- a/apps/client/src/widgets/attribute_widgets/values_input.tsx
+++ b/apps/client/src/widgets/attribute_widgets/values_input.tsx
@@ -25,8 +25,12 @@ interface ValuesInputProps {
renderValue?(value: string): ComponentChildren;
/** 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". */
+ addButtonText?: string;
/** Set onto the box, so that a host's own label points at the field. */
inputId?: string;
+ /** Set onto the box, for a host placing its fields in a tab order of its own. */
+ tabIndex?: number;
placeholder?: string;
disabled?: boolean;
}
@@ -40,13 +44,17 @@ 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, renderValue, removeButtonText, inputId, placeholder, disabled }: ValuesInputProps) {
+export default function ValuesInput({ labelType, values, onCommit, renderValue, removeButtonText, addButtonText, inputId, tabIndex, placeholder, disabled }: ValuesInputProps) {
const [ draft, setDraft ] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const isColor = labelType === "color";
// Every widget but the colour dialog has to be asked for its value, having no plain way of
// saying it is done with.
const needsAsking = PICKED_TYPES.has(labelType) && !isColor;
+ // A typed box is settled by Enter, but nothing on the page says so — so once it holds something
+ // 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 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
@@ -132,6 +140,7 @@ export default function ValuesInput({ labelType, values, onCommit, renderValue,
key="field"
ref={inputRef}
id={inputId}
+ tabIndex={tabIndex}
className="form-control"
type="color"
disabled={disabled}
@@ -141,6 +150,7 @@ export default function ValuesInput({ labelType, values, onCommit, renderValue,
key="field"
inputRef={inputRef}
id={inputId}
+ tabIndex={tabIndex}
type={LABEL_MAPPINGS[labelType] ?? "text"}
currentValue={draft}
// Only while the field is empty: beside chips it would read as one of them.
@@ -155,15 +165,17 @@ export default function ValuesInput({ labelType, values, onCommit, renderValue,
{/* 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. */}
- {needsAsking && (
+ {showAdd && (
<ActionButton
key="add"
className="values-input-add"
icon="bx bx-plus"
- text={t("promoted_attributes.add_value")}
+ 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 ?? "")}
/>
)}
diff --git a/apps/client/src/widgets/react/FormTextBoxList.css b/apps/client/src/widgets/react/FormTextBoxList.css
deleted file mode 100644
index 502692a231..0000000000
--- a/apps/client/src/widgets/react/FormTextBoxList.css
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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 {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 4px;
-
- .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;
- }
- }
-
- /* Last in the run rather than under it, so adding reads as extending the set in place. */
- .form-textbox-list-add {
- flex-shrink: 0;
- }
-}
diff --git a/apps/client/src/widgets/react/FormTextBoxList.spec.tsx b/apps/client/src/widgets/react/FormTextBoxList.spec.tsx
deleted file mode 100644
index 4dd97b845e..0000000000
--- a/apps/client/src/widgets/react/FormTextBoxList.spec.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { render } from "preact";
-import { act } from "preact/test-utils";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import FormTextBoxList from "./FormTextBoxList";
-
-describe("FormTextBoxList", () => {
- let container: HTMLElement;
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- });
-
- afterEach(() => {
- render(null, container);
- container.remove();
- });
-
- async function mount(props: Parameters<typeof FormTextBoxList>[0]) {
- await act(async () => render(<FormTextBoxList {...props} />, container));
- return container;
- }
-
- function inputs() {
- return [ ...container.querySelectorAll("input") ];
- }
-
- async function typeInto(input: HTMLInputElement | undefined, value: string) {
- await act(async () => {
- if (input) {
- input.value = value;
- input.dispatchEvent(new Event("input", { bubbles: true }));
- }
- });
- }
-
- const buttonTexts = { addButtonText: "Add", removeButtonText: "Remove" };
-
- it("seeds a row per value, and a single blank row when there are none", async () => {
- await mount({ initialValues: [ "a", "b" ], onChange: vi.fn(), ...buttonTexts });
- expect(inputs().map((input) => input.value)).toEqual([ "a", "b" ]);
-
- await act(async () => render(null, container));
- await mount({ initialValues: [], onChange: vi.fn(), ...buttonTexts });
- expect(inputs().map((input) => input.value)).toEqual([ "" ]);
- });
-
- it("reports only the filled rows, keeping a blank one in place for typing", async () => {
- const onChange = vi.fn();
- await mount({ initialValues: [ "a", "b" ], onChange, ...buttonTexts });
-
- // Emptying a row keeps it shown but drops it from what the host is told.
- await typeInto(inputs()[0], "");
- expect(onChange).toHaveBeenLastCalledWith([ "b" ]);
- expect(inputs()).toHaveLength(2);
-
- await typeInto(inputs()[0], "c");
- expect(onChange).toHaveBeenLastCalledWith([ "c", "b" ]);
- });
-
- it("removes the pressed row, leaving the drafts of the others untouched", async () => {
- const onChange = vi.fn();
- await mount({ initialValues: [ "a", "b", "c" ], onChange, ...buttonTexts });
-
- // A draft not yet reported (blank) must survive a removal above it.
- await typeInto(inputs()[2], "");
- await act(async () => container.querySelectorAll<HTMLElement>(".form-textbox-list-row .icon-action")[0]?.click());
-
- expect(onChange).toHaveBeenLastCalledWith([ "b" ]);
- expect(inputs().map((input) => input.value)).toEqual([ "b", "" ]);
- });
-
- it("adds a blank, focused row without reporting it to the host", async () => {
- const onChange = vi.fn();
- await mount({ initialValues: [ "a" ], onChange, ...buttonTexts });
-
- await act(async () => container.querySelector<HTMLElement>(".form-textbox-list-add")?.click());
-
- expect(inputs().map((input) => input.value)).toEqual([ "a", "" ]);
- expect(document.activeElement).toBe(inputs()[1]);
- // Only typing into the new row changes the values, so nothing is reported yet.
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it("disables the rows and both kinds of button when asked to", async () => {
- await mount({ initialValues: [ "a" ], disabled: true, onChange: vi.fn(), ...buttonTexts });
-
- expect(inputs()[0]?.disabled).toBe(true);
- expect(container.querySelector<HTMLButtonElement>(".form-textbox-list-add")?.disabled).toBe(true);
- expect(container.querySelector<HTMLButtonElement>(".form-textbox-list-row .icon-action")?.disabled).toBe(true);
- });
-});
diff --git a/apps/client/src/widgets/react/FormTextBoxList.tsx b/apps/client/src/widgets/react/FormTextBoxList.tsx
deleted file mode 100644
index 4a3dd01841..0000000000
--- a/apps/client/src/widgets/react/FormTextBoxList.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import "./FormTextBoxList.css";
-
-import { useEffect, useRef, useState } from "preact/hooks";
-
-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. */
-const MIN_CHIP_CHARS = 6;
-const MAX_CHIP_CHARS = 30;
-
-interface FormTextBoxListProps {
- /**
- * Seeds the rows. The list keeps its own draft afterwards and does not resync — a host whose
- * values can change identity under the editor remounts it (e.g. with a `key`) to reseed.
- */
- initialValues: string[];
- disabled?: boolean;
- /** Receives the filled rows, in order, whenever any row changes. Blank rows are not included. */
- onChange: (values: string[]) => void;
- /** What the add button offers, in the host's own words (e.g. "Add option"). */
- addButtonText: string;
- /** What removing a row means, in the host's own words (e.g. "Remove this option"). */
- removeButtonText: string;
-}
-
-/**
- * An ordered list of short texts, edited as one chip per entry — each holding its own text and a
- * remove button, laid out in a wrapping run alongside a button adding a fresh one. The rows are a
- * draft of the values — a row just added or emptied stays put for typing while only the filled rows
- * are reported — so a blank row never reaches the host.
- */
-export default function FormTextBoxList({ initialValues, disabled, onChange, addButtonText, removeButtonText }: FormTextBoxListProps) {
- // Ids of their own, so removing a row does not remount — and wipe the drafts of — those after it.
- const nextRowId = useRef(initialValues.length);
- const [ rows, setRows ] = useState(() => {
- const initial = initialValues.map((value, id) => ({ id, value }));
- // An empty list starts with one blank row, so the box to type the first value into is
- // already there rather than behind the add button.
- return initial.length ? initial : [ { id: nextRowId.current++, value: "" } ];
- });
- const containerRef = useRef<HTMLDivElement>(null);
- // Focus lands in the row the add button just created, once it exists.
- const pendingFocus = useRef(false);
-
- useEffect(() => {
- if (!pendingFocus.current) return;
- pendingFocus.current = false;
- const inputs = containerRef.current?.querySelectorAll("input");
- inputs?.[inputs.length - 1]?.focus();
- });
-
- function commitRows(newRows: { id: number; value: string }[]) {
- setRows(newRows);
- onChange(newRows.map((row) => row.value).filter((value) => value.trim() !== ""));
- }
-
- return (
- <div ref={containerRef} className="form-textbox-list">
- {rows.map((row) => (
- <Chip
- key={row.id}
- className="form-textbox-list-row"
- removeButtonText={removeButtonText}
- disabled={disabled}
- onRemove={() => commitRows(rows.filter((other) => other.id !== row.id))}
- >
- <FormTextBox
- currentValue={row.value}
- // A chip is as wide as its own word. `field-sizing` does this exactly (see
- // the stylesheet); `size` is what browsers without it go by, and is why the
- // width is asked for in characters rather than measured.
- size={Math.min(Math.max(row.value.length + 1, MIN_CHIP_CHARS), MAX_CHIP_CHARS)}
- disabled={disabled}
- onChange={(value) => commitRows(
- rows.map((other) => other.id === row.id ? { ...other, value } : other))}
- />
- </Chip>
- ))}
- <Button
- className="form-textbox-list-add"
- size="small"
- icon="bx bx-plus"
- text={addButtonText}
- disabled={disabled}
- onClick={() => {
- pendingFocus.current = true;
- setRows([ ...rows, { id: nextRowId.current++, value: "" } ]);
- }}
- />
- </div>
- );
-}