Compare commits

...

2 Commits

Author SHA1 Message Date
lucaronin
cd9e5fc403 fix: guard table resize against stale editor views 2026-04-11 16:37:44 +02:00
lucaronin
798a6b2125 refactor: make shortcut execution renderer-first 2026-04-11 15:42:53 +02:00
17 changed files with 554 additions and 93 deletions

View File

@@ -727,12 +727,13 @@ Data flows unidirectionally: `App` passes data and callbacks as props to child c
Selection-dependent note actions are wired through both the command palette and the native Note menu. For example, a deleted file opened from Changes view becomes a read-only diff preview, and that state enables the "Restore Deleted Note" menu/command while normal note mutation actions stay disabled.
Shortcut ownership is explicit:
Shortcut routing is explicit:
- `appCommandCatalog.ts` is the shared shortcut manifest for command IDs, modifier rules, and ownership
- Renderer-owned shortcuts flow through `useAppKeyboard` into `appCommandDispatcher.ts`
- Native-owned shortcuts flow through `menu.rs` into `useMenuEvents`, then into `appCommandDispatcher.ts`
- Deterministic QA uses `trigger_menu_command` in Tauri and `window.__laputaTest.triggerMenuCommand()` in browser runs to exercise the native-menu command path without flaky macOS key synthesis
- `appCommandCatalog.ts` is the shared shortcut manifest for command IDs and modifier rules
- `useAppKeyboard` is the primary execution path for real shortcut keypresses, including Tauri runs
- `menu.rs` and `useMenuEvents` emit the same command IDs for native menu clicks and accelerators
- `appCommandDispatcher.ts` suppresses the paired native-menu/renderer echo from a single shortcut so the command runs once
- Deterministic QA uses both real key events in a Tauri-like environment and `trigger_menu_command` to prove the keyboard path and the native menu path without relying on flaky macOS key synthesis
## Auto-Release & In-App Updates

View File

@@ -97,7 +97,7 @@ laputa-app/
│ │ ├── useCommandRegistry.ts # Command palette registry
│ │ ├── useAppCommands.ts # App-level commands
│ │ ├── useAppKeyboard.ts # Keyboard shortcuts
│ │ ├── appCommandCatalog.ts # Shortcut ownership + command metadata
│ │ ├── appCommandCatalog.ts # Shortcut combos + command metadata
│ │ ├── appCommandDispatcher.ts # Shared shortcut/menu command IDs + dispatch
│ │ ├── useSettings.ts # App settings
│ │ ├── useOnboarding.ts # First-launch flow
@@ -282,11 +282,11 @@ type SidebarSelection =
### Command Registry
`useCommandRegistry` + `useAppCommands` build a centralized command registry. Commands are registered with labels, shortcuts, and handlers. The `CommandPalette` (Cmd+K) fuzzy-searches this registry. Shortcut ownership now lives in `appCommandCatalog.ts`: renderer shortcuts (`useAppKeyboard`) resolve commands from that catalog, native menu events (`useMenuEvents`) emit the same command IDs, and `appCommandDispatcher.ts` owns execution rather than duplicate shortcut facts.
`useCommandRegistry` + `useAppCommands` build a centralized command registry. Commands are registered with labels, shortcuts, and handlers. The `CommandPalette` (Cmd+K) fuzzy-searches this registry. Shortcut combos live in `appCommandCatalog.ts`; real keypresses always flow through `useAppKeyboard`, native menu clicks emit the same command IDs through `useMenuEvents`, and `appCommandDispatcher.ts` suppresses the duplicate native/renderer echo from a single shortcut.
Commands whose availability depends on the current note or Git state must also flow through `update_menu_state` so the native menu stays in sync with the command palette. The deleted-note restore action in Changes view is the reference example: the row opens a deleted diff preview, the command palette exposes "Restore Deleted Note", and the Note menu enables the same action only while that preview is active.
For automated QA, prefer the `window.__laputaTest.triggerMenuCommand()` bridge for native-owned shortcuts and `window.__laputaTest.dispatchAppCommand()` only for renderer-only command paths. Do not treat flaky synthesized macOS keystrokes as proof that a native accelerator works.
For automated QA, prefer real key events in a Tauri-like environment for shortcut behavior and `window.__laputaTest.triggerMenuCommand()` for the native menu click path. Do not treat flaky synthesized macOS keystrokes as proof that a shortcut works.
## Running Tests
@@ -341,7 +341,7 @@ BASE_URL="http://localhost:5173" npx playwright test tests/smoke/<slug>.spec.ts
1. Register the command in `useAppCommands.ts` via the command registry
2. Add a corresponding menu bar item in `menu.rs` for discoverability
3. If it has a keyboard shortcut, register it in `appCommandCatalog.ts` with the canonical command ID, ownership (`renderer` vs `native-menu`), and modifier rule
3. If it has a keyboard shortcut, register it in `appCommandCatalog.ts` with the canonical command ID and modifier rule, then wire the matching native menu item in `menu.rs` if it should also appear in the menu bar
4. If its enabled state depends on runtime selection (active note, deleted preview, Git status, etc.), thread that flag through `useMenuEvents.ts` and `update_menu_state` so the native menu enables/disables correctly
### Modify styling

View File

