Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): create select choices straight from the promoted field

Elian Doran64f5890011c7
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 3a9554b616..610fa4a652 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1328,6 +1328,7 @@
"open_external_link": "Open external link",
"send_email": "Send an email to this address",
"call_phone": "Call this number",
+ "create_option": "Create \"{{- option}}\"",
"unknown_label_type": "Unknown label type '{{type}}'",
"unknown_attribute_type": "Unknown attribute type '{{type}}'",
"add_new_attribute": "Add new attribute",
diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsx
index 5392af7758..252f14db9f 100644
--- a/apps/client/src/widgets/PromotedAttributes.tsx
+++ b/apps/client/src/widgets/PromotedAttributes.tsx
@@ -1,6 +1,6 @@
import "./PromotedAttributes.css";
-import { DefinitionObject, extractAttributeDefinitionTypeAndName, UpdateAttributeResponse } from "@triliumnext/commons";
+import { DefinitionObject, extractAttributeDefinitionTypeAndName, promotedAttributeDefinitionParser, UpdateAttributeResponse } from "@triliumnext/commons";
import clsx from "clsx";
import { ComponentChild, MouseEventHandler, TargetedEvent } from "preact";
import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preact/hooks";
@@ -180,6 +180,26 @@ function LabelInput(props: CellProps & { inputId: string }) {
(value: string) => updateAttribute(note, cell, componentId, value, setCells),
[ cell, componentId, note, setCells ]);
+ // A choice created straight from the field is added to the definition — on whichever note owns
+ // it, typically a parent or template — so every note sharing the field offers it from now on.
+ // The reload that write triggers refreshes the cells with the new option.
+ const createOption = useCallback(async (option: string) => {
+ const newDefinition: DefinitionObject = {
+ ...definition,
+ selectOptions: [ ...(definition.selectOptions ?? []), option ]
+ };
+ await server.put(
+ `notes/${definitionAttr.noteId}/attribute`,
+ {
+ attributeId: definitionAttr.attributeId,
+ type: "label",
+ name: definitionAttr.name,
+ value: promotedAttributeDefinitionParser.serialize(newDefinition, "label")
+ },
+ componentId
+ );
+ }, [ definition, definitionAttr, componentId ]);
+
useTextLabelAutocomplete(inputId, valueAttr, definition, (e) => {
if (e.currentTarget instanceof HTMLInputElement) {
setDraft(e.currentTarget.value);
@@ -200,6 +220,7 @@ function LabelInput(props: CellProps & { inputId: string }) {
commitOn="blur"
numberPrecision={definition.numberPrecision}
selectOptions={definition.selectOptions}
+ onCreateOption={labelType === "select" ? createOption : undefined}
inputProps={{
className: "form-control promoted-attribute-input",
tabIndex: 200 + definitionAttr.position,
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.css b/apps/client/src/widgets/attribute_widgets/label_value_input.css
new file mode 100644
index 0000000000..7879a3b9f9
--- /dev/null
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.css
@@ -0,0 +1,9 @@
+/* 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.tsx
index dbd413bda0..093807832a 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
@@ -106,8 +106,10 @@ describe("LabelValueInput", () => {
});
expect(onCommit).not.toHaveBeenCalled();
+ // `focusout`, the bubbling event a browser fires alongside `blur`, is what the input listens
+ // for — both by its own binding and under preact/compat's `onBlur` remap.
await act(async () => {
- input?.dispatchEvent(new Event("blur", { bubbles: true }));
+ input?.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
});
expect(onCommit).toHaveBeenCalledWith("after");
});
@@ -148,6 +150,96 @@ describe("LabelValueInput", () => {
expect(onCommit).toHaveBeenCalledWith("Done");
});
+ describe("creatable select combobox", () => {
+ /** Lets the debounced suggestion fetch run; the dropdown 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 }));
+ }
+ });
+ }
+
+ it("lists every option on focus, and commits a pick, not the typing before it", async () => {
+ const onCommit = vi.fn();
+ await mount({
+ labelType: "select", value: "Todo", selectOptions: [ "Todo", "Done" ],
+ onCommit, onCreateOption: vi.fn()
+ });
+
+ // A combobox rather than a fixed dropdown.
+ expect(container.querySelector("select")).toBeNull();
+ const input = container.querySelector("input");
+ expect(input?.value).toBe("Todo");
+
+ // The box still holds the stored value, so the whole list is offered, unfiltered.
+ await act(async () => input?.focus());
+ expect((await settleDropdown()).map((item) => item.textContent)).toEqual([ "Todo", "Done" ]);
+
+ await typeInto(input, "Do");
+ expect(onCommit).not.toHaveBeenCalled();
+
+ // "Do" matches both options as a substring, plus the entry offering to create it.
+ const items = await settleDropdown();
+ const done = items.find((item) => item.textContent === "Done");
+ await act(async () => (done as HTMLElement | undefined)?.click());
+ expect(onCommit).toHaveBeenCalledWith("Done");
+ });
+
+ it("offers creating unmatched text as an explicit entry, never committing it on its own", async () => {
+ const onCommit = vi.fn();
+ const onCreateOption = vi.fn();
+ await mount({
+ labelType: "select", value: "", selectOptions: [ "Todo", "Done" ],
+ onCommit, onCreateOption
+ });
+
+ const input = container.querySelector("input");
+ await act(async () => input?.focus());
+ await typeInto(input, "Blocked");
+
+ // Nothing matches, so the create entry is the only row. Recognized by its class rather
+ // 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();
+
+ await act(async () => (items[0] as HTMLElement | undefined)?.click());
+ expect(onCreateOption).toHaveBeenCalledWith("Blocked");
+ expect(onCommit).toHaveBeenCalledWith("Blocked");
+ });
+
+ it("reverts unpicked text on blur, while an emptied box commits the unset value", async () => {
+ const onCommit = vi.fn();
+ await mount({
+ labelType: "select", value: "Todo", selectOptions: [ "Todo", "Done" ],
+ onCommit, onCreateOption: vi.fn()
+ });
+
+ const input = container.querySelector("input");
+ await typeInto(input, "Blo");
+ await act(async () => {
+ input?.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
+ });
+ expect(onCommit).not.toHaveBeenCalled();
+ expect(input?.value).toBe("Todo");
+
+ await typeInto(input, "");
+ await act(async () => {
+ input?.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
+ });
+ expect(onCommit).toHaveBeenCalledWith("");
+ });
+ });
+
it("opens an email or a phone through its scheme, not doubling one an old value carries", async () => {
const open = vi.spyOn(window, "open").mockImplementation(() => null);
try {
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
index 2ee49f4f51..9249d357d9 100644
--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
@@ -1,9 +1,12 @@
+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, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../services/i18n";
+import FormAutocomplete from "../react/FormAutocomplete";
/**
* The field a label of each type is edited through, shared so that a promoted field and a system
@@ -78,6 +81,14 @@ interface LabelValueInputProps {
numberPrecision?: number;
/** The values a select field offers, from the definition that declared it. */
selectOptions?: string[];
+ /**
+ * Called when the user asks a select field for a choice its definition does not offer yet;
+ * expected to add it to the definition, while the value itself still arrives via `onCommit`.
+ * Providing this turns the plain dropdown into a combobox: the full list opens on focus, typing
+ * filters it, and an unmatched text offers an explicit "Create" entry — never committing free
+ * text on its own, so a typo cannot slip into the shared definition.
+ */
+ onCreateOption?: (option: string) => void | Promise<void>;
/** Merged onto the input, for the id, tab order and data attributes a host needs to attach. */
inputProps?: InputHTMLAttributes<HTMLInputElement> & Record<`data-${string}`, string | undefined>;
}
@@ -90,7 +101,7 @@ interface LabelValueInputProps {
* checkbox, which a host wanting the label after the box has to arrange itself.
*/
export default function LabelValueInput({
- labelType, value, onCommit, commitOn = "input", numberPrecision, selectOptions, inputProps
+ labelType, value, onCommit, commitOn = "input", numberPrecision, selectOptions, onCreateOption, inputProps
}: LabelValueInputProps) {
const colorInputRef = useRef<HTMLInputElement>(null);
// What has been typed but not yet committed is still what the field shows, so anything acting on
@@ -108,6 +119,18 @@ export default function LabelValueInput({
}
}
+ if (labelType === "select" && onCreateOption) {
+ return (
+ <SelectComboBox
+ options={selectOptions ?? []}
+ value={value}
+ onCommit={onCommit}
+ onCreateOption={onCreateOption}
+ inputProps={inputProps}
+ />
+ );
+ }
+
const openButton = OPEN_BUTTONS[labelType];
const extraProps: InputHTMLAttributes<HTMLInputElement> = {};
@@ -137,7 +160,10 @@ export default function LabelValueInput({
// After the host's props, so that a host cannot leave the value uncommitted by supplying
// its own. A select commits as it is picked even for a host that commits on blur: there is
// nothing to type into it, so waiting for the blur would only hold a made choice back.
- [commitOn === "blur" && !isSelect ? "onBlur" : "onInput"]: commitFromEvent
+ // `focusout` by its DOM name rather than `onBlur`: preact/compat — loaded module-graph-wide
+ // by any compat-using import — remaps `onBlur` to `focusout` anyway, so naming the event
+ // keeps the binding the same whether or not compat happens to be loaded.
+ [commitOn === "blur" && !isSelect ? "onfocusout" : "onInput"]: commitFromEvent
},
isSelect ? selectOptionElements(
selectOptions ?? [],
@@ -191,6 +217,91 @@ 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: 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 ]);
+
+ // Narrowed because Preact types the attribute as possibly signal-backed, while the text box
+ // underneath takes the plain string.
+ const { id, ...restInputProps } = inputProps ?? {};
+
+ const source = useCallback(async (query: string) => {
+ const trimmed = query.trim();
+ // The stored value in the box means the list was only just opened, so the whole of it is
+ // offered rather than the near-empty tail that filtering by the value would leave.
+ const items = !trimmed || trimmed === value
+ ? [ ...options ]
+ : options.filter((option) => option.toLowerCase().includes(trimmed.toLowerCase()));
+
+ if (trimmed && trimmed !== value
+ && !options.some((option) => option.toLowerCase() === trimmed.toLowerCase())) {
+ items.push(CREATE_OPTION_SENTINEL + trimmed);
+ }
+ return items;
+ }, [ options, value ]);
+
+ return (
+ <FormAutocomplete
+ {...restInputProps}
+ id={typeof id === "string" ? id : undefined}
+ className={clsx(inputProps?.className, "label-select-combobox")}
+ currentValue={draft}
+ openOnFocus
+ 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>
+ : item}
+ onChange={(newValue) => {
+ if (newValue.startsWith(CREATE_OPTION_SENTINEL)) {
+ const option = newValue.substring(CREATE_OPTION_SENTINEL.length);
+ void onCreateOption(option);
+ setDraft(option);
+ onCommit(option);
+ } else if (options.includes(newValue)) {
+ setDraft(newValue);
+ onCommit(newValue);
+ } else {
+ // Not a pick yet — the text is a filter, held until an entry is chosen.
+ setDraft(newValue);
+ }
+ }}
+ onBlur={(leftBehind) => {
+ if (!leftBehind.trim()) {
+ setDraft("");
+ if (value) {
+ onCommit("");
+ }
+ } else if (leftBehind !== value) {
+ setDraft(value);
+ }
+ }}
+ />
+ );
+}
+
/**
* 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 defined