A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
editor: stop rebuilding table state on every keystroke
Ammar Ahmedc1a4629c59c5
diff --git a/packages/editor/src/extensions/table/__tests__/column-resizing.test.ts b/packages/editor/src/extensions/table/__tests__/column-resizing.test.tsnew file mode 100644index 000000000..bddf54ad6--- /dev/null+++ b/packages/editor/src/extensions/table/__tests__/column-resizing.test.ts@@ -0,0 +1,126 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/+import { Editor, Node } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import TableRow from "@tiptap/extension-table-row";+import { describe, expect, test, vi } from "vitest";+import { TableMap } from "../prosemirror-tables/tablemap.js";+import TableCell from "../../table-cell/index.js";+import TableHeader from "../../table-header/index.js";+import { columnResizingPluginKey } from "../prosemirror-tables/columnresizing.js";+import { Table } from "../index.js";++const Document = Node.create({+ name: "doc",+ topNode: true,+ content: "block+"+});++function createEditor(rows: number) {+ let html = `<p>intro</p><table><tbody>`;+ for (let i = 0; i < rows; i++)+ html += `<tr><td><p>Cell ${i}</p></td><td><p>Value ${i}</p></td></tr>`;+ html += "</tbody></table>";++ return new Editor({+ extensions: [+ StarterKit.configure({ document: false }),+ Table.configure({ resizable: true }),+ TableRow,+ TableCell,+ TableHeader,+ Document+ ],+ content: html+ });+}++/** The handle elements themselves, to tell reuse from rebuilding. */+function handleElements(editor: Editor) {+ return (+ columnResizingPluginKey+ .getState(editor.state)+ ?.decorations.find()+ .map(+ (decoration) =>+ (decoration as unknown as { type: { toDOM: Node } }).type.toDOM+ ) ?? []+ );+}++/** How many handles were built, drawn or not. */+function handles(editor: Editor) {+ return (+ columnResizingPluginKey.getState(editor.state)?.decorations.find().length ??+ 0+ );+}++describe("column resize handles", () => {+ test("a small table gets a handle for every cell", async () => {+ const editor = createEditor(10);+ await new Promise((r) => setTimeout(r, 0));++ editor.commands.setTextSelection(12);+ expect(handles(editor)).toBe(20);+ editor.destroy();+ });++ test("typing does not rebuild the handles", async () => {+ const editor = createEditor(2000);+ await new Promise((r) => setTimeout(r, 0));++ // put the caret in a cell inside the rendered run, where typing moves the+ // end of that run along with it+ const table = editor.state.doc.child(1);+ let at = editor.state.doc.child(0).nodeSize + 1;+ for (let i = 0; i < 5; i++) at += table.child(i).nodeSize;+ editor.commands.setTextSelection(at + 3);++ const before = handleElements(editor);+ expect(before.length).toBeGreaterThan(0);+ editor.commands.insertContent("x");+ editor.commands.insertContent("y");++ // mapped along with the text rather than built again, so they are the very+ // same handles. Compared by identity: two freshly built handles look alike.+ const after = handleElements(editor);+ expect(after).toHaveLength(before.length);+ expect(after[0]).toBe(before[0]);+ editor.destroy();+ });++ test("typing does not build the table map again", () => {+ // building the handles walks the map, and the map walks every cell of the+ // table -- far too much to do on every keystroke+ const editor = createEditor(2000);+ const table = editor.state.doc.child(1);+ let at = editor.state.doc.child(0).nodeSize + 1;+ for (let i = 0; i < 5; i++) at += table.child(i).nodeSize;+ editor.commands.setTextSelection(at + 3);+ editor.commands.insertContent("x");++ const built = vi.spyOn(TableMap, "get");+ editor.commands.insertContent("y");+ expect(built).not.toHaveBeenCalled();++ built.mockRestore();+ editor.destroy();+ });+});diff --git a/packages/editor/src/extensions/table/__tests__/fix-tables.test.ts b/packages/editor/src/extensions/table/__tests__/fix-tables.test.tsnew file mode 100644index 000000000..779929209--- /dev/null+++ b/packages/editor/src/extensions/table/__tests__/fix-tables.test.ts@@ -0,0 +1,123 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/+import { Editor, Node } from "@tiptap/core";+import StarterKit from "@tiptap/starter-kit";+import TableRow from "@tiptap/extension-table-row";+import { describe, expect, test, vi } from "vitest";+import { TableMap } from "../prosemirror-tables/tablemap.js";+import TableCell from "../../table-cell/index.js";+import TableHeader from "../../table-header/index.js";+import { Table } from "../index.js";++const Document = Node.create({ name: "doc", topNode: true, content: "block+" });++function createEditor(content: string) {+ return new Editor({+ extensions: [+ StarterKit.configure({ document: false }),+ Document,+ Table,+ TableRow,+ TableCell,+ TableHeader+ ],+ content+ });+}++function rows(cells: string[][]) {+ return cells+ .map((row) => `<tr>${row.map((c) => `<td><p>${c}</p></td>`).join("")}</tr>`)+ .join("");+}++describe("fixing tables", () => {+ test("a row short of a cell is filled in on the first edit", () => {+ const editor = createEditor(+ `<table><tbody>${rows([["a", "b"], ["c"]])}</tbody></table>`+ );+ expect(editor.state.doc.child(0).child(1).childCount).toBe(1);++ editor.commands.setTextSelection(4);+ editor.commands.insertContent("!");++ expect(editor.state.doc.child(0).child(1).childCount).toBe(2);+ editor.destroy();+ });++ test("editing a cell leaves the shape alone", () => {+ const editor = createEditor(+ `<table><tbody>${rows([+ ["a", "b"],+ ["c", "d"]+ ])}</tbody></table>`+ );+ editor.commands.setTextSelection(4);+ editor.commands.insertContent("!");++ const table = editor.state.doc.child(0);+ expect(table.childCount).toBe(2);+ expect(table.child(0).childCount).toBe(2);+ expect(editor.getText()).toContain("!");+ editor.destroy();+ });++ test("editing a cell does not build the table map again", () => {+ // the map is what makes checking a table expensive: it walks every cell,+ // and it is rebuilt whenever the table node changes -- which is every+ // keystroke inside one+ const editor = createEditor(+ `<table><tbody>${rows([+ ["a", "b"],+ ["c", "d"]+ ])}</tbody></table>`+ );+ editor.commands.setTextSelection(4);+ editor.commands.insertContent("!");++ const built = vi.spyOn(TableMap, "get");+ editor.commands.insertContent("?");+ expect(built).not.toHaveBeenCalled();++ built.mockRestore();+ editor.destroy();+ });++ test("a row deleted down to nothing is still repaired", () => {+ const editor = createEditor(+ `<table><tbody>${rows([+ ["a", "b"],+ ["c", "d"]+ ])}</tbody></table>`+ );+ const table = editor.state.doc.child(0);+ const secondRow = 1 + table.child(0).nodeSize;+ // drop one cell from the second row, leaving the table ragged+ editor.view.dispatch(+ editor.state.tr.delete(+ secondRow + 1,+ secondRow + 1 + table.child(1).child(0).nodeSize+ )+ );++ const fixed = editor.state.doc.child(0);+ expect(fixed.child(1).childCount).toBe(2);+ editor.destroy();+ });+});diff --git a/packages/editor/src/extensions/table/prosemirror-tables/columnresizing.ts b/packages/editor/src/extensions/table/prosemirror-tables/columnresizing.tsindex b39bb011a..7ccb6bb17 100644--- a/packages/editor/src/extensions/table/prosemirror-tables/columnresizing.ts+++ b/packages/editor/src/extensions/table/prosemirror-tables/columnresizing.ts@@ -120,6 +120,7 @@ export function columnResizing({type ResizeState = {dragging: Dragging | false;decorations: DecorationSet;+ builtFor?: { cell: number };};function createResizeState(@@ -138,15 +139,24 @@ function createResizeState(const cell = edgeCell(state, state.selection.from, "right");if (cell === -1) {copy.decorations = DecorationSet.empty;+ copy.builtFor = undefined;} else {- const handles = createColumnResizeHandles(- state,- cell,- prevState,- showResizeHandleOnSelection- );- if (handles) {- copy.decorations = handles;+ const was = prevState.builtFor;+ const built =+ was && tr.docChanged ? { cell: tr.mapping.map(was.cell) } : was;++ copy.builtFor = built;+ if (!built || built.cell !== cell) {+ const handles = createColumnResizeHandles(+ state,+ cell,+ prevState,+ showResizeHandleOnSelection+ );+ if (handles) {+ copy.decorations = handles;+ copy.builtFor = { cell };+ }}}}@@ -407,9 +417,18 @@ export function createColumnResizeHandles(return null;}+ const sizes = new Map<number, number>();+ table.forEach((row, rowOffset) => {+ row.forEach((cell, cellOffset) =>+ sizes.set(rowOffset + 1 + cellOffset, cell.nodeSize)+ );+ });+for (let i = 0; i < totalCells; i++) {const cellPos = map.map[i];- const pos = start + cellPos + table.nodeAt(cellPos)!.nodeSize - 1;+ const size = sizes.get(cellPos);+ if (size === undefined) continue;+ const pos = start + cellPos + size - 1;decorations.push(Decoration.widget(pos,diff --git a/packages/editor/src/extensions/table/prosemirror-tables/fixtables.ts b/packages/editor/src/extensions/table/prosemirror-tables/fixtables.tsindex 920ba1e5b..0d581e642 100644--- a/packages/editor/src/extensions/table/prosemirror-tables/fixtables.ts+++ b/packages/editor/src/extensions/table/prosemirror-tables/fixtables.ts@@ -1,8 +1,26 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/+// This file defines helpers for normalizing tables, making sure no// cells overlap (which can happen, if you have the wrong col- and// rowspans) and that each row has the same width. Uses the problems// reported by `TableMap`.-import { Node } from "prosemirror-model";import { EditorState, PluginKey, Transaction } from "prosemirror-state";import { tableNodeTypes, TableRole } from "./schema.js";@@ -29,16 +47,53 @@ export function fixTables(oldState?: EditorState): Transaction | undefined {let tr: Transaction | undefined;- const check = (node: Node, pos: number) => {- if (node.type.spec.tableRole == "table")- tr = fixTable(state, node, pos, tr);+ const check = (node: Node, pos: number, was?: Node) => {+ if (node.type.spec.tableRole != "table") return;+ if (was && wellFormed.get(was) && sameShape(was, node)) {+ wellFormed.set(node, true);+ return;+ }+ tr = fixTable(state, node, pos, tr);};- if (!oldState) state.doc.descendants(check);+ if (!oldState) state.doc.descendants((node, pos) => check(node, pos));else if (oldState.doc != state.doc)changedDescendants(oldState.doc, state.doc, 0, check);return tr;}+/**+ * Tables already found to be well formed. Checking one properly means walking+ * every cell, which is far too much to do on every keystroke, so a table that+ * was sound last time and has not changed shape since is taken on trust.+ */+const wellFormed = new WeakMap<Node, boolean>();++/**+ * Whether two versions of a table have the same cells in the same places.+ *+ * What can be wrong with a table -- a cell missing, two cells laid over each+ * other -- follows entirely from that, so a table whose shape has not moved has+ * nothing new to fix. Typing in a cell leaves every row but one untouched, so+ * this is mostly pointer comparisons, where working the answer out from the+ * table itself means walking every cell of it on every keystroke.+ */+function sameShape(before: Node, after: Node): boolean {+ if (before.childCount != after.childCount) return false;+ for (let row = 0; row < after.childCount; row++) {+ const was = before.child(row);+ const now = after.child(row);+ if (was == now) continue;+ if (was.childCount != now.childCount) return false;+ for (let cell = 0; cell < now.childCount; cell++) {+ const before = was.child(cell).attrs;+ const after = now.child(cell).attrs;+ if (before.colspan != after.colspan || before.rowspan != after.rowspan)+ return false;+ }+ }+ return true;+}+// Fix the given table, if necessary. Will append to the transaction// it was given, if non-null, or create a new one if necessary.export function fixTable(@@ -48,7 +103,10 @@ export function fixTable(tr: Transaction | undefined): Transaction | undefined {const map = TableMap.get(table);- if (!map.problems) return tr;+ if (!map.problems) {+ wellFormed.set(table, true);+ return tr;+ }if (!tr) tr = state.tr;// Track which rows we must add cells to, so that we can adjust that