@@ -0,0 +1,33 @@
---
type: ADR
id: "0052"
title: "Renderer-first shortcut execution with native-menu dedupe"
status: active
date: 2026-04-11
---
## Context
ADR 0051 gave Laputa a shared shortcut manifest and shared command IDs, but it still treated many shortcuts as native-menu-owned at execution time. In practice that meant `useAppKeyboard` deferred commands like `Cmd+Shift+I`, `Cmd+Shift+L`, and `Cmd+\` whenever the app ran under Tauri, and automated QA had to prove those flows by injecting menu-command IDs instead of pressing the real keys.
That is not a strong enough QA story for a keyboard-first app. If a user presses a shortcut while the editor is focused, we need a deterministic way to prove the actual key combo works. At the same time, we still want a native macOS menu bar with working menu items and accelerators.
## Decision
**Renderer keyboard handling is now the primary execution path for all shortcut-capable app commands, including commands that also have native menu accelerators. Native menu clicks and accelerators still emit the same command IDs, but the shared dispatcher suppresses the duplicate native/renderer echo from a single keypress so the command runs exactly once.**
## Options considered
- **Option A** (chosen): Renderer-first shortcut execution plus native-menu dedupe. This keeps shortcuts testable with real key events in a Tauri-like environment while preserving menu-bar parity and clickable native menu items. Downside: the dispatcher has to understand and suppress paired native/renderer echoes.
- **Option B**: Keep deferring native-owned shortcuts out of the renderer and prove them only through `trigger_menu_command`. Lower implementation churn, but it still leaves the real keystroke path unproven.
- **Option C**: Remove native accelerators entirely and keep shortcuts renderer-only. Simplest to reason about, but weaker desktop UX and poorer macOS menu discoverability.
## Consequences
- `appCommandCatalog.ts` remains the single manifest for command IDs and shortcut combos, but keyboard execution no longer depends on a separate owner flag.
- `useAppKeyboard` handles the actual key event for every shortcut-capable command, even in Tauri mode.
- `useMenuEvents` still handles menu clicks and test-triggered native command IDs, but shared dispatcher dedupe prevents a focused keypress from firing twice when the native menu accelerator also echoes back into the renderer.
- Deterministic QA now has two complementary proofs:
- real keyboard events in a Tauri-like environment for the actual shortcut combo
- `trigger_menu_command` for the native menu click/accelerator command path
- This ADR supersedes ADR 0051 by replacing “execution ownership lives in the manifest” with “shortcut combos live in the manifest, while execution is renderer-first and native menu dispatch is deduped.”

View File

@@ -106,4 +106,5 @@ proposed → active → superseded
| [0048](0048-relative-date-expressions-in-view-filters.md) | Relative date expressions in view filter conditions | active |
| [0049](0049-per-note-icon-property.md) | Per-note icon property (_icon on individual notes) | active |
| [0050](0050-deterministic-shortcut-command-routing.md) | Deterministic shortcut command routing | superseded → [0051](0051-shared-shortcut-manifest-for-testable-routing.md) |
| [0051](0051-shared-shortcut-manifest-for-testable-routing.md) | Shared shortcut manifest for testable routing | active |
| [0051](0051-shared-shortcut-manifest-for-testable-routing.md) | Shared shortcut manifest for testable routing | superseded → [0052](0052-renderer-first-shortcut-execution-with-native-menu-dedupe.md) |
| [0052](0052-renderer-first-shortcut-execution-with-native-menu-dedupe.md) | Renderer-first shortcut execution with native-menu dedupe | active |

View File

@@ -0,0 +1,234 @@
diff --git a/dist/index.cjs b/dist/index.cjs
index 6c65eb7d57e207a8cd1f2a2ae3bb99507c405cef..c163932957846385623eb2980bf1141eb6631db1 100644
--- a/dist/index.cjs
+++ b/dist/index.cjs
@@ -2443,6 +2443,21 @@ function handleMouseLeave(view) {
const pluginState = columnResizingPluginKey.getState(view.state);
if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging) updateHandle(view, -1);
}
+function safeDispatch(view, tr) {
+ try {
+ view.dispatch(tr);
+ return true;
+ } catch (_error) {
+ return false;
+ }
+}
+function safeDomAtPos(view, pos) {
+ try {
+ return view.domAtPos(pos);
+ } catch (_error) {
+ return null;
+ }
+}
function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
var _view$dom$ownerDocume;
if (!view.editable) return false;
@@ -2451,17 +2466,18 @@ function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging) return false;
const cell = view.state.doc.nodeAt(pluginState.activeHandle);
const width = currentColWidth(view, pluginState.activeHandle, cell.attrs);
- view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: {
+ if (width == null) return false;
+ if (!safeDispatch(view, view.state.tr.setMeta(columnResizingPluginKey, { setDragging: {
startX: event.clientX,
startWidth: width
- } }));
+ } }))) return false;
function finish(event$1) {
win.removeEventListener("mouseup", finish);
win.removeEventListener("mousemove", move);
const pluginState$1 = columnResizingPluginKey.getState(view.state);
if (pluginState$1 === null || pluginState$1 === void 0 ? void 0 : pluginState$1.dragging) {
updateColumnWidth(view, pluginState$1.activeHandle, draggedWidth(pluginState$1.dragging, event$1, cellMinWidth));
- view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }));
+ safeDispatch(view, view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }));
}
}
function move(event$1) {
@@ -2482,15 +2498,18 @@ function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
function currentColWidth(view, cellPos, { colspan, colwidth }) {
const width = colwidth && colwidth[colwidth.length - 1];
if (width) return width;
- const dom = view.domAtPos(cellPos);
- let domWidth = dom.node.childNodes[dom.offset].offsetWidth, parts = colspan;
+ const dom = safeDomAtPos(view, cellPos);
+ if (!dom) return null;
+ const cellDom = dom.node && dom.node.childNodes ? dom.node.childNodes[dom.offset] : null;
+ if (!cellDom || typeof cellDom.offsetWidth != "number") return null;
+ let domWidth = cellDom.offsetWidth, parts = colspan;
if (colwidth) {
for (let i = 0; i < colspan; i++) if (colwidth[i]) {
domWidth -= colwidth[i];
parts--;
}
}
- return domWidth / parts;
+ return parts ? domWidth / parts : null;
}
function domCellAround(target) {
while (target && target.nodeName != "TD" && target.nodeName != "TH") target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode;
@@ -2516,10 +2535,15 @@ function draggedWidth(dragging, event, resizeMinWidth) {
return Math.max(resizeMinWidth, dragging.startWidth + offset);
}
function updateHandle(view, value) {
- view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }));
+ safeDispatch(view, view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }));
}
function updateColumnWidth(view, cell, width) {
- const $cell = view.state.doc.resolve(cell);
+ let $cell;
+ try {
+ $cell = view.state.doc.resolve(cell);
+ } catch (_error) {
+ return false;
+ }
const table = $cell.node(-1), map = TableMap.get(table), start = $cell.start(-1);
const col = map.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
const tr = view.state.tr;
@@ -2537,16 +2561,24 @@ function updateColumnWidth(view, cell, width) {
colwidth
});
}
- if (tr.docChanged) view.dispatch(tr);
+ if (tr.docChanged) return safeDispatch(view, tr);
+ return true;
}
function displayColumnWidth(view, cell, width, defaultCellMinWidth) {
- const $cell = view.state.doc.resolve(cell);
+ let $cell;
+ try {
+ $cell = view.state.doc.resolve(cell);
+ } catch (_error) {
+ return false;
+ }
const table = $cell.node(-1), start = $cell.start(-1);
const col = TableMap.get(table).colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
- let dom = view.domAtPos($cell.start(-1)).node;
+ const domAtPos = safeDomAtPos(view, $cell.start(-1));
+ let dom = domAtPos && domAtPos.node;
while (dom && dom.nodeName != "TABLE") dom = dom.parentNode;
- if (!dom) return;
+ if (!dom) return false;
updateColumnsOnResize(table, dom.firstChild, dom, defaultCellMinWidth, col, width);
+ return true;
}
function zeroes(n) {
return Array(n).fill(0);
diff --git a/dist/index.js b/dist/index.js
index 5b4ac25594ba5722409332b1e5c812f108c9bf11..5b811ee70ff2fcb0c7587f838f00bc6fc19e906a 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -2443,6 +2443,21 @@ function handleMouseLeave(view) {
const pluginState = columnResizingPluginKey.getState(view.state);
if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging) updateHandle(view, -1);
}
+function safeDispatch(view, tr) {
+ try {
+ view.dispatch(tr);
+ return true;
+ } catch (_error) {
+ return false;
+ }
+}
+function safeDomAtPos(view, pos) {
+ try {
+ return view.domAtPos(pos);
+ } catch (_error) {
+ return null;
+ }
+}
function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
var _view$dom$ownerDocume;
if (!view.editable) return false;
@@ -2451,17 +2466,18 @@ function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging) return false;
const cell = view.state.doc.nodeAt(pluginState.activeHandle);
const width = currentColWidth(view, pluginState.activeHandle, cell.attrs);
- view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: {
+ if (width == null) return false;
+ if (!safeDispatch(view, view.state.tr.setMeta(columnResizingPluginKey, { setDragging: {
startX: event.clientX,
startWidth: width
- } }));
+ } }))) return false;
function finish(event$1) {
win.removeEventListener("mouseup", finish);
win.removeEventListener("mousemove", move);
const pluginState$1 = columnResizingPluginKey.getState(view.state);
if (pluginState$1 === null || pluginState$1 === void 0 ? void 0 : pluginState$1.dragging) {
updateColumnWidth(view, pluginState$1.activeHandle, draggedWidth(pluginState$1.dragging, event$1, cellMinWidth));
- view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }));
+ safeDispatch(view, view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }));
}
}
function move(event$1) {
@@ -2482,15 +2498,18 @@ function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
function currentColWidth(view, cellPos, { colspan, colwidth }) {
const width = colwidth && colwidth[colwidth.length - 1];
if (width) return width;
- const dom = view.domAtPos(cellPos);
- let domWidth = dom.node.childNodes[dom.offset].offsetWidth, parts = colspan;
+ const dom = safeDomAtPos(view, cellPos);
+ if (!dom) return null;
+ const cellDom = dom.node && dom.node.childNodes ? dom.node.childNodes[dom.offset] : null;
+ if (!cellDom || typeof cellDom.offsetWidth != "number") return null;
+ let domWidth = cellDom.offsetWidth, parts = colspan;
if (colwidth) {
for (let i = 0; i < colspan; i++) if (colwidth[i]) {
domWidth -= colwidth[i];
parts--;
}
}
- return domWidth / parts;
+ return parts ? domWidth / parts : null;
}
function domCellAround(target) {
while (target && target.nodeName != "TD" && target.nodeName != "TH") target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode;
@@ -2516,10 +2535,15 @@ function draggedWidth(dragging, event, resizeMinWidth) {
return Math.max(resizeMinWidth, dragging.startWidth + offset);
}
function updateHandle(view, value) {
- view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }));
+ safeDispatch(view, view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }));
}
function updateColumnWidth(view, cell, width) {
- const $cell = view.state.doc.resolve(cell);
+ let $cell;
+ try {
+ $cell = view.state.doc.resolve(cell);
+ } catch (_error) {
+ return false;
+ }
const table = $cell.node(-1), map = TableMap.get(table), start = $cell.start(-1);
const col = map.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
const tr = view.state.tr;
@@ -2537,16 +2561,24 @@ function updateColumnWidth(view, cell, width) {
colwidth
});
}
- if (tr.docChanged) view.dispatch(tr);
+ if (tr.docChanged) return safeDispatch(view, tr);
+ return true;
}
function displayColumnWidth(view, cell, width, defaultCellMinWidth) {
- const $cell = view.state.doc.resolve(cell);
+ let $cell;
+ try {
+ $cell = view.state.doc.resolve(cell);
+ } catch (_error) {
+ return false;
+ }
const table = $cell.node(-1), start = $cell.start(-1);
const col = TableMap.get(table).colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
- let dom = view.domAtPos($cell.start(-1)).node;
+ const domAtPos = safeDomAtPos(view, $cell.start(-1));
+ let dom = domAtPos && domAtPos.node;
while (dom && dom.nodeName != "TABLE") dom = dom.parentNode;
- if (!dom) return;
+ if (!dom) return false;
updateColumnsOnResize(table, dom.firstChild, dom, defaultCellMinWidth, col, width);
+ return true;
}
function zeroes(n) {
return Array(n).fill(0);

9
pnpm-lock.yaml generated
View File

@@ -8,6 +8,9 @@ patchedDependencies:
'@blocknote/core@0.46.2':
hash: 9a6d8a53058a8b6127326d40e8188f6b132b9b9e364b87e88e1c9aa3a1867aec
path: patches/@blocknote__core@0.46.2.patch
prosemirror-tables@1.8.5:
hash: cd456f0d1d88a3ce11bcf53122a0e0575c0d82810eddd887adae21d6ec570a8b
path: patches/prosemirror-tables@1.8.5.patch
importers:
@@ -4491,7 +4494,7 @@ snapshots:
prosemirror-highlight: 0.13.1(@shikijs/types@3.22.0)(@types/hast@3.0.4)(highlight.js@11.11.1)(lowlight@3.3.0)(prosemirror-model@1.25.4)(prosemirror-state@1.4.4)(prosemirror-transform@1.11.0)(prosemirror-view@1.41.6)
prosemirror-model: 1.25.4
prosemirror-state: 1.4.4
prosemirror-tables: 1.8.5
prosemirror-tables: 1.8.5(patch_hash=cd456f0d1d88a3ce11bcf53122a0e0575c0d82810eddd887adae21d6ec570a8b)
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.6
rehype-format: 5.0.1
@@ -6245,7 +6248,7 @@ snapshots:
prosemirror-schema-basic: 1.2.4
prosemirror-schema-list: 1.5.1
prosemirror-state: 1.4.4
prosemirror-tables: 1.8.5
prosemirror-tables: 1.8.5(patch_hash=cd456f0d1d88a3ce11bcf53122a0e0575c0d82810eddd887adae21d6ec570a8b)
prosemirror-trailing-node: 3.0.0(prosemirror-model@1.25.4)(prosemirror-state@1.4.4)(prosemirror-view@1.41.6)
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.6
@@ -8099,7 +8102,7 @@ snapshots:
prosemirror-transform: 1.11.0
prosemirror-view: 1.41.6
prosemirror-tables@1.8.5:
prosemirror-tables@1.8.5(patch_hash=cd456f0d1d88a3ce11bcf53122a0e0575c0d82810eddd887adae21d6ec570a8b):
dependencies:
prosemirror-keymap: 1.2.3
prosemirror-model: 1.25.4

View File

@@ -6,3 +6,4 @@ ignoredBuiltDependencies:
patchedDependencies:
'@blocknote/core@0.46.2': patches/@blocknote__core@0.46.2.patch
prosemirror-tables@1.8.5: patches/prosemirror-tables@1.8.5.patch

View File

@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
@@ -47,6 +47,9 @@ export function CommitDialog({ open, modifiedCount, suggestedMessage, onCommit,
{modifiedCount} file{modifiedCount !== 1 ? 's' : ''} changed
</Badge>
</div>
<DialogDescription className="sr-only">
Review changed files and enter a commit message before committing and pushing.
</DialogDescription>
</DialogHeader>
<textarea
ref={inputRef}

View File

@@ -1,5 +1,5 @@
import { useState, useRef, useEffect } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
@@ -52,6 +52,9 @@ export function CreateNoteDialog({ open, onClose, onCreate, defaultType, customT
<DialogContent showCloseButton={false} className="sm:max-w-[420px]">
<DialogHeader>
<DialogTitle>Create New Note</DialogTitle>
<DialogDescription className="sr-only">
Enter a title and choose a type for the new note.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1.5">

View File

@@ -51,7 +51,6 @@ export type AppCommandShortcutCombo =
| 'command-or-ctrl'
| 'command-or-ctrl-shift'
| 'command-shift'
export type AppCommandShortcutOwner = 'native-menu' | 'renderer'
type ShortcutEventLike = Pick<KeyboardEvent, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey' | 'key' | 'code'>
type SimpleHandlerKey =
@@ -104,7 +103,6 @@ interface AppCommandShortcutDefinition {
aliases?: string[]
code?: string
display: string
owner: AppCommandShortcutOwner
}
export interface AppCommandDefinition {
@@ -117,7 +115,7 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.appSettings]: {
route: { kind: 'handler', handler: 'onOpenSettings' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: ',', display: '⌘,', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: ',', display: '⌘,' },
},
[APP_COMMAND_IDS.appCheckForUpdates]: {
route: { kind: 'handler', handler: 'onCheckForUpdates' },
@@ -126,7 +124,7 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.fileNewNote]: {
route: { kind: 'handler', handler: 'onCreateNote' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'n', code: 'KeyN', display: '⌘N', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 'n', code: 'KeyN', display: '⌘N' },
},
[APP_COMMAND_IDS.fileNewType]: {
route: { kind: 'handler', handler: 'onCreateType' },
@@ -135,27 +133,27 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.fileDailyNote]: {
route: { kind: 'handler', handler: 'onOpenDailyNote' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'j', code: 'KeyJ', display: '⌘J', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 'j', code: 'KeyJ', display: '⌘J' },
},
[APP_COMMAND_IDS.fileQuickOpen]: {
route: { kind: 'handler', handler: 'onQuickOpen' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'p', code: 'KeyP', display: '⌘P', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 'p', code: 'KeyP', display: '⌘P' },
},
[APP_COMMAND_IDS.fileSave]: {
route: { kind: 'handler', handler: 'onSave' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 's', code: 'KeyS', display: '⌘S', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 's', code: 'KeyS', display: '⌘S' },
},
[APP_COMMAND_IDS.editFindInVault]: {
route: { kind: 'handler', handler: 'onSearch' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl-shift', key: 'f', code: 'KeyF', display: '⌘⇧F', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl-shift', key: 'f', code: 'KeyF', display: '⌘⇧F' },
},
[APP_COMMAND_IDS.editToggleRawEditor]: {
route: { kind: 'handler', handler: 'onToggleRawEditor' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '\\', display: '⌘\\', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '\\', display: '⌘\\' },
},
[APP_COMMAND_IDS.editToggleDiff]: {
route: { kind: 'handler', handler: 'onToggleDiff' },
@@ -164,27 +162,27 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.viewEditorOnly]: {
route: { kind: 'view-mode', value: 'editor-only' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '1', display: '⌘1', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '1', display: '⌘1' },
},
[APP_COMMAND_IDS.viewEditorList]: {
route: { kind: 'view-mode', value: 'editor-list' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '2', display: '⌘2', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '2', display: '⌘2' },
},
[APP_COMMAND_IDS.viewAll]: {
route: { kind: 'view-mode', value: 'all' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '3', display: '⌘3', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '3', display: '⌘3' },
},
[APP_COMMAND_IDS.viewToggleProperties]: {
route: { kind: 'handler', handler: 'onToggleInspector' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl-shift', key: 'i', code: 'KeyI', display: '⌘⇧I', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl-shift', key: 'i', code: 'KeyI', display: '⌘⇧I' },
},
[APP_COMMAND_IDS.viewToggleAiChat]: {
route: { kind: 'handler', handler: 'onToggleAIChat' },
menuOwned: true,
shortcut: { combo: 'command-shift', key: 'l', code: 'KeyL', display: '⌘⇧L', owner: 'native-menu' },
shortcut: { combo: 'command-shift', key: 'l', code: 'KeyL', display: '⌘⇧L' },
},
[APP_COMMAND_IDS.viewToggleBacklinks]: {
route: { kind: 'handler', handler: 'onToggleInspector' },
@@ -193,32 +191,32 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.viewCommandPalette]: {
route: { kind: 'handler', handler: 'onCommandPalette' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'k', code: 'KeyK', display: '⌘K', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 'k', code: 'KeyK', display: '⌘K' },
},
[APP_COMMAND_IDS.viewZoomIn]: {
route: { kind: 'handler', handler: 'onZoomIn' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '=', aliases: ['+'], display: '⌘=', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '=', aliases: ['+'], display: '⌘=' },
},
[APP_COMMAND_IDS.viewZoomOut]: {
route: { kind: 'handler', handler: 'onZoomOut' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '-', display: '⌘-', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '-', display: '⌘-' },
},
[APP_COMMAND_IDS.viewZoomReset]: {
route: { kind: 'handler', handler: 'onZoomReset' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '0', display: '⌘0', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '0', display: '⌘0' },
},
[APP_COMMAND_IDS.viewGoBack]: {
route: { kind: 'handler', handler: 'onGoBack' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '[', display: '⌘[', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: '[', display: '⌘[' },
},
[APP_COMMAND_IDS.viewGoForward]: {
route: { kind: 'handler', handler: 'onGoForward' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: ']', display: '⌘]', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: ']', display: '⌘]' },
},
[APP_COMMAND_IDS.goAllNotes]: {
route: { kind: 'filter', value: 'all' },
@@ -239,12 +237,12 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.noteToggleOrganized]: {
route: { kind: 'active-tab-handler', handler: 'onToggleOrganized' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'e', code: 'KeyE', display: '⌘E', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 'e', code: 'KeyE', display: '⌘E' },
},
[APP_COMMAND_IDS.noteToggleFavorite]: {
route: { kind: 'active-tab-handler', handler: 'onToggleFavorite' },
menuOwned: false,
shortcut: { combo: 'command-or-ctrl', key: 'd', code: 'KeyD', display: '⌘D', owner: 'renderer' },
shortcut: { combo: 'command-or-ctrl', key: 'd', code: 'KeyD', display: '⌘D' },
},
[APP_COMMAND_IDS.noteArchive]: {
route: { kind: 'active-tab-handler', handler: 'onArchiveNote' },
@@ -253,12 +251,12 @@ export const APP_COMMAND_DEFINITIONS: Record<AppCommandId, AppCommandDefinition>
[APP_COMMAND_IDS.noteDelete]: {
route: { kind: 'active-tab-handler', handler: 'onDeleteNote' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'Backspace', aliases: ['Delete'], display: '⌘⌫', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl', key: 'Backspace', aliases: ['Delete'], display: '⌘⌫' },
},
[APP_COMMAND_IDS.noteOpenInNewWindow]: {
route: { kind: 'handler', handler: 'onOpenInNewWindow' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl-shift', key: 'o', code: 'KeyO', display: '⌘⇧O', owner: 'native-menu' },
shortcut: { combo: 'command-or-ctrl-shift', key: 'o', code: 'KeyO', display: '⌘⇧O' },
},
[APP_COMMAND_IDS.noteRestoreDeleted]: {
route: { kind: 'handler', handler: 'onRestoreDeletedNote' },
@@ -355,10 +353,6 @@ export function isNativeMenuCommandId(value: string): value is AppCommandId {
return NATIVE_MENU_COMMAND_SET.has(value)
}
export function isNativeMenuShortcutCommand(id: AppCommandId): boolean {
return APP_COMMAND_DEFINITIONS[id].shortcut?.owner === 'native-menu'
}
export function shortcutCombosForEvent({
altKey,
ctrlKey,

View File

@@ -1,12 +1,13 @@
import { describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
APP_COMMAND_IDS,
dispatchAppCommand,
executeAppCommand,
findShortcutCommandId,
findShortcutCommandIdForEvent,
isAppCommandId,
isNativeMenuCommandId,
isNativeMenuShortcutCommand,
resetAppCommandDispatchStateForTests,
type AppCommandHandlers,
} from './appCommandDispatcher'
@@ -53,6 +54,10 @@ function makeHandlers(): AppCommandHandlers {
}
describe('appCommandDispatcher', () => {
afterEach(() => {
resetAppCommandDispatchStateForTests()
})
it('recognizes valid command ids', () => {
expect(isAppCommandId(APP_COMMAND_IDS.fileNewNote)).toBe(true)
expect(isAppCommandId('not-a-command')).toBe(false)
@@ -63,11 +68,6 @@ describe('appCommandDispatcher', () => {
expect(isNativeMenuCommandId(APP_COMMAND_IDS.noteToggleFavorite)).toBe(false)
})
it('matches shortcut ownership from the shared catalog', () => {
expect(isNativeMenuShortcutCommand(APP_COMMAND_IDS.fileNewNote)).toBe(true)
expect(isNativeMenuShortcutCommand(APP_COMMAND_IDS.noteToggleFavorite)).toBe(false)
})
it('finds raw editor and AI shortcuts from the shared catalog', () => {
expect(findShortcutCommandId('command-or-ctrl', '\\')).toBe(APP_COMMAND_IDS.editToggleRawEditor)
expect(findShortcutCommandId('command-shift', '¬', 'KeyL')).toBe(APP_COMMAND_IDS.viewToggleAiChat)
@@ -150,4 +150,20 @@ describe('appCommandDispatcher', () => {
expect(dispatchAppCommand(APP_COMMAND_IDS.goChanges, handlers)).toBe(true)
expect(handlers.onSelectFilter).toHaveBeenCalledWith('changes')
})
it('suppresses a native-menu echo after renderer keyboard dispatch', () => {
const handlers = makeHandlers()
expect(executeAppCommand(APP_COMMAND_IDS.viewToggleProperties, handlers, 'renderer-keyboard')).toBe(true)
expect(executeAppCommand(APP_COMMAND_IDS.viewToggleProperties, handlers, 'native-menu')).toBe(false)
expect(handlers.onToggleInspector).toHaveBeenCalledTimes(1)
})
it('suppresses a renderer keyboard echo after native-menu dispatch', () => {
const handlers = makeHandlers()
expect(executeAppCommand(APP_COMMAND_IDS.viewToggleAiChat, handlers, 'native-menu')).toBe(true)
expect(executeAppCommand(APP_COMMAND_IDS.viewToggleAiChat, handlers, 'renderer-keyboard')).toBe(false)
expect(handlers.onToggleAIChat).toHaveBeenCalledTimes(1)
})
})

View File

@@ -15,10 +15,15 @@ export {
findShortcutCommandIdForEvent,
isAppCommandId,
isNativeMenuCommandId,
isNativeMenuShortcutCommand,
} from './appCommandCatalog'
export type { AppCommandDefinition, AppCommandId, AppCommandShortcutCombo } from './appCommandCatalog'
export type AppCommandDispatchSource =
| 'direct'
| 'renderer-keyboard'
| 'native-menu'
| 'app-event'
export interface AppCommandHandlers {
onSetViewMode: (mode: ViewMode) => void
onCreateNote: () => void
@@ -138,6 +143,36 @@ const ACTIVE_TAB_HANDLER_EXECUTORS: Record<ActiveTabHandlerKey, (handlers: AppCo
onDeleteNote: (handlers, path) => handlers.onDeleteNote(path),
}
const SHORTCUT_ECHO_DEDUPE_WINDOW_MS = 150
let lastCommandDispatch:
| {
id: AppCommandId
source: AppCommandDispatchSource
timestamp: number
}
| null = null
function now(): number {
return globalThis.performance?.now?.() ?? Date.now()
}
function isShortcutEchoPair(a: AppCommandDispatchSource, b: AppCommandDispatchSource): boolean {
return (
(a === 'renderer-keyboard' && b === 'native-menu') ||
(a === 'native-menu' && b === 'renderer-keyboard')
)
}
function shouldSuppressDuplicateCommand(
id: AppCommandId,
source: AppCommandDispatchSource,
currentTimestamp: number,
): boolean {
if (!lastCommandDispatch || lastCommandDispatch.id !== id) return false
if (!isShortcutEchoPair(source, lastCommandDispatch.source)) return false
return currentTimestamp - lastCommandDispatch.timestamp <= SHORTCUT_ECHO_DEDUPE_WINDOW_MS
}
function dispatchActiveTabCommand(
pathRef: MutableRefObject<string | null>,
handler: (path: string) => void,
@@ -175,5 +210,26 @@ function dispatchDefinition(
}
export function dispatchAppCommand(id: AppCommandId, handlers: AppCommandHandlers): boolean {
return dispatchDefinition(APP_COMMAND_DEFINITIONS[id], handlers)
return executeAppCommand(id, handlers, 'direct')
}
export function executeAppCommand(
id: AppCommandId,
handlers: AppCommandHandlers,
source: AppCommandDispatchSource,
): boolean {
const timestamp = now()
if (shouldSuppressDuplicateCommand(id, source, timestamp)) {
return false
}
const dispatched = dispatchDefinition(APP_COMMAND_DEFINITIONS[id], handlers)
if (dispatched) {
lastCommandDispatch = { id, source, timestamp }
}
return dispatched
}
export function resetAppCommandDispatchStateForTests(): void {
lastCommandDispatch = null
}

View File

@@ -1,10 +1,8 @@
import { trackEvent } from '../lib/telemetry'
import { isTauri } from '../mock-tauri'
import {
APP_COMMAND_IDS,
dispatchAppCommand,
executeAppCommand,
findShortcutCommandIdForEvent,
isNativeMenuShortcutCommand,
type AppCommandHandlers,
} from './appCommandDispatcher'
@@ -47,11 +45,10 @@ export function handleAppKeyboardEvent(actions: KeyboardActions, event: Keyboard
const commandId = findShortcutCommandIdForEvent(event)
if (commandId === null) return
if (TEXT_EDITING_KEYS.has(event.key) && isTextInputFocused()) return
if (isTauri() && isNativeMenuShortcutCommand(commandId)) return
event.preventDefault()
if (commandId === APP_COMMAND_IDS.editFindInVault) {
trackEvent('search_used')
}
dispatchAppCommand(commandId, actions)
executeAppCommand(commandId, actions, 'renderer-keyboard')
}

View File

@@ -1,6 +1,7 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { renderHook } from '@testing-library/react'
import { useAppKeyboard } from './useAppKeyboard'
import { resetAppCommandDispatchStateForTests } from './appCommandDispatcher'
function fireKey(
key: string,
@@ -50,6 +51,7 @@ function makeActions() {
describe('useAppKeyboard', () => {
afterEach(() => {
delete (window as typeof window & { __TAURI__?: unknown }).__TAURI__
resetAppCommandDispatchStateForTests()
vi.restoreAllMocks()
})
@@ -95,39 +97,39 @@ describe('useAppKeyboard', () => {
expect(actions.onCreateNote).toHaveBeenCalled()
})
it('Cmd+N defers to native menu in Tauri', () => {
it('Cmd+N still works in Tauri mode', () => {
const actions = makeActions()
;(window as typeof window & { __TAURI__?: object }).__TAURI__ = {}
renderHook(() => useAppKeyboard(actions))
fireKey('n', { metaKey: true })
expect(actions.onCreateNote).not.toHaveBeenCalled()
expect(actions.onCreateNote).toHaveBeenCalled()
})
it('Cmd+\\ defers to native menu in Tauri', () => {
it('Cmd+\\ still works in Tauri mode', () => {
const actions = makeActions()
actions.onToggleRawEditor = vi.fn()
;(window as typeof window & { __TAURI__?: object }).__TAURI__ = {}
renderHook(() => useAppKeyboard(actions))
fireKey('\\', { metaKey: true })
expect(actions.onToggleRawEditor).not.toHaveBeenCalled()
expect(actions.onToggleRawEditor).toHaveBeenCalled()
})
it('Cmd+Shift+I defers to native menu in Tauri', () => {
it('Cmd+Shift+I still works in Tauri mode', () => {
const actions = makeActions()
const onToggleInspector = vi.fn()
;(window as typeof window & { __TAURI__?: object }).__TAURI__ = {}
renderHook(() => useAppKeyboard({ ...actions, onToggleInspector }))
fireKey('i', { metaKey: true, shiftKey: true })
expect(onToggleInspector).not.toHaveBeenCalled()
expect(onToggleInspector).toHaveBeenCalled()
})
it('Cmd+Shift+L defers to native menu in Tauri', () => {
it('Cmd+Shift+L still works in Tauri mode', () => {
const actions = makeActions()
const onToggleAIChat = vi.fn()
;(window as typeof window & { __TAURI__?: object }).__TAURI__ = {}
renderHook(() => useAppKeyboard({ ...actions, onToggleAIChat }))
fireKey('l', { metaKey: true, shiftKey: true })
expect(onToggleAIChat).not.toHaveBeenCalled()
expect(onToggleAIChat).toHaveBeenCalled()
})
it('Cmd+D triggers toggle favorite on active note', () => {
@@ -138,7 +140,7 @@ describe('useAppKeyboard', () => {
expect(actions.onToggleFavorite).toHaveBeenCalledWith('/vault/test.md')
})
it('Cmd+D still uses JS shortcut in Tauri when no native menu owns it', () => {
it('Cmd+D still works in Tauri mode', () => {
const actions = makeActions()
actions.onToggleFavorite = vi.fn()
;(window as typeof window & { __TAURI__?: object }).__TAURI__ = {}

View File

@@ -2,7 +2,7 @@ import { useEffect, useRef } from 'react'
import { isTauri } from '../mock-tauri'
import {
APP_COMMAND_EVENT_NAME,
dispatchAppCommand,
executeAppCommand,
isAppCommandId,
type AppCommandHandlers,
} from './appCommandDispatcher'
@@ -92,7 +92,7 @@ function useWindowAppCommandListener(handlersRef: { current: MenuEventHandlers }
useEffect(() => {
const handleCommandEvent = createWindowCommandListener((detail) => {
if (isAppCommandId(detail)) {
dispatchAppCommand(detail, handlersRef.current)
executeAppCommand(detail, handlersRef.current, 'app-event')
}
})
@@ -129,7 +129,7 @@ function useNativeMenuStateSync(state: MenuStatePayload) {
/** Dispatch a Tauri menu event ID to the matching handler. Exported for testing. */
export function dispatchMenuEvent(id: string, h: MenuEventHandlers): void {
if (!isAppCommandId(id)) return
dispatchAppCommand(id, h)
executeAppCommand(id, h, 'native-menu')
}
/** Listen for native macOS menu events and dispatch them to the appropriate handlers. */

View File

@@ -1,6 +1,6 @@
import { test, expect } from '@playwright/test'
import { triggerMenuCommand } from './testBridge'
import { createFixtureVaultCopy, openFixtureVault, removeFixtureVaultCopy } from '../helpers/fixtureVault'
import { createFixtureVaultCopy, openFixtureVaultTauri, removeFixtureVaultCopy } from '../helpers/fixtureVault'
let tempVaultDir: string
@@ -21,7 +21,7 @@ test.describe('keyboard command routing', () => {
const errors: string[] = []
page.on('pageerror', (error) => errors.push(error.message))
await openFixtureVault(page, tempVaultDir)
await openFixtureVaultTauri(page, tempVaultDir)
await triggerMenuCommand(page, 'file-new-note')
await expect(page.getByTestId('breadcrumb-filename-trigger')).toContainText(/untitled-note-\d+/i, { timeout: 5_000 })
@@ -31,32 +31,22 @@ test.describe('keyboard command routing', () => {
expect(errors).toEqual([])
})
test('native menu trigger toggles the properties panel through the shared command path', async ({ page }) => {
await openFixtureVault(page, tempVaultDir)
test('Meta+Shift+I toggles the properties panel in Tauri mode through the shared keyboard path @smoke', async ({ page }) => {
await openFixtureVaultTauri(page, tempVaultDir)
await page.getByText('Alpha Project', { exact: true }).first().click()
await page.locator('.bn-editor').click()
await triggerMenuCommand(page, 'view-toggle-properties')
await page.keyboard.press('Meta+Shift+I')
await expect(page.getByTitle('Close Properties (⌘⇧I)')).toBeVisible({ timeout: 5_000 })
await triggerMenuCommand(page, 'view-toggle-properties')
await page.keyboard.press('Meta+Shift+I')
await expect(page.getByTitle('Properties (⌘⇧I)')).toBeVisible({ timeout: 5_000 })
})
test('native menu trigger toggles the raw editor through the shared command path', async ({ page }) => {
await openFixtureVault(page, tempVaultDir)
await page.getByText('Alpha Project', { exact: true }).first().click()
await triggerMenuCommand(page, 'edit-toggle-raw-editor')
await expect(page.getByTestId('raw-editor-codemirror')).toBeVisible({ timeout: 5_000 })
await triggerMenuCommand(page, 'edit-toggle-raw-editor')
await expect(page.getByTestId('raw-editor-codemirror')).not.toBeVisible({ timeout: 5_000 })
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
})
test('Meta+Backslash toggles the raw editor through the keyboard path', async ({ page }) => {
await openFixtureVault(page, tempVaultDir)
test('Meta+Backslash toggles the raw editor in Tauri mode through the shared keyboard path @smoke', async ({ page }) => {
await openFixtureVaultTauri(page, tempVaultDir)
await page.getByText('Alpha Project', { exact: true }).first().click()
await page.locator('.bn-editor').click()
await page.keyboard.press('Meta+Backslash')
await expect(page.getByTestId('raw-editor-codemirror')).toBeVisible({ timeout: 5_000 })
@@ -66,15 +56,20 @@ test.describe('keyboard command routing', () => {
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
})
test('native menu trigger toggles the AI panel through the shared command path', async ({ page }) => {
await openFixtureVault(page, tempVaultDir)
test('Meta+Shift+L toggles the AI panel in Tauri mode, while Ctrl+Shift+L does not @smoke', async ({ page }) => {
await openFixtureVaultTauri(page, tempVaultDir)
await page.getByText('Alpha Project', { exact: true }).first().click()
await page.locator('.bn-editor').click()
await triggerMenuCommand(page, 'view-toggle-ai-chat')
await page.keyboard.press('Control+Shift+L')
await page.waitForTimeout(200)
await expect(page.getByTestId('ai-panel')).not.toBeVisible()
await page.keyboard.press('Meta+Shift+L')
await expect(page.getByTestId('ai-panel')).toBeVisible({ timeout: 5_000 })
await expect(page.getByTitle('Close AI panel')).toBeVisible()
await triggerMenuCommand(page, 'view-toggle-ai-chat')
await page.keyboard.press('Meta+Shift+L')
await expect(page.getByTestId('ai-panel')).not.toBeVisible({ timeout: 5_000 })
})
})

View File

@@ -0,0 +1,122 @@
import { test, expect, type Page } from '@playwright/test'
import { createFixtureVaultCopy, openFixtureVaultTauri, removeFixtureVaultCopy } from '../helpers/fixtureVault'
import { triggerMenuCommand } from './testBridge'
let tempVaultDir: string
function trackUnexpectedErrors(page: Page): string[] {
const errors: string[] = []
page.on('pageerror', (error) => {
errors.push(error.message)
})
page.on('console', (message) => {
if (message.type() !== 'error') return
const text = message.text()
if (text.includes('ws://localhost:9711')) return
errors.push(text)
})
return errors
}
async function createUntitledNote(page: Page): Promise<void> {
await triggerMenuCommand(page, 'file-new-note')
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
await expect.poll(async () => page.evaluate(() => {
const active = document.activeElement as HTMLElement | null
return Boolean(active?.isContentEditable || active?.closest('[contenteditable="true"]'))
}), {
timeout: 5_000,
}).toBe(true)
}
async function insertTable(page: Page): Promise<void> {
const editorSurface = page.locator('.bn-editor')
await expect(editorSurface).toBeVisible({ timeout: 5_000 })
await editorSurface.click()
await page.keyboard.type('/table')
const tableCommand = page.getByText('Table with editable cells', { exact: true })
await expect(tableCommand).toBeVisible({ timeout: 5_000 })
await tableCommand.click()
await expect(page.locator('table')).toHaveCount(1, { timeout: 5_000 })
}
async function dragFirstColumn(page: Page, deltaX: number): Promise<void> {
const firstCell = page.locator('table td, table th').first()
await expect(firstCell).toBeVisible({ timeout: 5_000 })
const box = await firstCell.boundingBox()
if (!box) throw new Error('Could not measure first table cell')
const handleX = box.x + box.width - 1
const handleY = box.y + (box.height / 2)
await page.mouse.move(handleX, handleY)
await expect(page.locator('.column-resize-handle')).toHaveCount(2, { timeout: 5_000 })
await page.mouse.down()
await page.mouse.move(handleX + deltaX, handleY, { steps: 8 })
await page.mouse.up()
}
test.describe('table resize crash fix', () => {
test.beforeEach((_, testInfo) => {
testInfo.setTimeout(60_000)
tempVaultDir = createFixtureVaultCopy()
})
test.afterEach(() => {
removeFixtureVaultCopy(tempVaultDir)
})
test('resizing a table column keeps the editor stable and changes the cell width', async ({ page }) => {
const errors = trackUnexpectedErrors(page)
await openFixtureVaultTauri(page, tempVaultDir)
await createUntitledNote(page)
await insertTable(page)
const firstCell = page.locator('table td, table th').first()
const before = await firstCell.boundingBox()
if (!before) throw new Error('Could not measure first table cell before resize')
await dragFirstColumn(page, 80)
const after = await firstCell.boundingBox()
if (!after) throw new Error('Could not measure first table cell after resize')
expect(after.width).toBeGreaterThan(before.width)
await expect(page.locator('table')).toHaveCount(1)
expect(errors).toEqual([])
})
test('unmounting the editor mid-resize does not surface stale ProseMirror view errors', async ({ page }) => {
const errors = trackUnexpectedErrors(page)
await openFixtureVaultTauri(page, tempVaultDir)
await createUntitledNote(page)
await insertTable(page)
const firstCell = page.locator('table td, table th').first()
await expect(firstCell).toBeVisible({ timeout: 5_000 })
const box = await firstCell.boundingBox()
if (!box) throw new Error('Could not measure first table cell before resize')
const handleX = box.x + box.width - 1
const handleY = box.y + (box.height / 2)
await page.mouse.move(handleX, handleY)
await expect(page.locator('.column-resize-handle')).toHaveCount(2, { timeout: 5_000 })
await page.mouse.down()
await page.keyboard.press('Meta+Backslash')
await expect(page.getByTestId('raw-editor-codemirror')).toBeVisible({ timeout: 5_000 })
await page.mouse.move(handleX + 80, handleY, { steps: 8 })
await page.mouse.up()
expect(errors).toEqual([])
})
})