Skip to content

Build your personal knowledge base with Trilium Notes

feat(attributes): edit a system attribute in the field its value calls for

Elian Doran79c5d3e8c244
diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.ts
index 6bb6ba84dd..69c27e1fd8 100644
--- a/apps/client/src/services/attributes.spec.ts
+++ b/apps/client/src/services/attributes.spec.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildNote } from "../test/easy-froca";
-import attributeService, { isBuiltinAttribute, removeOwnedAttributesByNameOrType, setAttribute, setBooleanWithInheritance, setLabel, setRelation } from "./attributes";
+import attributeService, { getBuiltinLabelValueType, isBuiltinAttribute, removeOwnedAttributesByNameOrType, setAttribute, setBooleanWithInheritance, setLabel, setRelation } from "./attributes";
import froca from "./froca";
import server from "./server.js";
@@ -420,6 +420,18 @@ describe("isBuiltinAttribute", () => {
expect(isBuiltinAttribute("label", "excludeFromNoteMap")).toBe(true);
});
+ it("reports the value type of a built-in label, and nothing for anything else", () => {
+ expect(getBuiltinLabelValueType("color")).toBe("color");
+ expect(getBuiltinLabelValueType("archived")).toBe("boolean");
+ expect(getBuiltinLabelValueType("pageSize")).toBe("number");
+ // Relations point at a note, so they carry no value type even under a shared name.
+ expect(getBuiltinLabelValueType("template")).toBe("boolean");
+ expect(getBuiltinLabelValueType("renderNote")).toBeUndefined();
+ // Matched exactly, as the built-in lookup is.
+ expect(getBuiltinLabelValueType("disabled:webViewSrc")).toBeUndefined();
+ expect(getBuiltinLabelValueType("myOwnLabel")).toBeUndefined();
+ });
+
it("matches exactly, so prefixed names are not built-ins", () => {
// A definition describes a built-in without being one, and a disabled one is inert.
expect(isBuiltinAttribute("label", "label:archived")).toBe(false);
diff --git a/apps/client/src/services/attributes.ts b/apps/client/src/services/attributes.ts
index 8611f7d44e..8949b87264 100644
--- a/apps/client/src/services/attributes.ts
+++ b/apps/client/src/services/attributes.ts
@@ -1,4 +1,4 @@
-import { AttributeType, BUILTIN_ATTRIBUTES } from "@triliumnext/commons";
+import { AttributeType, BUILTIN_ATTRIBUTES, type LabelType } from "@triliumnext/commons";
import type FNote from "../entities/fnote.js";
import froca from "./froca.js";
@@ -228,6 +228,20 @@ export function isBuiltinAttribute(type: "label" | "relation", name: string) {
*/
const BUILTIN_ATTRIBUTE_KEYS = new Set(BUILTIN_ATTRIBUTES.map(({ type, name }) => `${type}:${name}`));
+/**
+ * What kind of value a built-in label holds, or `undefined` for a name Trilium attaches no meaning to.
+ *
+ * Matched exactly, as {@link isBuiltinAttribute} is: a `disabled:` attribute is inert and a definition
+ * carries a definition string rather than a value of the type it describes.
+ */
+export function getBuiltinLabelValueType(name: string): LabelType | undefined {
+ return BUILTIN_LABEL_VALUE_TYPES.get(name);
+}
+
+const BUILTIN_LABEL_VALUE_TYPES = new Map<string, LabelType>(
+ BUILTIN_ATTRIBUTES.flatMap((attr) => attr.type === "label" ? [ [ attr.name, attr.valueType ] as const ] : [])
+);
+
export default {
addLabel,
setLabel,
diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsx
index eb18099cb3..e6f323cda5 100644
--- a/apps/client/src/widgets/PromotedAttributes.tsx
+++ b/apps/client/src/widgets/PromotedAttributes.tsx
@@ -1,9 +1,9 @@
import "./PromotedAttributes.css";
-import { DefinitionObject, extractAttributeDefinitionTypeAndName, LabelType, UpdateAttributeResponse } from "@triliumnext/commons";
+import { DefinitionObject, extractAttributeDefinitionTypeAndName, UpdateAttributeResponse } from "@triliumnext/commons";
import clsx from "clsx";
-import { ComponentChild, createElement, HTMLInputTypeAttribute, InputHTMLAttributes, MouseEventHandler, TargetedEvent, TargetedInputEvent } from "preact";
-import { Dispatch, StateUpdater, useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { ComponentChild, MouseEventHandler, TargetedEvent } from "preact";
+import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preact/hooks";
import NoteContext from "../components/note_context";
import FAttribute from "../entities/fattribute";
@@ -14,6 +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 { useNoteContext, useNoteLabel, useTriliumEvent, useUniqueName } from "./react/hooks";
import NoteAutocomplete from "./react/NoteAutocomplete";
@@ -170,35 +171,14 @@ function PromotedAttributeCell(props: CellProps) {
);
}
-const LABEL_MAPPINGS: Record<LabelType, HTMLInputTypeAttribute | undefined> = {
- text: "text",
- textarea: undefined,
- number: "number",
- boolean: "checkbox",
- date: "date",
- datetime: "datetime-local",
- time: "time",
- color: "hidden", // handled separately.
- url: "url"
-};
-
function LabelInput(props: CellProps & { inputId: string }) {
const { inputId, note, cell, componentId, setCells } = props;
const { valueName, valueAttr, definition, definitionAttr } = cell;
const [ valueDraft, setDraft ] = useState(valueAttr.value);
- const onChangeListener = useCallback(async (e: OnChangeEventData) => {
- const inputEl = e.target as HTMLInputElement;
- let value: string;
-
- if (inputEl.type === "checkbox") {
- value = inputEl.checked ? "true" : "false";
- } else {
- value = inputEl.value;
- }
-
- await updateAttribute(note, cell, componentId, value, setCells);
- }, [ cell, componentId, note, setCells ]);
- const extraInputProps: InputHTMLAttributes = {};
+ const labelType = definition.labelType ?? "text";
+ const commit = useCallback(
+ (value: string) => updateAttribute(note, cell, componentId, value, setCells),
+ [ cell, componentId, note, setCells ]);
useTextLabelAutocomplete(inputId, valueAttr, definition, (e) => {
if (e.currentTarget instanceof HTMLInputElement) {
@@ -211,109 +191,39 @@ function LabelInput(props: CellProps & { inputId: string }) {
setDraft(valueAttr.value);
}, [ valueAttr.value ]);
- switch (definition.labelType) {
- case "number": {
- let step = 1;
- for (let i = 0; i < (definition.numberPrecision || 0) && i < 10; i++) {
- step /= 10;
- }
- extraInputProps.step = step;
- break;
- }
- case "url": {
- extraInputProps.placeholder = t("promoted_attributes.url_placeholder");
- break;
- }
- }
-
-
- const inputNode = createElement(definition.labelType === "textarea" ? "textarea" : "input", {
- className: "form-control promoted-attribute-input",
- tabIndex: 200 + definitionAttr.position,
- id: inputId,
- type: LABEL_MAPPINGS[definition.labelType ?? "text"],
- value: valueDraft,
- checked: definition.labelType === "boolean" ? valueAttr.value === "true" : undefined,
- placeholder: t("promoted_attributes.unset-field-placeholder"),
- "data-attribute-id": valueAttr.attributeId,
- "data-attribute-type": valueAttr.type,
- "data-attribute-name": valueAttr.name,
- onBlur: onChangeListener,
- ...extraInputProps
- });
+ const input = (
+ <LabelValueInput
+ labelType={labelType}
+ // The draft is what the field shows: the autocomplete writes into it as the user picks.
+ value={(labelType === "boolean" ? valueAttr.value : valueDraft) ?? ""}
+ onCommit={commit}
+ commitOn="blur"
+ numberPrecision={definition.numberPrecision}
+ inputProps={{
+ className: "form-control promoted-attribute-input",
+ tabIndex: 200 + definitionAttr.position,
+ id: inputId,
+ placeholder: t("promoted_attributes.unset-field-placeholder"),
+ "data-attribute-id": valueAttr.attributeId,
+ "data-attribute-type": valueAttr.type,
+ "data-attribute-name": valueAttr.name
+ }}
+ />
+ );
- if (definition.labelType === "boolean") {
+ if (labelType === "boolean") {
return <>
<div>
- <label className="tn-checkbox">{inputNode}</label>
+ <label className="tn-checkbox">{input}</label>
</div>
<label for={inputId}>{definition.promotedAlias ?? valueName}</label>
</>;
}
- return (
- <div className="input-group">
- {inputNode}
- { definition.labelType === "color" && <ColorPicker {...props} onChange={onChangeListener} inputId={inputId} />}
- { definition.labelType === "url" && (
- <InputButton
- className="open-external-link-button"
- icon="bx bx-window-open"
- title={t("promoted_attributes.open_external_link")}
- onClick={(e) => {
- const inputEl = document.getElementById(inputId) as HTMLInputElement | null;
- const url = inputEl?.value;
- if (url) {
- window.open(url, "_blank");
- }
- }}
- />
- )}
- </div>
- );
+ return <div className="input-group">{input}</div>;
}
-// We insert a separate input since the color input does not support empty value.
-// This is a workaround to allow clearing the color input.
-function ColorPicker({ cell, onChange, inputId }: CellProps & {
- onChange: (e: TargetedEvent<HTMLInputElement, Event>) => Promise<void>,
- inputId: string;
-}) {
- const defaultColor = "#ffffff";
- const colorInputRef = useRef<HTMLInputElement>(null);
- return (
- <>
- <input
- ref={colorInputRef}
- className="form-control promoted-attribute-input"
- type="color"
- value={cell.valueAttr.value || defaultColor}
- onChange={onChange}
- />
- <InputButton
- icon="bx bxs-tag-x"
- title={t("promoted_attributes.remove_color")}
- onClick={(e) => {
- // Indicate to the user the color was reset.
- if (colorInputRef.current) {
- colorInputRef.current.value = defaultColor;
- }
-
- // Trigger the actual attribute change by injecting it into the hidden field.
- const inputEl = document.getElementById(inputId) as HTMLInputElement | null;
- if (!inputEl) return;
- inputEl.value = "";
- onChange({
- ...e,
- target: inputEl
- } as unknown as TargetedInputEvent<HTMLInputElement>);
- }}
- />
- </>
- );
-}
-
function RelationInput({ inputId, ...props }: CellProps & { inputId: string }) {
return (
<NoteAutocomplete
@@ -400,21 +310,6 @@ function PromotedActionButton({ icon, title, onClick }: {
);
}
-function InputButton({ icon, className, title, onClick }: {
- icon: string;
- className?: string;
- title: string;
- onClick: MouseEventHandler<HTMLSpanElement>;
-}) {
- return (
- <span
- className={clsx("input-group-text", className, icon)}
- title={title}
- onClick={onClick}
- />
- );
-}
-
function useTextLabelAutocomplete(inputId: string, valueAttr: Attribute, definition: DefinitionObject, onChangeListener: OnChangeListener) {
const [ attributeValues, setAttributeValues ] = useState<{ value: string }[] | null>(null);
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.ts b/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.ts
index 85ccb692ba..b58267b8e0 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.ts
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.ts
@@ -132,6 +132,33 @@ describe("attribute detail popup naming", () => {
expect(formatAttributeForSearch({ type: "relation", name: "template" })).toBe("~template");
});
+ it("counts a show as new by what it would put in the form, not by the objects it arrives in", async () => {
+ const { isSameShow } = await import("./attribute_detail");
+ const shown = opts({ attribute: { type: "label", name: "author", value: "Tolkien" } });
+
+ // The same row pressed again: a fresh opts object around an equal attribute is the same show,
+ // whether or not the attribute object itself survived.
+ expect(isSameShow(shown, { ...shown, x: 40, y: 90 })).toBe(true);
+ expect(isSameShow(shown, opts({ attribute: { type: "label", name: "author", value: "Tolkien" } }))).toBe(true);
+
+ // Anything the form would show differently is another show.
+ expect(isSameShow(shown, opts({ attribute: { type: "label", name: "author", value: "Lewis" } }))).toBe(false);
+ expect(isSameShow(shown, opts({ attribute: { type: "relation", name: "author", value: "Tolkien" } }))).toBe(false);
+ expect(isSameShow(shown, opts({ ...shown, isOwned: false }))).toBe(false);
+ expect(isSameShow(shown, opts({ ...shown, focus: "name" }))).toBe(false);
+
+ // ...but the very same request handed back is the host re-rendering around an untouched
+ // popup, which every keystroke does — rebuilding the form there costs the focus and, with a
+ // request that asks for it, re-selects the field so the next character replaces the name.
+ const focused = opts({ focus: "name" });
+ expect(isSameShow(focused, focused)).toBe(true);
+
+ // Opening and closing are shows of their own, so reopening rebuilds the form.
+ expect(isSameShow(null, shown)).toBe(false);
+ expect(isSameShow(shown, null)).toBe(false);
+ expect(isSameShow(null, null)).toBe(true);
+ });
+
it("explains only the names Trilium attaches a meaning to, and points at a help page where there is one", async () => {
const { lookupAttributeHelp } = await import("./attribute_detail");
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index 47a8c34b27..ac8363a02d 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -3,12 +3,12 @@ import "./attribute_name_suggestion.css";
import { type DefinitionObject, type LabelType, promotedAttributeDefinitionParser } from "@triliumnext/commons";
import { ComponentProps } from "preact";
-import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import appContext from "../../components/app_context.js";
import { isDefinitionName } from "../../entities/fattribute.js";
import type { Attribute } from "../../services/attribute_parser.js";
-import { isBuiltinAttribute } from "../../services/attributes.js";
+import { getBuiltinLabelValueType, isBuiltinAttribute } from "../../services/attributes.js";
import { isExperimentalFeatureEnabled } from "../../services/experimental_features.js";
import { focusSavedElement, saveFocusedElement } from "../../services/focus.js";
import froca from "../../services/froca.js";
@@ -30,6 +30,7 @@ import NoteLink, { NewNoteLink } from "../react/NoteLink.jsx";
import { disposeReactWidget, ParentComponent, renderReactWidgetAtElement } from "../react/react_utils.jsx";
import OptionsRow, { OptionsRowWithToggle } from "../type_widgets/options/components/OptionsRow.jsx";
import { ATTR_HELP, AttrHelpEntry } from "./attr_help.js";
+import LabelValueInput, { getTypedInputForLabel } from "./label_value_input.js";
export interface AttributeDetailOpts {
allAttributes?: Attribute[];
@@ -144,7 +145,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {
}
export interface AttributeDetailProps extends AttributeFormCallbacks {
- /** The attribute to show; `null` keeps the popup closed. A new object counts as a new show. */
+ /** The attribute to show; `null` keeps the popup closed. A different attribute is a new show. */
opts: AttributeDetailOpts | null;
/** The note being viewed, excluded from the related notes list. */
currentNoteId?: string | null;
@@ -162,12 +163,16 @@ export function AttributeDetail({ opts, currentNoteId, onDismiss, onCancel, ...f
const shown = !!opts;
const { onSaveAndClose } = formCallbacks;
- // A different opts object means a new show, so the form is keyed on this counter to remount
- // and reseed its fields from the new attribute.
+ // The form is keyed on this counter, so it is remounted and reseeded whenever the popup is shown
+ // something other than what it already holds. Being handed the same attribute over again is not
+ // that (see isSameShow): a row pressed a second time would otherwise tear the form down and
+ // fetch the related notes afresh, which is seen as the popup flickering.
const showCount = useRef(0);
const lastOpts = useRef<AttributeDetailOpts | null>(null);
- if (lastOpts.current !== opts) {
- lastOpts.current = opts;
+ const isNewShow = !isSameShow(lastOpts.current, opts);
+ lastOpts.current = opts;
+
+ if (isNewShow) {
showCount.current++;
if (opts) {
@@ -268,6 +273,37 @@ export function AttributeDetail({ opts, currentNoteId, onDismiss, onCancel, ...f
);
}
+/**
+ * Whether the popup is being shown what it is already showing. The form seeds its fields from the
+ * attribute once and is remounted to seed them again, so two shows whose fields would come out the
+ * same are one show — however many objects the host built along the way, which is more than one:
+ * the attributes editor re-parses its text on every press and the inherited list builds a fresh
+ * attribute per press, so identity says a great deal less here than the values do.
+ *
+ * A show asking for the focus is always a new one. It is asking to be acted upon, and mounting is
+ * the only time the form acts on it — but only where it is genuinely being asked again: the very
+ * same request handed back is the host re-rendering around a popup it has not touched, which every
+ * keystroke does (the name typed into the form is reported straight back out to it).
+ */
+export function isSameShow(previous: AttributeDetailOpts | null, next: AttributeDetailOpts | null) {
+ if (!previous || !next) {
+ return previous === next;
+ }
+
+ if (previous === next) {
+ return true;
+ }
+
+ return !next.focus
+ && previous.isOwned === next.isOwned
+ && previous.hideMultiplicity === next.hideMultiplicity
+ && previous.attribute.noteId === next.attribute.noteId
+ && previous.attribute.type === next.attribute.type
+ && previous.attribute.name === next.attribute.name
+ && previous.attribute.value === next.attribute.value
+ && !!previous.attribute.isInheritable === !!next.attribute.isInheritable;
+}
+
interface AttributeFormCallbacks {
/** Close discarding unsaved changes (close button, escape). */
onCancel: () => void;
@@ -306,6 +342,14 @@ function AttributeForm({ opts, attrType: initialAttrType, currentNoteId, onCance
const [ isInheritable, setIsInheritable ] = useState(!!attribute.isInheritable);
const [ definition, setDefinition ] = useState(() => parseDefinition(attribute, attrType));
const nameRef = useRef<HTMLInputElement>(null);
+ /**
+ * A system label whose value has a kind of its own is typed into the field that fits it — a palette
+ * for `#color`, a date picker for `#startDate`. The rest keep the autocomplete, which is worth more
+ * to them than a plain box would be: it offers the values the name has been given before.
+ */
+ const typedInput = useMemo(
+ () => attrType === "label" ? getTypedInputForLabel(getBuiltinLabelValueType(name)) : undefined,
+ [ 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[] }>();
@@ -450,19 +494,30 @@ function AttributeForm({ opts, attrType: initialAttrType, currentNoteId, onCance
{attrType === "label" && (
<OptionsRow name="attr-value" label={t("attribute_detail.value")}>
- <FormAutocomplete
- className="attr-input-value"
- currentValue={value}
- readOnly={!isOwned}
- source={suggestLabelValues}
- openOnFocus
- onChange={(newValue) => isComposing.current ? setValue(newValue) : commitValue(newValue)}
- onCompositionStart={() => isComposing.current = true}
- onCompositionEnd={(e) => {
- isComposing.current = false;
- commitValue(e.currentTarget.value);
- }}
- />
+ {typedInput ? (
+ <div className="input-group">
+ <LabelValueInput
+ labelType={typedInput}
+ value={value}
+ onCommit={commitValue}
+ inputProps={{ className: "form-control attr-input-value", readOnly: !isOwned }}
+ />
+ </div>
+ ) : (
+ <FormAutocomplete
+ className="attr-input-value"
+ currentValue={value}
+ readOnly={!isOwned}
+ source={suggestLabelValues}
+ openOnFocus
+ onChange={(newValue) => isComposing.current ? setValue(newValue) : commitValue(newValue)}
+ onCompositionStart={() => isComposing.current = true}
+ onCompositionEnd={(e) => {
+ isComposing.current = false;
+ commitValue(e.currentTarget.value);
+ }}
+ />
+ )}
</OptionsRow>
)}
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
new file mode 100644
index 0000000000..f15d5b1422
--- /dev/null
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.spec.tsx
@@ -0,0 +1,127 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { getBuiltinLabelValueType } from "../../services/attributes";
+import LabelValueInput, { getTypedInputForLabel, LABEL_MAPPINGS } from "./label_value_input";
+
+describe("getTypedInputForLabel", () => {
+ it("offers a field of its own only where one beats the box a host already shows", () => {
+ for (const labelType of [ "color", "date", "datetime", "time", "number", "url" ] as const) {
+ expect(getTypedInputForLabel(labelType)).toBe(labelType);
+ }
+
+ // Text keeps whatever the host offers, which may suggest values the name has held before.
+ expect(getTypedInputForLabel("text")).toBeUndefined();
+ expect(getTypedInputForLabel("textarea")).toBeUndefined();
+ // A flag means what it means by being present, so a checkbox over its value would mislead.
+ expect(getTypedInputForLabel("boolean")).toBeUndefined();
+ // A name Trilium attaches no meaning to has no type to go on.
+ expect(getTypedInputForLabel(undefined)).toBeUndefined();
+ });
+
+ it("types the system labels the attribute editor is opened on", () => {
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("color"))).toBe("color");
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("workspaceTabBackgroundColor"))).toBe("color");
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("startDate"))).toBe("date");
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("startTime"))).toBe("time");
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("docUrl"))).toBe("url");
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("pageSize"))).toBe("number");
+
+ // `#calendar:startDate` names the label a date is read from, so it is a name, not a date.
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("calendar:startDate"))).toBeUndefined();
+ // A label the user invented keeps the field it has always had.
+ expect(getTypedInputForLabel(getBuiltinLabelValueType("myOwnLabel"))).toBeUndefined();
+ });
+});
+
+describe("LabelValueInput", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ async function mount(props: Parameters<typeof LabelValueInput>[0]) {
+ await act(async () => render(<LabelValueInput {...props} />, container));
+ return container;
+ }
+
+ it("edits a colour through a picker while the stored value stays clearable", async () => {
+ const onCommit = vi.fn();
+ // A colour input cannot represent "no colour": bound to the value directly it would report
+ // black for an unset label, and offer no way back to unset.
+ await mount({ labelType: "color", value: "", onCommit });
+
+ const stored = container.querySelector<HTMLInputElement>("input[type=hidden]");
+ const picker = container.querySelector<HTMLInputElement>("input[type=color]");
+ expect(stored?.value).toBe("");
+ expect(picker?.value).toBe("#ffffff");
+
+ await act(async () => {
+ if (picker) {
+ picker.value = "#ff0000";
+ picker.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ expect(onCommit).toHaveBeenCalledWith("#ff0000");
+
+ const clear = container.querySelector<HTMLElement>(".input-group-text");
+ await act(async () => clear?.click());
+ expect(onCommit).toHaveBeenLastCalledWith("");
+ });
+
+ it("reports a flag as the words a label stores rather than as a checked box", async () => {
+ const onCommit = vi.fn();
+ await mount({ labelType: "boolean", value: "false", onCommit });
+
+ const checkbox = container.querySelector<HTMLInputElement>("input[type=checkbox]");
+ expect(checkbox?.checked).toBe(false);
+
+ await act(async () => {
+ if (checkbox) {
+ checkbox.checked = true;
+ checkbox.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ expect(onCommit).toHaveBeenCalledWith("true");
+ });
+
+ it("holds a change back until the field is left when asked to", async () => {
+ const onCommit = vi.fn();
+ await mount({ labelType: "text", value: "before", onCommit, commitOn: "blur" });
+
+ const input = container.querySelector<HTMLInputElement>("input");
+ await act(async () => {
+ if (input) {
+ input.value = "after";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ expect(onCommit).not.toHaveBeenCalled();
+
+ await act(async () => {
+ input?.dispatchEvent(new Event("blur", { bubbles: true }));
+ });
+ expect(onCommit).toHaveBeenCalledWith("after");
+ });
+
+ it("steps a number by the precision its definition declared", async () => {
+ await mount({ labelType: "number", value: "1", onCommit: vi.fn(), numberPrecision: 2 });
+
+ expect(container.querySelector("input")?.getAttribute("step")).toBe("0.01");
+ });
+
+ it("maps every label type to a field, colour included", () => {
+ // Guards the mapping against a type being added to the vocabulary without a field to edit it.
+ expect(Object.keys(LABEL_MAPPINGS).length).toBeGreaterThan(0);
+ expect(LABEL_MAPPINGS.color).toBe("hidden");
+ expect(LABEL_MAPPINGS.textarea).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
new file mode 100644
index 0000000000..f67b62c4fb
--- /dev/null
+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx
@@ -0,0 +1,169 @@
+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 { t } from "../../services/i18n";
+
+/**
+ * The field a label of each type is edited through, shared so that a promoted field and a system
+ * attribute of the same type are typed into the same kind of input.
+ *
+ * `color` is `hidden` because a colour input cannot hold an empty value: the hidden field carries the
+ * real one — empty included — while a visible picker sits beside it. See {@link LabelValueInput}.
+ */
+export const LABEL_MAPPINGS: Record<LabelType, HTMLInputTypeAttribute | undefined> = {
+ text: "text",
+ textarea: undefined,
+ number: "number",
+ boolean: "checkbox",
+ date: "date",
+ datetime: "datetime-local",
+ time: "time",
+ color: "hidden",
+ url: "url"
+};
+
+const DEFAULT_COLOR = "#ffffff";
+
+interface LabelValueInputProps {
+ labelType: LabelType;
+ /** The value as stored, which for a colour or a flag may be the empty string. */
+ value: string;
+ /** Receives the value to store, a flag already rendered as `"true"` or `"false"`. */
+ onCommit(value: string): void;
+ /**
+ * Whether a change is stored as it is made or once the field is left. The promoted grid commits on
+ * blur so that typing does not save on every keystroke; a popup that closes on its own commits as
+ * it goes. The colour picker and its clear button always commit at once — there is nothing to type.
+ */
+ commitOn?: "input" | "blur";
+ /** How many decimals a number field steps by, from the definition that declared it. */
+ numberPrecision?: number;
+ /** 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>;
+}
+
+/**
+ * The input for a label value, by the kind of value it holds.
+ *
+ * Only the field and the buttons belonging to it are rendered — never the surrounding row or the
+ * label — so that a host can lay it out as it needs. A flag is the one to watch: it renders a bare
+ * checkbox, which a host wanting the label after the box has to arrange itself.
+ */
+export default function LabelValueInput({
+ labelType, value, onCommit, commitOn = "input", numberPrecision, 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
+ // the value as it stands reads the element rather than the prop it was last rendered from.
+ const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement>(null);
+
+ function commitFromEvent(e: { currentTarget: EventTarget | null }) {
+ const input = e.currentTarget as HTMLInputElement | HTMLTextAreaElement | null;
+ if (!input) return;
+
+ if (input instanceof HTMLInputElement && input.type === "checkbox") {
+ onCommit(input.checked ? "true" : "false");
+ } else {
+ onCommit(input.value);
+ }
+ }
+
+ const extraProps: InputHTMLAttributes<HTMLInputElement> = {};
+ if (labelType === "number" && numberPrecision) {
+ let step = 1;
+ for (let i = 0; i < numberPrecision && i < 10; i++) {
+ step /= 10;
+ }
+ extraProps.step = step;
+ } else if (labelType === "url") {
+ extraProps.placeholder = t("promoted_attributes.url_placeholder");
+ }
+
+ const input = createElement(labelType === "textarea" ? "textarea" : "input", {
+ ref: inputRef,
+ type: LABEL_MAPPINGS[labelType],
+ value,
+ checked: labelType === "boolean" ? value === "true" : undefined,
+ ...extraProps,
+ ...inputProps,
+ // After the host's props, so that a host cannot leave the value uncommitted by supplying its own.
+ [commitOn === "blur" ? "onBlur" : "onInput"]: commitFromEvent
+ });
+
+ return (
+ <>
+ {input}
+ {labelType === "color" && (
+ <>
+ <input
+ ref={colorInputRef}
+ className={clsx("form-control", inputProps?.className)}
+ type="color"
+ disabled={inputProps?.disabled || inputProps?.readOnly}
+ value={value || DEFAULT_COLOR}
+ onInput={(e) => onCommit(e.currentTarget.value)}
+ />
+ <InputButton
+ icon="bx bxs-tag-x"
+ title={t("promoted_attributes.remove_color")}
+ onClick={() => {
+ // Show the reset, which clearing the stored value alone would not: the
+ // picker falls back to the default only while it has nothing of its own.
+ if (colorInputRef.current) {
+ colorInputRef.current.value = DEFAULT_COLOR;
+ }
+ onCommit("");
+ }}
+ />
+ </>
+ )}
+ {labelType === "url" && (
+ <InputButton
+ className="open-external-link-button"
+ icon="bx bx-window-open"
+ title={t("promoted_attributes.open_external_link")}
+ onClick={() => {
+ const url = inputRef.current?.value || value;
+ if (url) {
+ window.open(url, "_blank");
+ }
+ }}
+ />
+ )}
+ </>
+ );
+}
+
+export function InputButton({ icon, className, title, onClick }: {
+ icon: string;
+ className?: string;
+ title: string;
+ onClick: MouseEventHandler<HTMLSpanElement>;
+}) {
+ return (
+ <span
+ className={clsx("input-group-text", className, icon)}
+ title={title}
+ onClick={onClick}
+ />
+ );
+}
+
+/**
+ * The type to offer for a label whose kind is known ahead of any definition, or `undefined` where the
+ * field a host already shows is the better answer.
+ *
+ * `text` and `textarea` are left out because they gain nothing over a plain box — and a host offering
+ * suggestions over the values a name has held would lose them. `boolean` is left out because a system
+ * flag says what it means by being present at all: a checkbox over its value would read `#archived`
+ * with no value as switched off, which is the opposite of what it means.
+ */
+export function getTypedInputForLabel(labelType: LabelType | undefined): LabelType | undefined {
+ if (!labelType || labelType === "text" || labelType === "textarea" || labelType === "boolean") {
+ return undefined;
+ }
+
+ return labelType;
+}