Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Repair the typed-view U-b executor and close its coverage holes (#3092)
Nick Gomez2a9504e5536b
diff --git a/packages/app/src/editor/editor-rig.dom.test.tsx b/packages/app/src/editor/editor-rig.dom.test.tsxnew file mode 100644index 000000000..f46ae43bd--- /dev/null+++ b/packages/app/src/editor/editor-rig.dom.test.tsx@@ -0,0 +1,102 @@+/**+ * The contract of `pressEditorKey`, asserted on its own.+ *+ * The helper reports two things about a keystroke because "the keymap claimed+ * it" and "the document changed" are different questions, and its callers each+ * want a different one. The case where the two disagree is the reason the+ * result is a pair rather than a boolean, and no caller exercises that case+ * directly, so it is pinned here.+ */++import { cleanup } from '@testing-library/react';+import { Editor } from '@tiptap/core';+import { afterEach, describe, expect, test } from 'vitest';+import { pressEditorKey } from './editor-rig.test-helper';+import { sharedExtensions } from './extensions/shared';++const mounted: { editor: Editor; container: HTMLDivElement }[] = [];++afterEach(() => {+ for (const { editor, container } of mounted.splice(0)) {+ editor.destroy();+ container.remove();+ }+ cleanup();+});++function mount(content: string): Editor {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const editor = new Editor({+ element: container,+ content,+ extensions: sharedExtensions,+ editable: true,+ });+ editor.view.focus();+ // A view that reports no focus measures every focus-gated plugin as dormant,+ // so a rig that quietly lost focus would score a keystroke against half an+ // editor. Fail at the mount rather than inside an assertion.+ if (!editor.view.hasFocus()) {+ throw new Error('editor-rig mount: the view did not take focus');+ }+ mounted.push({ editor, container });+ return editor;+}++describe('pressEditorKey', () => {+ test('a key the keymap claims comes back handled', () => {+ const editor = mount('<p>alpha</p>');+ editor.commands.setTextSelection(3);++ expect(pressEditorKey(editor, 'Enter')).toEqual({ handled: true, docMoved: true });+ });++ test('a key nothing claims comes back unhandled', () => {+ const editor = mount('<p>alpha</p>');+ editor.commands.setTextSelection(3);++ expect(pressEditorKey(editor, 'F9')).toEqual({ handled: false, docMoved: false });+ });++ test('a key that only moves the selection is handled and moves no document', () => {+ // Enter inside a table cell: the table keymap claims it and advances the+ // caret to the next cell without touching the document. A single boolean+ // would have to call this either "handled", losing the fact that no new+ // typed bytes were reached, or "nothing happened", losing the fact that the+ // key was consumed and no native edit would follow it in a browser. Every+ // caller outside this file reads `docMoved`; `handled` is the half nothing+ // else reads, which is why the disagreement is pinned here.+ const editor = mount('<p></p>');+ editor.commands.insertTable({ rows: 2, cols: 2, withHeaderRow: true });+ editor.commands.insertContent('a');++ const docBefore = editor.state.doc;+ const selectionBefore = editor.state.selection.from;++ expect(pressEditorKey(editor, 'Enter')).toEqual({ handled: true, docMoved: false });+ expect(editor.state.doc.eq(docBefore)).toBe(true);+ expect(editor.state.selection.from).not.toBe(selectionBefore);+ });++ test('a Mod- chord reaches its handler and lands in the stored marks', () => {+ // The `Mod` prefix is the one part of the shortcut parse that resolves+ // differently per platform, and nothing else in this file exercises it, so+ // a drift in that mapping would surface only as a downstream chord test+ // failing for an unrelated-looking reason.+ //+ // A mark chord at a collapsed caret is also the second shape of the+ // handled/docMoved disagreement, and a different one from the table case+ // above: no selection moves either. The whole effect lands in the stored+ // marks, which is precisely what a steps-only replay used to discard, so+ // this doubles as the primitive-level pin for that half of the repair.+ const editor = mount('<p>alpha</p>');+ editor.commands.setTextSelection(3);++ const docBefore = editor.state.doc;++ expect(pressEditorKey(editor, 'Mod-b')).toEqual({ handled: true, docMoved: false });+ expect(editor.state.doc.eq(docBefore)).toBe(true);+ expect(editor.state.storedMarks?.map((mark) => mark.type.name)).toEqual(['strong']);+ });+});diff --git a/packages/app/src/editor/editor-rig.test-helper.ts b/packages/app/src/editor/editor-rig.test-helper.tsindex 73b55ded8..9f75c33e6 100644--- a/packages/app/src/editor/editor-rig.test-helper.ts+++ b/packages/app/src/editor/editor-rig.test-helper.ts@@ -11,7 +11,7 @@*/import { LinkFidelity } from '@inkeep/open-knowledge-core';-import { Editor, type Extensions } from '@tiptap/core';+import { Editor, type Extensions, isiOS, isMacOS } from '@tiptap/core';import Collaboration from '@tiptap/extension-collaboration';import StarterKit from '@tiptap/starter-kit';import { yUndoPluginKey } from '@tiptap/y-tiptap';@@ -87,6 +87,80 @@ export function firstLinkAttrs(editor: Editor): Record<string, unknown> | null {return attrs;}+/**+ * Resolve a TipTap shortcut string to the physical chord its keymap bindings+ * were normalized against, then build the `keydown` event for that chord. Kept+ * in step with TipTap's own `keyboardShortcut` normalization, including its+ * `Mod` -> Meta/Ctrl platform split, so a binding registered as 'Mod-u'+ * receives the same event here as it does in the product.+ */+function shortcutToKeydownEvent(shortcut: string): KeyboardEvent {+ const parts = shortcut.split(/-(?!$)/);+ let result = parts[parts.length - 1];+ if (result === 'Space') result = ' ';++ let alt = false;+ let ctrl = false;+ let shift = false;+ let meta = false;+ for (let i = 0; i < parts.length - 1; i += 1) {+ const mod = parts[i];+ if (/^(cmd|meta|m)$/i.test(mod)) meta = true;+ else if (/^a(lt)?$/i.test(mod)) alt = true;+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;+ else if (/^s(hift)?$/i.test(mod)) shift = true;+ else if (/^mod$/i.test(mod)) {+ if (isiOS() || isMacOS()) meta = true;+ else ctrl = true;+ } else throw new Error(`Unrecognized modifier name: ${mod}`);+ }++ return new KeyboardEvent('keydown', {+ key: result,+ altKey: alt,+ ctrlKey: ctrl,+ metaKey: meta,+ shiftKey: shift,+ bubbles: true,+ cancelable: true,+ });+}++/**+ * Press a key on a mounted editor by dispatching a real `keydown` at the+ * ProseMirror DOM, so the whole keymap chain runs the way it does for a user.+ *+ * Two hazards this exists to close:+ *+ * 1. `editor.commands.keyboardShortcut(name)` does not press a key. It captures+ * the transaction the keymap produced, then re-applies only that+ * transaction's `steps`, remapped through a mapping that has already+ * accumulated them. Selection, stored marks and every `setMeta` are dropped,+ * a multi-step transaction lands at shifted positions, and the command+ * returns `true` whether or not anything handled the key.+ * 2. "The document changed" is not "the key was handled". A key that only moves+ * the selection is handled and leaves the document identical, so a single+ * boolean collapses those two outcomes into one. Both are reported here so a+ * caller has to say which one it means.+ *+ * Focus is a third hazard and stays the caller's job, because it belongs at+ * mount rather than at each key: `editor.commands.focus()` defers the real DOM+ * focus into a `requestAnimationFrame`, so a synchronous read after it sees an+ * unfocused view and any plugin gated on `view.hasFocus()` stays dormant. Call+ * `editor.view.focus()` instead. The Playwright-tier write-up of the same trap,+ * including why `view.focus()` beats `view.dom.focus()`, is in+ * `packages/app/tests/stress/_helpers/editor-state.ts`.+ */+export function pressEditorKey(+ editor: Editor,+ shortcut: string,+): { handled: boolean; docMoved: boolean } {+ const before = editor.state.doc;+ const event = shortcutToKeydownEvent(shortcut);+ editor.view.dom.dispatchEvent(event);+ return { handled: event.defaultPrevented, docMoved: editor.state.doc !== before };+}+/** Distinct hrefs carried by link marks anywhere in the doc. */export function linkHrefs(editor: Editor): string[] {const hrefs = new Set<string>();diff --git a/packages/app/src/editor/extensions/shared.dom.test.tsx b/packages/app/src/editor/extensions/shared.dom.test.tsxindex 4c042b2a6..a19cf35a8 100644--- a/packages/app/src/editor/extensions/shared.dom.test.tsx+++ b/packages/app/src/editor/extensions/shared.dom.test.tsx@@ -2,6 +2,7 @@ import { cleanup } from '@testing-library/react';import { Editor } from '@tiptap/core';import { NodeSelection } from '@tiptap/pm/state';import { afterEach, describe, expect, test } from 'vitest';+import { pressEditorKey } from '../editor-rig.test-helper';import { sharedExtensions } from './shared';describe('sharedExtensions module graph', () => {@@ -178,7 +179,7 @@ describe('sharedExtensions module graph', () => {editor.commands.setTextSelection({ from: 1, to: 6 });expect(editor.isActive('strike')).toBe(false);- editor.commands.keyboardShortcut('Mod-Shift-x');+ pressEditorKey(editor, 'Mod-Shift-x');expect(editor.isActive('strike')).toBe(true);expect(editor.getHTML()).toContain('<s>alpha</s>');} finally {diff --git a/packages/app/tests/dom/serializer-seam-rederive.dom.test.tsx b/packages/app/tests/dom/serializer-seam-rederive.dom.test.tsxindex d8a5eefa3..de341d740 100644--- a/packages/app/tests/dom/serializer-seam-rederive.dom.test.tsx+++ b/packages/app/tests/dom/serializer-seam-rederive.dom.test.tsx@@ -22,6 +22,7 @@ import { MarkdownManager, stripFrontmatter } from '@inkeep/open-knowledge-core';import { cleanup } from '@testing-library/react';import { Editor, type JSONContent } from '@tiptap/core';import { afterEach, describe, expect, test } from 'vitest';+import { pressEditorKey } from '../../src/editor/editor-rig.test-helper';import { sharedExtensions } from '../../src/editor/extensions/shared';/** Configured as the server's shared manager is. */@@ -45,13 +46,6 @@ function mountEditor(): Editor {return editor;}-/** Press a key through the keymap; report whether the document actually moved. */-function pressKey(editor: Editor, shortcut: string): boolean {- const before = editor.state.doc;- editor.commands.keyboardShortcut(shortcut);- return editor.state.doc !== before;-}-/** Type text the way the view feeds it, so input rules get their chance. */function type(editor: Editor, characters: string): void {for (const character of characters) {@@ -93,7 +87,7 @@ describe('Shift+Enter at the end of a block', () => {test('the break the user typed is still there after re-derivation', () => {const editor = mountEditor();type(editor, 'foo');- expect(pressKey(editor, 'Shift-Enter')).toBe(true);+ expect(pressEditorKey(editor, 'Shift-Enter').docMoved).toBe(true);const typed = editor.getJSON();expect(countNodes(typed, 'hardBreak')).toBe(1);@@ -104,10 +98,10 @@ describe('Shift+Enter at the end of a block', () => {test('a break typed before an existing paragraph survives too', () => {const editor = mountEditor();type(editor, 'foo');- expect(pressKey(editor, 'Enter')).toBe(true);+ expect(pressEditorKey(editor, 'Enter').docMoved).toBe(true);type(editor, 'bar');editor.commands.setTextSelection(4);- expect(pressKey(editor, 'Shift-Enter')).toBe(true);+ expect(pressEditorKey(editor, 'Shift-Enter').docMoved).toBe(true);const typed = editor.getJSON();expect(countNodes(rederive(typed), 'hardBreak')).toBe(countNodes(typed, 'hardBreak'));@@ -116,7 +110,7 @@ describe('Shift+Enter at the end of a block', () => {test('CONTROL: a mid-paragraph break keeps the backslash spelling', () => {const editor = mountEditor();type(editor, 'foo');- expect(pressKey(editor, 'Shift-Enter')).toBe(true);+ expect(pressEditorKey(editor, 'Shift-Enter').docMoved).toBe(true);type(editor, 'bar');const typed = editor.getJSON();@@ -144,10 +138,10 @@ describe('an empty task item', () => {const editor = mountEditor();expect(editor.commands.toggleTaskList()).toBe(true);type(editor, 'a');- expect(pressKey(editor, 'Enter')).toBe(true);+ expect(pressEditorKey(editor, 'Enter').docMoved).toBe(true);type(editor, 'c');editor.commands.setTextSelection(3);- expect(pressKey(editor, 'Enter')).toBe(true);+ expect(pressEditorKey(editor, 'Enter').docMoved).toBe(true);const typed = editor.getJSON();const typedChecked = checkedAttrs(typed);diff --git a/packages/app/tests/dom/underline-round-trip.dom.test.tsx b/packages/app/tests/dom/underline-round-trip.dom.test.tsxindex 471444905..94e5a6049 100644--- a/packages/app/tests/dom/underline-round-trip.dom.test.tsx+++ b/packages/app/tests/dom/underline-round-trip.dom.test.tsx@@ -31,6 +31,7 @@ import { AllSelection, EditorState } from '@tiptap/pm/state';import { EditorView } from '@tiptap/pm/view';import { afterEach, describe, expect, test } from 'vitest';import { createHandlePaste } from '../../src/editor/clipboard/handle-paste';+import { pressEditorKey } from '../../src/editor/editor-rig.test-helper';const mdManager = new MarkdownManager({extensions: sharedExtensions,@@ -109,9 +110,8 @@ function textUnderMark(doc: JSONContent, markName: string): string {/*** Apply `Mod-U` over a typed run the way the keymap does: insert the prose,- * select the range, dispatch the chord. `keyboardShortcut` reports that it- * dispatched rather than that a handler consumed, so the mark itself is- * asserted before anything downstream is measured.+ * select the range, press the chord. The mark itself is asserted before+ * anything downstream is measured.*/function typeUnderlined(editor: Editor, before: string, underlined: string): void {editor.commands.insertContent(before);@@ -119,7 +119,7 @@ function typeUnderlined(editor: Editor, before: string, underlined: string): voieditor.commands.insertContent(underlined);const end = editor.state.selection.from;editor.commands.setTextSelection({ from: start, to: end });- editor.commands.keyboardShortcut('Mod-u');+ pressEditorKey(editor, 'Mod-u');editor.commands.setTextSelection(end);}@@ -190,7 +190,7 @@ describe('route 1 — Mod-U typed underline', () => {editor.commands.insertContent('x');editor.commands.setTextSelection({ from: 1, to: 2 });for (const chord of ['Mod-u', 'Mod-b', 'Mod-i', 'Mod-e']) {- editor.commands.keyboardShortcut(chord);+ pressEditorKey(editor, chord);}const applied = marksOn(editor.getJSON(), 'x');expect(applied).toEqual(expect.arrayContaining(['underline', 'strong', 'emphasis', 'code']));