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
test(attributes): reach the logic the new fields run on
Elian Doranc737ffd829b6
diff --git a/apps/client/src/services/attributes.spec.ts b/apps/client/src/services/attributes.spec.tsindex 248c6e6ab5..b94fe29c46 100644--- a/apps/client/src/services/attributes.spec.ts+++ b/apps/client/src/services/attributes.spec.ts@@ -244,6 +244,35 @@ describe("setLabelValues", () => {});});+describe("setRelationValues", () => {+ beforeEach(() => vi.clearAllMocks());++ it("writes the targets as relations of the name, reused and trimmed as a label set is", async () => {+ const note = buildNote({ title: "N" });+ for (const [ index, value ] of [ "aaa", "bbb" ].entries()) {+ note.attributes.push(`rel-${index}`);+ froca.attributes[`rel-${index}`] = {+ attributeId: `rel-${index}`, noteId: note.noteId, type: "relation",+ name: "crew", value, position: index, isInheritable: false+ } as never;+ }++ await attributeService.setRelationValues(note, "crew", [ "aaa", "ccc" ], "comp-1");++ // Only the target that changed is written — as a relation, through the slot already there.+ expect(server.put).toHaveBeenCalledTimes(1);+ expect(server.put).toHaveBeenCalledWith(+ `notes/${note.noteId}/attribute`,+ { attributeId: "rel-1", type: "relation", name: "crew", value: "ccc" },+ "comp-1"+ );++ vi.clearAllMocks();+ await attributeService.setRelationValues(note, "crew", [ "aaa" ], "comp-1");+ expect(server.remove).toHaveBeenCalledWith(`notes/${note.noteId}/attributes/rel-1`, "comp-1");+ });+});+describe("addSelectOption", () => {beforeEach(() => vi.clearAllMocks());diff --git a/apps/client/src/widgets/PromotedAttributes.spec.tsx b/apps/client/src/widgets/PromotedAttributes.spec.tsxindex 525ab4a372..9ea2eab1cc 100644--- a/apps/client/src/widgets/PromotedAttributes.spec.tsx+++ b/apps/client/src/widgets/PromotedAttributes.spec.tsx@@ -1,15 +1,61 @@-import { describe, expect, it, vi } from "vitest";+import { render } from "preact";+import { useState } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// A relation's target is picked in an Algolia autocomplete bound to jQuery, which is not loaded here.vi.mock("./react/NoteAutocomplete", () => ({ default: () => null }));+// The chip fields have specs of their own; here they hand over their props, which is where the+// grid's behaviour lives — what the field is given, and what committing through it does.+const multiInput = vi.hoisted(() => ({ current: null as Record<string, unknown> | null }));+vi.mock("./attribute_widgets/multi_value_input", () => ({+ default: (props: Record<string, unknown>) => {+ multiInput.current = props;+ return null;+ },+ BOOLEAN_OPTIONS: [ "true", "false" ]+}));+const relationInput = vi.hoisted(() => ({ current: null as Record<string, unknown> | null }));+vi.mock("./attribute_widgets/relation_values_input", () => ({+ default: (props: Record<string, unknown>) => {+ relationInput.current = props;+ return null;+ },+ RelationValueChips: () => null+}));++// The grid follows the note the tab shows; the tests hand it one directly. The context object is+// held stable: the grid rebuilds its cells when the context changes, told apart by identity.+const shownNote = vi.hoisted(() => ({ current: null as FNote | null }));+const noteContext = vi.hoisted(() => ({ viewScope: { viewMode: "default" } }));+vi.mock("./react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./react/hooks")>()),+ useNoteContext: () => ({+ note: shownNote.current,+ componentId: "cid",+ noteContext+ })+}));++import $ from "jquery";++import type Component from "../components/component";import FAttribute from "../entities/fattribute";import type FNote from "../entities/fnote";import froca from "../services/froca";+import type LoadResults from "../services/load_results";import noteAttributeCache from "../services/note_attribute_cache";+import server from "../services/server";import { randomString } from "../services/utils";import { buildNote } from "../test/easy-froca";-import { buildPromotedCells } from "./PromotedAttributes";+import { ParentComponent } from "./react/react_utils";+import PromotedAttributes, { buildPromotedCells, PromotedAttributesContent } from "./PromotedAttributes";++// A text field offers the values other notes hold under its name through the Algolia plugin, which+// is not loaded here; a stub that chains like jQuery does keeps the field's setup on its feet.+type PluggedIn = { autocomplete(...args: unknown[]): PluggedIn };+($.fn as unknown as PluggedIn).autocomplete = function (this: PluggedIn) { return this; };describe("buildPromotedCells", () => {it("gathers a label allowing several values into one field, leaving a single-valued one its own", () => {@@ -77,6 +123,182 @@ describe("buildPromotedCells", () => {expect(cells[0].values).toEqual([ "aaaaaaaaaaaa", "bbbbbbbbbbbb" ]);expect(cells[0].valueAttr).toMatchObject({ attributeId: "", type: "relation", name: "related" });});++ it("gives a single-valued definition its empty field too, and keeps it to the one value", () => {+ const empty = buildNote({ title: "Task", "#label:status": "promoted,single,text" });+ expect(buildPromotedCells(empty)).toHaveLength(1);+ expect(buildPromotedCells(empty)[0].valueAttr).toMatchObject({ attributeId: "", value: "" });++ // Holding two under a single-valued name — a definition retyped from multi — shows the first.+ const twice = buildNote({ title: "Task", "#label:status": "promoted,single,text", "#status": "open" });+ hold(twice, "label", "status", "closed");+ const cells = buildPromotedCells(twice);+ expect(cells).toHaveLength(1);+ expect(cells[0].valueAttr.value).toBe("open");+ });+});++describe("PromotedAttributesContent", () => {+ let container: HTMLElement;+ let put: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.clearAllMocks();+ multiInput.current = null;+ relationInput.current = null;+ put = vi.fn(async () => ({}));+ server.put = put as unknown as typeof server.put;+ // The text fields ask for the values other notes hold under the name, to suggest them.+ server.get = (async () => []) as unknown as typeof server.get;+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ /** The grid over cells of its own, holding them as the widget's hook does. */+ function Host({ note }: { note: FNote }) {+ const [ cells, setCells ] = useState<ReturnType<typeof buildPromotedCells> | undefined>(() => buildPromotedCells(note));+ return <PromotedAttributesContent note={note} componentId="cid" cells={cells} setCells={setCells} />;+ }++ function mount(note: FNote) {+ act(() => render(<Host note={note} />, container));+ }++ it("gives a single-valued label its own field, edited through the attribute holding the value", () => {+ const note = buildNote({+ title: "Task",+ "#label:status": "promoted,single,text",+ "#status": "open"+ });+ mount(note);++ const input = container.querySelector<HTMLInputElement>(".promoted-attribute-input");+ expect(input?.value).toBe("open");+ expect(input?.dataset.attributeName).toBe("status");+ });++ it("writes a multi label's set back by name, and patches the field it shows in place", async () => {+ const note = buildNote({ title: "Task", "#label:tags": "promoted,multi,text", "#tags": "alpha" });+ mount(note);++ expect(multiInput.current).toMatchObject({ labelType: "text", values: [ "alpha" ] });++ await act(async () => (multiInput.current?.onCommit as (values: string[]) => Promise<void>)([ "alpha", "beta" ]));++ // Only what the set gained is written — the attribute already there is left as it stands.+ expect(put).toHaveBeenCalledOnce();+ expect(put).toHaveBeenCalledWith(+ `notes/${note.noteId}/attribute`,+ { attributeId: undefined, type: "label", name: "tags", value: "beta" },+ "cid"+ );+ // The grid ignores reloads of its own making, so the field is patched by hand.+ expect(multiInput.current?.values).toEqual([ "alpha", "beta" ]);+ });++ it("adds a select option to the definition itself, the field offering it from then on", async () => {+ const note = buildNote({ title: "Task", "#label:status": "promoted,multi,select,options=Todo;Done" });+ mount(note);++ expect(multiInput.current?.options).toEqual([ "Todo", "Done" ]);++ await act(async () => (multiInput.current?.onCreateOption as (option: string) => Promise<void>)("Blocked"));++ // Written back to the very attribute declaring the field, options and the rest of it intact.+ expect(put).toHaveBeenCalledWith(+ `notes/${note.noteId}/attribute`,+ expect.objectContaining({ name: "label:status", value: expect.stringContaining("Blocked") }),+ "cid"+ );+ expect(multiInput.current?.options).toEqual([ "Todo", "Done", "Blocked" ]);+ });++ it("writes a multi relation's targets by name, as it writes a label's values", async () => {+ const target = buildNote({ title: "Alpha" });+ const other = buildNote({ title: "Beta" });+ const note = buildNote({ title: "Task", "#relation:crew": "promoted,multi", "~crew": target.noteId });+ mount(note);++ expect(relationInput.current?.values).toEqual([ target.noteId ]);++ await act(async () => (relationInput.current?.onCommit as (values: string[]) => Promise<void>)([ target.noteId, other.noteId ]));++ expect(put).toHaveBeenCalledWith(+ `notes/${note.noteId}/attribute`,+ { attributeId: undefined, type: "relation", name: "crew", value: other.noteId },+ "cid"+ );+ expect(relationInput.current?.values).toEqual([ target.noteId, other.noteId ]);+ });+});++describe("PromotedAttributes", () => {+ let container: HTMLElement;+ /** What the widget subscribed to, for handing it a reload as the real component tree would. */+ let handlers: Map<string, (data: unknown) => void>;++ beforeEach(() => {+ vi.clearAllMocks();+ multiInput.current = null;+ server.get = (async () => []) as unknown as typeof server.get;+ handlers = new Map();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ function mount(note: FNote) {+ shownNote.current = note;+ const parent = {+ componentId: "cid",+ registerHandler: (name: string, callback: (data: unknown) => void) => handlers.set(name, callback),+ removeHandler: () => {}+ } as unknown as Component;+ act(() => render(+ <ParentComponent.Provider value={parent}>+ <PromotedAttributes />+ </ParentComponent.Provider>,+ container+ ));+ }++ it("builds the fields the note's definitions ask for, and rebuilds on a change made elsewhere", () => {+ const note = buildNote({ title: "Task", "#label:tags": "promoted,multi,text", "#tags": "alpha" });+ mount(note);++ expect(container.querySelectorAll(".promoted-attribute-cell")).toHaveLength(1);+ expect(multiInput.current?.values).toEqual([ "alpha" ]);++ // Another client fills a value in: the reload reaches the grid, which rereads the note.+ hold(note, "label", "tags", "beta");+ const loadResults = {+ getAttributeRows: () => [ {+ noteId: note.noteId, type: "label", name: "tags", value: "beta", isInheritable: false+ } ]+ } as unknown as LoadResults;+ act(() => handlers.get("entitiesReloaded")?.({ loadResults }));++ expect(multiInput.current?.values).toEqual([ "alpha", "beta" ]);+ });++ it("keeps the grid empty for a table view, whose cells already edit the same fields", () => {+ const note = buildNote({+ title: "Grid", "#viewType": "table",+ "#label:tags": "promoted,multi,text", "#tags": "alpha"+ });+ mount(note);++ expect(container.querySelectorAll(".promoted-attribute-cell")).toHaveLength(0);+ });});/** Gives the note another attribute under a name it already carries, which one literal cannot. */diff --git a/apps/client/src/widgets/attribute_widgets/label_value_display.spec.tsx b/apps/client/src/widgets/attribute_widgets/label_value_display.spec.tsxnew file mode 100644index 0000000000..17b1daddef--- /dev/null+++ b/apps/client/src/widgets/attribute_widgets/label_value_display.spec.tsx@@ -0,0 +1,112 @@+import { render } from "preact";+import { describe, expect, it } from "vitest";++import { formatDateNumeric } from "../../utils/formatters";+import { applyLinkScheme, asLabelValues, formatLabelDate, LabelValueChips, renderLabelValue } from "./label_value_display";++/** Renders what {@link renderLabelValue} hands back, JSX and bare string alike, and reads the DOM. */+function draw(value: string, labelType: Parameters<typeof renderLabelValue>[1]) {+ const container = document.createElement("div");+ render(<span>{renderLabelValue(value, labelType)}</span>, container);+ const drawn = container.firstElementChild as HTMLElement;+ render(null, container);+ return drawn;+}++describe("renderLabelValue", () => {+ it("reads a date or datetime through the user's locale, and echoes what is no date at all", () => {+ expect(renderLabelValue("2025-05-05", "date")).toBe(formatDateNumeric("2025-05-05", false));+ expect(renderLabelValue("2025-05-05 14:30", "datetime")).toBe(formatDateNumeric("2025-05-05 14:30", true));+ // Free text left behind by retyping a label stays readable rather than crashing the formatter.+ expect(renderLabelValue("someday", "date")).toBe("someday");+ });++ it("reads a colour as its swatch, with the stored text kept to the tooltip", () => {+ const swatch = draw("#3d5a80", "color").querySelector<HTMLElement>(".label-color-swatch");+ expect(swatch?.title).toBe("#3d5a80");+ expect(swatch?.style.backgroundColor).toBeTruthy();+ });++ it("reads a flag as its mark, either answer marked as itself", () => {+ expect(draw("true", "boolean").querySelector(".label-flag-set")).not.toBeNull();+ expect(draw("false", "boolean").querySelector(".label-flag-unset")).not.toBeNull();+ });++ it("links a url through the scheme guard rather than as stored", () => {+ expect(draw("https://example.com", "url").querySelector("a")?.getAttribute("href"))+ .toBe("https://example.com");+ // The guard is the whole point: a script url must not reach the href.+ expect(draw("javascript:alert(1)", "url").querySelector("a")?.getAttribute("href"))+ .toBe("about:blank");+ });++ it("makes an email and a phone clickable by their schemes, shown as the bare value", () => {+ const email = draw("[email protected]", "email").querySelector("a");+ expect(email?.getAttribute("href")).toBe("mailto:[email protected]");+ expect(email?.textContent).toBe("[email protected]");+ expect(draw("+40123", "phone").querySelector("a")?.getAttribute("href")).toBe("tel:+40123");+ });++ it("leaves any other value as the text it is stored as", () => {+ expect(renderLabelValue("plain", "text")).toBe("plain");+ expect(renderLabelValue("42", "number")).toBe("42");+ expect(renderLabelValue("anything", undefined)).toBe("anything");+ });+});++describe("applyLinkScheme", () => {+ it("adds the scheme once, keeps one already stored, and yields nothing for no value", () => {+ expect(applyLinkScheme("[email protected]", "mailto:")).toBe("mailto:[email protected]");+ // An older value stored as a url already carries it.+ expect(applyLinkScheme("mailto:[email protected]", "mailto:")).toBe("mailto:[email protected]");+ expect(applyLinkScheme("", "mailto:")).toBe("");+ expect(applyLinkScheme(42, "tel:")).toBe("");+ });+});++describe("formatLabelDate", () => {+ it("formats what parses, echoes what does not, and yields nothing for what is no string", () => {+ expect(formatLabelDate("2025-05-05", false)).toBe(formatDateNumeric("2025-05-05", false));+ expect(formatLabelDate("not a date", false)).toBe("not a date");+ expect(formatLabelDate("", true)).toBe("");+ expect(formatLabelDate(42, true)).toBe("");+ });+});++describe("asLabelValues", () => {+ it("reads a set from whatever a multi-valued label left behind", () => {+ expect(asLabelValues([ "a", "b" ])).toEqual([ "a", "b" ]);+ // A retyped single-valued definition leaves a bare string; an unset field leaves nothing.+ expect(asLabelValues("lone")).toEqual([ "lone" ]);+ expect(asLabelValues("")).toEqual([]);+ expect(asLabelValues(undefined)).toEqual([]);+ // Anything unreadable within a stored array is left out rather than shown as a chip.+ expect(asLabelValues([ "a", 42, null ])).toEqual([ "a" ]);+ });+});++describe("LabelValueChips", () => {+ function drawChips(values: string[], labelType: Parameters<typeof renderLabelValue>[1]) {+ const container = document.createElement("div");+ render(<LabelValueChips values={values} labelType={labelType} />, container);+ const chips = [ ...container.querySelectorAll<HTMLElement>(".tn-chip") ];+ render(null, container);+ return chips;+ }++ it("washes a flag's chip with its answer, and reads a colour as a chip of the colour itself", () => {+ const flags = drawChips([ "true", "false" ], "boolean");+ expect(flags.map((chip) => chip.className.includes("label-flag-chip-set"))).toEqual([ true, false ]);+ expect(flags.map((chip) => chip.className.includes("label-flag-chip-unset"))).toEqual([ false, true ]);++ const [ colour ] = drawChips([ "#3d5a80" ], "color");+ expect(colour?.className).toContain("label-color-chip");+ expect(colour?.title).toBe("#3d5a80");+ });++ it("shows a plain set as one unwashed chip per value", () => {+ const chips = drawChips([ "a", "b" ], "text");+ expect(chips.map((chip) => chip.textContent)).toEqual([ "a", "b" ]);+ expect(chips.every((chip) => !chip.className.includes("label-flag-chip"))).toBe(true);+ });+});diff --git a/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsx b/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsxindex e15e47f3ec..5abb5ce54a 100644--- a/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsx+++ b/apps/client/src/widgets/attribute_widgets/relation_values_input.spec.tsx@@ -3,21 +3,31 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// The real box is an Algolia autocomplete bound to jQuery, which is not loaded here; the mock hands-// the test the props instead, `noteIdChanged` being the one the field's behaviour hangs off.+// the test the props instead, `noteIdChanged` being the one the field's behaviour hangs off. The ref+// is forwarded to the box it builds, as the real field forwards it to the box the plugin builds.const autocomplete = vi.hoisted(() => ({ current: null as Record<string, unknown> | null }));vi.mock("../react/NoteAutocomplete", async () => {const { h } = await import("preact");return {default: (props: Record<string, unknown>) => {autocomplete.current = props;- return h("input", { id: props.id as string | undefined });+ return h("input", { id: props.id as string | undefined, ref: props.inputRef });}};});+import $ from "jquery";+import { buildNote } from "../../test/easy-froca";import RelationValuesInput, { RelationValueChips } from "./relation_values_input";+// Taking a pick clears the box through the plugin, which holds text of its own; the plugin is not+// loaded here, so its two calls are stubbed where jQuery keeps them.+const setSelectedNotePath = vi.fn();+type PluggedIn = { autocomplete(...args: unknown[]): PluggedIn; setSelectedNotePath(path: string): void };+($.fn as unknown as PluggedIn).autocomplete = function (this: PluggedIn) { return this; };+($.fn as unknown as PluggedIn).setSelectedNotePath = setSelectedNotePath;+describe("RelationValuesInput", () => {let container: HTMLElement;@@ -59,6 +69,9 @@ describe("RelationValuesInput", () => {await act(async () => pick(gamma.noteId));expect(onCommit).toHaveBeenCalledWith([ alpha.noteId, gamma.noteId ]);+ // What was in the box is spent on the choice made: the plugin is told to let its text go,+ // or it would write the picked title right back over the cleared box.+ expect(setSelectedNotePath).toHaveBeenCalledWith("");// A target already held would come out as a second chip there is no telling apart — and// clearing the box reports an empty pick, which is not a target at all.@@ -68,9 +81,12 @@ describe("RelationValuesInput", () => {expect(onCommit).not.toHaveBeenCalled();});- it("points a host's own label at the box", async () => {- await mount({ values: [], onCommit: vi.fn(), inputId: "field-id" });- expect(container.querySelector("input")?.id).toBe("field-id");+ it("points a host's own label at the box, and hands it the host's place in the tab order", async () => {+ await mount({ values: [], onCommit: vi.fn(), inputId: "field-id", tabIndex: 205 });+ const input = container.querySelector("input");+ expect(input?.id).toBe("field-id");+ // Set onto the box by hand: the field does not carry the attribute through to it.+ expect(input?.getAttribute("tabindex")).toBe("205");});});diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex 2e26028bc5..4ab639021a 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -2,7 +2,21 @@ import { act } from "preact/test-utils";import type { CellComponent, ColumnComponent, ColumnDefinition, RowComponent } from "tabulator-tables";import { describe, expect, it, vi } from "vitest";+// A relation's target is picked in an Algolia autocomplete bound to jQuery, which is not loaded+// here; the mock hands the test the props, `noteIdChanged` being what an editor's behaviour hangs off.+const autocomplete = vi.hoisted(() => ({ current: null as Record<string, unknown> | null }));+vi.mock("../../react/NoteAutocomplete", async () => {+ const { h } = await import("preact");+ return {+ default: (props: Record<string, unknown>) => {+ autocomplete.current = props;+ return h("input", { className: "note-autocomplete-stub" });+ }+ };+});+import options from "../../../services/options";+import { buildNote } from "../../../test/easy-froca";import { formatLabelDate } from "../../attribute_widgets/label_value_display";import { type AttributeDefinitionInformation, buildColumnDefinitions, restoreExistingData, type ValuesEditorParams } from "./columns";@@ -199,9 +213,85 @@ describe("buildColumnDefinitions — typed columns", () => {});});+describe("buildColumnDefinitions — relation columns", () => {+ function relationColumn(isMulti: boolean) {+ return buildColumnDefinitions({+ info: [ { name: "assignee", type: "relation", isMulti } ],+ movableRows: false,+ existingColumnData: undefined,+ rowNumberHint: 1+ }).find((column) => column.field === "relations.assignee");+ }++ function rowTitled(title: string | undefined) {+ return { getData: () => ({ relationTitles: title === undefined ? undefined : { assignee: title } }) } as unknown as RowComponent;+ }++ it("sorts by the title the cell shows, and by nothing where a row or the column carries none", () => {+ const sorter = relationColumn(false)?.sorter;+ if (typeof sorter !== "function") throw new Error("expected a sorter of its own");+ const column = { getField: () => "relations.assignee" } as ColumnComponent;++ expect(sorter("b-id", "a-id", rowTitled("Alpha"), rowTitled("Beta"), column, "asc", {})).toBeLessThan(0);+ // A row without the relation sorts as nothing rather than by an id the user never sees.+ expect(sorter("b-id", "", rowTitled("Alpha"), rowTitled(undefined), column, "asc", {})).toBeGreaterThan(0);+ // A column that lost its field has no titles to read, which is not a reason to throw.+ expect(sorter("a", "b", rowTitled("Alpha"), rowTitled("Beta"), { getField: () => undefined } as unknown as ColumnComponent, "asc", {})).toBe(0);+ });++ it("shows a set of targets as the chips naming their notes", async () => {+ const alpha = buildNote({ title: "Alpha" });+ const beta = buildNote({ title: "Beta" });+ const formatter = relationColumn(true)?.formatter;+ if (typeof formatter !== "function") throw new Error("expected a formatter of its own");++ let element: HTMLElement | undefined;+ await act(async () => {+ element = formatter({ getValue: () => [ alpha.noteId, beta.noteId ] } as CellComponent, { type: "relation" }, () => {}) as HTMLElement;+ });++ const chips = [ ...(element?.querySelectorAll(".label-value-chips .tn-chip") ?? []) ];+ expect(chips.map((chip) => chip.textContent?.trim())).toEqual([ "Alpha", "Beta" ]);+ // Named as the links a relation cell offers for its one target, not as bare text.+ expect(chips[0]?.querySelector(".reference-link")?.getAttribute("data-href")).toBe(`#root/${alpha.noteId}`);+ });++ it("edits a set of targets through the same field the note's own promoted grid offers", async () => {+ const editor = relationColumn(true)?.editor;+ if (typeof editor !== "function") throw new Error("expected an editor of its own");++ let element: HTMLElement | false = false;+ await act(async () => {+ element = editor(+ { getValue: () => [] } as unknown as CellComponent, () => {}, vi.fn(), () => {},+ { labelType: "relation", options: [], isMulti: true } satisfies Partial<ValuesEditorParams>+ );+ });++ expect((element as unknown as HTMLElement)?.querySelector(".relation-values-input")).not.toBeNull();+ });++ it("edits a single target through the note search, standing over the cell", async () => {+ const editor = relationColumn(false)?.editor;+ if (typeof editor !== "function") throw new Error("expected an editor of its own");++ const success = vi.fn();+ let element: HTMLElement | false = false;+ await act(async () => {+ element = editor({ getValue: () => "old-id" } as CellComponent, () => {}, success, () => {}, {});+ });++ expect((element as unknown as HTMLElement)?.querySelector(".note-autocomplete-stub")).not.toBeNull();+ expect(autocomplete.current?.noteId).toBe("old-id");+ // The pick is the whole of the edit, so reporting it ends the edit too.+ (autocomplete.current?.noteIdChanged as (noteId: string) => void)("new-id");+ expect(success).toHaveBeenCalledWith("new-id");+ });+});+describe("buildColumnDefinitions — colour columns", () => {/** Opens a colour cell's editor, as Tabulator does, and hands back what it built. */- async function editColorCell(value: string) {+ async function editColorCell(value: string | undefined) {const [ column ] = buildColumnDefinitions({info: [ { name: "tint", type: "color" } ],movableRows: false,@@ -279,6 +369,10 @@ describe("buildColumnDefinitions — colour columns", () => {const { element, success } = await editColorCell("");expect(element.querySelector<HTMLInputElement>("input[type=hidden]")?.value).toBe("");expect(success).not.toHaveBeenCalled();++ // A cell never written at all holds no value, which reads the same as one emptied.+ const unset = await editColorCell(undefined);+ expect(unset.element.querySelector<HTMLInputElement>("input[type=hidden]")?.value).toBe("");});});diff --git a/apps/client/src/widgets/collections/table/data.spec.tsx b/apps/client/src/widgets/collections/table/data.spec.tsxnew file mode 100644index 0000000000..db245e76c9--- /dev/null+++ b/apps/client/src/widgets/collections/table/data.spec.tsx@@ -0,0 +1,141 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type Component from "../../../components/component";+import type FNote from "../../../entities/fnote";+import froca from "../../../services/froca";+import type LoadResults from "../../../services/load_results";+import { buildNote } from "../../../test/easy-froca";+import { ParentComponent } from "../../react/react_utils";+import useData from "./data";++describe("useData", () => {+ let container: HTMLElement;+ let handlers: Map<string, (data: unknown) => void>;+ let captured: ReturnType<typeof useData> | undefined;+ let resetNewAttributePosition: ReturnType<typeof vi.fn<() => void>>;++ beforeEach(() => {+ vi.clearAllMocks();+ handlers = new Map();+ captured = undefined;+ resetNewAttributePosition = vi.fn();+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ /** Runs the hook as the table does, under a parent that can hand it a reload. */+ function Probe({ note, noteIds }: { note: FNote; noteIds: string[] }) {+ captured = useData(note, noteIds, undefined, { current: undefined }, resetNewAttributePosition);+ return null;+ }++ async function mount(note: FNote, noteIds: string[]) {+ const parent = {+ componentId: "table-cid",+ registerHandler: (name: string, callback: (data: unknown) => void) => handlers.set(name, callback),+ removeHandler: () => {}+ } as unknown as Component;+ await act(async () => render(+ <ParentComponent.Provider value={parent}>+ <Probe note={note} noteIds={noteIds} />+ </ParentComponent.Provider>,+ container+ ));+ // The refresh the mount effect starts awaits its way through the caches; a whole turn of+ // the loop lets the chain settle before the assertions read what it wrote.+ await settle();+ }++ function settle() {+ return act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ }++ function collection() {+ const note = buildNote({+ title: "Collection",+ "#label:status(inheritable)": "promoted,single,select,options=Todo;Done",+ children: [ { title: "Task 1", "#status": "Todo" }, { title: "Task 2" } ]+ });+ const noteIds = note.getChildBranches()+ .map((branch) => branch.noteId)+ .filter((noteId): noteId is string => !!noteId);+ return { note, noteIds };+ }++ async function fire(loadResults: Record<string, unknown>) {+ await act(async () => handlers.get("entitiesReloaded")?.({ loadResults: loadResults as unknown as LoadResults }));+ await settle();+ }++ it("builds the columns the definitions ask for and a row per child", async () => {+ const { note, noteIds } = collection();+ await mount(note, noteIds);++ expect(captured?.columnDefs?.map((column) => column.field)).toContain("labels.status");+ expect(captured?.rowData?.map((row) => row.title)).toEqual([ "Task 1", "Task 2" ]);+ // The columns were built, so a pending "place the new one here" has been spent.+ expect(resetNewAttributePosition).toHaveBeenCalled();++ // A select cell's options are read from the note as the cell is opened, late enough to+ // include one the definition has just been given.+ const statusColumn = captured?.columnDefs?.find((column) => column.field === "labels.status");+ const editorParams = statusColumn?.editorParams;+ if (typeof editorParams !== "function") throw new Error("expected the params to be a function");+ expect(editorParams(undefined as never)).toMatchObject({ options: [ "Todo", "Done" ] });+ });++ it("refreshes only the rows for a row change, leaving the columns be", async () => {+ const { note, noteIds } = collection();+ await mount(note, noteIds);+ const columnsBefore = captured?.columnDefs;++ const task = froca.notes[noteIds[0]];+ task.title = "Renamed";+ await fire({+ getAttributeRows: () => [],+ getBranchRows: () => [ { parentNoteId: note.noteId } ],+ getNoteIds: () => []+ });++ expect(captured?.rowData?.map((row) => row.title)).toEqual([ "Renamed", "Task 2" ]);+ // The very same array: rebuilt columns are replaced wholesale in Tabulator, which would+ // throw away the scroll position on every edit.+ expect(captured?.columnDefs).toBe(columnsBefore);+ });++ it("rebuilds the columns for a definition changed elsewhere, but not for its own change", async () => {+ const { note, noteIds } = collection();+ await mount(note, noteIds);+ const columnsBefore = captured?.columnDefs;++ const definitionRows = [ {+ noteId: note.noteId, type: "label", name: "label:status", value: "promoted,single,text", isInheritable: true+ } ];++ // The table's own write comes back around: rebuilding now would pull the open editor+ // out from under the user, so its component id filters the change away.+ await fire({+ getAttributeRows: (componentId?: string) => componentId === "table-cid" ? [] : definitionRows,+ getBranchRows: () => [],+ getNoteIds: () => []+ });+ expect(captured?.columnDefs).toBe(columnsBefore);++ // The same change made elsewhere rebuilds the columns.+ await fire({+ getAttributeRows: () => definitionRows,+ getBranchRows: () => [],+ getNoteIds: () => []+ });+ expect(captured?.columnDefs).not.toBe(columnsBefore);+ });+});diff --git a/apps/client/src/widgets/collections/table/rows.spec.ts b/apps/client/src/widgets/collections/table/rows.spec.tsindex 6f98a5cce6..997e9ab111 100644--- a/apps/client/src/widgets/collections/table/rows.spec.ts+++ b/apps/client/src/widgets/collections/table/rows.spec.ts@@ -4,6 +4,7 @@ import FAttribute from "../../../entities/fattribute";import type FNote from "../../../entities/fnote";import froca from "../../../services/froca";import noteAttributeCache from "../../../services/note_attribute_cache";+import server from "../../../services/server";import { randomString } from "../../../services/utils";import { buildNote } from "../../../test/easy-froca";import getAttributeDefinitionInformation, { buildRowDefinitions } from "./rows.js";@@ -108,6 +109,58 @@ describe("buildRowDefinitions", () => {{ title: "Task 2", relations: { crew: [] }, relationTitles: { crew: "" } }]);});++ it("titles the whole subtree in the one visit, nested rows included", async () => {+ const target = buildNote({ title: "Deep target" });+ const parent = buildNote({+ title: "Collection",+ "#relation:assignee(inheritable)": "promoted,single",+ children: [+ { title: "Task", children: [ { title: "Subtask", "~assignee": target.noteId } ] }+ ]+ });++ const info = getAttributeDefinitionInformation(parent);+ const { definitions, hasSubtree } = await buildRowDefinitions(parent, info, false);++ expect(hasSubtree).toBe(true);+ expect(definitions[0]._children?.[0]).toMatchObject({+ title: "Subtask",+ relationTitles: { assignee: "Deep target" }+ });+ });++ it("has no titles to fill where no row holds a target at all", async () => {+ const parent = buildNote({+ title: "Collection",+ "#relation:assignee(inheritable)": "promoted,single",+ children: [ { title: "Task" } ]+ });++ const info = getAttributeDefinitionInformation(parent);+ const { definitions } = await buildRowDefinitions(parent, info, false);++ // No batch is fetched and nothing is written: an empty map sorts as nothing, same as "".+ expect(definitions[0].relationTitles).toEqual({});+ });++ it("titles a target since deleted as nothing, rather than as its id or a crash", async () => {+ // The target is not in the cache, so the batch asks the server — which no longer has it.+ server.post = (async () => ({ branches: [], notes: [], attributes: [] })) as unknown as typeof server.post;+ const parent = buildNote({+ title: "Collection",+ "#relation:assignee(inheritable)": "promoted,single",+ children: [ { title: "Task", "~assignee": "gonemissing12" } ]+ });++ const info = getAttributeDefinitionInformation(parent);+ const { definitions } = await buildRowDefinitions(parent, info, false);++ expect(definitions[0]).toMatchObject({+ relations: { assignee: "gonemissing12" },+ relationTitles: { assignee: "" }+ });+ });});/** Gives the note another relation under a name it already carries, which one literal cannot. */diff --git a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx b/apps/client/src/widgets/sidebar/AttributeList.spec.tsxindex f957bfe8c9..7cff712d23 100644--- a/apps/client/src/widgets/sidebar/AttributeList.spec.tsx+++ b/apps/client/src/widgets/sidebar/AttributeList.spec.tsx@@ -645,6 +645,34 @@ describe("AttributeList", () => {expect(picker?.value).toBe("#8000ff");});+ it("edits a select definition's options as chips in the popup, saved with the close", async () => {+ renderPanel(buildNote({+ id: "select-def", title: "Subject",+ "#label:status": "promoted,single,select,options=Todo"+ }));+ act(() => firstRow().click());++ // The options are entered as the values themselves are elsewhere: typed free, taken on enter.+ const optionsInput = document.querySelector<HTMLInputElement>(".attr-detail .values-input input");+ expect(optionsInput).not.toBeNull();+ act(() => {+ if (optionsInput) {+ optionsInput.value = "Done";+ optionsInput.dispatchEvent(new Event("input", { bubbles: true }));+ optionsInput.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ }+ });++ await act(async () => {+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ });++ expect(put).toHaveBeenCalledOnce();+ const [ , saved ] = put.mock.calls[0] as [ string, { name: string; value: string }[] ];+ expect(saved.find((attribute) => attribute.name === "label:status")?.value)+ .toContain("options=Todo;Done");+ });+it("commits the in-place edit on enter for a label, a textarea keeping it for its lines", async () => {renderPanel(noteWithAttributes());act(() => firstRow().querySelector<HTMLElement>(".attribute-value")?.click());@@ -740,6 +768,12 @@ describe("AttributeList", () => {act(() => fireEntitiesReloaded(() => affectingRows(note)));expect(container.querySelector(".attribute-value-editor")).toBeNull();expect(namesIn(container)).toContain("elsewhere");++ // A creation draft is dropped the same way: the rebuilt rows have no place for it either.+ act(() => container.querySelector<HTMLElement>(".attribute-add-row")?.click());+ expect(container.querySelector(".attribute-creation-editor")).not.toBeNull();+ act(() => fireEntitiesReloaded(() => affectingRows(note)));+ expect(container.querySelector(".attribute-creation-editor")).toBeNull();});it("discards what the popup was told when it is closed rather than pressed away from", async () => {