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
fix(collections/table): stop a cell edit from reloading its own rows (closes #6474)
Elian Doran0ed55f48ab24
diff --git a/apps/client/src/widgets/collections/table/data.spec.tsx b/apps/client/src/widgets/collections/table/data.spec.tsxindex db245e76c9..73594db65f 100644--- a/apps/client/src/widgets/collections/table/data.spec.tsx+++ b/apps/client/src/widgets/collections/table/data.spec.tsx@@ -71,8 +71,15 @@ describe("useData", () => {return { note, noteIds };}+ /** Hands the hook a reload reporting nothing but what the test overrides. */async function fire(loadResults: Record<string, unknown>) {- await act(async () => handlers.get("entitiesReloaded")?.({ loadResults: loadResults as unknown as LoadResults }));+ const reload = {+ getAttributeRows: () => [],+ getBranchRows: () => [],+ isNoteReloaded: () => false,+ ...loadResults+ };+ await act(async () => handlers.get("entitiesReloaded")?.({ loadResults: reload as unknown as LoadResults }));await settle();}@@ -100,11 +107,7 @@ describe("useData", () => {const task = froca.notes[noteIds[0]];task.title = "Renamed";- await fire({- getAttributeRows: () => [],- getBranchRows: () => [ { parentNoteId: note.noteId } ],- getNoteIds: () => []- });+ await fire({ getBranchRows: () => [ { parentNoteId: note.noteId } ] });expect(captured?.rowData?.map((row) => row.title)).toEqual([ "Renamed", "Task 2" ]);// The very same array: rebuilt columns are replaced wholesale in Tabulator, which would@@ -123,19 +126,38 @@ describe("useData", () => {// 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: () => []- });+ await fire({ getAttributeRows: (componentId?: string) => componentId === "table-cid" ? [] : definitionRows });expect(captured?.columnDefs).toBe(columnsBefore);// The same change made elsewhere rebuilds the columns.+ await fire({ getAttributeRows: () => definitionRows });+ expect(captured?.columnDefs).not.toBe(columnsBefore);+ });++ it("rebuilds the rows for a cell changed elsewhere, but not for its own edit", async () => {+ const { note, noteIds } = collection();+ await mount(note, noteIds);+ const rowsBefore = captured?.rowData;++ const task = froca.notes[noteIds[0]];+ task.title = "Renamed";+ const labelRows = [ { noteId: noteIds[0], type: "label", name: "status", value: "Done" } ];++ // The title and the label this table has just written come back as this table's own+ // reload: rebuilding the rows now would cancel the editor Tab has opened in the next cell.await fire({- getAttributeRows: () => definitionRows,- getBranchRows: () => [],- getNoteIds: () => []+ isNoteReloaded: (noteId: string, componentId?: string) => noteId === noteIds[0] && componentId !== "table-cid",+ getAttributeRows: (componentId?: string) => componentId === "table-cid" ? [] : labelRows});- expect(captured?.columnDefs).not.toBe(columnsBefore);+ expect(captured?.rowData).toBe(rowsBefore);++ // The same title change made elsewhere rebuilds the rows.+ await fire({ isNoteReloaded: (noteId: string) => noteId === noteIds[0] });+ expect(captured?.rowData?.map((row) => row.title)).toEqual([ "Renamed", "Task 2" ]);++ // As does a label changed elsewhere.+ const rowsAfterTitle = captured?.rowData;+ await fire({ getAttributeRows: () => labelRows });+ expect(captured?.rowData).not.toBe(rowsAfterTitle);});});diff --git a/apps/client/src/widgets/collections/table/data.tsx b/apps/client/src/widgets/collections/table/data.tsxindex 16257d49ac..7d6e93138c 100644--- a/apps/client/src/widgets/collections/table/data.tsx+++ b/apps/client/src/widgets/collections/table/data.tsx@@ -75,12 +75,15 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tablreturn;}- // React to external row updates. Only the rows: rebuilding the columns replaces them- // wholesale in Tabulator, which would throw away the scroll position on every edit.+ // React to external row updates, barring those this table made itself: rebuilding the rows+ // replaces them wholesale in Tabulator, which cancels the cell editor that Tab has just+ // opened — the cell the edit came from already shows what was committed to it.+ //+ // Only the rows: rebuilding the columns replaces them too, which would throw away the+ // scroll position on every edit.if (loadResults.getBranchRows().some(branch => branch.parentNoteId === note.noteId || noteIds.includes(branch.parentNoteId ?? ""))- || loadResults.getNoteIds().some(noteId => noteIds.includes(noteId))- || loadResults.getAttributeRows().some(attr => noteIds.includes(attr.noteId!))- || loadResults.getAttributeRows().some(attr => attr.name === "archived" && attr.noteId && noteIds.includes(attr.noteId))) {+ || noteIds.some(noteId => loadResults.isNoteReloaded(noteId, componentId))+ || loadResults.getAttributeRows(componentId).some(attr => noteIds.includes(attr.noteId ?? ""))) {refresh(false);return;}diff --git a/apps/client/src/widgets/collections/table/row_editing.spec.tsx b/apps/client/src/widgets/collections/table/row_editing.spec.tsxnew file mode 100644index 0000000000..fdd7db32a7--- /dev/null+++ b/apps/client/src/widgets/collections/table/row_editing.spec.tsx@@ -0,0 +1,103 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import type { CellComponent, EventCallBackMethods } from "tabulator-tables";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type Component from "../../../components/component";+import type FNote from "../../../entities/fnote";+import { setAttribute, setLabel, setLabelValues, setRelationValues } from "../../../services/attributes";+import server from "../../../services/server";+import { buildNote } from "../../../test/easy-froca";+import type AttributeDetailWidget from "../../attribute_widgets/attribute_detail";+import { ParentComponent } from "../../react/react_utils";+import useRowTableEditing from "./row_editing";++vi.mock("../../../services/attributes", () => ({+ setAttribute: vi.fn(),+ setLabel: vi.fn(),+ setLabelValues: vi.fn(),+ setRelationValues: vi.fn()+}));++describe("useRowTableEditing", () => {+ let container: HTMLElement;+ let events: Partial<EventCallBackMethods> | undefined;+ let note: FNote;++ beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ container = document.createElement("div");+ document.body.appendChild(container);+ note = buildNote({ title: "Task" });+ mount();+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ function Probe() {+ events = useRowTableEditing(+ { current: null },+ {} as AttributeDetailWidget,+ buildNote({ title: "Collection" })+ );+ return null;+ }++ function mount() {+ const parent = {+ componentId: "table-cid",+ registerHandler: () => {},+ removeHandler: () => {}+ } as unknown as Component;+ act(() => render(+ <ParentComponent.Provider value={parent}>+ <Probe />+ </ParentComponent.Provider>,+ container+ ));+ }++ /** Commits a cell as Tabulator does when the editor hands its value over. */+ async function editCell(field: string, value: unknown) {+ const cell = {+ getRow: () => ({ getData: () => ({ noteId: note.noteId }) }),+ getField: () => field,+ getValue: () => value+ } as unknown as CellComponent;+ await act(async () => { await events?.cellEdited?.(cell); });+ }++ // Every write carries the table's own component id, so that the reload it comes back as is+ // filtered out of useData rather than rebuilding the rows under the next cell's editor.+ it("stamps a title edit with the table's component id", async () => {+ await editCell("title", "Renamed");+ expect(server.put).toHaveBeenCalledWith(`notes/${note.noteId}/title`, { title: "Renamed" }, "table-cid");+ });++ it("stamps a label edit with the table's component id, normalising non-string values", async () => {+ await editCell("labels.status", "Done");+ expect(setLabel).toHaveBeenLastCalledWith(note.noteId, "status", "Done", false, "table-cid");++ await editCell("labels.done", true);+ expect(setLabel).toHaveBeenLastCalledWith(note.noteId, "done", "true", false, "table-cid");++ await editCell("labels.count", 3);+ expect(setLabel).toHaveBeenLastCalledWith(note.noteId, "count", "3", false, "table-cid");++ await editCell("labels.tag", [ "one", "two" ]);+ expect(setLabelValues).toHaveBeenCalledWith(note, "tag", [ "one", "two" ], "table-cid");+ });++ it("stamps a relation edit with the table's component id", async () => {+ await editCell("relations.owner", "targetNoteId");+ expect(setAttribute).toHaveBeenCalledWith(note, "relation", "owner", "targetNoteId", "table-cid");++ await editCell("relations.tags", [ "a", "b" ]);+ expect(setRelationValues).toHaveBeenCalledWith(note, "tags", [ "a", "b" ], "table-cid");+ });+});diff --git a/apps/client/src/widgets/collections/table/row_editing.ts b/apps/client/src/widgets/collections/table/row_editing.tsindex f70575a4f6..cc4396227f 100644--- a/apps/client/src/widgets/collections/table/row_editing.ts+++ b/apps/client/src/widgets/collections/table/row_editing.ts@@ -1,4 +1,5 @@import { RefObject } from "preact";+import { useContext } from "preact/hooks";import { EventCallBackMethods, RowComponent, Tabulator } from "tabulator-tables";import { CommandListenerData } from "../../../components/app_context";@@ -10,8 +11,14 @@ import note_create, { CreateNoteOpts } from "../../../services/note_create";import server from "../../../services/server";import AttributeDetailWidget from "../../attribute_widgets/attribute_detail";import { useLegacyImperativeHandlers } from "../../react/hooks";+import { ParentComponent } from "../../react/react_utils";export default function useRowTableEditing(api: RefObject<Tabulator>, attributeDetailWidget: AttributeDetailWidget, parentNote: FNote): Partial<EventCallBackMethods> {+ // Whose writes these are, so that useData can tell a cell this table edited itself from one+ // changed elsewhere. Rebuilding the rows for its own edit replaces them wholesale in Tabulator,+ // which cancels the editor Tab has just opened in the next cell.+ const componentId = useContext(ParentComponent)?.componentId;+// Adding new rowsuseLegacyImperativeHandlers({addNewRowCommand({ customOpts, parentNotePath: customNotePath }: CommandListenerData<"addNewRow">) {@@ -42,7 +49,7 @@ export default function useRowTableEditing(api: RefObject<Tabulator>, attributeDlet newValue = cell.getValue();if (field === "title") {- server.put(`notes/${noteId}/title`, { title: newValue });+ server.put(`notes/${noteId}/title`, { title: newValue }, componentId);return;}@@ -54,7 +61,7 @@ export default function useRowTableEditing(api: RefObject<Tabulator>, attributeDif (Array.isArray(newValue)) {const note = await froca.getNote(noteId);if (note) {- await setLabelValues(note, name, newValue as string[]);+ await setLabelValues(note, name, newValue as string[], componentId);}return;}@@ -64,16 +71,16 @@ export default function useRowTableEditing(api: RefObject<Tabulator>, attributeD} else if (typeof newValue === "number") {newValue = String(newValue);}- setLabel(noteId, name, newValue);+ setLabel(noteId, name, newValue, false, componentId);} else if (type === "relations") {const note = await froca.getNote(noteId);if (note) {// A set of targets is written as the several relations it is, as a set of// label values is.if (Array.isArray(newValue)) {- await setRelationValues(note, name, newValue as string[]);+ await setRelationValues(note, name, newValue as string[], componentId);} else {- setAttribute(note, "relation", name, newValue);+ setAttribute(note, "relation", name, newValue, componentId);}}}