Skip to content

Build your personal knowledge base with Trilium Notes

feat(table): edit a select column through the promoted field

Elian Doran59005138fdd8
diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.ts
index 950b5468b7..7b6bc54154 100644
--- a/apps/client/src/services/attributes.spec.ts
+++ b/apps/client/src/services/attributes.spec.ts
@@ -187,6 +187,55 @@ describe("addLabel / setLabel / setRelation", () => {
});
});
+describe("addSelectOption", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ /** The note carrying the definition, which is not the note the field is edited on. */
+ function definitionOf(value: string) {
+ const owner = buildNote({ title: "Owner", [`#label:status`]: value });
+ const definitionAttr = owner.getAttributeDefinitions()
+ .find((attr) => attr.name === "label:status");
+ if (!definitionAttr) throw new Error("expected the definition to be built");
+ return definitionAttr;
+ }
+
+ it("appends the option to the definition, writing it back to the note that owns it", async () => {
+ const definitionAttr = definitionOf("promoted,single,select,options=Todo;Done");
+
+ const newDefinition = await attributeService.addSelectOption(definitionAttr, "Blocked", "comp-1");
+
+ expect(newDefinition.selectOptions).toEqual([ "Todo", "Done", "Blocked" ]);
+ expect(server.put).toHaveBeenCalledWith(
+ `notes/${definitionAttr.noteId}/attribute`,
+ {
+ attributeId: definitionAttr.attributeId,
+ type: "label",
+ name: "label:status",
+ value: "promoted,single,select,options=Todo;Done;Blocked"
+ },
+ "comp-1"
+ );
+ });
+
+ it("gives a definition with no options its first, and escapes what the format claims", async () => {
+ await attributeService.addSelectOption(definitionOf("promoted,single,select"), "1,5 kg");
+ expect(server.put).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ value: "promoted,single,select,options=1%2C5 kg" }),
+ undefined
+ );
+ });
+
+ it("leaves an option it already offers alone, without a write", async () => {
+ const definitionAttr = definitionOf("promoted,single,select,options=Todo;Done");
+
+ const unchanged = await attributeService.addSelectOption(definitionAttr, "Done");
+
+ expect(unchanged.selectOptions).toEqual([ "Todo", "Done" ]);
+ expect(server.put).not.toHaveBeenCalled();
+ });
+});
+
describe("removeAttributeById / removeOwnedAttributesByNameOrType", () => {
beforeEach(() => vi.clearAllMocks());
diff --git a/apps/client/src/services/attributes.ts b/apps/client/src/services/attributes.ts
index 3f110627a1..a358af5025 100644
--- a/apps/client/src/services/attributes.ts
+++ b/apps/client/src/services/attributes.ts
@@ -1,5 +1,6 @@
-import { AttributeType, BUILTIN_ATTRIBUTES, type BuiltinLabel, type LabelType } from "@triliumnext/commons";
+import { AttributeType, BUILTIN_ATTRIBUTES, type BuiltinLabel, type DefinitionObject, type LabelType, promotedAttributeDefinitionParser } from "@triliumnext/commons";
+import type FAttribute from "../entities/fattribute.js";
import type FNote from "../entities/fnote.js";
import froca from "./froca.js";
import type { AttributeRow } from "./load_results.js";
@@ -108,6 +109,39 @@ function removeOwnedRelationByName(note: FNote, relationName: string) {
return false;
}
+/**
+ * Adds an option to a `select` definition, for a field offering to create the choice being typed
+ * into it.
+ *
+ * Written back to the very attribute the definition was read from — which is to say to whichever
+ * note owns it, typically a parent or a template, rather than to the note being edited — so that
+ * every note the field reaches offers the new option from now on.
+ *
+ * @param definitionAttr the `label:foo` attribute declaring the field.
+ * @param option the option to add; already offered, it is left as it stands.
+ * @returns the definition as it now reads, for a caller holding a parsed copy of its own.
+ */
+export async function addSelectOption(definitionAttr: FAttribute, option: string, componentId?: string) {
+ const definition = definitionAttr.getDefinition();
+ const options = definition.selectOptions ?? [];
+ if (options.includes(option)) {
+ return definition;
+ }
+
+ const newDefinition: DefinitionObject = { ...definition, selectOptions: [ ...options, option ] };
+ await server.put(
+ `notes/${definitionAttr.noteId}/attribute`,
+ {
+ attributeId: definitionAttr.attributeId,
+ type: "label",
+ name: definitionAttr.name,
+ value: promotedAttributeDefinitionParser.serialize(newDefinition, "label")
+ },
+ componentId
+ );
+ return newDefinition;
+}
+
/**
* Sets the attribute of the given note to the provided value if its truthy, or removes the attribute if the value is falsy.
* For an attribute with an empty value, pass an empty string instead.
@@ -258,6 +292,7 @@ export default {
setLabel,
setRelation,
setAttribute,
+ addSelectOption,
setBooleanWithInheritance,
removeAttributeById,
removeOwnedLabelByName,
diff --git a/apps/client/src/widgets/PromotedAttributes.tsx b/apps/client/src/widgets/PromotedAttributes.tsx
index e1c0759dfd..cbe7ad1146 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, promotedAttributeDefinitionParser, UpdateAttributeResponse } from "@triliumnext/commons";
+import { DefinitionObject, extractAttributeDefinitionTypeAndName, UpdateAttributeResponse } from "@triliumnext/commons";
import clsx from "clsx";
import { ComponentChild, MouseEventHandler, TargetedEvent } from "preact";
import { Dispatch, StateUpdater, useCallback, useEffect, useState } from "preact/hooks";
@@ -180,23 +180,10 @@ 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
+ // An option 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.
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
- );
+ const newDefinition = await attributes.addSelectOption(definitionAttr, option, componentId);
// The grid ignores reloads it is itself the source of (see usePromotedAttributeData), so the
// cells sharing the definition are patched in place, as updateAttribute does for a value —
// otherwise the list keeps offering the old options until something else changes.
@@ -205,7 +192,7 @@ function LabelInput(props: CellProps & { inputId: string }) {
? { ...c, definition: newDefinition }
: c
));
- }, [ definition, definitionAttr, componentId, setCells ]);
+ }, [ definitionAttr, componentId, setCells ]);
useTextLabelAutocomplete(inputId, valueAttr, definition, (e) => {
if (e.currentTarget instanceof HTMLInputElement) {
diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.ts
index 75ac1e8ba5..0c27f08ecf 100644
--- a/apps/client/src/widgets/collections/table/columns.spec.ts
+++ b/apps/client/src/widgets/collections/table/columns.spec.ts
@@ -1,6 +1,6 @@
-import { describe, expect, it } from "vitest";
-import { formatLabelDate, restoreExistingData } from "./columns";
-import type { ColumnDefinition } from "tabulator-tables";
+import { describe, expect, it, vi } from "vitest";
+import { buildColumnDefinitions, formatLabelDate, restoreExistingData, type SelectEditorParams } from "./columns";
+import type { CellComponent, ColumnDefinition } from "tabulator-tables";
import options from "../../../services/options";
@@ -134,6 +134,42 @@ describe("restoreExistingData", () => {
});
});
+describe("buildColumnDefinitions — select columns", () => {
+ /** Resolves the params a column hands its editor, which Tabulator asks for as a function. */
+ function editorParamsOf(column: ColumnDefinition | undefined) {
+ const params = column?.editorParams;
+ if (typeof params !== "function") throw new Error("expected the params to be a function");
+ return params({} as CellComponent) as SelectEditorParams;
+ }
+
+ function selectColumn(onCreateSelectOption?: (columnName: string, option: string) => void) {
+ const columns = buildColumnDefinitions({
+ info: [ { name: "status", type: "select", options: [ "Todo", "Done" ] } ],
+ movableRows: false,
+ existingColumnData: undefined,
+ rowNumberHint: 1,
+ onCreateSelectOption
+ });
+ return columns.find((column) => column.field === "labels.status");
+ }
+
+ it("hands the editor the column's own options, and a way to add to them", () => {
+ const onCreateSelectOption = vi.fn();
+ const params = editorParamsOf(selectColumn(onCreateSelectOption));
+
+ expect(params.options).toEqual([ "Todo", "Done" ]);
+
+ // The editor knows the option alone; the column it belongs to is bound in here.
+ params.onCreateOption?.("Blocked");
+ expect(onCreateSelectOption).toHaveBeenCalledWith("status", "Blocked");
+ });
+
+ it("leaves the editor no way to create where the caller offers none", () => {
+ // Without it the field stays a plain picker rather than calling something undefined.
+ expect(editorParamsOf(selectColumn()).onCreateOption).toBeUndefined();
+ });
+});
+
describe("formatLabelDate", () => {
it("renders dates and datetimes in the configured formatting locale", () => {
options.set("formattingLocale", "de");
diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsx
index f3d59186b7..76036ccbfe 100644
--- a/apps/client/src/widgets/collections/table/columns.tsx
+++ b/apps/client/src/widgets/collections/table/columns.tsx
@@ -5,6 +5,7 @@ import type { CellComponent, ColumnDefinition, EmptyCallback, FormatterParams, R
import froca from "../../../services/froca.js";
import { formatDateNumeric } from "../../../utils/formatters.js";
+import LabelValueInput from "../../attribute_widgets/label_value_input.jsx";
import Icon from "../../react/Icon.jsx";
import NoteAutocomplete from "../../react/NoteAutocomplete.jsx";
import { renderReactWidget } from "../../react/react_utils.jsx";
@@ -31,9 +32,9 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {
}
},
select: {
- // The choices come from the column's definition, so `editorParams` is attached per column
+ // The options come from the column's definition, so `editorParams` is attached per column
// in `buildColumnDefinitions` rather than here.
- editor: "list"
+ editor: wrapEditor(SelectEditor)
},
boolean: {
formatter: "tickCross",
@@ -123,9 +124,14 @@ interface BuildColumnArgs {
existingColumnData: ColumnDefinition[] | undefined;
rowNumberHint: number;
position?: number;
+ /**
+ * Adds an option to a select column's definition, for the entry its editor offers on a value
+ * the column does not list yet. Omitted, such a value cannot be created from a cell.
+ */
+ onCreateSelectOption?: (columnName: string, option: string) => void | Promise<void>;
}
-export function buildColumnDefinitions({ info, movableRows, existingColumnData, rowNumberHint, position }: BuildColumnArgs) {
+export function buildColumnDefinitions({ info, movableRows, existingColumnData, rowNumberHint, position, onCreateSelectOption }: BuildColumnArgs) {
let columnDefs: ColumnDefinition[] = [
{
title: "#",
@@ -172,10 +178,14 @@ 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.
+ // A select's options come from its own definition, so they attach per column. Handed as
+ // a function because that is the shape Tabulator types for params of an editor's own.
...(type === "select" && {
- editorParams: { values: options ?? [], clearable: true }
+ editorParams: (): Record<string, unknown> => ({
+ options: options ?? [],
+ onCreateOption: onCreateSelectOption
+ && ((option: string) => onCreateSelectOption(name, option))
+ } satisfies SelectEditorParams)
})
});
seenFields.add(field);
@@ -310,6 +320,42 @@ function NoteFormatter({ cell }: FormatterOpts) {
</span>;
}
+/**
+ * A select cell is edited through the very field the promoted-attribute grid offers, so a column and
+ * the note's own field behave alike — the options listed on opening, typing filtering them, and an
+ * unlisted value offered as one to create.
+ *
+ * The field is focused from the wrapper because it is reached through {@link LabelValueInput}, which
+ * 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 containerRef = useRef<HTMLDivElement>(null);
+ useEffect(() => containerRef.current?.querySelector("input")?.focus(), []);
+
+ return (
+ <div ref={containerRef} className="table-select-editor">
+ <LabelValueInput
+ labelType="select"
+ value={cell.getValue() ?? ""}
+ selectOptions={options}
+ onCommit={success}
+ onCreateOption={onCreateOption}
+ />
+ </div>
+ );
+}
+
+/**
+ * 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.
+ */
+export type SelectEditorParams = {
+ options: string[];
+ /** Absent where the definition cannot be written to, which leaves the field a plain picker. */
+ onCreateOption?: (option: string) => void | Promise<void>;
+};
+
function RelationEditor({ cell, success }: EditorOpts) {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => inputRef.current?.focus());
diff --git a/apps/client/src/widgets/collections/table/data.tsx b/apps/client/src/widgets/collections/table/data.tsx
index 94909939db..f9ea9409a2 100644
--- a/apps/client/src/widgets/collections/table/data.tsx
+++ b/apps/client/src/widgets/collections/table/data.tsx
@@ -36,7 +36,8 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tabl
movableRows,
existingColumnData: viewConfig?.tableData?.columns,
rowNumberHint: rowNumber,
- position: newAttributePosition?.current ?? undefined
+ position: newAttributePosition?.current ?? undefined,
+ onCreateSelectOption: (columnName, option) => addSelectOption(note, columnName, option)
});
setColumnDefs(columnDefs);
setRowData(rowData);
@@ -75,3 +76,19 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tabl
return { columnDefs, rowData, movableRows, hasChildren };
}
+
+/**
+ * Adds an option to the definition a select column reads from, for the entry its editor offers on a
+ * value the column does not list yet. The definition is looked up as the columns themselves are, so
+ * an inherited one is written where it lives and the option reaches every note the field covers.
+ *
+ * The write reloads the collection, which rebuilds the columns off the definition as it now reads —
+ * so nothing has to be patched in place here, unlike in the promoted grid.
+ */
+async function addSelectOption(parentNote: FNote, columnName: string, option: string) {
+ const definitionAttr = parentNote.getAttributeDefinitions()
+ .find((attr) => attr.name === `label:${columnName}`);
+ if (definitionAttr) {
+ await attributes.addSelectOption(definitionAttr, option);
+ }
+}