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(table): keep a cell open when it adds an option to its column
Elian Doran00bff43d632e
diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.tsindex 1e24544034..79be8ac7e9 100644--- a/apps/client/src/widgets/collections/table/columns.spec.ts+++ b/apps/client/src/widgets/collections/table/columns.spec.ts@@ -163,13 +163,17 @@ describe("buildColumnDefinitions — select columns", () => {return params({} as CellComponent) as SelectEditorParams;}- function selectColumn(onCreateSelectOption?: (columnName: string, option: string) => void) {+ function selectColumn(+ onCreateSelectOption?: (columnName: string, option: string) => void,+ currentSelectOptions?: (columnName: string) => string[] | undefined+ ) {const columns = buildColumnDefinitions({info: [ { name: "status", type: "select", options: [ "Todo", "Done" ] } ],movableRows: false,existingColumnData: undefined,rowNumberHint: 1,- onCreateSelectOption+ onCreateSelectOption,+ currentSelectOptions});return columns.find((column) => column.field === "labels.status");}@@ -185,6 +189,20 @@ describe("buildColumnDefinitions — select columns", () => {expect(onCreateSelectOption).toHaveBeenCalledWith("status", "Blocked");});+ it("asks for the options as a cell is opened, so one just created is already among them", () => {+ // A cell can add an option to the definition, and the table does not rebuild its columns for+ // a change of its own — so a column built before that must not answer with what it was built+ // with, or the option would go missing until something else rebuilt the table.+ const currentSelectOptions = vi.fn(() => [ "Todo", "Done", "Blocked" ]);+ const params = editorParamsOf(selectColumn(undefined, currentSelectOptions));++ expect(params.options).toEqual([ "Todo", "Done", "Blocked" ]);+ expect(currentSelectOptions).toHaveBeenCalledWith("status");++ // Asked but unanswered — a column whose definition has since gone — falls back to its own.+ expect(editorParamsOf(selectColumn(undefined, () => undefined)).options).toEqual([ "Todo", "Done" ]);+ });+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();diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsxindex 67b5f382a4..aeada477aa 100644--- a/apps/client/src/widgets/collections/table/columns.tsx+++ b/apps/client/src/widgets/collections/table/columns.tsx@@ -139,9 +139,15 @@ interface BuildColumnArgs {* the column does not list yet. Omitted, such a value cannot be created from a cell.*/onCreateSelectOption?: (columnName: string, option: string) => void | Promise<void>;+ /**+ * The options a select column offers, asked for as a cell is opened. A definition can gain an+ * option from the very editor that is open, which the columns as built know nothing about — so+ * where this is left out, or answers nothing, a cell falls back to the options it was built with.+ */+ currentSelectOptions?: (columnName: string) => string[] | undefined;}-export function buildColumnDefinitions({ info, movableRows, existingColumnData, rowNumberHint, position, onCreateSelectOption }: BuildColumnArgs) {+export function buildColumnDefinitions({ info, movableRows, existingColumnData, rowNumberHint, position, onCreateSelectOption, currentSelectOptions }: BuildColumnArgs) {let columnDefs: ColumnDefinition[] = [{title: "#",@@ -189,10 +195,12 @@ export function buildColumnDefinitions({ info, movableRows, existingColumnData,rowHandle: false,...labelTypeMappings[type ?? "text"],// 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.+ // a function because that is the shape Tabulator types for params of an editor's own —+ // which also means the options are answered for as each cell is opened, late enough to+ // include one the definition has just been given....(type === "select" && {editorParams: (): Record<string, unknown> => ({- options: options ?? [],+ options: currentSelectOptions?.(name) ?? options ?? [],isMulti,onCreateOption: onCreateSelectOption&& ((option: string) => onCreateSelectOption(name, option))diff --git a/apps/client/src/widgets/collections/table/data.tsx b/apps/client/src/widgets/collections/table/data.tsxindex f9ea9409a2..81decfa25c 100644--- a/apps/client/src/widgets/collections/table/data.tsx+++ b/apps/client/src/widgets/collections/table/data.tsx@@ -1,7 +1,8 @@import type { ColumnDefinition } from "tabulator-tables";import FNote from "../../../entities/fnote";import { useNoteLabelBoolean, useNoteLabelInt, useTriliumEvent } from "../../react/hooks";-import { useEffect, useState } from "preact/hooks";+import { ParentComponent } from "../../react/react_utils";+import { useContext, useEffect, useState } from "preact/hooks";import getAttributeDefinitionInformation, { buildRowDefinitions, TableData } from "./rows";import froca from "../../../services/froca";import { buildColumnDefinitions } from "./columns";@@ -17,6 +18,9 @@ export interface TableConfig {export default function useData(note: FNote, noteIds: string[], viewConfig: TableConfig | undefined, newAttributePosition: RefObject<number | undefined> | undefined, resetNewAttributePosition: () => void) {const [ maxDepth ] = useNoteLabelInt(note, "maxNestingDepth");const [ includeArchived ] = useNoteLabelBoolean(note, "includeArchived");+ // Whose writes these are, so that the table can tell a definition it changed itself from one+ // changed elsewhere — rebuilding for its own would pull the open editor out from under the user.+ const componentId = useContext(ParentComponent)?.componentId;const [ columnDefs, setColumnDefs ] = useState<ColumnDefinition[]>();const [ rowData, setRowData ] = useState<TableData[]>();@@ -37,7 +41,12 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: TablexistingColumnData: viewConfig?.tableData?.columns,rowNumberHint: rowNumber,position: newAttributePosition?.current ?? undefined,- onCreateSelectOption: (columnName, option) => addSelectOption(note, columnName, option)+ // Read from the note as a cell is opened rather than taken from `info`, which was read+ // when the columns were last built: a definition can gain an option from the very editor+ // that is open, and the table does not rebuild for a change of its own.+ currentSelectOptions: (columnName) => getAttributeDefinitionInformation(note)+ .find((definition) => definition.name === columnName)?.options,+ onCreateSelectOption: (columnName, option) => addSelectOption(note, columnName, option, componentId)});setColumnDefs(columnDefs);setRowData(rowData);@@ -50,8 +59,10 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: TabluseTriliumEvent("entitiesReloaded", ({ loadResults}) => {if (glob.device === "print") return;- // React to column changes.- if (loadResults.getAttributeRows().find(attr =>+ // React to column changes, barring those this table made itself: rebuilding the columns+ // replaces them wholesale, which takes down the editor that asked for the change — losing,+ // in a multi-valued cell, the values gathered but not yet handed over.+ if (loadResults.getAttributeRows(componentId).find(attr =>attr.type === "label" &&(attr.name?.startsWith("label:") || attr.name?.startsWith("relation:")) &&attributes.isAffecting(attr, note))) {@@ -82,13 +93,14 @@ export default function useData(note: FNote, noteIds: string[], viewConfig: Tabl* 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.+ * Stamped with the table's own component id, so that the reload it causes does not rebuild the+ * columns underneath the editor that asked for it. The option still reaches the cache, which is+ * where a cell being opened reads the choices it offers.*/-async function addSelectOption(parentNote: FNote, columnName: string, option: string) {+async function addSelectOption(parentNote: FNote, columnName: string, option: string, componentId?: string) {const definitionAttr = parentNote.getAttributeDefinitions().find((attr) => attr.name === `label:${columnName}`);if (definitionAttr) {- await attributes.addSelectOption(definitionAttr, option);+ await attributes.addSelectOption(definitionAttr, option, componentId);}}