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(attributes): offer a select promoted attribute type
Elian Doran6c19d14a4146
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6c14ee2f50..967c918c88 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -125,6 +125,7 @@ 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 controlsdiff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 4b9b923f87..3a9554b616 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -544,6 +544,11 @@"url": "URL","email": "Email","phone": "Phone",+ "select_type": "Choice",+ "select_options": "Options",+ "select_options_title": "The choices the field offers, in this order.",+ "add_option": "Add option",+ "remove_option": "Remove this option","precision_title": "Max number of decimal places.","precision": "Precision","digits": "digits",diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsxindex e6f323cda5..5392af7758 100644--- a/apps/client/src/widgets/PromotedAttributes.tsx+++ b/apps/client/src/widgets/PromotedAttributes.tsx@@ -199,6 +199,7 @@ function LabelInput(props: CellProps & { inputId: string }) {onCommit={commit}commitOn="blur"numberPrecision={definition.numberPrecision}+ selectOptions={definition.selectOptions}inputProps={{className: "form-control promoted-attribute-input",tabIndex: 200 + definitionAttr.position,diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsxindex c620cd7729..c33f547849 100644--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx@@ -24,6 +24,7 @@ import FormAutocomplete, { AUTOCOMPLETE_DROPDOWN_SELECTOR } from "../react/FormAimport FormDropdownList from "../react/FormDropdownList.jsx";import { FormDropdownDivider, FormListItem } from "../react/FormList.jsx";import FormTextBox, { FormTextBoxWithUnit } from "../react/FormTextBox.jsx";+import FormTextBoxList from "../react/FormTextBoxList.jsx";import HelpTooltipButton from "../react/HelpTooltipButton.jsx";import { suspendModalFocusTraps } from "../react/modal_focustrap.js";import NoteAutocomplete from "../react/NoteAutocomplete.jsx";@@ -608,6 +609,25 @@ export function AttributeForm({ opts, attrType: initialAttrType, currentNoteId,</OptionsRow>)}+ {attrType === "label-definition" && definition.labelType === "select" && (+ <OptionsRow+ name="attr-select-options"+ label={t("attribute_detail.select_options")}+ description={t("attribute_detail.select_options_title")}+ >+ {/* The draft rows need no synchronizing back from the definition: the form+ remounts per show (see above), so they are seeded once, like the fields+ around them. */}+ <FormTextBoxList+ initialValues={definition.selectOptions ?? []}+ disabled={!isOwned}+ addButtonText={t("attribute_detail.add_option")}+ removeButtonText={t("attribute_detail.remove_option")}+ onChange={(selectOptions) => commitDefinition({ selectOptions })}+ />+ </OptionsRow>+ )}+{attrType === "relation-definition" && (<OptionsRowname="attr-inverse-relation"@@ -763,6 +783,7 @@ export const LABEL_TYPES = [{ value: "textarea", title: t("attribute_detail.textarea"), icon: "bx bx-align-left" },{ value: "number", title: t("attribute_detail.number"), icon: "bx bx-hash" },{ value: "boolean", title: t("attribute_detail.boolean"), icon: "bx bx-toggle-left" },+ { value: "select", title: t("attribute_detail.select_type"), icon: "bx bx-list-ul" },{ value: "date", title: t("attribute_detail.date"), icon: "bx bx-calendar" },{ value: "datetime", title: t("attribute_detail.date_time"), icon: "bx bx-calendar-event" },{ value: "time", title: t("attribute_detail.time"), icon: "bx bx-time" },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 cdb2e4d1f4..dbd413bda0 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@@ -118,6 +118,36 @@ describe("LabelValueInput", () => {expect(container.querySelector("input")?.getAttribute("step")).toBe("0.01");});+ it("offers a select's options after the unset entry, keeping a stored value the options lost", async () => {+ const onCommit = vi.fn();+ await mount({+ labelType: "select",+ // A value the definition no longer names (its option renamed or removed) must stay shown.+ value: "Archived",+ selectOptions: [ "Todo", "Done" ],+ onCommit,+ commitOn: "blur",+ inputProps: { placeholder: "not set" }+ });++ const select = container.querySelector("select");+ expect([ ...(select?.options ?? []) ].map((option) => option.value))+ .toEqual([ "", "Todo", "Done", "Archived" ]);+ // The unset entry wears the host's placeholder, and the field dresses as a select.+ expect(select?.options[0]?.text).toBe("not set");+ expect(select?.value).toBe("Archived");+ expect(select?.className).toContain("form-select");++ // Picking commits at once even though the host asked for a blur commit.+ await act(async () => {+ if (select) {+ select.value = "Done";+ select.dispatchEvent(new Event("input", { bubbles: true }));+ }+ });+ expect(onCommit).toHaveBeenCalledWith("Done");+ });+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.tsxindex ca4181a71d..2ee49f4f51 100644--- a/apps/client/src/widgets/attribute_widgets/label_value_input.tsx+++ b/apps/client/src/widgets/attribute_widgets/label_value_input.tsx@@ -17,6 +17,7 @@ export const LABEL_MAPPINGS: Record<LabelType, HTMLInputTypeAttribute | undefinetextarea: undefined,number: "number",boolean: "checkbox",+ select: undefined,date: "date",datetime: "datetime-local",time: "time",@@ -75,6 +76,8 @@ interface LabelValueInputProps {commitOn?: "input" | "blur";/** How many decimals a number field steps by, from the definition that declared it. */numberPrecision?: number;+ /** The values a select field offers, from the definition that declared it. */+ selectOptions?: string[];/** 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>;}@@ -87,15 +90,15 @@ 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, inputProps+ labelType, value, onCommit, commitOn = "input", numberPrecision, selectOptions, 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);+ const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(null);function commitFromEvent(e: { currentTarget: EventTarget | null }) {- const input = e.currentTarget as HTMLInputElement | HTMLTextAreaElement | null;+ const input = e.currentTarget as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null;if (!input) return;if (input instanceof HTMLInputElement && input.type === "checkbox") {@@ -118,16 +121,31 @@ export default function LabelValueInput({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- });+ const isSelect = labelType === "select";+ const input = createElement(+ labelType === "textarea" ? "textarea" : isSelect ? "select" : "input",+ {+ ref: inputRef,+ type: LABEL_MAPPINGS[labelType],+ value,+ checked: labelType === "boolean" ? value === "true" : undefined,+ ...extraProps,+ ...inputProps,+ // Bootstrap draws the chevron for `form-select`, which the host — handing the class of a+ // field one types into — has no reason to know to pass.+ ...(isSelect && { className: clsx(inputProps?.className, "form-select") }),+ // 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+ },+ isSelect ? selectOptionElements(+ selectOptions ?? [],+ value,+ // Narrowed because Preact types the attribute as possibly signal-backed.+ typeof inputProps?.placeholder === "string" ? inputProps.placeholder : undefined+ ) : undefined+ );return (<>@@ -173,6 +191,23 @@ export default function LabelValueInput({);}+/**+ * 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+ * options, then the stored value if the options no longer name it (renamed or removed since it was+ * picked), so that what the note holds is shown rather than silently blanked.+ */+function selectOptionElements(options: string[], value: string, placeholder?: string) {+ const entries = [ ...options ];+ if (value && !options.includes(value)) {+ entries.push(value);+ }+ return [+ <option key="" value="">{placeholder ?? ""}</option>,+ ...entries.map((option) => <option key={option} value={option}>{option}</option>)+ ];+}+export function InputButton({ icon, className, title, onClick }: {icon: string;className?: string;diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex eca9085148..f3d59186b7 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -15,6 +15,8 @@ export interface AttributeDefinitionInformation {name: string;title?: string;type?: ColumnType;+ /** The values a `select` column offers, from the definition that declared it. */+ options?: string[];}const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {@@ -28,6 +30,11 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {shiftEnterSubmit: true}},+ select: {+ // The choices come from the column's definition, so `editorParams` is attached per column+ // in `buildColumnDefinitions` rather than here.+ editor: "list"+ },boolean: {formatter: "tickCross",editor: "tickCross",@@ -151,7 +158,7 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,];const seenFields = new Set<string>();- for (const { name, title, type } of info) {+ for (const { name, title, type, options } of info) {const prefix = (type === "relation" ? "relations" : "labels");const field = `${prefix}.${name}`;@@ -165,6 +172,11 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,editor: "input",rowHandle: false,...labelTypeMappings[type ?? "text"],+ // A select's choices come from its definition, so they attach per column. `clearable`+ // restores the blank the promoted grid offers as its unset entry.+ ...(type === "select" && {+ editorParams: { values: options ?? [], clearable: true }+ })});seenFields.add(field);}diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.tsindex 75542010fc..e6b7c83bd9 100644--- a/apps/client/src/widgets/collections/table/rows.ts+++ b/apps/client/src/widgets/collections/table/rows.ts@@ -94,7 +94,8 @@ export default function getAttributeDefinitionInformation(parentNote: FNote) {info.push({name,title: def.promotedAlias,- type+ type,+ options: def.selectOptions});}return info;diff --git a/apps/client/src/widgets/react/FormTextBoxList.css b/apps/client/src/widgets/react/FormTextBoxList.cssnew file mode 100644index 0000000000..b3c609055e--- /dev/null+++ b/apps/client/src/widgets/react/FormTextBoxList.css@@ -0,0 +1,21 @@+.form-textbox-list {+ display: flex;+ flex-direction: column;+ gap: 4px;++ .form-textbox-list-row {+ display: flex;+ align-items: center;+ gap: 4px;++ > input {+ flex: 1;+ min-width: 0;+ }+ }++ /* Sized to its words: a full-width bar under the rows would read as a field of the list itself. */+ .form-textbox-list-add {+ align-self: flex-start;+ }+}diff --git a/apps/client/src/widgets/react/FormTextBoxList.spec.tsx b/apps/client/src/widgets/react/FormTextBoxList.spec.tsxnew file mode 100644index 0000000000..4dd97b845e--- /dev/null+++ b/apps/client/src/widgets/react/FormTextBoxList.spec.tsx@@ -0,0 +1,93 @@+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.tsxnew file mode 100644index 0000000000..ce393e9a89--- /dev/null+++ b/apps/client/src/widgets/react/FormTextBoxList.tsx@@ -0,0 +1,85 @@+import "./FormTextBoxList.css";++import { useEffect, useRef, useState } from "preact/hooks";++import ActionButton from "./ActionButton.jsx";+import Button from "./Button.jsx";+import FormTextBox from "./FormTextBox.jsx";++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 box per entry with a remove button and a button+ * adding a fresh row. 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) => (+ <div key={row.id} className="form-textbox-list-row">+ <FormTextBox+ currentValue={row.value}+ disabled={disabled}+ onChange={(value) => commitRows(+ rows.map((other) => other.id === row.id ? { ...other, value } : other))}+ />+ <ActionButton+ icon="bx bx-x"+ text={removeButtonText}+ disabled={disabled}+ onClick={() => commitRows(rows.filter((other) => other.id !== row.id))}+ />+ </div>+ ))}+ <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>+ );+}diff --git a/packages/commons/src/lib/promoted_attribute_definition_parser.spec.ts b/packages/commons/src/lib/promoted_attribute_definition_parser.spec.tsindex 60af67be35..00ae57e857 100644--- a/packages/commons/src/lib/promoted_attribute_definition_parser.spec.ts+++ b/packages/commons/src/lib/promoted_attribute_definition_parser.spec.ts@@ -48,6 +48,20 @@ describe("promoted_attribute_definition_parser.parse", () => {expect(parse("precision")).toEqual({ numberPrecision: NaN });});+ it("parses the select options, dropping blank entries and decoding the escapes", () => {+ expect(parse("options=Todo;In progress;Done")).toEqual({+ selectOptions: [ "Todo", "In progress", "Done" ]+ });+ // `%2C`/`%3B`/`%25` carry the characters the format claims for itself.+ expect(parse("options=1%2C5 kg;a%3Bb;100%25")).toEqual({+ selectOptions: [ "1,5 kg", "a;b", "100%" ]+ });+ // A blank entry offers nothing to pick; an empty or missing value means no options at all.+ expect(parse("options=a;;b;")).toEqual({ selectOptions: [ "a", "b" ] });+ expect(parse("options=")).toEqual({ selectOptions: [] });+ expect(parse("options")).toEqual({ selectOptions: [] });+ });+it("parses the promoted alias verbatim, including spaces", () => {expect(parse("alias=My Label")).toEqual({ promotedAlias: "My Label" });expect(parse("alias=")).toEqual({ promotedAlias: "" });@@ -130,6 +144,18 @@ describe("promoted_attribute_definition_parser.serialize", () => {.toBe("single,number,precision=0");});+ it("writes the options only for a select with some, escaping the separators", () => {+ expect(serialize({ labelType: "select", selectOptions: [ "Todo", "In progress" ] }, "label"))+ .toBe("single,select,options=Todo;In progress");+ // The characters the format claims for itself are escaped; everything else is verbatim.+ expect(serialize({ labelType: "select", selectOptions: [ "1,5 kg", "a;b", "100%" ] }, "label"))+ .toBe("single,select,options=1%2C5 kg;a%3Bb;100%25");+ // No options, an empty list, or a non-select type all write no token.+ expect(serialize({ labelType: "select" }, "label")).toBe("single,select");+ expect(serialize({ labelType: "select", selectOptions: [] }, "label")).toBe("single,select");+ expect(serialize({ labelType: "text", selectOptions: [ "a" ] }, "label")).toBe("single,text");+ });+it("writes the inverse relation for relations only, filtering invalid characters", () => {expect(serialize({ inverseRelation: "isChildOf" }, "relation")).toBe("single,inverse=isChildOf");@@ -151,6 +177,21 @@ describe("promoted_attribute_definition_parser round-trip", () => {expect(serialize(parse(relationDefinition), "relation")).toBe(relationDefinition);});+ it("round-trips select options through the escaping, edge cases included", () => {+ // Values that already look like escapes must survive a round trip unchanged.+ for (const options of [+ [ "Todo", "In progress", "Done" ],+ [ "1,5 kg", "a;b", "100%" ],+ [ "50%25", "%2C", "a%3Bb" ],+ [ "C:\\Users\\bin", "a=b" ]+ ]) {+ const definition = { labelType: "select", selectOptions: options } as const;+ expect(parse(serialize(definition, "label"))).toEqual({+ labelType: "select", multiplicity: "single", selectOptions: options+ });+ }+ });+it("parses a serialized definition back to the same object, for every label type", () => {for (const labelType of LABEL_TYPES) {const definition = {diff --git a/packages/commons/src/lib/promoted_attribute_definition_parser.ts b/packages/commons/src/lib/promoted_attribute_definition_parser.tsindex 8052bed3d8..c51af6468a 100644--- a/packages/commons/src/lib/promoted_attribute_definition_parser.ts+++ b/packages/commons/src/lib/promoted_attribute_definition_parser.ts@@ -6,8 +6,8 @@ import { filterAttributeName } from "./attribute_names.js";* type cannot be added to the union without {@link parse} also accepting it.*/export const LABEL_TYPES = [- "text", "textarea", "number", "boolean", "date", "datetime", "time", "url", "email", "phone",- "color"+ "text", "textarea", "number", "boolean", "select", "date", "datetime", "time", "url", "email",+ "phone", "color"] as const;export type LabelType = typeof LABEL_TYPES[number];@@ -21,6 +21,8 @@ export interface DefinitionObject {labelType?: LabelType;multiplicity?: Multiplicity;numberPrecision?: number;+ /** The values a `select` field offers, in the order they are offered. */+ selectOptions?: string[];promotedAlias?: string;inverseRelation?: string;}@@ -50,6 +52,13 @@ function parse(value: string): DefinitionObject {} else if (token.startsWith("precision")) {// A missing value parses to NaN, which the consumers treat as "no precision set".defObj.numberPrecision = parseInt(parameterValue(token) ?? "");+ } else if (token.startsWith("options")) {+ // A blank entry offers nothing to pick and is dropped, so `options=` and a stray `;;`+ // both parse to what they mean rather than to invisible choices.+ defObj.selectOptions = (parameterValue(token) ?? "")+ .split(";")+ .filter((option) => option !== "")+ .map(decodeOption);} else if (token.startsWith("alias")) {defObj.promotedAlias = parameterValue(token);} else if (token.startsWith("inverse")) {@@ -99,6 +108,11 @@ function serialize(definition: DefinitionObject, valueType: "label" | "relation"if (labelType === "number" && definition.numberPrecision !== undefined) {props.push(`precision=${definition.numberPrecision}`);}++ // Options are only meaningful for a select, and an empty list means the same as none at all.+ if (labelType === "select" && definition.selectOptions?.length) {+ props.push(`options=${definition.selectOptions.map(encodeOption).join(";")}`);+ }} else if (definition.inverseRelation?.trim()) {props.push(`inverse=${filterAttributeName(definition.inverseRelation)}`);}@@ -132,6 +146,26 @@ function parameterValue(token: string): string | undefined {return separatorIndex < 0 ? undefined : token.substring(separatorIndex + 1);}+/**+ * Escapes a select option for storage inside the `options=` token, where `;` separates the options+ * and `,` would be cut by the definition tokenizer before this module ever saw it.+ *+ * Substitution (URL-style) rather than a `\`-escape on purpose: an escaped form must not *contain*+ * the raw separators, or every already-shipped parser — the split in {@link parse} runs before any+ * token logic — would cut straight through it, and the fragments of an option could even spell a+ * live token (`multi`, a label type, …) and be executed as one. `%` is the only character claimed+ * from the option itself, and the exact triplets below essentially never occur in natural text.+ */+function encodeOption(option: string): string {+ // `%` first, so the escapes written below are not re-escaped.+ return option.replace(/%/g, "%25").replace(/,/g, "%2C").replace(/;/g, "%3B");+}++/** The exact inverse of {@link encodeOption}: `%25` last, so a decoded `%` cannot start a triplet. */+function decodeOption(option: string): string {+ return option.replace(/%2C/gi, ",").replace(/%3B/gi, ";").replace(/%25/gi, "%");+}+function isLabelType(token: string): token is LabelType {return (LABEL_TYPES as readonly string[]).includes(token);}