Compare commits

...

38 Commits

Author SHA1 Message Date
lucaronin
5b5f949c74 fix: initialize new notes with empty h1 focus 2026-04-12 00:58:11 +02:00
lucaronin
57a5693922 fix: stabilize new note editor focus 2026-04-12 00:06:49 +02:00
lucaronin
2ca8f1b2a6 fix: remove legacy title section fallback 2026-04-11 23:51:58 +02:00
lucaronin
eb65bb8f05 fix: dedupe new note command palette entries 2026-04-11 22:05:13 +02:00
lucaronin
8fb229ede3 fix: preserve square brackets in parsed note titles 2026-04-11 21:27:30 +02:00
lucaronin
ce84b34890 fix: restore cmd shift i properties shortcut 2026-04-11 20:59:16 +02:00
lucaronin
e98a186389 fix: align note list date row spacing 2026-04-11 20:30:48 +02:00
lucaronin
258b54b074 refactor: make shortcut QA modes explicit 2026-04-11 19:03:15 +02:00
lucaronin
f694b9b5e4 fix: unblock native ai panel shortcut in tauri 2026-04-11 18:34:39 +02:00
lucaronin
32ee2b781b test: stabilize keyboard shortcut smoke 2026-04-11 17:36:23 +02:00
lucaronin
c78793cfe3 fix: verify editor-focused keyboard shortcuts 2026-04-11 17:23:20 +02:00
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
lucaronin
dbf54657f0 fix: harden untitled h1 auto-rename flow 2026-04-11 15:22:34 +02:00
lucaronin
0c365eb7dd test: cover raw editor keyboard toggle 2026-04-11 14:23:25 +02:00
lucaronin
20b789271d fix: verify view row hover state 2026-04-11 14:06:03 +02:00
lucaronin
36d3c8731b fix: hide view counts while row actions are visible 2026-04-11 13:52:35 +02:00
lucaronin
e412fa8fd7 fix: restore breadcrumb action icon size 2026-04-11 13:33:42 +02:00
lucaronin
76c37cf783 fix: narrow shortcut dispatcher route handling 2026-04-11 13:02:31 +02:00
lucaronin
4b60b9539d refactor: centralize shortcut routing metadata 2026-04-11 12:59:11 +02:00
lucaronin
69e520b5aa fix: prevent cmd+n note creation crash 2026-04-11 12:30:05 +02:00
lucaronin
272f2c0b3c design: replace app icon with Tolaria drop icon 2026-04-11 12:12:12 +02:00
lucaronin
d7bdab5b2e fix: relax test bridge command typing 2026-04-11 11:07:52 +02:00
lucaronin
5a5ea8d6f0 fix: align test bridge window typing 2026-04-11 11:04:47 +02:00
lucaronin
86306dc9de test: stabilize keyboard menu smoke bridge 2026-04-11 10:59:38 +02:00
lucaronin
974ca6148b fix: return false for unhandled app commands 2026-04-11 10:44:45 +02:00
lucaronin
b1bc056afb refactor: unify shortcut command routing 2026-04-11 10:39:08 +02:00
lucaronin
c24f60c594 fix: restore breadcrumb action icon sizing 2026-04-10 21:22:27 +02:00
lucaronin
71a3be577d fix: always show breadcrumb filename 2026-04-10 21:08:45 +02:00
lucaronin
717fa9d1a6 fix: prefer note icons in favorite rows 2026-04-10 20:58:18 +02:00
lucaronin
78e76e0d54 fix: defer native menu shortcuts in tauri 2026-04-10 20:43:36 +02:00
lucaronin
b01c6b4a4b fix: format rename rust helpers 2026-04-10 20:25:19 +02:00
lucaronin
db4359981f fix: update rename filename wikilinks 2026-04-10 20:20:08 +02:00
lucaronin
98d19e4c41 fix: align created label to right edge in note list date row 2026-04-10 20:01:40 +02:00
lucaronin
5ebffc447b feat: standardize canonical wikilink targets 2026-04-10 19:57:21 +02:00
lucaronin
a44dd41f95 feat: style note list status chips 2026-04-10 18:31:51 +02:00
lucaronin
eb67b98d96 test: scope quick open smoke locators 2026-04-10 18:14:52 +02:00
lucaronin
968c4d05a9 feat: add breadcrumb filename rename controls 2026-04-10 17:59:21 +02:00
145 changed files with 6235 additions and 2251 deletions

View File

@@ -1,2 +1,2 @@
HOTSPOT_THRESHOLD=9.68
AVERAGE_THRESHOLD=9.33
HOTSPOT_THRESHOLD=9.7
AVERAGE_THRESHOLD=9.36

View File

@@ -14,7 +14,7 @@ These frontmatter field names have special meaning in Laputa's UI:
| Field | Meaning | UI behavior |
|---|---|---|
| `title:` | Human-readable title (synced with filename) | Breadcrumb, sidebar. Filename = `slugify(title).md` |
| `title:` | Legacy display-title fallback for older notes | Used only when a note has no H1; new notes do not write it automatically |
| `type:` | Entity type (Project, Person, Quarter…) | Type chip in note list + sidebar grouping |
| `status:` | Lifecycle stage (active, done, blocked…) | Colored chip in note list + editor header |
| `icon:` | Per-note icon (emoji, Phosphor name, or HTTP/HTTPS image URL) | Rendered on note title surfaces; editable from the Properties panel |
@@ -237,16 +237,17 @@ Laputa separates **display title** from the file identifier:
- **Display title resolution** (`extract_title` in `vault/parsing.rs`): first `# H1` on the first non-empty body line, then legacy frontmatter `title:`, then slug-to-title from the filename stem.
- **Opening a note is read-only**: selecting a note does not inject or auto-correct `title:` frontmatter.
- **On rename / explicit title edits** (`rename_note`): Laputa updates both filename and `title` frontmatter atomically, plus wikilinks across the vault.
- **Explicit filename actions** (`rename_note`): breadcrumb rename/sync actions update the filename and wikilinks across the vault. The editor body remains the title editing surface.
- **Untitled drafts** start as `untitled-*.md` and are auto-renamed on save once the note gains an H1.
### Title Field (UI)
### Title Surface (UI)
The dedicated `TitleField` is a fallback editing surface, not the canonical one:
The BlockNote body is the only title editing surface:
- If the note already has an H1, the editor body is the primary title surface and the dedicated title row is hidden.
- If the note has no H1 and is not an untitled draft, `TitleField` appears above the editor and `onTitleSync` updates `title:` frontmatter plus the filename.
- `TitleField` also responds to `laputa:focus-editor` events with `selectTitle: true` for new-note flows that start without an H1.
- The first H1 is the canonical display title.
- There is no separate title row above the editor, even when a note has no H1.
- Notes without an H1 show the editor body and placeholder only.
- Filename changes are explicit breadcrumb actions, not a dedicated title-input side effect.
### Sidebar Selection

View File

@@ -671,6 +671,7 @@ The vault backend (`src-tauri/src/vault/`) is split into focused submodules:
| `save_image` | Save base64 image to vault |
| `copy_image_to_vault` | Copy image file to vault |
| `update_menu_state` | Update native menu checkmarks and enabled/disabled state for selection-dependent actions |
| `trigger_menu_command` | Emit a native menu command ID for deterministic shortcut QA |
## Mock Layer
@@ -706,6 +707,7 @@ No Redux or global context. State lives in the root `App.tsx` and custom hooks:
| `useUnifiedSearch` | Query, results, loading state | Keyword search |
| `useSettings` | App settings (API keys, GitHub token) | Persistent settings |
| `useVaultConfig` | Per-vault UI preferences | Vault-specific config |
| `appCommandDispatcher` | Canonical shortcut/menu command IDs | Shared execution path for renderer and native menu commands |
Data flows unidirectionally: `App` passes data and callbacks as props to child components. No child-to-child communication — everything goes through `App`.
@@ -725,6 +727,18 @@ 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 routing is explicit:
- `appCommandCatalog.ts` is the shared shortcut manifest for command IDs, modifier rules, and deterministic QA metadata
- `useAppKeyboard` is the primary execution path for real shortcut keypresses, including Tauri runs
- macOS browser-reserved chords such as `Cmd+Shift+L` are unblocked at webview init via `tauri-plugin-prevent-default`, then continue through the same renderer-first command path
- `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 two explicit proof paths from the shared manifest:
- renderer shortcut-event proof through `window.__laputaTest.triggerShortcutCommand()`
- native menu-command proof through `trigger_menu_command`
- The browser harness is only a deterministic desktop command bridge; exact native accelerator delivery still requires real Tauri QA for commands flagged as manual-native-critical
## Auto-Release & In-App Updates
### Release Pipeline

View File

@@ -65,7 +65,6 @@ laputa-app/
│ │ ├── WelcomeScreen.tsx # Onboarding screen
│ │ ├── GitHubVaultModal.tsx # GitHub vault clone/create
│ │ ├── GitHubDeviceFlow.tsx # GitHub OAuth device flow
│ │ ├── TitleField.tsx # Editable note title above editor
│ │ ├── ConflictResolverModal.tsx # Git conflict resolution
│ │ ├── CommitDialog.tsx # Git commit modal
│ │ ├── CreateNoteDialog.tsx # New note modal
@@ -97,6 +96,8 @@ laputa-app/
│ │ ├── useCommandRegistry.ts # Command palette registry
│ │ ├── useAppCommands.ts # App-level commands
│ │ ├── useAppKeyboard.ts # Keyboard shortcuts
│ │ ├── appCommandCatalog.ts # Shortcut combos + command metadata
│ │ ├── appCommandDispatcher.ts # Shared shortcut/menu command IDs + dispatch
│ │ ├── useSettings.ts # App settings
│ │ ├── useOnboarding.ts # First-launch flow
│ │ ├── useCodeMirror.ts # CodeMirror raw editor
@@ -280,10 +281,17 @@ 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. The native macOS menu bar also triggers commands via `useMenuEvents`.
`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. On macOS, any browser-reserved chord that WKWebView swallows before that path must also be added to the narrow `tauri-plugin-prevent-default` registration in `src-tauri/src/lib.rs`. The same shortcut manifest also declares the deterministic QA mode for each shortcut-capable command.
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 shortcut QA, use the explicit proof path from `appCommandCatalog.ts`:
- `window.__laputaTest.triggerShortcutCommand()` for deterministic renderer shortcut-event coverage
- `window.__laputaTest.triggerMenuCommand()` for deterministic native menu-command coverage
That browser harness is a deterministic desktop command bridge, not real native accelerator QA. For macOS browser-reserved chords, still perform native QA in the real Tauri app because the webview-init prevent-default layer is only active there. Do not treat flaky synthesized macOS keystrokes as proof that a shortcut works unless you also confirm the visible app behavior.
## Running Tests
```bash
@@ -337,7 +345,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 `useAppKeyboard.ts`
3. If it has a keyboard shortcut, register it in `appCommandCatalog.ts` with the canonical command ID, modifier rule, and deterministic QA mode, 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,29 @@
---
type: ADR
id: "0050"
title: "Deterministic shortcut command routing"
status: active
date: 2026-04-11
---
## Context
Laputa is keyboard-first, but shortcut execution had split ownership: `useAppKeyboard` handled some shortcuts in the renderer while `menu.rs` owned others as native Tauri menu accelerators. That split made QA unreliable. Browser tests could prove the renderer path, but not the native menu path, and flaky macOS key synthesis made `Cmd+Shift+L`, `Cmd+Shift+I`, and `Cmd+N` regressions easy to miss.
## Decision
**Keyboard shortcuts and native menu accelerators now dispatch through the same canonical app command IDs. Renderer-owned shortcuts call the shared dispatcher directly; native menu items emit the same IDs into the frontend, and tests get a deterministic menu-command trigger that exercises that route without relying on synthesized native keystrokes.**
## Options considered
- **Option A** (chosen): Shared command IDs plus deterministic menu-command trigger — keeps native desktop UX while making menu-owned commands testable in unit tests, Playwright, and native QA. Downside: one more command layer to maintain.
- **Option B**: Move every shortcut to the renderer — simpler automated testing, but worse macOS menu-bar parity and weaker native UX.
- **Option C**: Keep renderer and native shortcuts separate — lowest code churn, but continues to produce false confidence and shortcut regressions.
## Consequences
- `appCommandDispatcher.ts` owns the canonical shortcut command IDs and the shared execution path used by `useAppKeyboard` and `useMenuEvents`.
- Native menu routing remains explicit in `menu.rs`; adding or changing a native shortcut now requires wiring the accelerator and the matching command ID in one place.
- Automated QA can trigger menu-owned commands deterministically through the shared `window.__laputaTest.triggerMenuCommand()` bridge in browser runs and through the native `trigger_menu_command` Tauri command in desktop runs.
- Keyboard QA should prefer real menu selection or the deterministic menu-command trigger for native-owned shortcuts, and reserve synthesized keystrokes for renderer-owned shortcuts or true end-to-end spot checks.
- This decision supersedes the blanket assumption in ADR 0020 that all shortcut verification can be treated as plain keyboard-event testing.

View File

@@ -0,0 +1,31 @@
---
type: ADR
id: "0051"
title: "Shared shortcut manifest for testable routing"
status: active
date: 2026-04-11
---
## Context
ADR 0050 moved renderer shortcuts and native menu events onto the same command dispatcher, but shortcut ownership still drifted across multiple places: `appKeyboardShortcuts.ts`, `appCommandDispatcher.ts`, command-palette metadata, and `menu.rs`. That made shortcut regressions easy to reintroduce because the same facts had to be updated manually in several files.
The riskiest failures were exactly the native-owned commands that matter most in a keyboard-first app: `Cmd+\` for raw editor, `Cmd+Shift+I` for properties, and `Cmd+Shift+L` for the AI panel. We need one declarative place that says which command owns which shortcut, whether the shortcut is renderer-owned or native-menu-owned, and how tests should trigger it.
## Decision
**Shortcut-capable app commands are now defined in a shared frontend manifest that owns command IDs, routing semantics, and shortcut ownership. Renderer keyboard handling resolves commands from that manifest, native menu routing dispatches the same command IDs, and deterministic QA for native-owned shortcuts targets those IDs rather than duplicating shortcut facts in ad hoc code paths.**
## Options considered
- **Option A** (chosen): Shared shortcut manifest plus shared dispatcher and deterministic menu-command QA. This reduces drift, improves CodeScene on the command router, and makes native-owned shortcuts provable without flaky macOS key synthesis. Downside: one more manifest to maintain.
- **Option B**: Keep the shared dispatcher from ADR 0050 but continue storing shortcut ownership in separate key maps and menu lists. Lower churn, but it keeps the exact source of the regressions we reopened.
- **Option C**: Move all shortcuts into renderer-only handlers. Easier to test, but weaker macOS menu-bar parity and worse native desktop UX.
## Consequences
- `appCommandCatalog.ts` is now the frontend source of truth for shortcut-capable command IDs, ownership, modifier rules, and dispatch kind.
- `appCommandDispatcher.ts` is reduced to route execution instead of carrying a large switch plus duplicated ownership metadata.
- `useAppKeyboard.ts` resolves shortcuts from the shared manifest, including the distinction between `Cmd+Shift+L` (macOS-only) and `CmdOrCtrl+Shift+I/F/O`.
- Native-menu smoke tests should use `window.__laputaTest.triggerMenuCommand()` or the Tauri `trigger_menu_command` bridge to prove the native command path. Renderer-only commands may still be proven with direct keyboard events.
- This ADR supersedes ADR 0050 by replacing “shared command IDs are enough” with “shared command IDs plus shared shortcut ownership metadata are required.”

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

@@ -0,0 +1,30 @@
---
type: ADR
id: "0053"
title: "Webview-init prevention for browser-reserved shortcuts"
status: active
date: 2026-04-11
---
## Context
ADR 0052 made renderer-first shortcut handling the primary path for command execution, with native menu accelerators deduped afterward. That works for normal shortcuts, but native QA on macOS showed that `Cmd+Shift+L` still failed to reach the app even though the shared command path and the Note menu item both worked.
The gap is WKWebView itself: some browser-reserved chords are swallowed by the webview before the renderer-level shortcut listener can execute. That makes the shortcut untestable with the real native keypress even though the command bus is correct.
## Decision
**Laputa will keep renderer-first shortcut execution, but for macOS browser-reserved chords we will add a narrow Tauri webview-init prevention layer using `tauri-plugin-prevent-default` so the real keystroke reaches the shared command path.**
## Options considered
- **Option A** (chosen): Add a narrow `tauri-plugin-prevent-default` registration for only the known browser-reserved chords we actually use. This preserves ADR 0052, keeps the command bus unified, and fixes the real native keystroke path without broad shortcut capture.
- **Option B**: Keep relying on renderer capture listeners alone. Simpler, but it fails for chords that WKWebView consumes before renderer code sees them.
- **Option C**: Use a global shortcut plugin as the fallback path. This would catch the keystroke natively, but it reserves the chord outside Laputa and is too heavy for app-local shortcuts.
## Consequences
- Shortcut ownership stays unified: command IDs and execution still live in the shared renderer/native command bus.
- macOS-only browser-reserved chords now have one extra declaration point in `src-tauri/src/lib.rs`, and that list must stay intentionally small.
- Native QA remains mandatory for any shortcut added to that list, because browser dev and mocked Tauri tests do not exercise the webview-init layer.
- Re-evaluate this decision if Tauri/WKWebView exposes a better app-local native shortcut hook that does not require browser-reserved-key workarounds.

View File

@@ -0,0 +1,35 @@
---
type: ADR
id: "0054"
title: "Deterministic shortcut QA matrix"
status: active
date: 2026-04-11
---
## Context
ADR 0052 made renderer-first shortcut execution the primary runtime path, and ADR 0053 added a narrow macOS webview-init prevent-default layer for browser-reserved chords such as `Cmd+Shift+L`. Those decisions improved behavior, but the automated QA story was still muddy:
- browser smoke tests were describing a mocked desktop harness as if it were native Tauri QA
- some tests used `page.keyboard.press()` for commands whose real desktop accelerators are intercepted or reserved by the browser shell
- native menu command coverage existed, but the catalog did not declare which deterministic proof path each shortcut should use
That made it too easy to ship a shortcut with passing automation while overstating what the automation had actually proven.
## Decision
**Laputa will treat shortcut QA as an explicit part of the shared command manifest. Every shortcut-capable command must have a deterministic automated proof path, and the test harness must distinguish renderer shortcut-event proof from native menu-command proof instead of calling the browser harness “native Tauri QA”.**
## Options considered
- **Option A** (chosen): Add a deterministic shortcut QA matrix to the shared command catalog. Renderer shortcut handling can be exercised through synthetic `keydown` events generated from the manifest, while native menu commands are exercised through `trigger_menu_command`. Pros: deterministic, explicit, and honest about what is being proved. Cons: still requires real native QA for exact accelerator delivery on macOS.
- **Option B**: Keep using ad hoc Playwright key presses and browser-side menu shims. Lower change cost, but still allows false claims about native coverage and still depends on browser-reserved shortcuts behaving nicely.
- **Option C**: Block all shortcut work until full native Tauri automation exists. Strongest eventual guarantee, but it would leave the keyboard-first app without a usable deterministic QA strategy today.
## Consequences
- `appCommandCatalog.ts` now owns not just command IDs and modifier rules, but also the deterministic QA mode for each shortcut-capable command.
- Browser harness smoke tests must describe themselves as a desktop command bridge, not native app QA.
- Renderer shortcut behavior can be verified deterministically without depending on browser chrome or flaky AppleScript key synthesis.
- Native menu-command behavior can be verified deterministically through the Tauri command bridge.
- Exact desktop accelerator delivery still requires real Tauri QA for commands flagged as needing manual native verification, especially browser-reserved macOS chords.

View File

@@ -0,0 +1,42 @@
---
type: ADR
id: "0055"
title: "H1 is the only editor title surface"
status: active
date: 2026-04-11
supersedes: "0044"
---
## Context
ADR-0044 moved Laputa to H1-as-title, but the frontend still carried a legacy fallback: when a note had no H1, `TitleField` and the old title section could reappear above the editor. That left two competing title surfaces in the product and made it possible for deleting an H1 to resurrect UI that was supposed to be gone.
The result was both behavioral drift and stale tests: some code paths still treated the dedicated title row as a valid editing surface even though the product direction is now keyboard-first writing directly in the document body.
## Decision
**The editor body is now the only title surface. Laputa never renders a separate title section above the editor, regardless of whether a note currently has an H1.**
Display-title behavior stays:
1. First H1 in the body
2. Legacy frontmatter `title:`
3. Filename-derived fallback
But the UI no longer exposes a dedicated title field for cases 2 or 3. When a note has no H1, the editor simply shows normal body content or the empty-editor placeholder.
Filename operations remain explicit:
- untitled notes still auto-rename from H1 on save
- manual filename rename/sync remains in the breadcrumb
## Options considered
- **Option A** (chosen): remove the fallback title section entirely. This makes the editor honest, removes a stale code path, and keeps title editing aligned with the keyboard-first document model.
- **Option B**: keep the fallback title field for non-H1 notes. This preserves an alternate rename path, but it reintroduces the exact dual-surface ambiguity that ADR-0044 tried to escape.
- **Option C**: hide the title section with CSS only. Low churn, but it leaves dead render/state paths in place and makes regressions like “delete H1 and old title row returns” easy to reintroduce.
## Consequences
- Deleting an H1 no longer reveals any legacy title UI; the user stays in the editor body.
- `TitleField` and the title-section render path are removed from the frontend.
- Breadcrumb filename controls are now the only explicit file-identifier editing surface outside the editor body.
- Older tests that asserted title editing through `TitleField` are obsolete and should be replaced by H1-title or breadcrumb-filename coverage.

View File

@@ -99,9 +99,15 @@ proposed → active → superseded
| [0041](0041-filekind-all-files-in-vault-scanner.md) | fileKind field — scan all vault files, not just markdown | active |
| [0042](0042-trash-auto-purge-safety-model.md) | Trash auto-purge safety model | superseded → [0045](0045-permanent-delete-no-trash.md) |
| [0043](0043-reactive-vault-state-on-save.md) | Reactive vault state: editor changes propagate immediately to all UI | active |
| [0044](0044-h1-as-title-primary-source.md) | H1 as primary title source — filename as stable identifier | active |
| [0044](0044-h1-as-title-primary-source.md) | H1 as primary title source — filename as stable identifier | superseded → [0055](0055-h1-is-the-only-editor-title-surface.md) |
| [0045](0045-permanent-delete-no-trash.md) | Permanent delete with confirm modal — no Trash system | active |
| [0046](0046-starter-vault-cloned-from-github.md) | Starter vault cloned from GitHub at runtime — no bundled content | active |
| [0047](0047-regex-mode-for-view-filter-conditions.md) | Regex mode for view filter conditions | active |
| [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 | 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 |
| [0053](0053-webview-init-prevention-for-browser-reserved-shortcuts.md) | Webview-init prevention for browser-reserved shortcuts | active |
| [0054](0054-deterministic-shortcut-qa-matrix.md) | Deterministic shortcut QA matrix | active |
| [0055](0055-h1-is-the-only-editor-title-surface.md) | H1 is the only editor title surface | active |

View File

@@ -13,7 +13,7 @@
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "playwright test",
"playwright:smoke": "playwright test --config playwright.smoke.config.ts tests/smoke/example.spec.ts tests/smoke/fix-ai-chat-empty-body-v3.spec.ts tests/smoke/fix-crash-create-note.spec.ts tests/smoke/getting-started-template.spec.ts tests/smoke/h1-title-decoupled.spec.ts tests/smoke/wikilink-path-fix.spec.ts",
"playwright:smoke": "playwright test --config playwright.smoke.config.ts tests/smoke/example.spec.ts tests/smoke/fix-ai-chat-empty-body-v3.spec.ts tests/smoke/fix-crash-create-note.spec.ts tests/smoke/getting-started-template.spec.ts tests/smoke/h1-title-decoupled.spec.ts tests/smoke/h1-untitled-auto-rename.spec.ts tests/smoke/keyboard-command-routing.spec.ts tests/smoke/wikilink-path-fix.spec.ts",
"playwright:regression": "playwright test tests/smoke/",
"playwright:integration": "playwright test --config playwright.integration.config.ts",
"test:coverage": "vitest run --coverage",

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

51
src-tauri/Cargo.lock generated
View File

@@ -1012,6 +1012,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "embed-resource"
version = "3.0.6"
@@ -2150,6 +2156,15 @@ dependencies = [
"once_cell",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.17"
@@ -2278,6 +2293,7 @@ dependencies = [
"tauri-plugin-dialog",
"tauri-plugin-log",
"tauri-plugin-opener",
"tauri-plugin-prevent-default",
"tauri-plugin-process",
"tauri-plugin-updater",
"tempfile",
@@ -4504,6 +4520,27 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
dependencies = [
"heck 0.5.0",
"proc-macro2",
"quote",
"syn 2.0.115",
]
[[package]]
name = "subtle"
version = "2.6.1"
@@ -4887,6 +4924,20 @@ dependencies = [
"zbus",
]
[[package]]
name = "tauri-plugin-prevent-default"
version = "4.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6260061932cad80647a823d0c5a3633f4eec62160a8f57bad0ab82b537477ef2"
dependencies = [
"bitflags 2.11.0",
"itertools",
"serde",
"strum",
"tauri",
"thiserror 2.0.18",
]
[[package]]
name = "tauri-plugin-process"
version = "2.3.1"

View File

@@ -35,6 +35,7 @@ tauri-plugin-dialog = "2"
tauri-plugin-updater = "2.10.0"
tauri-plugin-process = "2.3.1"
tauri-plugin-opener = "2"
tauri-plugin-prevent-default = "4.0.4"
sentry = "0.37"
uuid = { version = "1", features = ["v4"] }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.3 KiB

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 115 KiB

View File

@@ -3,6 +3,7 @@ use crate::menu;
use crate::settings::Settings;
use crate::vault_list;
use crate::vault_list::VaultList;
use serde::Deserialize;
use super::parse_build_label;
@@ -41,23 +42,29 @@ pub async fn check_mcp_status() -> Result<crate::mcp::McpStatus, String> {
// ── Menu commands ───────────────────────────────────────────────────────────
#[cfg(desktop)]
#[tauri::command]
pub fn update_menu_state(
app_handle: tauri::AppHandle,
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MenuStateUpdate {
has_active_note: bool,
has_modified_files: Option<bool>,
has_conflicts: Option<bool>,
has_restorable_deleted_note: Option<bool>,
}
#[cfg(desktop)]
#[tauri::command]
pub fn update_menu_state(
app_handle: tauri::AppHandle,
state: MenuStateUpdate,
) -> Result<(), String> {
menu::set_note_items_enabled(&app_handle, has_active_note);
if let Some(v) = has_modified_files {
menu::set_note_items_enabled(&app_handle, state.has_active_note);
if let Some(v) = state.has_modified_files {
menu::set_git_commit_items_enabled(&app_handle, v);
}
if let Some(v) = has_conflicts {
if let Some(v) = state.has_conflicts {
menu::set_git_conflict_items_enabled(&app_handle, v);
}
if let Some(v) = has_restorable_deleted_note {
if let Some(v) = state.has_restorable_deleted_note {
menu::set_restore_deleted_item_enabled(&app_handle, v);
}
Ok(())
@@ -67,14 +74,23 @@ pub fn update_menu_state(
#[tauri::command]
pub fn update_menu_state(
_app_handle: tauri::AppHandle,
_has_active_note: bool,
_has_modified_files: Option<bool>,
_has_conflicts: Option<bool>,
_has_restorable_deleted_note: Option<bool>,
_state: MenuStateUpdate,
) -> Result<(), String> {
Ok(())
}
#[cfg(desktop)]
#[tauri::command]
pub fn trigger_menu_command(app_handle: tauri::AppHandle, id: String) -> Result<(), String> {
menu::emit_custom_menu_event(&app_handle, &id)
}
#[cfg(mobile)]
#[tauri::command]
pub fn trigger_menu_command(_app_handle: tauri::AppHandle, _id: String) -> Result<(), String> {
Err("Native menu commands are not available on mobile".into())
}
// ── Settings & config commands ──────────────────────────────────────────────
#[tauri::command]

View File

@@ -45,6 +45,17 @@ pub fn rename_note(
vault::rename_note(&vault_path, &old_path, &new_title, old_title.as_deref())
}
#[tauri::command]
pub fn rename_note_filename(
vault_path: String,
old_path: String,
new_filename_stem: String,
) -> Result<RenameResult, String> {
let vault_path = expand_tilde(&vault_path);
let old_path = expand_tilde(&old_path);
vault::rename_note_filename(&vault_path, &old_path, &new_filename_stem)
}
#[tauri::command]
pub fn auto_rename_untitled(
vault_path: String,

View File

@@ -86,6 +86,7 @@ fn setup_common_plugins(app: &mut tauri::App) -> Result<(), Box<dyn std::error::
#[cfg(desktop)]
fn setup_desktop_plugins(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
setup_macos_webview_shortcut_prevention(app)?;
app.handle()
.plugin(tauri_plugin_updater::Builder::new().build())?;
app.handle().plugin(tauri_plugin_process::init())?;
@@ -94,6 +95,35 @@ fn setup_desktop_plugins(app: &mut tauri::App) -> Result<(), Box<dyn std::error:
Ok(())
}
const MACOS_WEBVIEW_RESERVED_COMMAND_SHIFT_KEYS: &[&str] = &["L"];
#[cfg(all(desktop, target_os = "macos"))]
fn setup_macos_webview_shortcut_prevention(
app: &mut tauri::App,
) -> Result<(), Box<dyn std::error::Error>> {
use tauri_plugin_prevent_default::ModifierKey::{MetaKey, ShiftKey};
use tauri_plugin_prevent_default::{Flags, KeyboardShortcut};
let mut builder = tauri_plugin_prevent_default::Builder::new().with_flags(Flags::empty());
// WKWebView can swallow some browser-reserved chords before our shared
// renderer shortcut handler sees them. Keep this list narrow and verify
// every addition with native QA.
for key in MACOS_WEBVIEW_RESERVED_COMMAND_SHIFT_KEYS {
builder = builder.shortcut(KeyboardShortcut::with_modifiers(key, &[MetaKey, ShiftKey]));
}
app.handle().plugin(builder.build())?;
Ok(())
}
#[cfg(not(all(desktop, target_os = "macos")))]
fn setup_macos_webview_shortcut_prevention(
_app: &mut tauri::App,
) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn setup_app(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
setup_common_plugins(app)?;
@@ -113,6 +143,77 @@ fn setup_app(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn with_invoke_handler(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
builder.invoke_handler(tauri::generate_handler![
commands::list_vault,
commands::list_vault_folders,
commands::get_note_content,
commands::save_note_content,
commands::update_frontmatter,
commands::delete_frontmatter_property,
commands::rename_note,
commands::rename_note_filename,
commands::auto_rename_untitled,
commands::detect_renames,
commands::update_wikilinks_for_renames,
commands::get_file_history,
commands::get_modified_files,
commands::get_file_diff,
commands::get_file_diff_at_commit,
commands::get_vault_pulse,
commands::git_commit,
commands::get_build_number,
commands::get_last_commit_info,
commands::git_pull,
commands::git_push,
commands::git_remote_status,
commands::get_conflict_files,
commands::get_conflict_mode,
commands::git_resolve_conflict,
commands::git_commit_conflict_resolution,
commands::git_discard_file,
commands::is_git_repo,
commands::init_git_repo,
commands::check_claude_cli,
commands::stream_claude_chat,
commands::stream_claude_agent,
commands::reload_vault,
commands::reload_vault_entry,
commands::sync_note_title,
commands::save_image,
commands::copy_image_to_vault,
commands::delete_note,
commands::batch_delete_notes,
commands::migrate_is_a_to_type,
commands::create_vault_folder,
commands::batch_archive_notes,
commands::get_settings,
commands::update_menu_state,
commands::trigger_menu_command,
commands::save_settings,
commands::load_vault_list,
commands::save_vault_list,
commands::github_list_repos,
commands::github_create_repo,
commands::clone_repo,
commands::github_device_flow_start,
commands::github_device_flow_poll,
commands::github_get_user,
commands::search_vault,
commands::create_empty_vault,
commands::create_getting_started_vault,
commands::check_vault_exists,
commands::get_default_vault_path,
commands::register_mcp_tools,
commands::check_mcp_status,
commands::repair_vault,
commands::reinit_telemetry,
commands::list_views,
commands::save_view_cmd,
commands::delete_view_cmd
])
}
#[cfg(desktop)]
fn handle_run_event(app_handle: &tauri::AppHandle, event: &tauri::RunEvent) {
use tauri::Manager;
@@ -134,74 +235,8 @@ pub fn run() {
#[cfg(desktop)]
let builder = builder.manage(WsBridgeChild(Mutex::new(None)));
builder
with_invoke_handler(builder)
.setup(setup_app)
.invoke_handler(tauri::generate_handler![
commands::list_vault,
commands::list_vault_folders,
commands::get_note_content,
commands::save_note_content,
commands::update_frontmatter,
commands::delete_frontmatter_property,
commands::rename_note,
commands::auto_rename_untitled,
commands::detect_renames,
commands::update_wikilinks_for_renames,
commands::get_file_history,
commands::get_modified_files,
commands::get_file_diff,
commands::get_file_diff_at_commit,
commands::get_vault_pulse,
commands::git_commit,
commands::get_build_number,
commands::get_last_commit_info,
commands::git_pull,
commands::git_push,
commands::git_remote_status,
commands::get_conflict_files,
commands::get_conflict_mode,
commands::git_resolve_conflict,
commands::git_commit_conflict_resolution,
commands::git_discard_file,
commands::is_git_repo,
commands::init_git_repo,
commands::check_claude_cli,
commands::stream_claude_chat,
commands::stream_claude_agent,
commands::reload_vault,
commands::reload_vault_entry,
commands::sync_note_title,
commands::save_image,
commands::copy_image_to_vault,
commands::delete_note,
commands::batch_delete_notes,
commands::migrate_is_a_to_type,
commands::create_vault_folder,
commands::batch_archive_notes,
commands::get_settings,
commands::update_menu_state,
commands::save_settings,
commands::load_vault_list,
commands::save_vault_list,
commands::github_list_repos,
commands::github_create_repo,
commands::clone_repo,
commands::github_device_flow_start,
commands::github_device_flow_poll,
commands::github_get_user,
commands::search_vault,
commands::create_empty_vault,
commands::create_getting_started_vault,
commands::check_vault_exists,
commands::get_default_vault_path,
commands::register_mcp_tools,
commands::check_mcp_status,
commands::repair_vault,
commands::reinit_telemetry,
commands::list_views,
commands::save_view_cmd,
commands::delete_view_cmd
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|app_handle, event| {
@@ -209,3 +244,13 @@ pub fn run() {
handle_run_event(app_handle, &event);
});
}
#[cfg(test)]
mod tests {
use super::MACOS_WEBVIEW_RESERVED_COMMAND_SHIFT_KEYS;
#[test]
fn macos_webview_shortcut_prevention_includes_ai_panel_shortcut() {
assert_eq!(MACOS_WEBVIEW_RESERVED_COMMAND_SHIFT_KEYS, ["L"]);
}
}

View File

@@ -78,6 +78,7 @@ const CUSTOM_IDS: &[&str] = &[
GO_ALL_NOTES,
GO_ARCHIVED,
GO_CHANGES,
GO_INBOX,
NOTE_TOGGLE_ORGANIZED,
NOTE_ARCHIVE,
NOTE_DELETE,
@@ -211,6 +212,8 @@ fn build_view_menu(app: &App) -> MenuResult {
.id(VIEW_ALL)
.accelerator("CmdOrCtrl+3")
.build(app)?;
// Keep Cmd+Shift+I on the renderer path. The menu item stays available,
// but the native accelerator has proven unreliable for this command.
let toggle_properties = MenuItemBuilder::new("Toggle Properties Panel")
.id(VIEW_TOGGLE_PROPERTIES)
.build(app)?;
@@ -404,14 +407,21 @@ pub fn setup_menu(app: &App) -> Result<(), Box<dyn std::error::Error>> {
app.on_menu_event(|app_handle, event| {
let id = event.id().0.as_str();
if CUSTOM_IDS.contains(&id) {
let _ = app_handle.emit("menu-event", id);
}
let _ = emit_custom_menu_event(app_handle, id);
});
Ok(())
}
pub fn emit_custom_menu_event(app_handle: &AppHandle, id: &str) -> Result<(), String> {
if !CUSTOM_IDS.contains(&id) {
return Err(format!("Unknown custom menu event: {id}"));
}
app_handle
.emit("menu-event", id)
.map_err(|err| format!("Failed to emit menu-event {id}: {err}"))
}
fn set_items_enabled(app_handle: &AppHandle, ids: &[&str], enabled: bool) {
let Some(menu) = app_handle.menu() else {
return;

View File

@@ -12,7 +12,8 @@ use super::{is_md_file, parse_md_file, parse_non_md_file, scan_vault, VaultEntry
/// Bump this when VaultEntry fields change to force a full rescan.
/// v12: fix gray_matter YAML sanitization (unquoted colons / hash comments in list items)
const CACHE_VERSION: u32 = 12;
/// v13: preserve plain square brackets in parsed markdown H1 titles
const CACHE_VERSION: u32 = 13;
#[derive(Debug, Serialize, Deserialize)]
struct VaultCache {

View File

@@ -20,8 +20,8 @@ pub use getting_started::{create_getting_started_vault, default_vault_path, vaul
pub use image::{copy_image_to_vault, save_image};
pub use migration::migrate_is_a_to_type;
pub use rename::{
auto_rename_untitled, detect_renames, rename_note, update_wikilinks_for_renames,
DetectedRename, RenameResult,
auto_rename_untitled, detect_renames, rename_note, rename_note_filename,
update_wikilinks_for_renames, DetectedRename, RenameResult,
};
pub use title_sync::{sync_title_on_open, SyncAction};
pub use trash::{batch_delete_notes, delete_note};

View File

@@ -249,7 +249,9 @@ fn extract_wikilink_display(inner: &str) -> &str {
inner.find('|').map_or(inner, |idx| &inner[idx + 1..])
}
/// Process a markdown link `[text](url)`, extracting only the link text.
/// Process bracketed text.
/// Real markdown links `[text](url)` are unwrapped to `text`.
/// Plain bracketed text `[text]` is preserved verbatim.
fn process_markdown_link(
chars: &mut std::iter::Peekable<impl Iterator<Item = char>>,
result: &mut String,
@@ -258,8 +260,13 @@ fn process_markdown_link(
if chars.peek() == Some(&'(') {
chars.next();
skip_until(chars, ')');
result.push_str(&inner);
return;
}
result.push('[');
result.push_str(&inner);
result.push(']');
}
/// Collect chars inside a wikilink until `]]`, consuming both closing brackets.
@@ -363,6 +370,15 @@ mod tests {
assert_eq!(extract_h1_title(content), Some("Spaced Title".to_string()));
}
#[test]
fn test_extract_h1_title_preserves_plain_square_brackets() {
let content = "# [26Q2] Tolaria MVP\n\nBody.";
assert_eq!(
extract_h1_title(content),
Some("[26Q2] Tolaria MVP".to_string())
);
}
#[test]
fn test_extract_h1_title_none_when_no_h1() {
assert_eq!(extract_h1_title("Just body text."), None);
@@ -726,7 +742,7 @@ mod tests {
#[test]
fn test_strip_markdown_chars_bracket_without_url() {
assert_eq!(strip_markdown_chars("[just brackets]"), "just brackets");
assert_eq!(strip_markdown_chars("[just brackets]"), "[just brackets]");
}
#[test]

View File

@@ -1,5 +1,6 @@
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use walkdir::WalkDir;
@@ -28,13 +29,17 @@ pub(super) fn title_to_slug(title: &str) -> String {
.join("-")
}
/// Build a regex that matches wiki links referencing old title or path stem.
fn build_wikilink_pattern(old_title: &str, old_path_stem: &str) -> Option<Regex> {
let pattern_str = format!(
r"\[\[(?:{}|{})(\|[^\]]*?)?\]\]",
regex::escape(old_title),
regex::escape(old_path_stem),
);
/// Build a regex that matches wiki links referencing any of the provided targets.
fn build_wikilink_pattern(targets: &[&str]) -> Option<Regex> {
let escaped_targets: Vec<String> = targets
.iter()
.filter(|target| !target.is_empty())
.map(|target| regex::escape(target))
.collect();
if escaped_targets.is_empty() {
return None;
}
let pattern_str = format!(r"\[\[(?:{})(\|[^\]]*?)?\]\]", escaped_targets.join("|"));
Regex::new(&pattern_str).ok()
}
@@ -44,13 +49,13 @@ fn is_replaceable_md_file(path: &Path, exclude: &Path) -> bool {
}
/// Replace wikilink references in a single file's content. Returns updated content if changed.
fn replace_wikilinks_in_content(content: &str, re: &Regex, new_title: &str) -> Option<String> {
fn replace_wikilinks_in_content(content: &str, re: &Regex, new_target: &str) -> Option<String> {
if !re.is_match(content) {
return None;
}
let replaced = re.replace_all(content, |caps: &regex::Captures| match caps.get(1) {
Some(pipe) => format!("[[{}{}]]", new_title, pipe.as_str()),
None => format!("[[{}]]", new_title),
Some(pipe) => format!("[[{}{}]]", new_target, pipe.as_str()),
None => format!("[[{}]]", new_target),
});
if replaced != content {
Some(replaced.into_owned())
@@ -59,15 +64,6 @@ fn replace_wikilinks_in_content(content: &str, re: &Regex, new_title: &str) -> O
}
}
/// Parameters for a vault-wide wikilink replacement.
struct WikilinkReplacement<'a> {
vault_path: &'a Path,
old_title: &'a str,
new_title: &'a str,
old_path_stem: &'a str,
exclude_path: &'a Path,
}
/// Collect all .md file paths in vault eligible for wikilink replacement.
fn collect_md_files(vault_path: &Path, exclude: &Path) -> Vec<std::path::PathBuf> {
WalkDir::new(vault_path)
@@ -79,47 +75,76 @@ fn collect_md_files(vault_path: &Path, exclude: &Path) -> Vec<std::path::PathBuf
.collect()
}
fn unique_wikilink_targets(targets: Vec<&str>) -> Vec<&str> {
let mut seen = HashSet::new();
targets
.into_iter()
.filter(|target| !target.is_empty())
.filter(|target| seen.insert(*target))
.collect()
}
fn collect_legacy_wikilink_targets<'a>(old_title: &'a str, old_path_stem: &'a str) -> Vec<&'a str> {
let old_filename_stem = old_path_stem.rsplit('/').next().unwrap_or(old_path_stem);
unique_wikilink_targets(vec![old_title, old_path_stem, old_filename_stem])
}
/// Replace wiki link references across all vault markdown files.
fn update_wikilinks_in_vault(params: &WikilinkReplacement) -> usize {
let re = match build_wikilink_pattern(params.old_title, params.old_path_stem) {
fn update_wikilinks_in_vault(
vault_path: &Path,
old_targets: &[&str],
new_target: &str,
exclude_path: &Path,
) -> usize {
let re = match build_wikilink_pattern(old_targets) {
Some(r) => r,
None => return 0,
};
replace_wikilinks_in_files(collect_md_files(vault_path, exclude_path), &re, new_target)
}
let files = collect_md_files(params.vault_path, params.exclude_path);
fn replace_wikilinks_in_files(
files: Vec<std::path::PathBuf>,
re: &Regex,
replacement: &str,
) -> usize {
files
.iter()
.filter(|path| {
let content = match fs::read_to_string(path) {
Ok(c) => c,
Err(_) => return false,
};
match replace_wikilinks_in_content(&content, &re, params.new_title) {
Some(new_content) => fs::write(path, &new_content).is_ok(),
None => false,
}
})
.filter(|path| rewrite_wikilinks_in_file(path, re, replacement))
.count()
}
fn rewrite_wikilinks_in_file(path: &Path, re: &Regex, replacement: &str) -> bool {
let Ok(content) = fs::read_to_string(path) else {
return false;
};
let Some(new_content) = replace_wikilinks_in_content(&content, re, replacement) else {
return false;
};
fs::write(path, &new_content).is_ok()
}
/// Extract the value of the `title:` frontmatter field from raw content.
fn extract_fm_title_value(content: &str) -> Option<String> {
if !content.starts_with("---\n") {
return None;
}
let fm = content[4..].split("\n---").next()?;
for line in fm.lines() {
let t = line.trim_start();
for prefix in &["title:", "\"title\":"] {
if let Some(rest) = t.strip_prefix(prefix) {
let val = rest.trim().trim_matches('"').trim_matches('\'');
if !val.is_empty() {
return Some(val.to_string());
}
}
}
}
None
fm.lines()
.map(str::trim_start)
.find_map(extract_title_value_from_frontmatter_line)
}
fn extract_title_value_from_frontmatter_line(line: &str) -> Option<String> {
["title:", "\"title\":"]
.iter()
.find_map(|prefix| line.strip_prefix(prefix))
.map(str::trim)
.map(|value| value.trim_matches('"').trim_matches('\''))
.filter(|value| !value.is_empty())
.map(|value| value.to_string())
}
/// Update the `title:` frontmatter field in content.
@@ -168,6 +193,22 @@ fn unique_dest_path(dest_dir: &Path, filename: &str, exclude: &Path) -> std::pat
}
}
fn normalize_filename_stem(new_filename_stem: &str) -> Result<String, String> {
let trimmed = new_filename_stem.trim();
let stem = trimmed.strip_suffix(".md").unwrap_or(trimmed).trim();
if stem.is_empty() {
return Err("New filename cannot be empty".to_string());
}
if is_invalid_filename_stem(stem) {
return Err("Invalid filename".to_string());
}
Ok(stem.to_string())
}
fn is_invalid_filename_stem(stem: &str) -> bool {
stem == "." || stem == ".." || stem.contains('/') || stem.contains('\\')
}
/// Rename a note: update its frontmatter title, rename the file, and update wiki links across the vault.
///
/// When `old_title_hint` is provided it is used instead of extracting the title from
@@ -237,13 +278,9 @@ pub fn rename_note(
// Update wikilinks across the vault
let vault_prefix = format!("{}/", vault.to_string_lossy());
let old_path_stem = to_path_stem(old_path, &vault_prefix);
let updated_files = update_wikilinks_in_vault(&WikilinkReplacement {
vault_path: vault,
old_title,
new_title,
old_path_stem,
exclude_path: &new_file,
});
let new_path_stem = to_path_stem(&new_path_str, &vault_prefix).to_string();
let old_targets = collect_legacy_wikilink_targets(old_title, old_path_stem);
let updated_files = update_wikilinks_in_vault(vault, &old_targets, &new_path_stem, &new_file);
Ok(RenameResult {
new_path: new_path_str,
@@ -251,6 +288,67 @@ pub fn rename_note(
})
}
/// Rename only the file path stem while preserving title/frontmatter content.
pub fn rename_note_filename(
vault_path: &str,
old_path: &str,
new_filename_stem: &str,
) -> Result<RenameResult, String> {
let vault = Path::new(vault_path);
let old_file = Path::new(old_path);
if !old_file.exists() {
return Err(format!("File does not exist: {}", old_path));
}
let normalized_stem = normalize_filename_stem(new_filename_stem)?;
let old_filename = old_file
.file_name()
.map(|f| f.to_string_lossy().to_string())
.unwrap_or_default();
let content =
fs::read_to_string(old_file).map_err(|e| format!("Failed to read {}: {}", old_path, e))?;
let fm_title = extract_fm_title_value(&content);
let old_title = super::extract_title(fm_title.as_deref(), &content, &old_filename);
let new_filename = format!("{}.md", normalized_stem);
if old_filename == new_filename {
return Ok(RenameResult {
new_path: old_path.to_string(),
updated_files: 0,
});
}
let parent_dir = old_file
.parent()
.ok_or("Cannot determine parent directory")?;
let new_file = parent_dir.join(&new_filename);
if new_file.exists() && new_file != old_file {
return Err("A note with that name already exists".to_string());
}
fs::rename(old_file, &new_file).map_err(|e| {
format!(
"Failed to rename {} to {}: {}",
old_path,
new_file.to_string_lossy(),
e
)
})?;
let vault_prefix = format!("{}/", vault.to_string_lossy());
let old_path_stem = to_path_stem(old_path, &vault_prefix);
let new_path = new_file.to_string_lossy().to_string();
let new_path_stem = to_path_stem(&new_path, &vault_prefix).to_string();
let old_targets = collect_legacy_wikilink_targets(&old_title, old_path_stem);
let updated_files = update_wikilinks_in_vault(vault, &old_targets, &new_path_stem, &new_file);
Ok(RenameResult {
new_path,
updated_files,
})
}
/// Check if a filename matches the untitled pattern (e.g. "untitled-note-1234567890.md").
fn is_untitled_filename(filename: &str) -> bool {
let stem = filename.strip_suffix(".md").unwrap_or(filename);
@@ -352,22 +450,12 @@ pub fn update_wikilinks_for_renames(
.strip_suffix(".md")
.unwrap_or(&rename.new_path);
let old_filename_stem = old_stem.split('/').next_back().unwrap_or(old_stem);
let new_filename_stem = new_stem.split('/').next_back().unwrap_or(new_stem);
// Build title from filename stem (kebab-case → Title Case)
let old_title = super::parsing::slug_to_title(old_filename_stem);
let new_title = super::parsing::slug_to_title(new_filename_stem);
// The new file is the exclude target (don't rewrite wikilinks inside the renamed file itself)
let new_file = vault.join(&rename.new_path);
let updated = update_wikilinks_in_vault(&WikilinkReplacement {
vault_path: vault,
old_title: &old_title,
new_title: &new_title,
old_path_stem: old_filename_stem,
exclude_path: &new_file,
});
let old_targets = collect_legacy_wikilink_targets(&old_title, old_stem);
let updated = update_wikilinks_in_vault(vault, &old_targets, new_stem, &new_file);
total_updated += updated;
}
@@ -457,11 +545,11 @@ mod tests {
assert_eq!(result.updated_files, 2);
let other_content = fs::read_to_string(vault.join("note/other.md")).unwrap();
assert!(other_content.contains("[[Sprint Retrospective]]"));
assert!(other_content.contains("[[note/sprint-retrospective]]"));
assert!(!other_content.contains("[[Weekly Review]]"));
let project_content = fs::read_to_string(vault.join("project/my-project.md")).unwrap();
assert!(project_content.contains("[[Sprint Retrospective]]"));
assert!(project_content.contains("[[note/sprint-retrospective]]"));
}
#[test]
@@ -521,7 +609,33 @@ mod tests {
assert_eq!(result.updated_files, 1);
let ref_content = fs::read_to_string(vault.join("note/ref.md")).unwrap();
assert!(ref_content.contains("[[Sprint Retro|my review]]"));
assert!(ref_content.contains("[[note/sprint-retro|my review]]"));
}
#[test]
fn test_rename_note_updates_filename_only_wikilinks_to_canonical_path() {
let dir = TempDir::new().unwrap();
let vault = dir.path();
create_test_file(vault, "note/weekly-review.md", "# Weekly Review\n");
create_test_file(
vault,
"note/ref.md",
"# Ref\n\nSee [[weekly-review]] for info.\n",
);
let old_path = vault.join("note/weekly-review.md");
let result = rename_note(
vault.to_str().unwrap(),
old_path.to_str().unwrap(),
"Sprint Retro",
None,
)
.unwrap();
assert_eq!(result.updated_files, 1);
let ref_content = fs::read_to_string(vault.join("note/ref.md")).unwrap();
assert!(ref_content.contains("[[note/sprint-retro]]"));
assert!(!ref_content.contains("[[weekly-review]]"));
}
#[test]
@@ -698,6 +812,58 @@ mod tests {
assert!(vault.join("note/my-note.md").exists());
}
#[test]
fn test_rename_note_filename_preserves_title_and_updates_path_wikilinks() {
let dir = TempDir::new().unwrap();
let vault = dir.path();
create_test_file(
vault,
"note/project-kickoff.md",
"---\ntitle: Project Kickoff\ntype: Note\n---\n\n# Project Kickoff\n\nBody.\n",
);
create_test_file(
vault,
"note/ref.md",
"# Ref\n\nSee [[note/project-kickoff]] and [[Project Kickoff]].\n",
);
let old_path = vault.join("note/project-kickoff.md");
let result = rename_note_filename(
vault.to_str().unwrap(),
old_path.to_str().unwrap(),
"manual-name",
)
.unwrap();
assert!(result.new_path.ends_with("manual-name.md"));
assert!(!old_path.exists());
let renamed = fs::read_to_string(&result.new_path).unwrap();
assert!(renamed.contains("title: Project Kickoff"));
assert!(renamed.contains("# Project Kickoff"));
let ref_content = fs::read_to_string(vault.join("note/ref.md")).unwrap();
assert!(ref_content.contains("[[note/manual-name]]"));
assert!(!ref_content.contains("[[Project Kickoff]]"));
assert!(!ref_content.contains("[[note/project-kickoff]]"));
}
#[test]
fn test_rename_note_filename_rejects_existing_destination() {
let dir = TempDir::new().unwrap();
let vault = dir.path();
create_test_file(vault, "note/current.md", "# Current\n");
create_test_file(vault, "note/manual-name.md", "# Existing\n");
let result = rename_note_filename(
vault.to_str().unwrap(),
vault.join("note/current.md").to_str().unwrap(),
"manual-name",
);
assert_eq!(result.unwrap_err(), "A note with that name already exists");
}
#[test]
fn test_rename_note_with_old_title_hint_updates_wikilinks() {
// Simulates H1 sync: content already saved with new H1, but wikilinks still use old title.
@@ -736,11 +902,11 @@ mod tests {
assert!(!vault.join("note/weekly-review.md").exists());
let other_content = fs::read_to_string(vault.join("note/other.md")).unwrap();
assert!(other_content.contains("[[Sprint Retrospective]]"));
assert!(other_content.contains("[[note/sprint-retrospective]]"));
assert!(!other_content.contains("[[Weekly Review]]"));
let project_content = fs::read_to_string(vault.join("project/my-project.md")).unwrap();
assert!(project_content.contains("[[Sprint Retrospective]]"));
assert!(project_content.contains("[[note/sprint-retrospective]]"));
}
#[test]
@@ -770,7 +936,7 @@ mod tests {
assert_eq!(result.updated_files, 1);
let other_content = fs::read_to_string(vault.join("note/other.md")).unwrap();
assert!(other_content.contains("[[Sprint Retrospective]]"));
assert!(other_content.contains("[[note/sprint-retrospective]]"));
}
#[test]

View File

@@ -280,7 +280,7 @@ function App() {
})
const appSave = useAppSave({
updateEntry: vault.updateEntry, setTabs: notes.setTabs, setToastMessage,
updateEntry: vault.updateEntry, setTabs: notes.setTabs, handleSwitchTab: notes.handleSwitchTab, setToastMessage,
loadModifiedFiles: vault.loadModifiedFiles, reloadViews: vault.reloadViews,
clearUnsaved: vault.clearUnsaved, unsavedPaths: vault.unsavedPaths,
tabs: notes.tabs, activeTabPath: notes.activeTabPath,
@@ -288,6 +288,13 @@ function App() {
replaceEntry: vault.replaceEntry, resolvedPath,
})
const handleFilenameRename = useCallback((path: string, newFilenameStem: string) => {
appSave.savePendingForPath(path)
.then(() => notes.handleRenameFilename(path, newFilenameStem, resolvedPath, vault.replaceEntry))
.then(vault.loadModifiedFiles)
.catch((err) => console.error('Filename rename failed:', err))
}, [appSave, notes, resolvedPath, vault])
const aiActivity = useAiActivity({
onOpenNote: vaultBridge.openNoteByPath,
onOpenTab: vaultBridge.openNoteByPath,
@@ -700,7 +707,7 @@ function App() {
onUnarchiveNote={activeDeletedFile ? undefined : entryActions.handleUnarchiveNote}
onContentChange={appSave.handleContentChange}
onSave={appSave.handleSave}
onTitleSync={activeDeletedFile ? undefined : appSave.handleTitleSync}
onRenameFilename={activeDeletedFile ? undefined : handleFilenameRename}
rawToggleRef={rawToggleRef}
diffToggleRef={diffToggleRef}
canGoBack={canGoBack}

View File

@@ -141,12 +141,10 @@ describe('BreadcrumbBar — title in breadcrumb (always rendered, CSS-toggled)',
const { container } = render(<BreadcrumbBar entry={baseEntry} {...defaultProps} />)
const bar = container.querySelector('.breadcrumb-bar')!
expect(bar).toHaveClass('border-b', 'border-transparent')
expect(bar).not.toHaveAttribute('data-title-hidden')
bar.setAttribute('data-title-hidden', '')
expect(bar).toHaveAttribute('data-title-hidden')
})
it('uses the active separator state when raw mode forces the title into the breadcrumb', () => {
it('keeps the breadcrumb title visible in raw mode', () => {
const { container } = render(
<BreadcrumbBar entry={baseEntry} {...defaultProps} rawMode onToggleRaw={vi.fn()} />,
)
@@ -155,6 +153,71 @@ describe('BreadcrumbBar — title in breadcrumb (always rendered, CSS-toggled)',
})
})
describe('BreadcrumbBar — filename controls', () => {
it('shows the sync button when the filename diverges from the title slug', () => {
const entry = { ...baseEntry, title: 'Fresh Title', filename: 'untitled-note-123.md' }
render(<BreadcrumbBar entry={entry} {...defaultProps} onRenameFilename={vi.fn()} />)
expect(screen.getByTestId('breadcrumb-sync-button')).toBeInTheDocument()
})
it('hides the sync button when the filename already matches the title slug', () => {
const entry = { ...baseEntry, title: 'Test Note', filename: 'test-note.md' }
render(<BreadcrumbBar entry={entry} {...defaultProps} onRenameFilename={vi.fn()} />)
expect(screen.queryByTestId('breadcrumb-sync-button')).not.toBeInTheDocument()
})
it('clicking the sync button renames the file to the title slug', () => {
const onRenameFilename = vi.fn()
const entry = { ...baseEntry, title: 'Fresh Title', filename: 'untitled-note-123.md' }
render(<BreadcrumbBar entry={entry} {...defaultProps} onRenameFilename={onRenameFilename} />)
fireEvent.click(screen.getByTestId('breadcrumb-sync-button'))
expect(onRenameFilename).toHaveBeenCalledWith(entry.path, 'fresh-title')
})
it('lets keyboard users press Enter on the filename to start editing', () => {
render(<BreadcrumbBar entry={baseEntry} {...defaultProps} onRenameFilename={vi.fn()} />)
fireEvent.keyDown(screen.getByTestId('breadcrumb-filename-trigger'), { key: 'Enter' })
expect(screen.getByTestId('breadcrumb-filename-input')).toHaveValue('test')
})
it('double-clicking the filename enters edit mode and Enter confirms the rename', () => {
const onRenameFilename = vi.fn()
render(<BreadcrumbBar entry={baseEntry} {...defaultProps} onRenameFilename={onRenameFilename} />)
fireEvent.doubleClick(screen.getByTestId('breadcrumb-filename-trigger'))
const input = screen.getByTestId('breadcrumb-filename-input')
fireEvent.change(input, { target: { value: 'renamed-file' } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(onRenameFilename).toHaveBeenCalledWith(baseEntry.path, 'renamed-file')
})
it('pressing Escape while editing cancels the inline rename', () => {
const onRenameFilename = vi.fn()
render(<BreadcrumbBar entry={baseEntry} {...defaultProps} onRenameFilename={onRenameFilename} />)
fireEvent.doubleClick(screen.getByTestId('breadcrumb-filename-trigger'))
const input = screen.getByTestId('breadcrumb-filename-input')
fireEvent.change(input, { target: { value: 'renamed-file' } })
fireEvent.keyDown(input, { key: 'Escape' })
expect(onRenameFilename).not.toHaveBeenCalled()
expect(screen.queryByTestId('breadcrumb-filename-input')).not.toBeInTheDocument()
})
it('blur confirms the inline rename when the value changed', () => {
const onRenameFilename = vi.fn()
render(<BreadcrumbBar entry={baseEntry} {...defaultProps} onRenameFilename={onRenameFilename} />)
fireEvent.doubleClick(screen.getByTestId('breadcrumb-filename-trigger'))
const input = screen.getByTestId('breadcrumb-filename-input')
fireEvent.change(input, { target: { value: 'renamed-on-blur' } })
fireEvent.blur(input)
expect(onRenameFilename).toHaveBeenCalledWith(baseEntry.path, 'renamed-on-blur')
})
})
describe('BreadcrumbBar — action buttons always right-aligned', () => {
it('actions container has ml-auto so buttons are always right-aligned', () => {
const { container } = render(<BreadcrumbBar entry={baseEntry} {...defaultProps} />)

View File

@@ -1,6 +1,9 @@
import { memo } from 'react'
import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'
import type { VaultEntry } from '../types'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import {
MagnifyingGlass,
GitBranch,
@@ -14,8 +17,10 @@ import {
ArrowUUpLeft,
Star,
CheckCircle,
ArrowsClockwise,
} from '@phosphor-icons/react'
import { NoteTitleIcon } from './NoteTitleIcon'
import { slugify } from '../hooks/useNoteCreation'
interface BreadcrumbBarProps {
entry: VaultEntry
@@ -37,175 +42,485 @@ interface BreadcrumbBarProps {
onDelete?: () => void
onArchive?: () => void
onUnarchive?: () => void
onRenameFilename?: (path: string, newFilenameStem: string) => void
/** Ref for direct DOM manipulation — avoids re-render on scroll. */
barRef?: React.Ref<HTMLDivElement>
}
const DISABLED_ICON_STYLE = { opacity: 0.4, cursor: 'not-allowed' } as const
const BREADCRUMB_ICON_CLASS = 'size-[16px]'
function RawToggleButton({ rawMode, onToggleRaw }: { rawMode?: boolean; onToggleRaw?: () => void }) {
function focusFilenameInput(
isEditing: boolean,
inputRef: React.RefObject<HTMLInputElement | null>,
) {
if (!isEditing) return
inputRef.current?.focus()
inputRef.current?.select()
}
function beginFilenameEditing(
onRenameFilename: BreadcrumbBarProps['onRenameFilename'],
filenameStem: string,
setDraftStem: (value: string) => void,
setIsEditing: (value: boolean) => void,
) {
if (!onRenameFilename) return
setDraftStem(filenameStem)
setIsEditing(true)
}
function resolveFilenameRenameTarget(draftStem: string, filenameStem: string): string | null {
const nextStem = normalizeFilenameStemInput(draftStem)
if (!nextStem || nextStem === filenameStem) return null
return nextStem
}
function handleFilenameInputKeyDown(
event: KeyboardEvent<HTMLInputElement>,
submitRename: () => void,
cancelEditing: () => void,
) {
switch (event.key) {
case 'Enter':
event.preventDefault()
submitRename()
return
case 'Escape':
event.preventDefault()
cancelEditing()
return
default:
return
}
}
function IconActionButton({
title,
onClick,
className,
style,
disabled,
tabIndex,
children,
testId,
}: {
title: string
onClick?: () => void
className?: string
style?: CSSProperties
disabled?: boolean
tabIndex?: number
children: ReactNode
testId?: string
}) {
return (
<button
className={cn(
'flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors',
rawMode ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
)}
onClick={onToggleRaw}
title={rawMode ? 'Back to editor' : 'Raw editor'}
<Button
type="button"
variant="ghost"
size="icon-xs"
className={cn('text-muted-foreground [&_svg:not([class*=size-])]:size-4', className)}
style={style}
onClick={onClick}
disabled={disabled}
tabIndex={tabIndex}
title={title}
data-testid={testId}
>
<Code size={16} />
</button>
{children}
</Button>
)
}
function BreadcrumbActions({ entry, showDiffToggle, diffMode, diffLoading, onToggleDiff,
rawMode, onToggleRaw, forceRawMode,
showAIChat, onToggleAIChat, inspectorCollapsed, onToggleInspector,
onToggleFavorite, onToggleOrganized, onDelete, onArchive, onUnarchive,
}: Omit<BreadcrumbBarProps, 'wordCount'>) {
function RawToggleButton({ rawMode, onToggleRaw }: { rawMode?: boolean; onToggleRaw?: () => void }) {
return (
<div className="breadcrumb-bar__actions ml-auto flex items-center" style={{ gap: 12 }}>
<button
className={cn(
"flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors",
entry.favorite ? "text-yellow-500" : "text-muted-foreground hover:text-foreground"
)}
onClick={onToggleFavorite}
title={entry.favorite ? 'Remove from favorites' : 'Add to favorites'}
>
<Star size={16} weight={entry.favorite ? 'fill' : 'regular'} />
</button>
{onToggleOrganized && (
<button
className={cn(
"flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors",
entry.organized ? "text-green-600" : "text-muted-foreground hover:text-foreground"
)}
onClick={onToggleOrganized}
title={entry.organized ? 'Mark as unorganized (back to Inbox) (Cmd+E)' : 'Mark as organized (remove from Inbox) (Cmd+E)'}
>
<CheckCircle size={16} weight={entry.organized ? 'fill' : 'regular'} />
</button>
)}
<button
className="flex items-center justify-center border-none bg-transparent p-0 text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
title="Search in file"
>
<MagnifyingGlass size={16} />
</button>
{showDiffToggle ? (
<button
className={cn(
"flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors",
diffMode ? "text-foreground" : "text-muted-foreground hover:text-foreground"
)}
onClick={onToggleDiff}
disabled={diffLoading}
title={diffLoading ? 'Loading diff...' : diffMode ? 'Back to editor' : 'Show diff'}
>
<GitBranch size={16} />
</button>
) : (
<button
className="flex items-center justify-center border-none bg-transparent p-0 text-muted-foreground"
style={DISABLED_ICON_STYLE}
title="No changes"
tabIndex={-1}
>
<GitBranch size={16} />
</button>
)}
{!forceRawMode && <RawToggleButton rawMode={rawMode} onToggleRaw={onToggleRaw} />}
<button
className="flex items-center justify-center border-none bg-transparent p-0 text-muted-foreground"
style={DISABLED_ICON_STYLE}
title="Coming soon"
tabIndex={-1}
>
<CursorText size={16} />
</button>
<button
className={cn(
"flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors",
showAIChat ? "" : "text-muted-foreground hover:text-foreground"
)}
style={showAIChat ? { color: 'var(--primary)' } : undefined}
onClick={onToggleAIChat}
title={showAIChat ? 'Close AI Chat' : 'Open AI Chat'}
>
<Sparkle size={16} weight={showAIChat ? 'fill' : 'regular'} />
</button>
{entry.archived ? (
<button
className="flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors text-muted-foreground hover:text-foreground"
onClick={onUnarchive}
title="Unarchive"
>
<ArrowUUpLeft size={16} />
</button>
) : (
<button
className="flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors text-muted-foreground hover:text-foreground"
onClick={onArchive}
title="Archive"
>
<Archive size={16} />
</button>
)}
<button
className="flex items-center justify-center border-none bg-transparent p-0 cursor-pointer transition-colors text-muted-foreground hover:text-destructive"
onClick={onDelete}
title="Delete (Cmd+Delete)"
>
<Trash size={16} />
</button>
{inspectorCollapsed && (
<button
className="flex items-center justify-center border-none bg-transparent p-0 text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
onClick={onToggleInspector}
title="Properties (⌘⇧I)"
>
<SlidersHorizontal size={16} />
</button>
)}
<button
className="flex items-center justify-center border-none bg-transparent p-0 text-muted-foreground"
style={DISABLED_ICON_STYLE}
title="Coming soon"
tabIndex={-1}
>
<DotsThree size={16} />
</button>
<IconActionButton
title={rawMode ? 'Back to editor' : 'Raw editor'}
onClick={onToggleRaw}
className={cn(rawMode ? 'text-foreground' : 'hover:text-foreground')}
>
<Code size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function FavoriteAction({ favorite, onToggleFavorite }: { favorite: boolean; onToggleFavorite?: () => void }) {
return (
<IconActionButton
title={favorite ? 'Remove from favorites' : 'Add to favorites'}
onClick={onToggleFavorite}
className={cn(favorite ? 'text-yellow-500' : 'hover:text-foreground')}
>
<Star size={16} weight={favorite ? 'fill' : 'regular'} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function OrganizedAction({
organized,
onToggleOrganized,
}: {
organized: boolean
onToggleOrganized?: () => void
}) {
if (!onToggleOrganized) return null
return (
<IconActionButton
title={organized ? 'Mark as unorganized (back to Inbox) (Cmd+E)' : 'Mark as organized (remove from Inbox) (Cmd+E)'}
onClick={onToggleOrganized}
className={cn(organized ? 'text-green-600' : 'hover:text-foreground')}
>
<CheckCircle size={16} weight={organized ? 'fill' : 'regular'} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function SearchAction() {
return (
<IconActionButton title="Search in file" className="hover:text-foreground">
<MagnifyingGlass size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function DiffAction({
showDiffToggle,
diffMode,
diffLoading,
onToggleDiff,
}: Pick<BreadcrumbBarProps, 'showDiffToggle' | 'diffMode' | 'diffLoading' | 'onToggleDiff'>) {
if (!showDiffToggle) {
return (
<IconActionButton title="No changes" style={DISABLED_ICON_STYLE} tabIndex={-1}>
<GitBranch size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
return (
<IconActionButton
title={diffLoading ? 'Loading diff...' : diffMode ? 'Back to editor' : 'Show diff'}
onClick={onToggleDiff}
disabled={diffLoading}
className={cn(diffMode ? 'text-foreground' : 'hover:text-foreground')}
>
<GitBranch size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function PlaceholderAction({ title, children }: { title: string; children: ReactNode }) {
return (
<IconActionButton title={title} style={DISABLED_ICON_STYLE} tabIndex={-1}>
{children}
</IconActionButton>
)
}
function AIChatAction({ showAIChat, onToggleAIChat }: Pick<BreadcrumbBarProps, 'showAIChat' | 'onToggleAIChat'>) {
return (
<IconActionButton
title={showAIChat ? 'Close AI Chat' : 'Open AI Chat'}
onClick={onToggleAIChat}
className={cn(showAIChat ? 'text-primary' : 'hover:text-foreground')}
>
<Sparkle size={16} weight={showAIChat ? 'fill' : 'regular'} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function ArchiveAction({
archived,
onArchive,
onUnarchive,
}: Pick<VaultEntry, 'archived'> & Pick<BreadcrumbBarProps, 'onArchive' | 'onUnarchive'>) {
if (archived) {
return (
<IconActionButton title="Unarchive" onClick={onUnarchive} className="hover:text-foreground">
<ArrowUUpLeft size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
return (
<IconActionButton title="Archive" onClick={onArchive} className="hover:text-foreground">
<Archive size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function DeleteAction({ onDelete }: Pick<BreadcrumbBarProps, 'onDelete'>) {
return (
<IconActionButton title="Delete (Cmd+Delete)" onClick={onDelete} className="hover:text-destructive">
<Trash size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function InspectorAction({
inspectorCollapsed,
onToggleInspector,
}: Pick<BreadcrumbBarProps, 'inspectorCollapsed' | 'onToggleInspector'>) {
if (!inspectorCollapsed) return null
return (
<IconActionButton title="Properties (⌘⇧I)" onClick={onToggleInspector} className="hover:text-foreground">
<SlidersHorizontal size={16} className={BREADCRUMB_ICON_CLASS} />
</IconActionButton>
)
}
function normalizeFilenameStemInput(value: string): string {
const trimmed = value.trim()
return trimmed.replace(/\.md$/i, '').trim()
}
function deriveSyncStem(entry: VaultEntry): string | null {
const expectedStem = slugify(entry.title.trim())
const filenameStem = entry.filename.replace(/\.md$/, '')
if (!expectedStem || expectedStem === filenameStem) return null
return expectedStem
}
function FilenameInput({
inputRef,
draftStem,
onDraftStemChange,
onBlur,
onKeyDown,
}: {
inputRef: React.RefObject<HTMLInputElement | null>
draftStem: string
onDraftStemChange: (nextValue: string) => void
onBlur: () => void
onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => void
}) {
return (
<Input
ref={inputRef}
value={draftStem}
onChange={(event) => onDraftStemChange(event.target.value)}
onBlur={onBlur}
onKeyDown={onKeyDown}
className="h-7 w-[180px] text-sm"
data-testid="breadcrumb-filename-input"
aria-label="Rename filename"
/>
)
}
function FilenameTrigger({
entry,
filenameStem,
onStartEditing,
}: {
entry: VaultEntry
filenameStem: string
onStartEditing: () => void
}) {
const handleKeyDown = useCallback((event: KeyboardEvent<HTMLButtonElement>) => {
if (event.key !== 'Enter') return
event.preventDefault()
onStartEditing()
}, [onStartEditing])
return (
<Button
type="button"
variant="ghost"
size="xs"
className="h-auto min-w-0 gap-1 px-0 py-0 text-sm font-medium text-foreground hover:bg-transparent hover:text-foreground"
onDoubleClick={onStartEditing}
onKeyDown={handleKeyDown}
data-testid="breadcrumb-filename-trigger"
aria-label={`Filename ${filenameStem}. Press Enter to rename`}
>
<NoteTitleIcon icon={entry.icon} size={15} testId="breadcrumb-note-icon" />
<span className="truncate">{filenameStem}</span>
</Button>
)
}
function SyncFilenameButton({
entryPath,
syncStem,
onRenameFilename,
}: {
entryPath: string
syncStem: string | null
onRenameFilename?: (path: string, newFilenameStem: string) => void
}) {
if (!syncStem || !onRenameFilename) return null
return (
<TooltipProvider delayDuration={100}>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
className="text-muted-foreground hover:text-foreground"
onClick={() => onRenameFilename(entryPath, syncStem)}
data-testid="breadcrumb-sync-button"
aria-label="Rename file to match title"
>
<ArrowsClockwise size={14} />
</Button>
</TooltipTrigger>
<TooltipContent>
Rename file to match title
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
function FilenameDisplay({
entry,
filenameStem,
syncStem,
onRenameFilename,
onStartEditing,
}: {
entry: VaultEntry
filenameStem: string
syncStem: string | null
onRenameFilename?: (path: string, newFilenameStem: string) => void
onStartEditing: () => void
}) {
return (
<div className="flex min-w-0 items-center gap-1">
<FilenameTrigger entry={entry} filenameStem={filenameStem} onStartEditing={onStartEditing} />
<SyncFilenameButton entryPath={entry.path} syncStem={syncStem} onRenameFilename={onRenameFilename} />
</div>
)
}
function BreadcrumbTitle({ entry }: { entry: VaultEntry }) {
function FilenameCrumb({ entry, onRenameFilename }: Pick<BreadcrumbBarProps, 'entry' | 'onRenameFilename'>) {
const filenameStem = useMemo(() => entry.filename.replace(/\.md$/, ''), [entry.filename])
const syncStem = useMemo(() => deriveSyncStem(entry), [entry])
const [isEditing, setIsEditing] = useState(false)
const [draftStem, setDraftStem] = useState(filenameStem)
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
focusFilenameInput(isEditing, inputRef)
}, [isEditing])
const startEditing = useCallback(() => {
beginFilenameEditing(onRenameFilename, filenameStem, setDraftStem, setIsEditing)
}, [onRenameFilename, filenameStem])
const cancelEditing = useCallback(() => {
setDraftStem(filenameStem)
setIsEditing(false)
}, [filenameStem])
const submitRename = useCallback(() => {
setIsEditing(false)
const nextStem = resolveFilenameRenameTarget(draftStem, filenameStem)
if (!nextStem) return
onRenameFilename?.(entry.path, nextStem)
}, [draftStem, filenameStem, onRenameFilename, entry.path])
const handleInputKeyDown = useCallback((event: KeyboardEvent<HTMLInputElement>) => {
handleFilenameInputKeyDown(event, submitRename, cancelEditing)
}, [submitRename, cancelEditing])
if (isEditing) {
return (
<FilenameInput
inputRef={inputRef}
draftStem={draftStem}
onDraftStemChange={setDraftStem}
onBlur={submitRename}
onKeyDown={handleInputKeyDown}
/>
)
}
return (
<FilenameDisplay
entry={entry}
filenameStem={filenameStem}
syncStem={syncStem}
onRenameFilename={onRenameFilename}
onStartEditing={startEditing}
/>
)
}
function BreadcrumbActions({
entry,
showDiffToggle,
diffMode,
diffLoading,
onToggleDiff,
rawMode,
onToggleRaw,
forceRawMode,
showAIChat,
onToggleAIChat,
inspectorCollapsed,
onToggleInspector,
onToggleFavorite,
onToggleOrganized,
onDelete,
onArchive,
onUnarchive,
}: Omit<BreadcrumbBarProps, 'wordCount' | 'barRef' | 'onRenameFilename'>) {
return (
<div className="breadcrumb-bar__actions ml-auto flex items-center" style={{ gap: 12 }}>
<FavoriteAction favorite={entry.favorite} onToggleFavorite={onToggleFavorite} />
<OrganizedAction organized={entry.organized} onToggleOrganized={onToggleOrganized} />
<SearchAction />
<DiffAction
showDiffToggle={showDiffToggle}
diffMode={diffMode}
diffLoading={diffLoading}
onToggleDiff={onToggleDiff}
/>
{!forceRawMode && <RawToggleButton rawMode={rawMode} onToggleRaw={onToggleRaw} />}
<PlaceholderAction title="Coming soon">
<CursorText size={16} className={BREADCRUMB_ICON_CLASS} />
</PlaceholderAction>
<AIChatAction showAIChat={showAIChat} onToggleAIChat={onToggleAIChat} />
<ArchiveAction archived={entry.archived} onArchive={onArchive} onUnarchive={onUnarchive} />
<DeleteAction onDelete={onDelete} />
<InspectorAction inspectorCollapsed={inspectorCollapsed} onToggleInspector={onToggleInspector} />
<PlaceholderAction title="Coming soon">
<DotsThree size={16} className={BREADCRUMB_ICON_CLASS} />
</PlaceholderAction>
</div>
)
}
function BreadcrumbTitle({
entry,
onRenameFilename,
}: Pick<BreadcrumbBarProps, 'entry' | 'onRenameFilename'>) {
const typeLabel = entry.isA ?? 'Note'
const filenameStem = entry.filename.replace(/\.md$/, '')
return (
<div className="flex items-center gap-1.5 min-w-0 text-sm text-muted-foreground">
<span className="shrink-0">{typeLabel}</span>
<span className="shrink-0 text-border"></span>
<span className="flex min-w-0 items-center gap-1 truncate font-medium text-foreground">
<NoteTitleIcon icon={entry.icon} size={15} testId="breadcrumb-note-icon" />
<span className="truncate">{filenameStem}</span>
</span>
<div className="flex min-w-0 items-center gap-1 truncate">
<FilenameCrumb entry={entry} onRenameFilename={onRenameFilename} />
</div>
</div>
)
}
export const BreadcrumbBar = memo(function BreadcrumbBar({
entry, barRef, ...actionProps
entry,
barRef,
onRenameFilename,
...actionProps
}: BreadcrumbBarProps) {
// In raw/diff mode the title section is not rendered — always show title in breadcrumb.
// Using a prop-driven attribute avoids the timing issues of DOM mutation in useEffect.
const titleAlwaysVisible = actionProps.rawMode || actionProps.diffMode
return (
<div
ref={barRef}
data-tauri-drag-region
{...(titleAlwaysVisible ? { 'data-title-hidden': '' } : {})}
data-title-hidden=""
className="breadcrumb-bar flex shrink-0 items-center border-b border-transparent"
style={{
height: 52,
@@ -215,7 +530,7 @@ export const BreadcrumbBar = memo(function BreadcrumbBar({
}}
>
<div className="breadcrumb-bar__title flex-1 min-w-0">
<BreadcrumbTitle entry={entry} />
<BreadcrumbTitle entry={entry} onRenameFilename={onRenameFilename} />
</div>
<BreadcrumbActions entry={entry} {...actionProps} />
</div>

View File

@@ -0,0 +1,70 @@
import { readFileSync } from 'node:fs'
import { render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { BreadcrumbBar } from './BreadcrumbBar'
import './Editor.css'
import type { VaultEntry } from '../types'
const baseEntry: VaultEntry = {
path: '/vault/note/test.md',
filename: 'test.md',
title: 'Test Note',
isA: 'Note',
aliases: [],
belongsTo: [],
relatedTo: [],
status: null,
archived: false,
modifiedAt: 1700000000,
createdAt: null,
fileSize: 100,
snippet: '',
wordCount: 0,
relationships: {},
icon: null,
color: null,
order: null,
outgoingLinks: [],
template: null,
sort: null,
sidebarLabel: null,
view: null,
visible: null,
properties: {},
organized: false,
favorite: false,
favoriteIndex: null,
listPropertiesDisplay: [],
hasH1: false,
}
const defaultProps = {
wordCount: 100,
showDiffToggle: false,
diffMode: false,
diffLoading: false,
onToggleDiff: vi.fn(),
}
describe('BreadcrumbBar filename visibility', () => {
it('keeps the filename visible in the breadcrumb by default', () => {
render(<BreadcrumbBar entry={baseEntry} {...defaultProps} />)
expect(screen.getByText('test')).toBeVisible()
})
it('keeps the filename visible even when the bar is marked as title-hidden', () => {
const { container } = render(<BreadcrumbBar entry={baseEntry} {...defaultProps} />)
container.querySelector('.breadcrumb-bar')?.setAttribute('data-title-hidden', '')
expect(screen.getByText('test')).toBeVisible()
})
it('keeps breadcrumb action buttons on the zero-padding footprint', () => {
const editorCss = readFileSync(`${process.cwd()}/src/components/Editor.css`, 'utf8')
expect(editorCss).toContain(".breadcrumb-bar__actions [data-slot='button']")
expect(editorCss).toContain('width: auto;')
expect(editorCss).toContain('height: auto;')
expect(editorCss).toContain('padding: 0;')
expect(editorCss).toContain('border-radius: 0;')
})
})

View File

@@ -19,7 +19,7 @@ const makeCommand = (overrides: Partial<CommandAction> = {}): CommandAction => (
const commands: CommandAction[] = [
makeCommand({ id: 'search-notes', label: 'Search Notes', group: 'Navigation', shortcut: '⌘P', keywords: ['find'] }),
makeCommand({ id: 'create-note', label: 'Create New Note', group: 'Note', shortcut: '⌘N' }),
makeCommand({ id: 'create-note', label: 'New Note', group: 'Note', shortcut: '⌘N' }),
makeCommand({ id: 'commit-push', label: 'Commit & Push', group: 'Git', keywords: ['git', 'sync'] }),
makeCommand({ id: 'open-settings', label: 'Open Settings', group: 'Settings', shortcut: '⌘,' }),
makeCommand({ id: 'disabled-cmd', label: 'Disabled Command', group: 'Note', enabled: false }),
@@ -47,7 +47,7 @@ describe('CommandPalette', () => {
it('shows all enabled commands grouped by category', () => {
render(<CommandPalette open={true} commands={commands} onClose={onClose} />)
expect(screen.getByText('Search Notes')).toBeInTheDocument()
expect(screen.getByText('Create New Note')).toBeInTheDocument()
expect(screen.getByText('New Note')).toBeInTheDocument()
expect(screen.getByText('Commit & Push')).toBeInTheDocument()
expect(screen.getByText('Open Settings')).toBeInTheDocument()
// Disabled command should not appear
@@ -115,7 +115,7 @@ describe('CommandPalette', () => {
fireEvent.keyDown(window, { key: 'ArrowDown' })
fireEvent.keyDown(window, { key: 'Enter' })
// Second enabled command (Create New Note) should execute
// Second enabled command (New Note) should execute
expect(commands[1].execute).toHaveBeenCalled()
expect(onClose).toHaveBeenCalled()
})
@@ -168,7 +168,7 @@ describe('CommandPalette', () => {
describe('relevance ranking', () => {
const relevanceCommands: CommandAction[] = [
makeCommand({ id: 'create-note', label: 'Create New Note', group: 'Note' }),
makeCommand({ id: 'create-note', label: 'New Note', group: 'Note' }),
makeCommand({ id: 'toggle-raw', label: 'Toggle Raw Editor', group: 'View' }),
makeCommand({ id: 'search-notes', label: 'Search Notes', group: 'Navigation' }),
]
@@ -182,24 +182,20 @@ describe('CommandPalette', () => {
).map(el => el.textContent)
}
it('ranks "Toggle Raw Editor" before "Create New Note" for query "raw"', () => {
it('shows only the relevant raw command for query "raw"', () => {
render(<CommandPalette open={true} commands={relevanceCommands} onClose={onClose} />)
fireEvent.change(screen.getByPlaceholderText('Type a command...'), { target: { value: 'raw' } })
const labels = getVisibleLabels()
const rawIdx = labels.indexOf('Toggle Raw Editor')
const createIdx = labels.indexOf('Create New Note')
expect(rawIdx).toBeGreaterThanOrEqual(0)
expect(createIdx).toBeGreaterThanOrEqual(0)
expect(rawIdx).toBeLessThan(createIdx)
expect(labels).toEqual(['Toggle Raw Editor'])
})
it('ranks "Create New Note" first for query "new note"', () => {
it('ranks "New Note" first for query "new note"', () => {
render(<CommandPalette open={true} commands={relevanceCommands} onClose={onClose} />)
fireEvent.change(screen.getByPlaceholderText('Type a command...'), { target: { value: 'new note' } })
const labels = getVisibleLabels()
expect(labels[0]).toBe('Create New Note')
expect(labels[0]).toBe('New Note')
})
it('preserves default section order with empty query', () => {

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

@@ -22,7 +22,8 @@
opacity: 0.55;
}
/* Breadcrumb bar: title + border toggled via data attribute (no React re-render) */
/* Breadcrumb bar: border can still react to the data attribute, but the
breadcrumb filename/title stays visible at all times. */
.breadcrumb-bar {
transition: border-color 0.2s ease;
}
@@ -32,11 +33,19 @@
}
.breadcrumb-bar__title {
display: none;
display: flex;
}
.breadcrumb-bar[data-title-hidden] .breadcrumb-bar__title {
display: flex;
.breadcrumb-bar__actions [data-slot='button'] {
width: auto;
height: auto;
min-width: 0;
padding: 0;
border-radius: 0;
}
.breadcrumb-bar__actions [data-slot='button']:hover {
background: transparent;
}
/* Scroll area wrapping title + editor — single scroll context for alignment */
@@ -195,57 +204,6 @@
width: 100%;
}
/* --- Title Section: wraps icon + title + separator --- */
.title-section {
width: 100%;
flex-shrink: 0;
}
.title-section__heading {
position: relative;
}
.title-section__inline-add-icon {
position: absolute;
left: 8px;
top: 0;
z-index: 1;
opacity: 0;
pointer-events: none;
transition: opacity 0.15s;
}
.title-section:hover .title-section__inline-add-icon,
.title-section__inline-add-icon:focus-within {
opacity: 1;
pointer-events: auto;
}
.title-section__row {
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 10px;
padding-top: 8px;
margin-left: 8px;
}
/* No emoji: title aligns flush left (no indent for icon area) */
.title-section__row--no-icon {
margin-left: 0;
}
/* When emoji is present, restore top padding to the row itself */
.title-section__row:has(.note-icon-button--active) {
padding-top: 32px;
}
.title-section__separator {
border-bottom: 1px solid var(--border-primary, rgba(0, 0, 0, 0.08));
margin-top: 12px;
margin-left: 8px;
}
/* --- Note Icon Area --- */
.note-icon-area {
display: flex;
@@ -294,7 +252,6 @@
transition: opacity 0.15s;
}
.title-section:hover .note-icon-button--add,
.note-icon-button--add:focus-visible {
opacity: 1;
}
@@ -343,56 +300,6 @@
color: var(--destructive, #ef4444);
}
/* --- Title Field --- */
.title-field {
flex: 1;
min-width: 0;
}
.title-field__input {
display: block;
width: 100%;
border: none;
outline: none;
background: transparent;
font-size: var(--headings-h1-font-size, 32px);
font-weight: var(--headings-h1-font-weight, 700);
line-height: var(--headings-h1-line-height, 1.2);
letter-spacing: var(--headings-h1-letter-spacing, -0.015em);
color: var(--foreground);
padding: 0;
resize: none;
overflow: hidden;
font-family: inherit;
field-sizing: content;
}
.title-field__input::placeholder {
color: var(--text-faint, #ccc);
}
.title-field__input:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.title-field__filename {
display: block;
font-size: 11px;
color: var(--text-faint, #999);
margin-top: 2px;
}
/* When the legacy title UI is shown, hide the first H1 heading in BlockNote
to avoid duplicate title display. Otherwise the editor's H1 remains visible
and serves as the title surface. */
.title-section[data-title-ui-visible] ~ .editor__blocknote-container [data-node-type="blockContainer"]:first-child [data-content-type="heading"][data-level="1"] {
display: none;
}
.title-section[data-title-ui-visible] ~ .editor__blocknote-container [data-node-type="blockContainer"]:first-child:has([data-content-type="heading"][data-level="1"]) {
display: none;
}
/* =============================================
Disable BlockNote/Mantine editor animations
=============================================

View File

@@ -413,7 +413,7 @@ describe('wikilink autocomplete', () => {
expect(items.length).toBeGreaterThan(0)
items[0].onItemClick()
expect(mockEditor.insertInlineContent).toHaveBeenCalledWith([
{ type: 'wikilink', props: { target: 'vault/project/test|Alpha Project' } },
{ type: 'wikilink', props: { target: 'vault/project/test' } },
' ',
])
})
@@ -566,7 +566,7 @@ describe('person @mention autocomplete', () => {
expect(items.length).toBeGreaterThan(0)
items[0].onItemClick()
expect(mockEditor.insertInlineContent).toHaveBeenCalledWith([
{ type: 'wikilink', props: { target: 'vault/person/matteo-cellini|Matteo Cellini' } },
{ type: 'wikilink', props: { target: 'vault/person/matteo-cellini' } },
' ',
])
})

View File

@@ -54,8 +54,8 @@ interface EditorProps {
onUnarchiveNote?: (path: string) => void
onContentChange?: (path: string, content: string) => void
onSave?: () => void
/** Called when the user edits the title in TitleField. */
onTitleSync?: (path: string, newTitle: string) => void
/** Called when the user explicitly renames the filename from the breadcrumb. */
onRenameFilename?: (path: string, newFilenameStem: string) => void
canGoBack?: boolean
canGoForward?: boolean
onGoBack?: () => void
@@ -203,7 +203,7 @@ export const Editor = memo(function Editor(props: EditorProps) {
showAIChat, onToggleAIChat,
vaultPath, noteList, noteListFilter,
onToggleFavorite, onToggleOrganized, onDeleteNote, onArchiveNote, onUnarchiveNote,
onContentChange, onSave, onTitleSync,
onContentChange, onSave, onRenameFilename,
onFileCreated, onFileModified, onVaultChanged,
isConflicted, onKeepMine, onKeepTheirs,
} = props
@@ -254,7 +254,7 @@ export const Editor = memo(function Editor(props: EditorProps) {
onUnarchiveNote={onUnarchiveNote}
vaultPath={vaultPath}
rawLatestContentRef={rawLatestContentRef}
onTitleChange={onTitleSync}
onRenameFilename={onRenameFilename}
isConflicted={isConflicted}
onKeepMine={onKeepMine}
onKeepTheirs={onKeepTheirs}

View File

@@ -75,6 +75,7 @@ export function EditorRightPanel({
content={inspectorContent}
entries={entries}
gitHistory={gitHistory}
vaultPath={vaultPath}
onNavigate={onNavigateWikilink}
onViewCommitDiff={onViewCommitDiff}
onUpdateFrontmatter={onUpdateFrontmatter}

View File

@@ -68,6 +68,12 @@
color: var(--headings-h1-color);
letter-spacing: var(--headings-h1-letter-spacing);
}
.editor__blocknote-container [data-content-type="heading"]:not([data-level])[data-is-empty-and-focused] .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child)::before,
.editor__blocknote-container [data-content-type="heading"]:not([data-level])[data-is-only-empty-block] .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child)::before,
.editor__blocknote-container [data-content-type="heading"][data-level="1"][data-is-empty-and-focused] .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child)::before,
.editor__blocknote-container [data-content-type="heading"][data-level="1"][data-is-only-empty-block] .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child)::before {
content: "Title" !important;
}
.editor__blocknote-container .bn-block-outer:has(> .bn-block > [data-content-type="heading"][data-level="2"]) {
margin-top: var(--headings-h2-margin-top) !important;

View File

@@ -24,6 +24,7 @@ interface InspectorProps {
content: string | null
entries: VaultEntry[]
gitHistory: GitCommit[]
vaultPath?: string
onNavigate: (target: string) => void
onViewCommitDiff?: (commitHash: string) => void
onUpdateFrontmatter?: (path: string, key: string, value: FrontmatterValue) => Promise<void>
@@ -41,6 +42,7 @@ export function Inspector({
content,
entries,
gitHistory,
vaultPath,
onNavigate,
onViewCommitDiff,
onUpdateFrontmatter,
@@ -96,6 +98,7 @@ export function Inspector({
frontmatter={frontmatter}
entries={entries}
typeEntryMap={typeEntryMap}
vaultPath={vaultPath}
onNavigate={onNavigate}
onAddProperty={onAddProperty ? handleAddProperty : undefined}
onUpdateProperty={onUpdateFrontmatter ? handleUpdateProperty : undefined}

View File

@@ -179,7 +179,7 @@ describe('DynamicRelationshipsPanel', () => {
fireEvent.change(screen.getByPlaceholderText('Relationship name'), { target: { value: 'Related to' } })
fireEvent.change(screen.getByPlaceholderText('Note title'), { target: { value: 'AI' } })
fireEvent.click(screen.getByTestId('submit-add-relationship'))
expect(onAddProperty).toHaveBeenCalledWith('Related to', '[[AI]]')
expect(onAddProperty).toHaveBeenCalledWith('Related to', '[[topic/ai]]')
})
it('cancels add relationship form', () => {
@@ -427,14 +427,14 @@ describe('DynamicRelationshipsPanel', () => {
const input = screen.getByTestId('add-relation-ref-input')
fireEvent.change(input, { target: { value: 'AI' } })
fireEvent.keyDown(input, { key: 'Enter' })
expect(onUpdateProperty).toHaveBeenCalledWith('Belongs to', ['[[project/my-project]]', '[[AI]]'])
expect(onUpdateProperty).toHaveBeenCalledWith('Belongs to', ['[[project/my-project]]', '[[topic/ai]]'])
})
it('does not add duplicate refs', () => {
render(
<DynamicRelationshipsPanel
typeEntryMap={{}}
frontmatter={{ 'Belongs to': ['[[AI]]'] }}
frontmatter={{ 'Belongs to': ['[[topic/ai]]'] }}
entries={entries}
onNavigate={onNavigate}
onUpdateProperty={onUpdateProperty}
@@ -533,7 +533,7 @@ describe('DynamicRelationshipsPanel', () => {
fireEvent.click(screen.getByTestId('create-and-open-option'))
expect(onCreateAndOpenNote).toHaveBeenCalledWith('Brand New Note')
await vi.waitFor(() => {
expect(onUpdateProperty).toHaveBeenCalledWith('Belongs to', ['[[project/my-project]]', '[[Brand New Note]]'])
expect(onUpdateProperty).toHaveBeenCalledWith('Belongs to', ['[[project/my-project]]', '[[brand-new-note]]'])
})
})
@@ -647,7 +647,7 @@ describe('DynamicRelationshipsPanel', () => {
fireEvent.click(screen.getByTestId('create-and-open-option'))
expect(onCreateAndOpenNote).toHaveBeenCalledWith('New Person')
await vi.waitFor(() => {
expect(onAddProperty).toHaveBeenCalledWith('Mentions', '[[New Person]]')
expect(onAddProperty).toHaveBeenCalledWith('Mentions', '[[new-person]]')
})
})
})

View File

@@ -123,7 +123,7 @@ describe('NoteItem', () => {
render(<NoteItem entry={entry} isSelected={false} typeEntryMap={{}} onClickNote={vi.fn()} />)
const dateRow = screen.getByTestId('note-date-row')
expect(dateRow.className).toContain('justify-between')
expect(dateRow.className).toContain('grid')
expect(dateRow).toHaveTextContent('2d ago')
expect(dateRow).toHaveTextContent('Created 5d ago')
})

View File

@@ -163,7 +163,7 @@ function StandardNoteContent({
<>
{/* eslint-disable-next-line react-hooks/static-components -- icon lookup from static map, no internal state */}
<TypeIcon width={14} height={14} className="absolute right-3 top-2.5" style={{ color: typeColor }} data-testid="type-icon" />
<div className="space-y-2 pr-5" data-testid="note-content-stack">
<div className="space-y-2" data-testid="note-content-stack">
<NoteTitleRow
entry={entry}
isBinary={isBinary}
@@ -206,7 +206,7 @@ function NoteTitleRow({
noteStatus: NoteStatus
}) {
return (
<div className={cn('truncate text-[13px]', isBinary ? 'text-muted-foreground' : 'text-foreground', isSelected && !isBinary ? 'font-semibold' : 'font-medium')}>
<div className={cn('truncate pr-5 text-[13px]', isBinary ? 'text-muted-foreground' : 'text-foreground', isSelected && !isBinary ? 'font-semibold' : 'font-medium')}>
{noteStatus !== 'clean' && !isBinary && <StatusDot noteStatus={noteStatus} />}
<NoteTitleIcon icon={entry.icon} size={15} className="mr-1" testId="note-title-icon" />
{entry.title}
@@ -222,9 +222,9 @@ function NoteDateRow({ entry }: { entry: VaultEntry }) {
if (!modifiedLabel && !createdLabel) return null
return (
<div className="flex items-center justify-between gap-3 text-[10px] text-muted-foreground" data-testid="note-date-row">
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 text-[10px] text-muted-foreground" data-testid="note-date-row">
<span>{modifiedLabel}</span>
{createdLabel && <span className="shrink-0">{createdLabel}</span>}
{createdLabel && <span className="justify-self-end text-right">{createdLabel}</span>}
</div>
)
}

View File

@@ -9,6 +9,23 @@ import {
renderNoteList,
} from '../test-utils/noteListTestUtils'
function makeBookTypeEntries(
displayProps: string[] = [],
entryOverrides: Parameters<typeof makeEntry>[0] = {},
) {
return [
makeTypeDefinition('Book', displayProps),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
createdAt: 1700000000,
...entryOverrides,
}),
]
}
describe('NoteList rendering', () => {
it('shows an empty state when there are no entries', () => {
renderNoteList({ entries: [] })
@@ -137,20 +154,8 @@ describe('NoteList rendering', () => {
})
it('shows the inbox customize-columns action and falls back to type-defined chips', () => {
const entries = [
makeTypeDefinition('Book', ['Priority']),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
properties: { Priority: 'High', Owner: 'Luca' },
createdAt: 1700000000,
}),
]
renderNoteList({
entries,
entries: makeBookTypeEntries(['Priority'], { properties: { Priority: 'High', Owner: 'Luca' } }),
selection: { kind: 'filter', filter: 'inbox' },
inboxNoteListProperties: null,
onUpdateInboxNoteListProperties: () => undefined,
@@ -163,20 +168,9 @@ describe('NoteList rendering', () => {
it('opens the inbox column picker from the global event and saves new columns', () => {
const onUpdateInboxNoteListProperties = vi.fn()
const entries = [
makeTypeDefinition('Book', ['Priority']),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
properties: { Priority: 'High', Owner: 'Luca' },
createdAt: 1700000000,
}),
]
renderNoteList({
entries,
entries: makeBookTypeEntries(['Priority'], { properties: { Priority: 'High', Owner: 'Luca' } }),
selection: { kind: 'filter', filter: 'inbox' },
inboxNoteListProperties: null,
onUpdateInboxNoteListProperties,
@@ -194,20 +188,8 @@ describe('NoteList rendering', () => {
})
it('shows status in the type column picker when at least one note has it set', () => {
const entries = [
makeTypeDefinition('Book'),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
status: 'Active',
createdAt: 1700000000,
}),
]
renderNoteList({
entries,
entries: makeBookTypeEntries([], { status: 'Active' }),
selection: { kind: 'sectionGroup', type: 'Book' },
onUpdateTypeSort: () => undefined,
})
@@ -221,21 +203,8 @@ describe('NoteList rendering', () => {
})
it('keeps blank statuses out of the type column picker', () => {
const entries = [
makeTypeDefinition('Book'),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
status: '',
properties: { Owner: 'Luca' },
createdAt: 1700000000,
}),
]
renderNoteList({
entries,
entries: makeBookTypeEntries([], { status: '', properties: { Owner: 'Luca' } }),
selection: { kind: 'sectionGroup', type: 'Book' },
onUpdateTypeSort: () => undefined,
})
@@ -250,41 +219,41 @@ describe('NoteList rendering', () => {
})
it('renders status as a note-list chip when a type displays it', () => {
const entries = [
makeTypeDefinition('Book', ['status']),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
status: 'Active',
createdAt: 1700000000,
}),
]
renderNoteList({
entries,
entries: makeBookTypeEntries(['status'], { status: 'Active' }),
selection: { kind: 'sectionGroup', type: 'Book' },
})
expect(screen.getByTestId('property-chips')).toHaveTextContent('Active')
const chip = screen.getByTestId('property-chip-status-0')
expect(chip).toHaveTextContent('• Active')
expect(chip).toHaveStyle({ backgroundColor: 'var(--accent-green-light)', color: 'var(--accent-green)' })
})
it('auto-detects status-like property values in note-list chips', () => {
renderNoteList({
entries: makeBookTypeEntries(['Phase'], { properties: { Phase: 'Draft' } }),
selection: { kind: 'sectionGroup', type: 'Book' },
})
const chip = screen.getByTestId('property-chip-phase-0')
expect(chip).toHaveTextContent('• Draft')
expect(chip).toHaveStyle({ backgroundColor: 'var(--accent-yellow-light)', color: 'var(--accent-yellow)' })
})
it('keeps unknown status values on neutral note-list chip styling', () => {
renderNoteList({
entries: makeBookTypeEntries(['status'], { status: 'Needs Review' }),
selection: { kind: 'sectionGroup', type: 'Book' },
})
const chip = screen.getByTestId('property-chip-status-0')
expect(chip).toHaveTextContent('• Needs Review')
expect(chip.getAttribute('style')).toBeNull()
})
it('uses inbox overrides when configured', () => {
const entries = [
makeTypeDefinition('Book', ['Priority']),
makeEntry({
path: '/vault/book.md',
filename: 'book.md',
title: 'Book Note',
isA: 'Book',
properties: { Priority: 'High', Owner: 'Luca' },
createdAt: 1700000000,
}),
]
renderNoteList({
entries,
entries: makeBookTypeEntries(['Priority'], { properties: { Priority: 'High', Owner: 'Luca' } }),
selection: { kind: 'filter', filter: 'inbox' },
inboxNoteListProperties: ['Owner'],
onUpdateInboxNoteListProperties: () => undefined,

View File

@@ -48,6 +48,7 @@ export function QuickOpenPalette({ open, entries, onSelect, onClose }: QuickOpen
return (
<div
data-testid="quick-open-palette"
className="fixed inset-0 z-[1000] flex justify-center bg-[var(--shadow-dialog)] pt-[15vh]"
onClick={onClose}
>

View File

@@ -1,7 +1,6 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, act } from '@testing-library/react'
import { RawEditorView } from './RawEditorView'
import { extractWikilinkQuery, detectYamlError } from '../utils/rawEditorUtils'
function entry(title: string, path = `/vault/note/${title}.md`) {
return {
@@ -23,61 +22,6 @@ const defaultProps = {
onSave: vi.fn(),
}
describe('extractWikilinkQuery', () => {
it('returns null when no [[ trigger', () => {
expect(extractWikilinkQuery('hello world', 5)).toBeNull()
})
it('returns empty string immediately after [[', () => {
const text = 'see [['
expect(extractWikilinkQuery(text, text.length)).toBe('')
})
it('returns query after [[', () => {
const text = 'see [[Proj'
expect(extractWikilinkQuery(text, text.length)).toBe('Proj')
})
it('returns null when ]] closes the link', () => {
const text = '[[Proj]]'
expect(extractWikilinkQuery(text, text.length)).toBeNull()
})
it('returns null when newline is in query', () => {
const text = '[[Proj\ncontinued'
expect(extractWikilinkQuery(text, text.length)).toBeNull()
})
it('handles cursor before end of text', () => {
const text = '[[Proj after'
expect(extractWikilinkQuery(text, 6)).toBe('Proj')
})
})
describe('detectYamlError', () => {
it('returns null for content without frontmatter', () => {
expect(detectYamlError('# Title\n\nSome content.')).toBeNull()
})
it('returns null for valid frontmatter', () => {
expect(detectYamlError('---\ntitle: My Note\n---\n\n# Title')).toBeNull()
})
it('returns error for unclosed frontmatter', () => {
const error = detectYamlError('---\ntitle: My Note\n\n# Title')
expect(error).toContain('Unclosed frontmatter')
})
it('returns error for tab indentation in frontmatter', () => {
const error = detectYamlError('---\n\ttitle: My Note\n---\n')
expect(error).toContain('tab indentation')
})
it('returns null for content not starting with ---', () => {
expect(detectYamlError('Not frontmatter')).toBeNull()
})
})
describe('RawEditorView', () => {
it('renders CodeMirror container', () => {
render(<RawEditorView {...defaultProps} />)

View File

@@ -1,22 +1,21 @@
import { useRef, useState, useCallback, useEffect, useMemo } from 'react'
import { trackEvent } from '../lib/telemetry'
import type { EditorView } from '@codemirror/view'
import { preFilterWikilinks, deduplicateByPath, MIN_QUERY_LENGTH } from '../utils/wikilinkSuggestions'
import { attachClickHandlers, enrichSuggestionItems } from '../utils/suggestionEnrichment'
import { MIN_QUERY_LENGTH } from '../utils/wikilinkSuggestions'
import { buildTypeEntryMap } from '../utils/typeColors'
import { NoteSearchList } from './NoteSearchList'
import { extractWikilinkQuery, detectYamlError } from '../utils/rawEditorUtils'
import {
buildRawEditorAutocompleteState,
buildRawEditorBaseItems,
detectYamlError,
extractWikilinkQuery,
getRawEditorDropdownPosition,
replaceActiveWikilinkQuery,
type RawEditorAutocompleteState,
} from '../utils/rawEditorUtils'
import { useCodeMirror } from '../hooks/useCodeMirror'
import type { WikilinkSuggestionItem } from './WikilinkSuggestionMenu'
import type { VaultEntry } from '../types'
interface AutocompleteState {
caretTop: number
caretLeft: number
selectedIndex: number
items: WikilinkSuggestionItem[]
}
export interface RawEditorViewProps {
content: string
path: string
@@ -32,13 +31,6 @@ export interface RawEditorViewProps {
const DEBOUNCE_MS = 500
const DROPDOWN_MAX_HEIGHT = 200
function getCursorCoords(view: EditorView): { top: number; left: number } | null {
const pos = view.state.selection.main.head
const coords = view.coordsAtPos(pos)
if (!coords) return null
return { top: coords.bottom, left: coords.left }
}
export function RawEditorView({ content, path, entries, onContentChange, onSave, latestContentRef, vaultPath }: RawEditorViewProps) {
const containerRef = useRef<HTMLDivElement>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
@@ -52,23 +44,14 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
useEffect(() => { onContentChangeRef.current = onContentChange }, [onContentChange])
useEffect(() => { onSaveRef.current = onSave }, [onSave])
const [autocomplete, setAutocomplete] = useState<AutocompleteState | null>(null)
const [autocomplete, setAutocomplete] = useState<RawEditorAutocompleteState | null>(null)
const [yamlError, setYamlError] = useState<string | null>(() => detectYamlError(content))
const typeEntryMap = useMemo(() => buildTypeEntryMap(entries), [entries])
const baseItems = useMemo(
() => deduplicateByPath(entries.map(entry => ({
title: entry.title,
aliases: [...new Set([entry.filename.replace(/\.md$/, ''), ...entry.aliases])],
group: entry.isA || 'Note',
entryTitle: entry.title,
path: entry.path,
}))),
[entries],
)
const baseItems = useMemo(() => buildRawEditorBaseItems(entries), [entries])
const insertWikilinkRef = useRef<(entryTitle: string) => void>(() => {})
const insertWikilinkRef = useRef<(target: string) => void>(() => {})
const latestContentRefStable = useRef(latestContentRef)
useEffect(() => { latestContentRefStable.current = latestContentRef }, [latestContentRef])
@@ -91,12 +74,15 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
setAutocomplete(null)
return
}
const coords = getCursorCoords(view)
if (!coords) { setAutocomplete(null); return }
const candidates = preFilterWikilinks(baseItems, query)
const withHandlers = attachClickHandlers(candidates, (title: string) => insertWikilinkRef.current(title), vaultPath ?? '')
const items = enrichSuggestionItems(withHandlers, query, typeEntryMap)
setAutocomplete({ caretTop: coords.top, caretLeft: coords.left, selectedIndex: 0, items })
const nextAutocomplete = buildRawEditorAutocompleteState({
view,
baseItems,
query,
typeEntryMap,
onInsertTarget: (target: string) => insertWikilinkRef.current(target),
vaultPath: vaultPath ?? '',
})
setAutocomplete(nextAutocomplete)
}, [baseItems, typeEntryMap, vaultPath])
const handleSave = useCallback(() => {
@@ -120,30 +106,25 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
onEscape: handleEscape,
})
const insertWikilink = useCallback((entryTitle: string) => {
const insertWikilink = useCallback((target: string) => {
const view = viewRef.current
if (!view) return
const cursor = view.state.selection.main.head
const doc = view.state.doc.toString()
const before = doc.slice(0, cursor)
const triggerIdx = before.lastIndexOf('[[')
if (triggerIdx === -1) return
const after = doc.slice(cursor)
const newText = `${doc.slice(0, triggerIdx)}[[${entryTitle}]]${after}`
const newCursor = triggerIdx + entryTitle.length + 4
const replacement = replaceActiveWikilinkQuery(doc, cursor, target)
if (!replacement) return
view.dispatch({
changes: { from: 0, to: doc.length, insert: newText },
selection: { anchor: newCursor },
changes: { from: 0, to: doc.length, insert: replacement.text },
selection: { anchor: replacement.cursor },
})
trackEvent('wikilink_inserted')
setAutocomplete(null)
if (debounceRef.current) clearTimeout(debounceRef.current)
debounceRef.current = null
latestDocRef.current = newText
onContentChangeRef.current(pathRef.current, newText)
latestDocRef.current = replacement.text
onContentChangeRef.current(pathRef.current, replacement.text)
view.focus()
}, [viewRef])
@@ -165,9 +146,9 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
} else if (e.key === 'Enter') {
e.preventDefault()
const item = autocomplete.items[autocomplete.selectedIndex]
if (item) insertWikilink(item.entryTitle ?? item.title)
if (item) item.onItemClick()
}
}, [autocomplete, insertWikilink])
}, [autocomplete])
// Flush pending debounce on unmount
useEffect(() => {
@@ -179,15 +160,7 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
}
}, [])
const dropdownBelow = autocomplete
? autocomplete.caretTop + 20 + DROPDOWN_MAX_HEIGHT <= window.innerHeight
: true
const dropdownTop = autocomplete
? (dropdownBelow ? autocomplete.caretTop + 4 : autocomplete.caretTop - DROPDOWN_MAX_HEIGHT - 24)
: 0
const dropdownLeft = autocomplete
? Math.min(autocomplete.caretLeft, window.innerWidth - 260)
: 0
const dropdownPosition = getRawEditorDropdownPosition(autocomplete, DROPDOWN_MAX_HEIGHT, window)
return (
<div className="flex flex-1 flex-col min-h-0 relative" style={{ background: 'var(--background)' }} onKeyDown={handleAutocompleteKey} role="presentation">
@@ -212,8 +185,8 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
<div
className="fixed z-50 min-w-64 max-w-xs rounded-md border shadow-lg overflow-auto"
style={{
top: dropdownTop,
left: dropdownLeft,
top: dropdownPosition.top,
left: dropdownPosition.left,
maxHeight: DROPDOWN_MAX_HEIGHT,
background: 'var(--popover)',
borderColor: 'var(--border)',
@@ -224,7 +197,7 @@ export function RawEditorView({ content, path, entries, onContentChange, onSave,
items={autocomplete.items}
selectedIndex={autocomplete.selectedIndex}
getItemKey={(item, i) => `${item.title}-${item.path ?? i}`}
onItemClick={(item) => insertWikilink(item.entryTitle ?? item.title)}
onItemClick={(item) => item.onItemClick()}
onItemHover={(i) => setAutocomplete(prev => prev ? { ...prev, selectedIndex: i } : null)}
/>
</div>

View File

@@ -900,12 +900,60 @@ describe('Sidebar', () => {
favorite: true, favoriteIndex: 0,
}
function getFavoriteAndTypeRows(favoriteTitle = 'My Favorite Note') {
const favoriteLabel = screen.getByText(favoriteTitle)
const favoriteRow = favoriteLabel.closest('.cursor-pointer')
const typeLabel = screen.getByText('Projects')
const typeRow = typeLabel.closest('.cursor-pointer')
expect(favoriteRow).not.toBeNull()
expect(typeRow).not.toBeNull()
return {
favoriteLabel,
favoriteRow: favoriteRow as HTMLElement,
typeLabel,
typeRow: typeRow as HTMLElement,
}
}
function expectFavoriteIconToMatchTypeSizing(favoriteRow: HTMLElement) {
const favoriteIcon = favoriteRow.querySelector('svg')
expect(favoriteIcon).not.toBeNull()
expect(favoriteIcon!.getAttribute('width')).toBe('16')
expect(favoriteIcon!.getAttribute('height')).toBe('16')
expect(favoriteIcon!.getAttribute('style')).toContain('var(--accent-red)')
return favoriteIcon as SVGElement
}
function expectFavoriteRowToMatchTypeRow(favoriteTitle = 'My Favorite Note') {
const { favoriteLabel, favoriteRow, typeLabel, typeRow } = getFavoriteAndTypeRows(favoriteTitle)
expect(favoriteRow.className).toBe(typeRow.className)
expect(favoriteRow.style.padding).toBe(typeRow.style.padding)
expect(favoriteRow.style.gap).toBe(typeRow.style.gap)
expect(favoriteLabel.className).toContain(typeLabel.className)
expect(favoriteLabel.className).toContain('truncate')
return {
favoriteRow,
typeRow,
favoriteIcon: expectFavoriteIconToMatchTypeSizing(favoriteRow),
}
}
it('shows FAVORITES section when there are favorites', () => {
render(<Sidebar entries={[...mockEntries, favEntry]} selection={defaultSelection} onSelect={() => {}} />)
expect(screen.getByText('FAVORITES')).toBeInTheDocument()
expect(screen.getByText('My Favorite Note')).toBeInTheDocument()
})
it('preserves plain square brackets in favorite titles', () => {
const bracketedFavorite = { ...favEntry, title: '[26Q2] Tolaria MVP' }
render(<Sidebar entries={[...mockEntries, bracketedFavorite]} selection={defaultSelection} onSelect={() => {}} />)
expect(screen.getByText('[26Q2] Tolaria MVP')).toBeInTheDocument()
})
it('hides FAVORITES section when no favorites', () => {
render(<Sidebar entries={mockEntries} selection={defaultSelection} onSelect={() => {}} />)
expect(screen.queryByText('FAVORITES')).not.toBeInTheDocument()
@@ -920,21 +968,28 @@ describe('Sidebar', () => {
it('matches the Types row styling and type color for favorites', () => {
render(<Sidebar entries={[...mockEntries, favEntry]} selection={defaultSelection} onSelect={() => {}} />)
expectFavoriteRowToMatchTypeRow()
})
const favoriteLabel = screen.getByText('My Favorite Note')
const favoriteRow = favoriteLabel.closest('.cursor-pointer')
const typeLabel = screen.getByText('Projects')
const typeRow = typeLabel.closest('.cursor-pointer')
const favoriteIcon = favoriteRow?.querySelector('svg')
it('prefers a favorite note emoji icon over the type icon fallback', () => {
const emojiFavorite = { ...favEntry, title: 'Emoji Favorite', icon: '🚀' }
expect(favoriteRow?.className).toBe(typeRow?.className)
expect(favoriteRow?.style.padding).toBe(typeRow?.style.padding)
expect(favoriteRow?.style.gap).toBe(typeRow?.style.gap)
expect(favoriteLabel.className).toContain(typeLabel.className)
expect(favoriteLabel.className).toContain('truncate')
expect(favoriteIcon?.getAttribute('width')).toBe('16')
expect(favoriteIcon?.getAttribute('height')).toBe('16')
expect(favoriteIcon?.getAttribute('style')).toContain('var(--accent-red)')
render(<Sidebar entries={[...mockEntries, emojiFavorite]} selection={defaultSelection} onSelect={() => {}} />)
const emojiRow = screen.getByText('Emoji Favorite').closest('.cursor-pointer')
expect(within(emojiRow as HTMLElement).getByText('🚀')).toBeInTheDocument()
expect(emojiRow?.querySelector('svg')).toBeNull()
})
it('uses a favorite note phosphor icon and keeps the type color', () => {
const iconFavorite = { ...favEntry, title: 'Icon Favorite', icon: 'rocket' }
render(<Sidebar entries={[...mockEntries, iconFavorite]} selection={defaultSelection} onSelect={() => {}} />)
const { favoriteIcon, typeRow } = expectFavoriteRowToMatchTypeRow('Icon Favorite')
const typeIcon = typeRow.querySelector('svg')
expect(typeIcon).not.toBeNull()
expect(favoriteIcon.innerHTML).not.toBe(typeIcon!.innerHTML)
})
it('falls back to a neutral icon color when the favorite type has no defined color', () => {
@@ -1121,12 +1176,15 @@ describe('Sidebar', () => {
const navItem = label.closest('[class*="cursor-pointer"]') as HTMLElement
const countChip = navItem.querySelector('span:last-child') as HTMLElement
expect(countChip).toBeTruthy()
expect(viewItem.className).toContain('[&>div>span:last-child]:transition-opacity')
expect(viewItem.className).toContain('group-hover:[&>div>span:last-child]:opacity-0')
expect(viewItem.className).toContain('group-focus-within:[&>div>span:last-child]:opacity-0')
expect(countChip.className).toContain('transition-opacity')
expect(countChip.className).toContain('group-hover:opacity-0')
expect(countChip.className).toContain('group-focus-within:opacity-0')
const actionButton = within(viewItem).getByTitle('Edit view')
const actionContainer = actionButton.parentElement as HTMLElement
expect(actionContainer.className).toContain('pointer-events-none')
expect(actionContainer.className).toContain('group-hover:pointer-events-auto')
expect(actionContainer.className).toContain('group-focus-within:pointer-events-auto')
expect(actionContainer.className).toContain('group-hover:opacity-100')
expect(actionContainer.className).toContain('group-focus-within:opacity-100')
})

View File

@@ -1,168 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { TitleField } from './TitleField'
describe('TitleField', () => {
it('renders the title in the input', () => {
render(<TitleField title="My Note" filename="my-note.md" onTitleChange={() => {}} />)
expect(screen.getByTestId('title-field-input')).toHaveValue('My Note')
})
it('calls onTitleChange on blur with new value', () => {
const onChange = vi.fn()
render(<TitleField title="Old Title" filename="old-title.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
fireEvent.change(input, { target: { value: 'New Title' } })
fireEvent.blur(input)
expect(onChange).toHaveBeenCalledWith('New Title')
})
it('does not call onTitleChange if title unchanged', () => {
const onChange = vi.fn()
render(<TitleField title="Same Title" filename="same-title.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
fireEvent.focus(input)
fireEvent.blur(input)
expect(onChange).not.toHaveBeenCalled()
})
it('reverts to original title if input is emptied', () => {
const onChange = vi.fn()
render(<TitleField title="Keep This" filename="keep-this.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
fireEvent.change(input, { target: { value: '' } })
fireEvent.blur(input)
expect(onChange).not.toHaveBeenCalled()
expect(input).toHaveValue('Keep This')
})
it('shows filename indicator when slug differs and title is focused', () => {
render(<TitleField title="My Note" filename="wrong-name.md" onTitleChange={() => {}} />)
// Not shown when unfocused
expect(screen.queryByTestId('title-field-filename')).not.toBeInTheDocument()
// Shown when focused
fireEvent.focus(screen.getByTestId('title-field-input'))
expect(screen.getByTestId('title-field-filename')).toHaveTextContent('my-note.md')
})
it('does not show filename when slug matches and not editing', () => {
render(<TitleField title="My Note" filename="my-note.md" onTitleChange={() => {}} />)
expect(screen.queryByTestId('title-field-filename')).not.toBeInTheDocument()
})
it('disables input when editable is false', () => {
render(<TitleField title="Read Only" filename="read-only.md" editable={false} onTitleChange={() => {}} />)
expect(screen.getByTestId('title-field-input')).toBeDisabled()
})
it('commits title on Enter key', () => {
const onChange = vi.fn()
render(<TitleField title="Before" filename="before.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
fireEvent.change(input, { target: { value: 'After' } })
fireEvent.keyDown(input, { key: 'Enter' })
// In jsdom, blur() after keyDown needs explicit blur event
fireEvent.blur(input)
expect(onChange).toHaveBeenCalledWith('After')
})
it('reverts on Escape key', () => {
const onChange = vi.fn()
render(<TitleField title="Original" filename="original.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
fireEvent.change(input, { target: { value: 'Changed' } })
fireEvent.keyDown(input, { key: 'Escape' })
// Escape reverts value and blurs
expect(input).toHaveValue('Original')
})
it('shows new title optimistically after commit (before prop updates)', () => {
const onChange = vi.fn()
const { rerender } = render(<TitleField title="Old Title" filename="old-title.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
fireEvent.focus(input)
fireEvent.change(input, { target: { value: 'New Title' } })
fireEvent.blur(input)
// After commit, should show new title even though prop is still "Old Title"
expect(input).toHaveValue('New Title')
// After prop updates to match, should still show new title
rerender(<TitleField title="New Title" filename="new-title.md" onTitleChange={onChange} />)
expect(input).toHaveValue('New Title')
})
it('resets optimistic title when prop changes from external source', () => {
const onChange = vi.fn()
const { rerender } = render(<TitleField title="Title A" filename="title-a.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
// Simulate external title change (e.g., tab switch)
rerender(<TitleField title="Title B" filename="title-b.md" onTitleChange={onChange} />)
expect(input).toHaveValue('Title B')
})
it('responds to laputa:focus-editor event with selectTitle', () => {
render(<TitleField title="Focus Me" filename="focus-me.md" onTitleChange={() => {}} />)
const input = screen.getByTestId('title-field-input')
window.dispatchEvent(new CustomEvent('laputa:focus-editor', { detail: { selectTitle: true } }))
expect(document.activeElement).toBe(input)
})
it('resets stale localValue when title prop changes after focus', () => {
// Regression: creating a new note fires focus-editor before React re-renders,
// so handleFocus captures the OLD note's title into localValue.
// When React re-renders with the new title, localValue should be cleared.
const onChange = vi.fn()
const { rerender } = render(<TitleField title="Old Note" filename="old-note.md" onTitleChange={onChange} />)
const input = screen.getByTestId('title-field-input')
// Simulate: focus fires while title prop is still "Old Note"
fireEvent.focus(input)
expect(input).toHaveValue('Old Note')
// React re-renders with new note's title (tab switched)
rerender(<TitleField title="Untitled note" filename="untitled-note.md" onTitleChange={onChange} />)
expect(input).toHaveValue('Untitled note')
})
it('shows vault-relative path (without .md) only when title is focused', () => {
render(<TitleField title="ADR" filename="0001-tauri-stack.md" notePath="/Users/luca/Laputa/docs/adr/0001-tauri-stack.md" vaultPath="/Users/luca/Laputa" onTitleChange={() => {}} />)
// Path hidden by default
expect(screen.queryByTestId('title-field-path')).not.toBeInTheDocument()
// Focus title → path appears
fireEvent.focus(screen.getByTestId('title-field-input'))
expect(screen.getByTestId('title-field-path')).toHaveTextContent('docs/adr/0001-tauri-stack')
// No bare filename shown when path is visible
expect(screen.queryByTestId('title-field-filename')).not.toBeInTheDocument()
})
it('hides path on blur', () => {
render(<TitleField title="ADR" filename="0001-tauri-stack.md" notePath="/Users/luca/Laputa/docs/adr/0001-tauri-stack.md" vaultPath="/Users/luca/Laputa" onTitleChange={() => {}} />)
const input = screen.getByTestId('title-field-input')
fireEvent.focus(input)
expect(screen.getByTestId('title-field-path')).toBeInTheDocument()
fireEvent.blur(input)
expect(screen.queryByTestId('title-field-path')).not.toBeInTheDocument()
})
it('hides path for notes at vault root even when focused', () => {
render(<TitleField title="Root Note" filename="root-note.md" notePath="/Users/luca/Laputa/root-note.md" vaultPath="/Users/luca/Laputa" onTitleChange={() => {}} />)
fireEvent.focus(screen.getByTestId('title-field-input'))
expect(screen.queryByTestId('title-field-path')).not.toBeInTheDocument()
})
it('hides path when vaultPath is not provided', () => {
render(<TitleField title="Note" filename="note.md" onTitleChange={() => {}} />)
fireEvent.focus(screen.getByTestId('title-field-input'))
expect(screen.queryByTestId('title-field-path')).not.toBeInTheDocument()
})
it('resolves vault-relative path when paths differ by symlink prefix', () => {
// vaultPath uses symlink /Users/luca/... but notePath is canonical /Volumes/Jupiter/...
render(<TitleField title="ADR" filename="0001-tauri-stack.md" notePath="/Volumes/Jupiter/Workspace/laputa-app/demo-vault-v2/docs/adr/0001-tauri-stack.md" vaultPath="/Users/luca/Workspace/laputa-app/demo-vault-v2" onTitleChange={() => {}} />)
fireEvent.focus(screen.getByTestId('title-field-input'))
expect(screen.getByTestId('title-field-path')).toHaveTextContent('docs/adr/0001-tauri-stack')
})
it('handles vaultPath with trailing slash', () => {
render(<TitleField title="ADR" filename="0001-tauri-stack.md" notePath="/Users/luca/Laputa/docs/adr/0001-tauri-stack.md" vaultPath="/Users/luca/Laputa/" onTitleChange={() => {}} />)
fireEvent.focus(screen.getByTestId('title-field-input'))
expect(screen.getByTestId('title-field-path')).toHaveTextContent('docs/adr/0001-tauri-stack')
})
})

View File

@@ -1,170 +0,0 @@
import { useState, useCallback, useRef, useEffect } from 'react'
import { slugify } from '../hooks/useNoteCreation'
interface TitleFieldProps {
title: string
filename: string
editable?: boolean
/** Absolute path of the note file. */
notePath?: string
/** Absolute path of the vault root. */
vaultPath?: string
/** Called when the user finishes editing the title (blur or Enter). */
onTitleChange: (newTitle: string) => void
}
/** Manages local edit + optimistic title state for TitleField. */
function useOptimisticTitle(title: string, onTitleChange: (t: string) => void) {
const [localValue, setLocalValue] = useState<string | null>(null)
// [optimisticTitle, forPropTitle]: shown after commit until title prop catches up
const [optimistic, setOptimistic] = useState<[string, string] | null>(null)
const isFocusedRef = useRef(false)
const [prevTitle, setPrevTitle] = useState(title)
// Reset local edit when the title prop changes (e.g. note switch).
// This prevents a stale handleFocus closure from locking in the old note's title
// when focus-editor fires before React re-renders with the new tab.
if (prevTitle !== title) {
setPrevTitle(title)
if (localValue !== null) setLocalValue(null)
}
// Clear optimistic once the prop changes (rename completed or tab switched)
const optimisticValue = optimistic && optimistic[1] === title ? optimistic[0] : null
const value = localValue ?? optimisticValue ?? title
const isEditing = localValue !== null || optimisticValue !== null
const handleFocus = useCallback(() => {
isFocusedRef.current = true
setLocalValue(title)
}, [title])
const commitTitle = useCallback(() => {
isFocusedRef.current = false
const trimmed = (localValue ?? '').trim()
if (trimmed && trimmed !== title) {
setLocalValue(null)
setOptimistic([trimmed, title])
onTitleChange(trimmed)
} else {
setLocalValue(null)
}
}, [localValue, title, onTitleChange])
const revert = useCallback(() => setLocalValue(null), [])
const setEdit = useCallback((v: string) => setLocalValue(v), [])
return { value, isEditing, handleFocus, commitTitle, revert, setEdit }
}
/**
* Dedicated title input field above the editor.
* Displays the title as an editable field and shows the resulting filename below.
*/
export function TitleField({ title, filename, editable = true, notePath, vaultPath, onTitleChange }: TitleFieldProps) {
const inputRef = useRef<HTMLTextAreaElement>(null)
const [isFocused, setIsFocused] = useState(false)
const { value, isEditing, handleFocus, commitTitle, revert, setEdit } =
useOptimisticTitle(title, onTitleChange)
// Auto-resize textarea to fit content (fallback for browsers without field-sizing: content)
const autoResize = useCallback(() => {
const el = inputRef.current
if (!el) return
el.style.height = 'auto'
el.style.height = el.scrollHeight + 'px'
}, [])
useEffect(() => {
autoResize()
// Schedule a second measurement after the browser has painted, to catch
// cases where scrollHeight is stale on the first read (e.g. tab switch).
const id = requestAnimationFrame(autoResize)
return () => cancelAnimationFrame(id)
}, [value, autoResize])
// Re-measure when container width changes (text may re-wrap)
useEffect(() => {
const el = inputRef.current
if (!el) return
const ro = new ResizeObserver(autoResize)
ro.observe(el)
return () => ro.disconnect()
}, [autoResize])
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent).detail
if (detail?.selectTitle && inputRef.current) {
inputRef.current.focus()
inputRef.current.select()
}
}
window.addEventListener('laputa:focus-editor', handler)
return () => window.removeEventListener('laputa:focus-editor', handler)
}, [])
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.preventDefault()
inputRef.current?.blur()
}
if (e.key === 'Escape') {
revert()
inputRef.current?.blur()
}
}, [revert])
const expectedSlug = slugify(value.trim() || title)
const currentStem = filename.replace(/\.md$/, '')
// Compute vault-relative path (only for notes in subdirectories)
const relativePath = (() => {
if (!notePath || !vaultPath) return null
const vp = vaultPath.replace(/\/+$/, '')
const np = notePath.replace(/\.md$/, '')
if (np.startsWith(vp + '/')) return np.slice(vp.length + 1)
// Fallback: match by vault directory name for symlink-resolved paths
const vaultName = vp.split('/').pop()
if (!vaultName) return null
const segments = np.split('/')
const idx = segments.lastIndexOf(vaultName)
if (idx >= 0) return segments.slice(idx + 1).join('/')
return null
})()
const isSubdirectory = relativePath != null && relativePath.includes('/')
// Show path only when title is focused and note is in a subdirectory
const showRelativePath = isFocused && isSubdirectory
// Show filename hint when slug differs, but only when focused (not always)
const showFilename = isFocused && !showRelativePath && (isEditing || currentStem !== expectedSlug)
return (
<div className="title-field" data-testid="title-field">
<textarea
ref={inputRef}
className="title-field__input"
value={value}
rows={1}
onChange={e => { setEdit(e.target.value); autoResize() }}
onFocus={() => { setIsFocused(true); handleFocus() }}
onBlur={() => { setIsFocused(false); commitTitle() }}
onKeyDown={handleKeyDown}
disabled={!editable}
placeholder="Untitled"
spellCheck={false}
data-testid="title-field-input"
/>
{showFilename && (
<span className="title-field__filename" data-testid="title-field-filename">
{expectedSlug}.md
</span>
)}
{showRelativePath && (
<span className="title-field__path" data-testid="title-field-path" style={{ display: 'block', fontSize: 11, color: 'var(--muted-foreground)', marginTop: 2 }}>
{relativePath}
</span>
)}
</div>
)
}

View File

@@ -7,18 +7,6 @@ vi.mock('../BreadcrumbBar', () => ({
BreadcrumbBar: () => <div data-testid="breadcrumb-bar" />,
}))
vi.mock('../TitleField', () => ({
TitleField: () => <div data-testid="title-field-input" />,
}))
vi.mock('../NoteIcon', () => ({
NoteIcon: ({ icon }: { icon: string | null }) => (
icon
? <button type="button" data-testid="note-icon-display" />
: <button type="button" data-testid="note-icon-add" />
),
}))
vi.mock('../ArchivedNoteBanner', () => ({
ArchivedNoteBanner: () => <div data-testid="archived-banner" />,
}))
@@ -69,12 +57,7 @@ function createModel(overrides: Record<string, unknown> = {}) {
onKeepTheirs: vi.fn(),
breadcrumbBarRef: createRef<HTMLDivElement>(),
wordCount: 12,
titleSectionRef: createRef<HTMLDivElement>(),
showTitleSection: true,
hasDisplayIcon: false,
entryIcon: null,
vaultPath: '/vault',
onTitleChange: vi.fn(),
cssVars: {},
onNavigateWikilink: vi.fn(),
onEditorChange: vi.fn(),
@@ -95,27 +78,12 @@ function createModel(overrides: Record<string, unknown> = {}) {
}
describe('EditorContentLayout', () => {
it('does not render a standalone add-icon row when the note has no icon', () => {
it('never renders the legacy title section', () => {
const { container } = render(<EditorContentLayout {...createModel()} />)
expect(container.querySelector('.title-section__add-icon')).toBeNull()
expect(container.querySelector('.title-section__inline-add-icon')).not.toBeNull()
expect(screen.getByTestId('note-icon-add')).toBeInTheDocument()
})
it('keeps the existing icon and title inside the same title row', () => {
const { container } = render(
<EditorContentLayout
{...createModel({
hasDisplayIcon: true,
entryIcon: 'rocket',
})}
/>,
)
const titleRow = container.querySelector('.title-section__row')
expect(titleRow?.querySelector('[data-testid="note-icon-display"]')).not.toBeNull()
expect(titleRow?.querySelector('[data-testid="title-field-input"]')).not.toBeNull()
expect(container.querySelector('.title-section')).toBeNull()
expect(screen.queryByTestId('title-field-input')).not.toBeInTheDocument()
expect(screen.getByTestId('single-editor-view')).toBeInTheDocument()
})
it('shows the loading skeleton instead of stale editor chrome while switching tabs', () => {

View File

@@ -1,8 +1,6 @@
import type React from 'react'
import { DiffView } from '../DiffView'
import { BreadcrumbBar } from '../BreadcrumbBar'
import { TitleField } from '../TitleField'
import { NoteIcon } from '../NoteIcon'
import { ArchivedNoteBanner } from '../ArchivedNoteBanner'
import { ConflictNoteBanner } from '../ConflictNoteBanner'
import { RawEditorView } from '../RawEditorView'
@@ -29,6 +27,7 @@ type BreadcrumbActions = Pick<
| 'onDeleteNote'
| 'onArchiveNote'
| 'onUnarchiveNote'
| 'onRenameFilename'
>
function EditorLoadingSkeleton() {
@@ -127,54 +126,11 @@ function ActiveTabBreadcrumb({
onDelete={bindPath(actions.onDeleteNote, path)}
onArchive={bindPath(actions.onArchiveNote, path)}
onUnarchive={bindPath(actions.onUnarchiveNote, path)}
onRenameFilename={actions.onRenameFilename}
/>
)
}
function TitleSection({
activeTab,
entryIcon,
hasDisplayIcon,
path,
showTitleSection,
titleSectionRef,
vaultPath,
onTitleChange,
}: Pick<
EditorContentModel,
'activeTab' | 'entryIcon' | 'hasDisplayIcon' | 'path' | 'showTitleSection' | 'titleSectionRef' | 'vaultPath' | 'onTitleChange'
>) {
if (!activeTab) return null
return (
<div ref={titleSectionRef} className="title-section" data-title-ui-visible={showTitleSection || undefined}>
{showTitleSection && (
<>
<div className="title-section__heading">
{!hasDisplayIcon && (
<div className="title-section__inline-add-icon">
<NoteIcon icon={null} editable />
</div>
)}
<div className={`title-section__row${hasDisplayIcon ? '' : ' title-section__row--no-icon'}`}>
{hasDisplayIcon && <NoteIcon icon={entryIcon} editable />}
<TitleField
title={activeTab.entry.title}
filename={activeTab.entry.filename}
editable
notePath={path}
vaultPath={vaultPath}
onTitleChange={(newTitle) => onTitleChange?.(path, newTitle)}
/>
</div>
</div>
<div className="title-section__separator" />
</>
)}
</div>
)
}
function EditorChrome({
isArchived,
onUnarchiveNote,
@@ -208,52 +164,28 @@ function EditorChrome({
function EditorCanvas({
showEditor,
cssVars,
activeTab,
entryIcon,
hasDisplayIcon,
path,
showTitleSection,
titleSectionRef,
vaultPath,
onTitleChange,
editor,
entries,
onNavigateWikilink,
onEditorChange,
isDeletedPreview,
vaultPath,
}: Pick<
EditorContentModel,
| 'showEditor'
| 'cssVars'
| 'activeTab'
| 'entryIcon'
| 'hasDisplayIcon'
| 'path'
| 'showTitleSection'
| 'titleSectionRef'
| 'vaultPath'
| 'onTitleChange'
| 'editor'
| 'entries'
| 'onNavigateWikilink'
| 'onEditorChange'
| 'isDeletedPreview'
| 'vaultPath'
>) {
if (!showEditor) return null
return (
<div className="editor-scroll-area" style={cssVars as React.CSSProperties}>
<div className="editor-content-wrapper">
<TitleSection
activeTab={activeTab}
entryIcon={entryIcon}
hasDisplayIcon={hasDisplayIcon}
path={path}
showTitleSection={showTitleSection}
titleSectionRef={titleSectionRef}
vaultPath={vaultPath}
onTitleChange={onTitleChange}
/>
<SingleEditorView
editor={editor}
entries={entries}
@@ -288,12 +220,7 @@ export function EditorContentLayout(model: EditorContentModel) {
onKeepTheirs,
breadcrumbBarRef,
wordCount,
titleSectionRef,
showTitleSection,
hasDisplayIcon,
entryIcon,
vaultPath,
onTitleChange,
cssVars,
onNavigateWikilink,
onEditorChange,
@@ -333,6 +260,7 @@ export function EditorContentLayout(model: EditorContentModel) {
onDeleteNote: model.onDeleteNote,
onArchiveNote: model.onArchiveNote,
onUnarchiveNote: model.onUnarchiveNote,
onRenameFilename: model.onRenameFilename,
}}
/>
<EditorChrome
@@ -358,14 +286,7 @@ export function EditorContentLayout(model: EditorContentModel) {
<EditorCanvas
showEditor={showEditor}
cssVars={cssVars}
activeTab={activeTab}
entryIcon={entryIcon}
hasDisplayIcon={hasDisplayIcon}
path={path}
showTitleSection={showTitleSection}
titleSectionRef={titleSectionRef}
vaultPath={vaultPath}
onTitleChange={onTitleChange}
editor={editor}
entries={entries}
onNavigateWikilink={onNavigateWikilink}

View File

@@ -46,47 +46,47 @@ function deriveState(tab: EditorContentTab | null, overrides?: Partial<VaultEntr
}
describe('deriveEditorContentState', () => {
it('hides the legacy title section when loaded content contains a top-level H1', () => {
it('marks loaded content with a top-level H1 as titled', () => {
const state = deriveState({
entry: baseEntry,
content: '---\ntitle: Legacy Project\n---\n# Legacy Project\n\nBody',
})
expect(state.hasH1).toBe(true)
expect(state.showTitleSection).toBe(false)
expect(state.showEditor).toBe(true)
})
it('keeps the title section for notes without an H1', () => {
it('keeps editor content visible for notes without an H1', () => {
const state = deriveState({
entry: baseEntry,
content: '---\ntitle: Legacy Project\n---\nBody without a heading',
})
expect(state.hasH1).toBe(false)
expect(state.showTitleSection).toBe(false)
expect(state.showEditor).toBe(true)
})
it('hides the legacy title section when a frontmatter title drives the display title', () => {
it('keeps editor content visible when a legacy frontmatter title exists', () => {
const state = deriveState({
entry: baseEntry,
content: '---\ntitle: Spring 2026\nstatus: Active\n---\n## Goals',
})
expect(state.hasH1).toBe(false)
expect(state.showTitleSection).toBe(false)
expect(state.showEditor).toBe(true)
})
it('keeps the title section when the document title still comes from the filename', () => {
it('does not fall back to a separate title section when the filename drives the display title', () => {
const state = deriveState({
entry: baseEntry,
content: '---\nstatus: Active\n---\nBody without a heading',
})
expect(state.hasH1).toBe(false)
expect(state.showTitleSection).toBe(true)
expect(state.showEditor).toBe(true)
})
it('hides the title section for untitled drafts before they get an H1', () => {
it('keeps untitled drafts in the editor even before they get an H1', () => {
const draftEntry = {
...baseEntry,
path: '/vault/untitled-note-1700000000.md',
@@ -105,6 +105,6 @@ describe('deriveEditorContentState', () => {
})
expect(state.hasH1).toBe(false)
expect(state.showTitleSection).toBe(false)
expect(state.showEditor).toBe(true)
})
})

View File

@@ -1,5 +1,5 @@
import type { NoteStatus, VaultEntry } from '../../types'
import { contentDefinesDisplayTitle, extractH1TitleFromContent } from '../../utils/noteTitle'
import { extractH1TitleFromContent } from '../../utils/noteTitle'
import { countWords } from '../../utils/wikilinks'
export interface EditorContentTab {
@@ -14,17 +14,11 @@ interface EditorContentStateInput {
activeStatus: NoteStatus
}
interface TitleSectionState {
hasDisplayTitle: boolean
hasH1: boolean
}
interface VisibilityState {
effectiveRawMode: boolean
isDeletedPreview: boolean
isNonMarkdownText: boolean
showEditor: boolean
showTitleSection: boolean
}
export interface EditorContentState {
@@ -35,7 +29,6 @@ export interface EditorContentState {
isNonMarkdownText: boolean
effectiveRawMode: boolean
showEditor: boolean
showTitleSection: boolean
path: string
wordCount: number
}
@@ -49,38 +42,18 @@ function contentHasTopLevelH1(activeTab: EditorContentTab | null): boolean {
return activeTab ? extractH1TitleFromContent(activeTab.content) !== null : false
}
function contentDefinesTitle(activeTab: EditorContentTab | null): boolean {
return activeTab ? contentDefinesDisplayTitle(activeTab.content) : false
}
function resolveHasH1(activeTab: EditorContentTab | null, freshEntry: VaultEntry | undefined): boolean {
return contentHasTopLevelH1(activeTab) || freshEntry?.hasH1 === true || activeTab?.entry.hasH1 === true
}
function resolveHasDisplayTitle(activeTab: EditorContentTab | null, hasH1: boolean): boolean {
return hasH1 || contentDefinesTitle(activeTab)
}
function deriveTitleSectionState(activeTab: EditorContentTab | null, freshEntry: VaultEntry | undefined): TitleSectionState {
const hasH1 = resolveHasH1(activeTab, freshEntry)
return {
hasDisplayTitle: resolveHasDisplayTitle(activeTab, hasH1),
hasH1,
}
}
function deriveVisibilityState(input: {
activeStatus: NoteStatus
activeTab: EditorContentTab | null
freshEntry: VaultEntry | undefined
hasDisplayTitle: boolean
rawMode: boolean
}): VisibilityState {
const {
activeStatus,
activeTab,
freshEntry,
hasDisplayTitle,
rawMode,
} = input
const isDeletedPreview = !!activeTab && !freshEntry
@@ -92,36 +65,23 @@ function deriveVisibilityState(input: {
isNonMarkdownText,
effectiveRawMode,
showEditor: !effectiveRawMode,
showTitleSection: !isDeletedPreview && !hasDisplayTitle && !isUnsavedUntitledDraft(activeTab, activeStatus),
}
}
function isUnsavedUntitledDraft(activeTab: EditorContentTab | null, activeStatus: NoteStatus): boolean {
if (!activeTab) return false
if (!activeTab.entry.filename.startsWith('untitled-')) return false
return activeStatus === 'new' || activeStatus === 'unsaved' || activeStatus === 'pendingSave'
}
export function deriveEditorContentState({
activeTab,
entries,
rawMode,
activeStatus,
}: EditorContentStateInput): EditorContentState {
export function deriveEditorContentState(input: EditorContentStateInput): EditorContentState {
const { activeTab, entries, rawMode } = input
const freshEntry = findFreshEntry(activeTab, entries)
const titleState = deriveTitleSectionState(activeTab, freshEntry)
const hasH1 = resolveHasH1(activeTab, freshEntry)
const visibilityState = deriveVisibilityState({
activeStatus,
activeTab,
freshEntry,
hasDisplayTitle: titleState.hasDisplayTitle,
rawMode,
})
return {
freshEntry,
isArchived: freshEntry?.archived ?? activeTab?.entry.archived ?? false,
hasH1: titleState.hasH1,
hasH1,
...visibilityState,
path: activeTab?.entry.path ?? '',
wordCount: activeTab ? countWords(activeTab.content) : 0,

View File

@@ -1,9 +1,8 @@
import type React from 'react'
import { useEffect, useRef } from 'react'
import { useRef } from 'react'
import type { useCreateBlockNote } from '@blocknote/react'
import type { NoteStatus, VaultEntry } from '../../types'
import { useEditorTheme } from '../../hooks/useTheme'
import { resolveNoteIcon } from '../../utils/noteIcon'
import { deriveEditorContentState } from './editorContentState'
export interface Tab {
@@ -39,7 +38,7 @@ export interface EditorContentProps {
onUnarchiveNote?: (path: string) => void
vaultPath?: string
rawLatestContentRef?: React.MutableRefObject<string | null>
onTitleChange?: (path: string, newTitle: string) => void
onRenameFilename?: (path: string, newFilenameStem: string) => void
isConflicted?: boolean
onKeepMine?: (path: string) => void
onKeepTheirs?: (path: string) => void
@@ -50,7 +49,6 @@ export function useEditorContentModel(props: EditorContentProps) {
activeTab,
entries,
rawMode,
activeStatus,
diffMode,
} = props
@@ -62,42 +60,17 @@ export function useEditorContentModel(props: EditorContentProps) {
effectiveRawMode,
showEditor: showContentEditor,
path,
showTitleSection,
wordCount,
} = deriveEditorContentState({
activeTab,
entries,
rawMode,
activeStatus,
activeStatus: props.activeStatus,
})
const showEditor = !diffMode && showContentEditor
const entryIcon = activeTab?.entry.icon ?? null
const hasDisplayIcon = resolveNoteIcon(entryIcon).kind !== 'none'
const titleSectionRef = useRef<HTMLDivElement | null>(null)
const breadcrumbBarRef = useRef<HTMLDivElement | null>(null)
useEffect(() => {
if (!showEditor) return
const bar = breadcrumbBarRef.current
const titleSection = titleSectionRef.current
if (!bar || !titleSection) return
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) bar.removeAttribute('data-title-hidden')
else bar.setAttribute('data-title-hidden', '')
},
{ threshold: 0 },
)
observer.observe(titleSection)
return () => {
observer.disconnect()
bar.removeAttribute('data-title-hidden')
}
}, [path, showEditor])
return {
...props,
cssVars,
@@ -106,11 +79,7 @@ export function useEditorContentModel(props: EditorContentProps) {
effectiveRawMode,
forceRawMode: isNonMarkdownText || isDeletedPreview,
showEditor,
entryIcon,
hasDisplayIcon,
path,
showTitleSection,
titleSectionRef,
breadcrumbBarRef,
wordCount,
}

View File

@@ -6,7 +6,12 @@ import { containsWikilinks } from '../DynamicPropertiesPanel'
import type { FrontmatterValue } from '../Inspector'
import { NoteSearchList } from '../NoteSearchList'
import { useNoteSearch } from '../../hooks/useNoteSearch'
import { resolveEntry } from '../../utils/wikilink'
import {
resolveEntry,
canonicalWikilinkTargetForEntry,
canonicalWikilinkTargetForTitle,
formatWikilinkRef,
} from '../../utils/wikilink'
import { isWikilink, resolveRefProps } from './shared'
import { LinkButton } from './LinkButton'
@@ -15,6 +20,61 @@ function hasExactTitleMatch(entries: VaultEntry[], title: string): boolean {
return resolveEntry(entries, title) !== undefined
}
function inferVaultPath(entries: VaultEntry[]): string {
if (entries.length === 0) return ''
const segments = entries.map((entry) => entry.path.split('/').slice(0, -1))
const prefix: string[] = []
const maxDepth = Math.min(...segments.map((parts) => parts.length))
for (let i = 0; i < maxDepth; i += 1) {
const segment = segments[0][i]
if (segments.every((parts) => parts[i] === segment)) prefix.push(segment)
else break
}
return prefix.join('/')
}
function canonicalRefForEntry(entry: VaultEntry, vaultPath: string): string {
return formatWikilinkRef(canonicalWikilinkTargetForEntry(entry, vaultPath))
}
function canonicalRefForTitle(title: string, entries: VaultEntry[], vaultPath: string): string {
return formatWikilinkRef(canonicalWikilinkTargetForTitle(title, entries, vaultPath))
}
function shouldShowSearchDropdown(focused: boolean, trimmed: string, resultCount: number, showCreate: boolean): boolean {
return focused && trimmed.length > 0 && (resultCount > 0 || showCreate)
}
function confirmRelationshipSelection({
showCreate,
selectedIndex,
createIndex,
trimmed,
selectedEntry,
onCreate,
onSelectEntry,
onFallback,
}: {
showCreate: boolean
selectedIndex: number
createIndex: number
trimmed: string
selectedEntry?: VaultEntry
onCreate?: (title: string) => void
onSelectEntry?: (entry: VaultEntry) => void
onFallback?: () => void
}): void {
if (showCreate && selectedIndex === createIndex && trimmed) {
onCreate?.(trimmed)
return
}
if (selectedEntry) {
onSelectEntry?.(selectedEntry)
return
}
onFallback?.()
}
/** Shared keyboard navigation for search dropdowns with an optional "create" item. */
function useSearchKeyboard(
search: ReturnType<typeof useNoteSearch>,
@@ -90,7 +150,7 @@ function CreateAndOpenOption({ title, selected, onClick, onHover }: {
function SearchDropdownWithCreate({ search, onSelect, query, entries, onCreateAndOpen }: {
search: ReturnType<typeof useNoteSearch>
onSelect: (title: string) => void
onSelect: (entry: VaultEntry) => void
query: string
entries: VaultEntry[]
onCreateAndOpen?: (title: string) => void
@@ -108,7 +168,7 @@ function SearchDropdownWithCreate({ search, onSelect, query, entries, onCreateAn
items={search.results}
selectedIndex={search.selectedIndex}
getItemKey={(item) => item.entry.path}
onItemClick={(item) => onSelect(item.entry.title)}
onItemClick={(item) => onSelect(item.entry)}
onItemHover={(i) => search.setSelectedIndex(i)}
className="max-h-[160px] overflow-y-auto"
/>
@@ -125,11 +185,12 @@ function SearchDropdownWithCreate({ search, onSelect, query, entries, onCreateAn
)
}
function InlineAddNote({ entries, onAdd, onCreateAndOpenNote }: {
entries: VaultEntry[]
onAdd: (noteTitle: string) => void
onCreateAndOpenNote?: (title: string) => Promise<boolean>
}) {
function useInlineAddNoteState(
entries: VaultEntry[],
vaultPath: string,
onAdd: (ref: string) => void,
onCreateAndOpenNote?: (title: string) => Promise<boolean>,
) {
const [active, setActive] = useState(false)
const [query, setQuery] = useState('')
const inputRef = useRef<HTMLInputElement>(null)
@@ -138,25 +199,82 @@ function InlineAddNote({ entries, onAdd, onCreateAndOpenNote }: {
const trimmed = query.trim()
const { showCreate, createIndex, totalItems } = useCreateOption(entries, trimmed, search.results.length, !!onCreateAndOpenNote)
const dismiss = useCallback(() => { setQuery(''); setActive(false) }, [])
const dismiss = useCallback(() => {
setQuery('')
setActive(false)
}, [])
const selectAndClose = useCallback((title: string) => {
onAdd(title)
const selectAndClose = useCallback((ref: string) => {
onAdd(ref)
dismiss()
}, [onAdd, dismiss])
const handleCreateAndOpen = useCreateAndOpen(onCreateAndOpenNote, onAdd, dismiss)
const selectEntryAndClose = useCallback((entry: VaultEntry) => {
selectAndClose(canonicalRefForEntry(entry, vaultPath))
}, [selectAndClose, vaultPath])
const handleCreateAndOpen = useCreateAndOpen(
onCreateAndOpenNote,
(title) => onAdd(canonicalRefForTitle(title, entries, vaultPath)),
dismiss,
)
const handleFallback = useCallback(() => {
if (!trimmed) return
selectAndClose(canonicalRefForTitle(trimmed, entries, vaultPath))
}, [trimmed, selectAndClose, entries, vaultPath])
const handleConfirm = useCallback(() => {
if (showCreate && search.selectedIndex === createIndex) {
handleCreateAndOpen(trimmed)
return
}
const title = search.selectedEntry?.title ?? trimmed
if (title) selectAndClose(title)
}, [search.selectedEntry, search.selectedIndex, trimmed, selectAndClose, showCreate, createIndex, handleCreateAndOpen])
confirmRelationshipSelection({
showCreate,
selectedIndex: search.selectedIndex,
createIndex,
trimmed,
selectedEntry: search.selectedEntry,
onCreate: handleCreateAndOpen,
onSelectEntry: selectEntryAndClose,
onFallback: handleFallback,
})
}, [showCreate, search.selectedIndex, search.selectedEntry, createIndex, trimmed, handleCreateAndOpen, selectEntryAndClose, handleFallback])
const handleKeyDown = useSearchKeyboard(search, totalItems, handleConfirm, dismiss)
const showDropdown = shouldShowSearchDropdown(active, trimmed, search.results.length, showCreate)
return {
active,
setActive,
query,
setQuery,
inputRef,
search,
dismiss,
handleKeyDown,
showDropdown,
selectEntryAndClose,
showCreate,
handleCreateAndOpen,
}
}
function InlineAddNote({ entries, vaultPath, onAdd, onCreateAndOpenNote }: {
entries: VaultEntry[]
vaultPath: string
onAdd: (ref: string) => void
onCreateAndOpenNote?: (title: string) => Promise<boolean>
}) {
const {
active,
setActive,
query,
setQuery,
inputRef,
search,
dismiss,
handleKeyDown,
showDropdown,
selectEntryAndClose,
handleCreateAndOpen,
} = useInlineAddNoteState(entries, vaultPath, onAdd, onCreateAndOpenNote)
if (!active) {
return (
@@ -171,8 +289,6 @@ function InlineAddNote({ entries, onAdd, onCreateAndOpenNote }: {
)
}
const showDropdown = trimmed.length > 0 && (search.results.length > 0 || showCreate)
return (
<div className="relative mt-1">
<div className="group/add relative flex items-center">
@@ -197,7 +313,7 @@ function InlineAddNote({ entries, onAdd, onCreateAndOpenNote }: {
{showDropdown && (
<SearchDropdownWithCreate
search={search}
onSelect={selectAndClose}
onSelect={selectEntryAndClose}
query={query}
entries={entries}
onCreateAndOpen={onCreateAndOpenNote ? (title) => { handleCreateAndOpen(title) } : undefined}
@@ -207,11 +323,11 @@ function InlineAddNote({ entries, onAdd, onCreateAndOpenNote }: {
)
}
function RelationshipGroup({ label, refs, entries, typeEntryMap, onNavigate, onRemoveRef, onAddRef, onCreateAndOpenNote }: {
label: string; refs: string[]; entries: VaultEntry[]; typeEntryMap: Record<string, VaultEntry>
function RelationshipGroup({ label, refs, entries, typeEntryMap, vaultPath, onNavigate, onRemoveRef, onAddRef, onCreateAndOpenNote }: {
label: string; refs: string[]; entries: VaultEntry[]; typeEntryMap: Record<string, VaultEntry>; vaultPath: string
onNavigate: (target: string) => void
onRemoveRef?: (ref: string) => void
onAddRef?: (noteTitle: string) => void
onAddRef?: (ref: string) => void
onCreateAndOpenNote?: (title: string) => Promise<boolean>
}) {
if (refs.length === 0) return null
@@ -234,6 +350,7 @@ function RelationshipGroup({ label, refs, entries, typeEntryMap, onNavigate, onR
{onAddRef && (
<InlineAddNote
entries={entries}
vaultPath={vaultPath}
onAdd={onAddRef}
onCreateAndOpenNote={onCreateAndOpenNote}
/>
@@ -269,22 +386,30 @@ function NoteTargetInput({ entries, value, onChange, onSubmit, onCancel, onCreat
const trimmed = value.trim()
const { showCreate, createIndex, totalItems } = useCreateOption(entries, trimmed, search.results.length, !!onCreateAndOpenNote)
const handleConfirm = useCallback(() => {
if (showCreate && search.selectedIndex === createIndex) {
onSubmitWithCreate?.(trimmed)
} else if (search.selectedEntry) {
onChange(search.selectedEntry.title)
setFocused(false)
} else {
onSubmit?.()
}
}, [showCreate, search.selectedIndex, search.selectedEntry, createIndex, trimmed, onChange, onSubmit, onSubmitWithCreate])
const selectEntry = useCallback((entry: VaultEntry) => {
onChange(entry.title)
setFocused(false)
}, [onChange])
const handleEscape = useCallback(() => { onCancel?.() }, [onCancel])
const handleConfirm = useCallback(() => {
confirmRelationshipSelection({
showCreate,
selectedIndex: search.selectedIndex,
createIndex,
trimmed,
selectedEntry: search.selectedEntry,
onCreate: onSubmitWithCreate,
onSelectEntry: selectEntry,
onFallback: onSubmit,
})
}, [showCreate, search.selectedIndex, search.selectedEntry, createIndex, trimmed, onSubmitWithCreate, selectEntry, onSubmit])
const handleEscape = useCallback(() => {
onCancel?.()
}, [onCancel])
const handleKeyDown = useSearchKeyboard(search, totalItems, handleConfirm, handleEscape)
const showDropdown = focused && trimmed.length > 0 && (search.results.length > 0 || showCreate)
const showDropdown = shouldShowSearchDropdown(focused, trimmed, search.results.length, showCreate)
return (
<div className="relative">
@@ -301,7 +426,7 @@ function NoteTargetInput({ entries, value, onChange, onSubmit, onCancel, onCreat
{showDropdown && (
<SearchDropdownWithCreate
search={search}
onSelect={(title) => { onChange(title); setFocused(false) }}
onSelect={selectEntry}
query={value}
entries={entries}
onCreateAndOpen={onCreateAndOpenNote ? (title) => onSubmitWithCreate?.(title) : undefined}
@@ -311,8 +436,56 @@ function NoteTargetInput({ entries, value, onChange, onSubmit, onCancel, onCreat
)
}
function AddRelationshipForm({ entries, onAddProperty, onCreateAndOpenNote }: {
function useRelationshipPanelState(
frontmatter: ParsedFrontmatter,
entries: VaultEntry[],
vaultPath: string | undefined,
onAddProperty?: (key: string, value: FrontmatterValue) => void,
onUpdateProperty?: (key: string, value: FrontmatterValue) => void,
onDeleteProperty?: (key: string) => void,
) {
const relationshipEntries = useMemo(() => extractRelationshipRefs(frontmatter), [frontmatter])
const resolvedVaultPath = useMemo(() => vaultPath ?? inferVaultPath(entries), [vaultPath, entries])
const handleRemoveRef = useCallback((key: string, refToRemove: string) => {
if (!onUpdateProperty || !onDeleteProperty) return
const group = relationshipEntries.find(g => g.key === key)
if (!group) return
const result = updateRefsForRemoval(group.refs, refToRemove)
if (result === null) onDeleteProperty(key)
else onUpdateProperty(key, result)
}, [relationshipEntries, onUpdateProperty, onDeleteProperty])
const handleAddRef = useCallback((key: string, ref: string) => {
if (!onUpdateProperty) return
const existing = relationshipEntries.find(g => g.key === key)?.refs ?? []
const result = updateRefsForAddition(existing, ref)
if (result !== false) onUpdateProperty(key, result)
}, [relationshipEntries, onUpdateProperty])
const canEdit = !!onUpdateProperty && !!onDeleteProperty
const existingRelKeys = useMemo(
() => new Set(relationshipEntries.map(g => g.key.toLowerCase())),
[relationshipEntries],
)
const missingSuggestedRels = useMemo(
() => (onAddProperty ? SUGGESTED_RELATIONSHIPS.filter(r => !existingRelKeys.has(r.toLowerCase())) : []),
[onAddProperty, existingRelKeys],
)
return {
relationshipEntries,
resolvedVaultPath,
handleRemoveRef,
handleAddRef,
canEdit,
missingSuggestedRels,
}
}
function AddRelationshipForm({ entries, vaultPath, onAddProperty, onCreateAndOpenNote }: {
entries: VaultEntry[]
vaultPath: string
onAddProperty: (key: string, value: FrontmatterValue) => void
onCreateAndOpenNote?: (title: string) => Promise<boolean>
}) {
@@ -327,16 +500,16 @@ function AddRelationshipForm({ entries, onAddProperty, onCreateAndOpenNote }: {
const submitForm = useCallback((targetOverride?: string) => {
const key = relKey.trim()
const target = (targetOverride ?? relTarget).trim()
if (!key || !target) return
onAddProperty(key, `[[${target}]]`)
const rawTarget = (targetOverride ?? relTarget).trim()
if (!key || !rawTarget) return
onAddProperty(key, canonicalRefForTitle(rawTarget, entries, vaultPath))
resetForm()
}, [relKey, relTarget, onAddProperty, resetForm])
}, [relKey, relTarget, entries, vaultPath, onAddProperty, resetForm])
const addPropertyForKey = useCallback((title: string) => {
const key = relKey.trim()
if (key) onAddProperty(key, `[[${title}]]`)
}, [relKey, onAddProperty])
if (key) onAddProperty(key, canonicalRefForTitle(title, entries, vaultPath))
}, [relKey, entries, vaultPath, onAddProperty])
const handleCreateAndSubmit = useCreateAndOpen(onCreateAndOpenNote, addPropertyForKey, resetForm)
@@ -381,10 +554,9 @@ function updateRefsForRemoval(refs: string[], refToRemove: string): FrontmatterV
return remaining.length === 1 ? remaining[0] : remaining
}
function updateRefsForAddition(refs: string[], noteTitle: string): FrontmatterValue | false {
const newRef = `[[${noteTitle}]]`
if (refs.includes(newRef)) return false
const updated = [...refs, newRef]
function updateRefsForAddition(refs: string[], refToAdd: string): FrontmatterValue | false {
if (refs.includes(refToAdd)) return false
const updated = [...refs, refToAdd]
return updated.length === 1 ? updated[0] : updated
}
@@ -396,10 +568,11 @@ function DisabledLinkButton() {
const SUGGESTED_RELATIONSHIPS = ['Belongs to', 'Related to', 'Has'] as const
function SuggestedRelationshipSlot({ label, entries, onAdd, onCreateAndOpenNote }: {
function SuggestedRelationshipSlot({ label, entries, vaultPath, onAdd, onCreateAndOpenNote }: {
label: string
entries: VaultEntry[]
onAdd: (noteTitle: string) => void
vaultPath: string
onAdd: (ref: string) => void
onCreateAndOpenNote?: (title: string) => Promise<boolean>
}) {
return (
@@ -407,6 +580,7 @@ function SuggestedRelationshipSlot({ label, entries, onAdd, onCreateAndOpenNote
<span className="mb-1 block text-[12px] text-muted-foreground/50">{label}</span>
<InlineAddNote
entries={entries}
vaultPath={vaultPath}
onAdd={onAdd}
onCreateAndOpenNote={onCreateAndOpenNote}
/>
@@ -414,50 +588,30 @@ function SuggestedRelationshipSlot({ label, entries, onAdd, onCreateAndOpenNote
)
}
export function DynamicRelationshipsPanel({ frontmatter, entries, typeEntryMap, onNavigate, onAddProperty, onUpdateProperty, onDeleteProperty, onCreateAndOpenNote }: {
frontmatter: ParsedFrontmatter; entries: VaultEntry[]; typeEntryMap: Record<string, VaultEntry>
export function DynamicRelationshipsPanel({ frontmatter, entries, typeEntryMap, vaultPath, onNavigate, onAddProperty, onUpdateProperty, onDeleteProperty, onCreateAndOpenNote }: {
frontmatter: ParsedFrontmatter; entries: VaultEntry[]; typeEntryMap: Record<string, VaultEntry>; vaultPath?: string
onNavigate: (target: string) => void
onAddProperty?: (key: string, value: FrontmatterValue) => void
onUpdateProperty?: (key: string, value: FrontmatterValue) => void
onDeleteProperty?: (key: string) => void
onCreateAndOpenNote?: (title: string) => Promise<boolean>
}) {
const relationshipEntries = useMemo(() => extractRelationshipRefs(frontmatter), [frontmatter])
const handleRemoveRef = useCallback((key: string, refToRemove: string) => {
if (!onUpdateProperty || !onDeleteProperty) return
const group = relationshipEntries.find(g => g.key === key)
if (!group) return
const result = updateRefsForRemoval(group.refs, refToRemove)
if (result === null) onDeleteProperty(key)
else onUpdateProperty(key, result)
}, [relationshipEntries, onUpdateProperty, onDeleteProperty])
const handleAddRef = useCallback((key: string, noteTitle: string) => {
if (!onUpdateProperty) return
const existing = relationshipEntries.find(g => g.key === key)?.refs ?? []
const result = updateRefsForAddition(existing, noteTitle)
if (result !== false) onUpdateProperty(key, result)
}, [relationshipEntries, onUpdateProperty])
const canEdit = !!onUpdateProperty && !!onDeleteProperty
const existingRelKeys = useMemo(
() => new Set(relationshipEntries.map(g => g.key.toLowerCase())),
[relationshipEntries],
)
const missingSuggestedRels = onAddProperty
? SUGGESTED_RELATIONSHIPS.filter(r => !existingRelKeys.has(r.toLowerCase()))
: []
const {
relationshipEntries,
resolvedVaultPath,
handleRemoveRef,
handleAddRef,
canEdit,
missingSuggestedRels,
} = useRelationshipPanelState(frontmatter, entries, vaultPath, onAddProperty, onUpdateProperty, onDeleteProperty)
return (
<div>
{relationshipEntries.map(({ key, refs }) => (
<RelationshipGroup
key={key} label={key} refs={refs} entries={entries} typeEntryMap={typeEntryMap} onNavigate={onNavigate}
key={key} label={key} refs={refs} entries={entries} typeEntryMap={typeEntryMap} vaultPath={resolvedVaultPath} onNavigate={onNavigate}
onRemoveRef={canEdit ? (ref) => handleRemoveRef(key, ref) : undefined}
onAddRef={canEdit ? (noteTitle) => handleAddRef(key, noteTitle) : undefined}
onAddRef={canEdit ? (ref) => handleAddRef(key, ref) : undefined}
onCreateAndOpenNote={canEdit ? onCreateAndOpenNote : undefined}
/>
))}
@@ -466,12 +620,13 @@ export function DynamicRelationshipsPanel({ frontmatter, entries, typeEntryMap,
key={label}
label={label}
entries={entries}
onAdd={(noteTitle) => onAddProperty!(label, `[[${noteTitle}]]`)}
vaultPath={resolvedVaultPath}
onAdd={(ref) => onAddProperty!(label, ref)}
onCreateAndOpenNote={onCreateAndOpenNote}
/>
))}
{onAddProperty
? <AddRelationshipForm entries={entries} onAddProperty={onAddProperty} onCreateAndOpenNote={onCreateAndOpenNote} />
? <AddRelationshipForm entries={entries} vaultPath={resolvedVaultPath} onAddProperty={onAddProperty} onCreateAndOpenNote={onCreateAndOpenNote} />
: <DisabledLinkButton />
}
</div>

View File

@@ -11,10 +11,10 @@ function targetMatchesEntry(target: string, entryPath: string, matchTargets: Set
return false
}
function refsMatchTargets(refs: string[], targets: Set<string>): boolean {
function refsMatchTargets(refs: string[], entryPath: string, targets: Set<string>): boolean {
return refs.some((ref) => {
const target = wikilinkTarget(ref)
return targets.has(target) || targets.has(target.split('/').pop() ?? '')
return targetMatchesEntry(target, entryPath, targets)
})
}
@@ -29,7 +29,7 @@ export function useReferencedBy(entry: VaultEntry | null, entries: VaultEntry[])
for (const other of entries) {
if (other.path === entry.path) continue
for (const [key, refs] of Object.entries(other.relationships)) {
if (key !== 'Type' && refsMatchTargets(refs, matchTargets)) {
if (key !== 'Type' && refsMatchTargets(refs, entry.path, matchTargets)) {
results.push({ entry: other, viaKey: key })
}
}

View File

@@ -3,6 +3,8 @@ import { Link } from '@phosphor-icons/react'
import { cn } from '@/lib/utils'
import type { VaultEntry } from '../../types'
import { resolveNoteIcon } from '../../utils/noteIcon'
import { detectPropertyType } from '../../utils/propertyTypes'
import { getMappedStatusStyle } from '../../utils/statusStyles'
import { getTypeColor, getTypeLightColor } from '../../utils/typeColors'
import { isUrlValue, normalizeUrl, openExternalUrl } from '../../utils/url'
import { resolveEntry, wikilinkDisplay, wikilinkTarget } from '../../utils/wikilink'
@@ -14,7 +16,7 @@ interface PropertyChipValue {
typeIcon: ComponentType<SVGAttributes<SVGSVGElement>> | null
style?: CSSProperties
action?: { kind: 'note'; entry: VaultEntry } | { kind: 'url'; url: string }
tone: 'neutral' | 'relationship' | 'url'
tone: 'neutral' | 'relationship' | 'status' | 'url'
}
const URL_CHIP_STYLE: CSSProperties = {
@@ -22,6 +24,8 @@ const URL_CHIP_STYLE: CSSProperties = {
color: 'var(--accent-blue)',
}
type ChipScalarValue = string | number | boolean | null
function toChipTestId(propName: string, index: number): string {
const slug = propName.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
return `property-chip-${slug || 'value'}-${index}`
@@ -115,6 +119,29 @@ function resolveScalarChip(value: unknown): PropertyChipValue | null {
}
}
function resolveStatusChip(value: ChipScalarValue): PropertyChipValue | null {
const label = formatChipLabel(value)
if (!label) return null
const status = String(value)
const style = getMappedStatusStyle(status)
return {
label: `${label}`,
noteIcon: null,
typeIcon: null,
style: style ? { backgroundColor: style.bg, color: style.color } : undefined,
tone: 'status',
}
}
function resolvePropertyValueChip(propName: string, value: ChipScalarValue | undefined): PropertyChipValue | null {
if (value === undefined) return null
if (detectPropertyType(propName, value) !== 'status') {
return resolveScalarChip(value)
}
return resolveStatusChip(value)
}
function resolveRelationshipChipValues(
entry: VaultEntry,
propName: string,
@@ -135,7 +162,7 @@ function resolveScalarChipValues(entry: VaultEntry, propName: string): PropertyC
const rawValue = entry.properties[propertyKey]
const values = Array.isArray(rawValue) ? rawValue : [rawValue]
return values
.map((value) => resolveScalarChip(value))
.map((value) => resolvePropertyValueChip(propertyKey, value))
.filter((chip): chip is PropertyChipValue => chip !== null)
}
@@ -146,7 +173,7 @@ function resolvePropertyChipValues(
typeEntryMap: Record<string, VaultEntry>,
): PropertyChipValue[] {
if (propName.toLowerCase() === 'status') {
const statusChip = resolveScalarChip(entry.status)
const statusChip = resolvePropertyValueChip(propName, entry.status)
return statusChip ? [statusChip] : []
}

View File

@@ -87,16 +87,17 @@ function ViewItem({
const count = useMemo(() => evaluateView(view.definition, entries).length, [view.definition, entries])
return (
<div className="group relative [&>div>span:last-child]:transition-opacity group-hover:[&>div>span:last-child]:opacity-0 group-focus-within:[&>div>span:last-child]:opacity-0">
<div className="group relative">
<NavItem
icon={Funnel}
emoji={view.definition.icon}
label={view.definition.name}
count={count}
badgeClassName="transition-opacity group-hover:opacity-0 group-focus-within:opacity-0"
isActive={isActive}
onClick={onSelect}
/>
<div className="absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100">
<div className="pointer-events-none absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-0.5 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
{onEditView && (
<button
className="rounded p-0.5 text-muted-foreground hover:text-foreground"
@@ -360,7 +361,7 @@ const FAVORITE_TYPE_ICON_MAP: Record<string, string> = {
function getFavoriteIcon(entry: VaultEntry, typeEntryMap: Record<string, VaultEntry>) {
const typeEntry = entry.isA ? typeEntryMap[entry.isA] : undefined
return typeEntry?.icon ?? FAVORITE_TYPE_ICON_MAP[entry.isA ?? ''] ?? 'file-text'
return entry.icon ?? typeEntry?.icon ?? FAVORITE_TYPE_ICON_MAP[entry.isA ?? ''] ?? 'file-text'
}
function SortableFavoriteItem({

View File

@@ -0,0 +1,458 @@
import type { SidebarFilter } from '../types'
import type { ViewMode } from './useViewMode'
export const APP_COMMAND_IDS = {
appSettings: 'app-settings',
appCheckForUpdates: 'app-check-for-updates',
fileNewNote: 'file-new-note',
fileNewType: 'file-new-type',
fileDailyNote: 'file-daily-note',
fileQuickOpen: 'file-quick-open',
fileSave: 'file-save',
editFindInVault: 'edit-find-in-vault',
editToggleRawEditor: 'edit-toggle-raw-editor',
editToggleDiff: 'edit-toggle-diff',
viewEditorOnly: 'view-editor-only',
viewEditorList: 'view-editor-list',
viewAll: 'view-all',
viewToggleProperties: 'view-toggle-properties',
viewToggleAiChat: 'view-toggle-ai-chat',
viewToggleBacklinks: 'view-toggle-backlinks',
viewCommandPalette: 'view-command-palette',
viewZoomIn: 'view-zoom-in',
viewZoomOut: 'view-zoom-out',
viewZoomReset: 'view-zoom-reset',
viewGoBack: 'view-go-back',
viewGoForward: 'view-go-forward',
goAllNotes: 'go-all-notes',
goArchived: 'go-archived',
goChanges: 'go-changes',
goInbox: 'go-inbox',
noteToggleOrganized: 'note-toggle-organized',
noteToggleFavorite: 'note-toggle-favorite',
noteArchive: 'note-archive',
noteDelete: 'note-delete',
noteOpenInNewWindow: 'note-open-in-new-window',
noteRestoreDeleted: 'note-restore-deleted',
vaultOpen: 'vault-open',
vaultRemove: 'vault-remove',
vaultRestoreGettingStarted: 'vault-restore-getting-started',
vaultCommitPush: 'vault-commit-push',
vaultPull: 'vault-pull',
vaultResolveConflicts: 'vault-resolve-conflicts',
vaultViewChanges: 'vault-view-changes',
vaultInstallMcp: 'vault-install-mcp',
vaultReload: 'vault-reload',
vaultRepair: 'vault-repair',
} as const
export type AppCommandId = (typeof APP_COMMAND_IDS)[keyof typeof APP_COMMAND_IDS]
export type AppCommandShortcutCombo =
| 'command-or-ctrl'
| 'command-or-ctrl-shift'
| 'command-shift'
export type AppCommandDeterministicQaMode =
| 'renderer-shortcut-event'
| 'native-menu-command'
type ShortcutEventLike = Pick<KeyboardEvent, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey' | 'key' | 'code'>
export interface AppCommandDeterministicQaDefinition {
preferredMode: AppCommandDeterministicQaMode
supportsRendererShortcutEvent: boolean
supportsNativeMenuCommand: boolean
requiresManualNativeAcceleratorQa: boolean
}
export interface AppCommandShortcutEventOptions {
preferControl?: boolean
}
export type AppCommandShortcutEventInit = Pick<
KeyboardEventInit,
'altKey' | 'bubbles' | 'cancelable' | 'code' | 'ctrlKey' | 'key' | 'metaKey' | 'shiftKey'
>
type SimpleHandlerKey =
| 'onOpenSettings'
| 'onCheckForUpdates'
| 'onCreateNote'
| 'onCreateType'
| 'onOpenDailyNote'
| 'onQuickOpen'
| 'onSave'
| 'onSearch'
| 'onToggleRawEditor'
| 'onToggleDiff'
| 'onToggleInspector'
| 'onToggleAIChat'
| 'onCommandPalette'
| 'onZoomIn'
| 'onZoomOut'
| 'onZoomReset'
| 'onGoBack'
| 'onGoForward'
| 'onOpenVault'
| 'onRemoveActiveVault'
| 'onRestoreGettingStarted'
| 'onCommitPush'
| 'onPull'
| 'onResolveConflicts'
| 'onViewChanges'
| 'onInstallMcp'
| 'onReloadVault'
| 'onRepairVault'
| 'onOpenInNewWindow'
| 'onRestoreDeletedNote'
type ActiveTabHandlerKey =
| 'onToggleOrganized'
| 'onToggleFavorite'
| 'onArchiveNote'
| 'onDeleteNote'
type AppCommandRoute =
| { kind: 'view-mode'; value: ViewMode }
| { kind: 'filter'; value: SidebarFilter }
| { kind: 'handler'; handler: SimpleHandlerKey }
| { kind: 'active-tab-handler'; handler: ActiveTabHandlerKey }
interface AppCommandShortcutDefinition {
combo: AppCommandShortcutCombo
key: string
aliases?: string[]
code?: string
display: string
}
export interface AppCommandDefinition {
route: AppCommandRoute
menuOwned: boolean
shortcut?: AppCommandShortcutDefinition
preferredShortcutQaMode?: AppCommandDeterministicQaMode
}
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: '⌘,' },
},
[APP_COMMAND_IDS.appCheckForUpdates]: {
route: { kind: 'handler', handler: 'onCheckForUpdates' },
menuOwned: true,
},
[APP_COMMAND_IDS.fileNewNote]: {
route: { kind: 'handler', handler: 'onCreateNote' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: 'n', code: 'KeyN', display: '⌘N' },
},
[APP_COMMAND_IDS.fileNewType]: {
route: { kind: 'handler', handler: 'onCreateType' },
menuOwned: true,
},
[APP_COMMAND_IDS.fileDailyNote]: {
route: { kind: 'handler', handler: 'onOpenDailyNote' },
menuOwned: true,
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' },
},
[APP_COMMAND_IDS.fileSave]: {
route: { kind: 'handler', handler: 'onSave' },
menuOwned: true,
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' },
},
[APP_COMMAND_IDS.editToggleRawEditor]: {
route: { kind: 'handler', handler: 'onToggleRawEditor' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '\\', display: '⌘\\' },
},
[APP_COMMAND_IDS.editToggleDiff]: {
route: { kind: 'handler', handler: 'onToggleDiff' },
menuOwned: true,
},
[APP_COMMAND_IDS.viewEditorOnly]: {
route: { kind: 'view-mode', value: 'editor-only' },
menuOwned: true,
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' },
},
[APP_COMMAND_IDS.viewAll]: {
route: { kind: 'view-mode', value: 'all' },
menuOwned: true,
shortcut: { combo: 'command-or-ctrl', key: '3', display: '⌘3' },
},
[APP_COMMAND_IDS.viewToggleProperties]: {
route: { kind: 'handler', handler: 'onToggleInspector' },
menuOwned: true,
preferredShortcutQaMode: 'renderer-shortcut-event',
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' },
},
[APP_COMMAND_IDS.viewToggleBacklinks]: {
route: { kind: 'handler', handler: 'onToggleInspector' },
menuOwned: true,
},
[APP_COMMAND_IDS.viewCommandPalette]: {
route: { kind: 'handler', handler: 'onCommandPalette' },
menuOwned: true,
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: '⌘=' },
},
[APP_COMMAND_IDS.viewZoomOut]: {
route: { kind: 'handler', handler: 'onZoomOut' },
menuOwned: true,
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' },
},
[APP_COMMAND_IDS.viewGoBack]: {
route: { kind: 'handler', handler: 'onGoBack' },
menuOwned: true,
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: '⌘]' },
},
[APP_COMMAND_IDS.goAllNotes]: {
route: { kind: 'filter', value: 'all' },
menuOwned: true,
},
[APP_COMMAND_IDS.goArchived]: {
route: { kind: 'filter', value: 'archived' },
menuOwned: true,
},
[APP_COMMAND_IDS.goChanges]: {
route: { kind: 'filter', value: 'changes' },
menuOwned: true,
},
[APP_COMMAND_IDS.goInbox]: {
route: { kind: 'filter', value: 'inbox' },
menuOwned: true,
},
[APP_COMMAND_IDS.noteToggleOrganized]: {
route: { kind: 'active-tab-handler', handler: 'onToggleOrganized' },
menuOwned: true,
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' },
},
[APP_COMMAND_IDS.noteArchive]: {
route: { kind: 'active-tab-handler', handler: 'onArchiveNote' },
menuOwned: true,
},
[APP_COMMAND_IDS.noteDelete]: {
route: { kind: 'active-tab-handler', handler: 'onDeleteNote' },
menuOwned: true,
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' },
},
[APP_COMMAND_IDS.noteRestoreDeleted]: {
route: { kind: 'handler', handler: 'onRestoreDeletedNote' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultOpen]: {
route: { kind: 'handler', handler: 'onOpenVault' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultRemove]: {
route: { kind: 'handler', handler: 'onRemoveActiveVault' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultRestoreGettingStarted]: {
route: { kind: 'handler', handler: 'onRestoreGettingStarted' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultCommitPush]: {
route: { kind: 'handler', handler: 'onCommitPush' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultPull]: {
route: { kind: 'handler', handler: 'onPull' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultResolveConflicts]: {
route: { kind: 'handler', handler: 'onResolveConflicts' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultViewChanges]: {
route: { kind: 'handler', handler: 'onViewChanges' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultInstallMcp]: {
route: { kind: 'handler', handler: 'onInstallMcp' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultReload]: {
route: { kind: 'handler', handler: 'onReloadVault' },
menuOwned: true,
},
[APP_COMMAND_IDS.vaultRepair]: {
route: { kind: 'handler', handler: 'onRepairVault' },
menuOwned: true,
},
}
const APP_COMMAND_SET = new Set<string>(Object.values(APP_COMMAND_IDS))
const NATIVE_MENU_COMMAND_SET = new Set<string>(
(Object.entries(APP_COMMAND_DEFINITIONS) as Array<[AppCommandId, AppCommandDefinition]>)
.filter(([, definition]) => definition.menuOwned)
.map(([id]) => id),
)
const MANUAL_NATIVE_ACCELERATOR_QA_COMMAND_SET = new Set<AppCommandId>([
APP_COMMAND_IDS.appSettings,
APP_COMMAND_IDS.fileNewNote,
APP_COMMAND_IDS.fileDailyNote,
APP_COMMAND_IDS.fileQuickOpen,
APP_COMMAND_IDS.fileSave,
APP_COMMAND_IDS.editFindInVault,
APP_COMMAND_IDS.viewToggleAiChat,
APP_COMMAND_IDS.viewCommandPalette,
APP_COMMAND_IDS.noteToggleOrganized,
APP_COMMAND_IDS.noteToggleFavorite,
])
const shortcutKeyMaps = {
'command-or-ctrl': new Map<string, AppCommandId>(),
'command-or-ctrl-shift': new Map<string, AppCommandId>(),
'command-shift': new Map<string, AppCommandId>(),
} satisfies Record<AppCommandShortcutCombo, Map<string, AppCommandId>>
const shortcutCodeMaps = {
'command-or-ctrl': new Map<string, AppCommandId>(),
'command-or-ctrl-shift': new Map<string, AppCommandId>(),
'command-shift': new Map<string, AppCommandId>(),
} satisfies Record<AppCommandShortcutCombo, Map<string, AppCommandId>>
const COMMAND_ONLY_COMBOS: readonly AppCommandShortcutCombo[] = ['command-or-ctrl']
const COMMAND_SHIFT_COMBOS: readonly AppCommandShortcutCombo[] = ['command-shift', 'command-or-ctrl-shift']
const COMMAND_OR_CTRL_SHIFT_COMBOS: readonly AppCommandShortcutCombo[] = ['command-or-ctrl-shift']
const NO_SHORTCUT_COMBOS: readonly AppCommandShortcutCombo[] = []
function normalizeShortcutKey(key: string): string {
return key.length === 1 ? key.toLowerCase() : key
}
for (const [id, definition] of Object.entries(APP_COMMAND_DEFINITIONS) as Array<[AppCommandId, AppCommandDefinition]>) {
const shortcut = definition.shortcut
if (!shortcut) continue
shortcutKeyMaps[shortcut.combo].set(normalizeShortcutKey(shortcut.key), id)
for (const alias of shortcut.aliases ?? []) {
shortcutKeyMaps[shortcut.combo].set(normalizeShortcutKey(alias), id)
}
if (shortcut.code) {
shortcutCodeMaps[shortcut.combo].set(shortcut.code, id)
}
}
export function isAppCommandId(value: string): value is AppCommandId {
return APP_COMMAND_SET.has(value)
}
export function isNativeMenuCommandId(value: string): value is AppCommandId {
return NATIVE_MENU_COMMAND_SET.has(value)
}
export function getDeterministicShortcutQaDefinition(
id: AppCommandId,
): AppCommandDeterministicQaDefinition | null {
const definition = APP_COMMAND_DEFINITIONS[id]
if (!definition.shortcut) return null
return {
preferredMode:
definition.preferredShortcutQaMode
?? (definition.menuOwned ? 'native-menu-command' : 'renderer-shortcut-event'),
supportsRendererShortcutEvent: true,
supportsNativeMenuCommand: definition.menuOwned,
requiresManualNativeAcceleratorQa: MANUAL_NATIVE_ACCELERATOR_QA_COMMAND_SET.has(id),
}
}
export function getShortcutEventInit(
id: AppCommandId,
options: AppCommandShortcutEventOptions = {},
): AppCommandShortcutEventInit | null {
const shortcut = APP_COMMAND_DEFINITIONS[id].shortcut
if (!shortcut) return null
const useControl = options.preferControl ?? false
return {
key: shortcut.key,
code: shortcut.code,
altKey: false,
bubbles: true,
cancelable: true,
ctrlKey: useControl,
metaKey: !useControl,
shiftKey: shortcut.combo !== 'command-or-ctrl',
}
}
export function shortcutCombosForEvent({
altKey,
ctrlKey,
metaKey,
shiftKey,
}: Pick<ShortcutEventLike, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey'>): readonly AppCommandShortcutCombo[] {
if (altKey || (!metaKey && !ctrlKey)) return NO_SHORTCUT_COMBOS
if (shiftKey) {
return metaKey && !ctrlKey ? COMMAND_SHIFT_COMBOS : COMMAND_OR_CTRL_SHIFT_COMBOS
}
return COMMAND_ONLY_COMBOS
}
export function findShortcutCommandId(
combo: AppCommandShortcutCombo,
key: string,
code?: string,
): AppCommandId | null {
if (code) {
const codeMatch = shortcutCodeMaps[combo].get(code)
if (codeMatch) return codeMatch
}
return shortcutKeyMaps[combo].get(normalizeShortcutKey(key)) ?? null
}
export function findShortcutCommandIdForEvent(event: ShortcutEventLike): AppCommandId | null {
for (const combo of shortcutCombosForEvent(event)) {
const commandId = findShortcutCommandId(combo, event.key, event.code)
if (commandId) return commandId
}
return null
}

View File

@@ -0,0 +1,212 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
APP_COMMAND_IDS,
dispatchAppCommand,
executeAppCommand,
findShortcutCommandId,
findShortcutCommandIdForEvent,
isAppCommandId,
isNativeMenuCommandId,
resetAppCommandDispatchStateForTests,
type AppCommandHandlers,
} from './appCommandDispatcher'
import {
getDeterministicShortcutQaDefinition,
getShortcutEventInit,
} from './appCommandCatalog'
function makeHandlers(): AppCommandHandlers {
return {
onSetViewMode: vi.fn(),
onCreateNote: vi.fn(),
onCreateType: vi.fn(),
onOpenDailyNote: vi.fn(),
onQuickOpen: vi.fn(),
onSave: vi.fn(),
onOpenSettings: vi.fn(),
onToggleInspector: vi.fn(),
onCommandPalette: vi.fn(),
onZoomIn: vi.fn(),
onZoomOut: vi.fn(),
onZoomReset: vi.fn(),
onToggleOrganized: vi.fn(),
onToggleFavorite: vi.fn(),
onArchiveNote: vi.fn(),
onDeleteNote: vi.fn(),
onSearch: vi.fn(),
onToggleRawEditor: vi.fn(),
onToggleDiff: vi.fn(),
onToggleAIChat: vi.fn(),
onGoBack: vi.fn(),
onGoForward: vi.fn(),
onCheckForUpdates: vi.fn(),
onSelectFilter: vi.fn(),
onOpenVault: vi.fn(),
onRemoveActiveVault: vi.fn(),
onRestoreGettingStarted: vi.fn(),
onCommitPush: vi.fn(),
onPull: vi.fn(),
onResolveConflicts: vi.fn(),
onViewChanges: vi.fn(),
onInstallMcp: vi.fn(),
onOpenInNewWindow: vi.fn(),
onReloadVault: vi.fn(),
onRepairVault: vi.fn(),
onRestoreDeletedNote: vi.fn(),
activeTabPathRef: { current: '/vault/test.md' },
}
}
describe('appCommandDispatcher', () => {
afterEach(() => {
resetAppCommandDispatchStateForTests()
})
it('recognizes valid command ids', () => {
expect(isAppCommandId(APP_COMMAND_IDS.fileNewNote)).toBe(true)
expect(isAppCommandId('not-a-command')).toBe(false)
})
it('distinguishes native menu ids from keyboard-only ids', () => {
expect(isNativeMenuCommandId(APP_COMMAND_IDS.fileNewNote)).toBe(true)
expect(isNativeMenuCommandId(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)
})
it('gives every shortcut command an explicit deterministic QA strategy', () => {
expect(getDeterministicShortcutQaDefinition(APP_COMMAND_IDS.fileNewNote)).toMatchObject({
preferredMode: 'native-menu-command',
supportsRendererShortcutEvent: true,
supportsNativeMenuCommand: true,
requiresManualNativeAcceleratorQa: true,
})
expect(getDeterministicShortcutQaDefinition(APP_COMMAND_IDS.viewToggleProperties)).toMatchObject({
preferredMode: 'renderer-shortcut-event',
supportsRendererShortcutEvent: true,
supportsNativeMenuCommand: true,
requiresManualNativeAcceleratorQa: false,
})
expect(getDeterministicShortcutQaDefinition(APP_COMMAND_IDS.noteToggleFavorite)).toMatchObject({
preferredMode: 'renderer-shortcut-event',
supportsRendererShortcutEvent: true,
supportsNativeMenuCommand: false,
requiresManualNativeAcceleratorQa: true,
})
})
it('builds deterministic keyboard events from the shared shortcut manifest', () => {
expect(getShortcutEventInit(APP_COMMAND_IDS.viewToggleAiChat)).toMatchObject({
key: 'l',
code: 'KeyL',
metaKey: true,
ctrlKey: false,
shiftKey: true,
})
expect(getShortcutEventInit(APP_COMMAND_IDS.viewToggleAiChat, { preferControl: true })).toMatchObject({
key: 'l',
code: 'KeyL',
metaKey: false,
ctrlKey: true,
shiftKey: true,
})
expect(getShortcutEventInit(APP_COMMAND_IDS.appCheckForUpdates)).toBeNull()
})
it('resolves event modifiers through the shared shortcut catalog', () => {
expect(
findShortcutCommandIdForEvent({
key: '¬',
code: 'KeyL',
altKey: false,
ctrlKey: false,
metaKey: true,
shiftKey: true,
}),
).toBe(APP_COMMAND_IDS.viewToggleAiChat)
expect(
findShortcutCommandIdForEvent({
key: 'I',
code: 'KeyI',
altKey: false,
ctrlKey: false,
metaKey: true,
shiftKey: true,
}),
).toBe(APP_COMMAND_IDS.viewToggleProperties)
expect(
findShortcutCommandIdForEvent({
key: 'l',
code: 'KeyL',
altKey: false,
ctrlKey: true,
metaKey: false,
shiftKey: true,
}),
).toBeNull()
})
it('dispatches create note through the shared command path', () => {
const handlers = makeHandlers()
expect(dispatchAppCommand(APP_COMMAND_IDS.fileNewNote, handlers)).toBe(true)
expect(handlers.onCreateNote).toHaveBeenCalled()
})
it('dispatches inspector toggle through the shared command path', () => {
const handlers = makeHandlers()
expect(dispatchAppCommand(APP_COMMAND_IDS.viewToggleProperties, handlers)).toBe(true)
expect(handlers.onToggleInspector).toHaveBeenCalled()
})
it('dispatches AI panel toggle through the shared command path', () => {
const handlers = makeHandlers()
expect(dispatchAppCommand(APP_COMMAND_IDS.viewToggleAiChat, handlers)).toBe(true)
expect(handlers.onToggleAIChat).toHaveBeenCalled()
})
it('uses the active note for note-scoped commands', () => {
const handlers = makeHandlers()
expect(dispatchAppCommand(APP_COMMAND_IDS.noteToggleFavorite, handlers)).toBe(true)
expect(dispatchAppCommand(APP_COMMAND_IDS.noteToggleOrganized, handlers)).toBe(true)
expect(dispatchAppCommand(APP_COMMAND_IDS.noteDelete, handlers)).toBe(true)
expect(handlers.onToggleFavorite).toHaveBeenCalledWith('/vault/test.md')
expect(handlers.onToggleOrganized).toHaveBeenCalledWith('/vault/test.md')
expect(handlers.onDeleteNote).toHaveBeenCalledWith('/vault/test.md')
})
it('no-ops note-scoped commands when there is no active note', () => {
const handlers = makeHandlers()
handlers.activeTabPathRef.current = null
expect(dispatchAppCommand(APP_COMMAND_IDS.noteToggleFavorite, handlers)).toBe(false)
expect(dispatchAppCommand(APP_COMMAND_IDS.noteToggleOrganized, handlers)).toBe(false)
expect(dispatchAppCommand(APP_COMMAND_IDS.noteDelete, handlers)).toBe(false)
expect(handlers.onToggleFavorite).not.toHaveBeenCalled()
expect(handlers.onToggleOrganized).not.toHaveBeenCalled()
expect(handlers.onDeleteNote).not.toHaveBeenCalled()
})
it('dispatches navigation filters through the same shared command path', () => {
const handlers = makeHandlers()
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

@@ -0,0 +1,235 @@
import type { MutableRefObject } from 'react'
import type { SidebarFilter } from '../types'
import {
APP_COMMAND_DEFINITIONS,
type AppCommandId,
type AppCommandDefinition,
} from './appCommandCatalog'
import type { ViewMode } from './useViewMode'
export const APP_COMMAND_EVENT_NAME = 'laputa:dispatch-command'
export {
APP_COMMAND_IDS,
findShortcutCommandId,
findShortcutCommandIdForEvent,
isAppCommandId,
isNativeMenuCommandId,
} 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
onCreateType?: () => void
onOpenDailyNote: () => void
onQuickOpen: () => void
onSave: () => void
onOpenSettings: () => void
onToggleInspector: () => void
onCommandPalette: () => void
onZoomIn: () => void
onZoomOut: () => void
onZoomReset: () => void
onToggleOrganized?: (path: string) => void
onToggleFavorite?: (path: string) => void
onArchiveNote: (path: string) => void
onDeleteNote: (path: string) => void
onSearch: () => void
onToggleRawEditor?: () => void
onToggleDiff?: () => void
onToggleAIChat?: () => void
onGoBack?: () => void
onGoForward?: () => void
onCheckForUpdates?: () => void
onSelectFilter?: (filter: SidebarFilter) => void
onOpenVault?: () => void
onRemoveActiveVault?: () => void
onRestoreGettingStarted?: () => void
onCommitPush?: () => void
onPull?: () => void
onResolveConflicts?: () => void
onViewChanges?: () => void
onInstallMcp?: () => void
onOpenInNewWindow?: () => void
onReloadVault?: () => void
onRepairVault?: () => void
onRestoreDeletedNote?: () => void
activeTabPathRef: MutableRefObject<string | null>
}
type SimpleHandlerKey = keyof Pick<
AppCommandHandlers,
| 'onOpenSettings'
| 'onCheckForUpdates'
| 'onCreateNote'
| 'onCreateType'
| 'onOpenDailyNote'
| 'onQuickOpen'
| 'onSave'
| 'onSearch'
| 'onToggleRawEditor'
| 'onToggleDiff'
| 'onToggleInspector'
| 'onToggleAIChat'
| 'onCommandPalette'
| 'onZoomIn'
| 'onZoomOut'
| 'onZoomReset'
| 'onGoBack'
| 'onGoForward'
| 'onOpenVault'
| 'onRemoveActiveVault'
| 'onRestoreGettingStarted'
| 'onCommitPush'
| 'onPull'
| 'onResolveConflicts'
| 'onViewChanges'
| 'onInstallMcp'
| 'onReloadVault'
| 'onRepairVault'
| 'onOpenInNewWindow'
| 'onRestoreDeletedNote'
>
type ActiveTabHandlerKey = keyof Pick<
AppCommandHandlers,
'onToggleOrganized' | 'onToggleFavorite' | 'onArchiveNote' | 'onDeleteNote'
>
const SIMPLE_HANDLER_EXECUTORS: Record<SimpleHandlerKey, (handlers: AppCommandHandlers) => void> = {
onOpenSettings: (handlers) => handlers.onOpenSettings(),
onCheckForUpdates: (handlers) => handlers.onCheckForUpdates?.(),
onCreateNote: (handlers) => handlers.onCreateNote(),
onCreateType: (handlers) => handlers.onCreateType?.(),
onOpenDailyNote: (handlers) => handlers.onOpenDailyNote(),
onQuickOpen: (handlers) => handlers.onQuickOpen(),
onSave: (handlers) => handlers.onSave(),
onSearch: (handlers) => handlers.onSearch(),
onToggleRawEditor: (handlers) => handlers.onToggleRawEditor?.(),
onToggleDiff: (handlers) => handlers.onToggleDiff?.(),
onToggleInspector: (handlers) => handlers.onToggleInspector(),
onToggleAIChat: (handlers) => handlers.onToggleAIChat?.(),
onCommandPalette: (handlers) => handlers.onCommandPalette(),
onZoomIn: (handlers) => handlers.onZoomIn(),
onZoomOut: (handlers) => handlers.onZoomOut(),
onZoomReset: (handlers) => handlers.onZoomReset(),
onGoBack: (handlers) => handlers.onGoBack?.(),
onGoForward: (handlers) => handlers.onGoForward?.(),
onOpenVault: (handlers) => handlers.onOpenVault?.(),
onRemoveActiveVault: (handlers) => handlers.onRemoveActiveVault?.(),
onRestoreGettingStarted: (handlers) => handlers.onRestoreGettingStarted?.(),
onCommitPush: (handlers) => handlers.onCommitPush?.(),
onPull: (handlers) => handlers.onPull?.(),
onResolveConflicts: (handlers) => handlers.onResolveConflicts?.(),
onViewChanges: (handlers) => handlers.onViewChanges?.(),
onInstallMcp: (handlers) => handlers.onInstallMcp?.(),
onReloadVault: (handlers) => handlers.onReloadVault?.(),
onRepairVault: (handlers) => handlers.onRepairVault?.(),
onOpenInNewWindow: (handlers) => handlers.onOpenInNewWindow?.(),
onRestoreDeletedNote: (handlers) => handlers.onRestoreDeletedNote?.(),
}
const ACTIVE_TAB_HANDLER_EXECUTORS: Record<ActiveTabHandlerKey, (handlers: AppCommandHandlers, path: string) => void> = {
onToggleOrganized: (handlers, path) => handlers.onToggleOrganized?.(path),
onToggleFavorite: (handlers, path) => handlers.onToggleFavorite?.(path),
onArchiveNote: (handlers, path) => handlers.onArchiveNote(path),
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,
): boolean {
const path = pathRef.current
if (!path) return false
handler(path)
return true
}
function dispatchDefinition(
definition: AppCommandDefinition,
handlers: AppCommandHandlers,
): boolean {
switch (definition.route.kind) {
case 'view-mode':
handlers.onSetViewMode(definition.route.value)
return true
case 'filter':
handlers.onSelectFilter?.(definition.route.value)
return true
case 'handler': {
const handler = definition.route.handler
SIMPLE_HANDLER_EXECUTORS[handler as SimpleHandlerKey](handlers)
return true
}
case 'active-tab-handler': {
const handler = definition.route.handler
return dispatchActiveTabCommand(
handlers.activeTabPathRef,
(path) => ACTIVE_TAB_HANDLER_EXECUTORS[handler as ActiveTabHandlerKey](handlers, path),
)
}
}
}
export function dispatchAppCommand(id: AppCommandId, handlers: AppCommandHandlers): boolean {
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,43 +1,39 @@
import type { MutableRefObject } from 'react'
import type { ViewMode } from './useViewMode'
import { trackEvent } from '../lib/telemetry'
import {
APP_COMMAND_IDS,
executeAppCommand,
findShortcutCommandIdForEvent,
type AppCommandHandlers,
} from './appCommandDispatcher'
export interface KeyboardActions {
onQuickOpen: () => void
onCommandPalette: () => void
onSearch: () => void
onCreateNote: () => void
onOpenDailyNote: () => void
onSave: () => void
onOpenSettings: () => void
onDeleteNote: (path: string) => void
onArchiveNote: (path: string) => void
onSetViewMode: (mode: ViewMode) => void
onZoomIn: () => void
onZoomOut: () => void
onZoomReset: () => void
onGoBack?: () => void
onGoForward?: () => void
onToggleAIChat?: () => void
onToggleRawEditor?: () => void
onToggleInspector?: () => void
onToggleFavorite?: (path: string) => void
onToggleOrganized?: (path: string) => void
onOpenInNewWindow?: () => void
activeTabPathRef: MutableRefObject<string | null>
}
type ShortcutHandler = () => void
type ShortcutMap = Record<string, ShortcutHandler>
export type KeyboardActions = Pick<
AppCommandHandlers,
| 'onQuickOpen'
| 'onCommandPalette'
| 'onSearch'
| 'onCreateNote'
| 'onOpenDailyNote'
| 'onSave'
| 'onOpenSettings'
| 'onDeleteNote'
| 'onArchiveNote'
| 'onSetViewMode'
| 'onZoomIn'
| 'onZoomOut'
| 'onZoomReset'
| 'onGoBack'
| 'onGoForward'
| 'onToggleAIChat'
| 'onToggleRawEditor'
| 'onToggleInspector'
| 'onToggleFavorite'
| 'onToggleOrganized'
| 'onOpenInNewWindow'
| 'activeTabPathRef'
>
const TEXT_EDITING_KEYS = new Set(['Backspace', 'Delete'])
const VIEW_MODE_KEYS: Record<string, ViewMode> = {
'1': 'editor-only',
'2': 'editor-list',
'3': 'all',
}
function isTextInputFocused(): boolean {
const active = document.activeElement
if (!(active instanceof HTMLElement)) return false
@@ -45,104 +41,14 @@ function isTextInputFocused(): boolean {
return active.isContentEditable || active.closest('[contenteditable="true"]') !== null
}
function isCommandOrCtrlOnly(e: KeyboardEvent): boolean {
return (e.metaKey || e.ctrlKey) && e.altKey === false
}
function isCommandOrCtrlShiftOnly(e: KeyboardEvent): boolean {
return isCommandOrCtrlOnly(e) && e.shiftKey
}
function isCommandShiftOnly(e: KeyboardEvent): boolean {
return e.metaKey && e.ctrlKey === false && e.altKey === false && e.shiftKey
}
function withActiveTab(
activeTabPathRef: MutableRefObject<string | null>,
handler: (path: string) => void,
): ShortcutHandler {
return () => {
const path = activeTabPathRef.current
if (path) handler(path)
}
}
export function createCommandKeyMap(actions: KeyboardActions): ShortcutMap {
const { activeTabPathRef } = actions
return {
k: actions.onCommandPalette,
p: actions.onQuickOpen,
n: actions.onCreateNote,
j: actions.onOpenDailyNote,
s: actions.onSave,
',': actions.onOpenSettings,
d: withActiveTab(activeTabPathRef, (path) => actions.onToggleFavorite?.(path)),
e: withActiveTab(activeTabPathRef, (path) => actions.onToggleOrganized?.(path)),
Backspace: withActiveTab(activeTabPathRef, actions.onDeleteNote),
Delete: withActiveTab(activeTabPathRef, actions.onDeleteNote),
'[': () => actions.onGoBack?.(),
']': () => actions.onGoForward?.(),
'=': actions.onZoomIn,
'+': actions.onZoomIn,
'-': actions.onZoomOut,
'0': actions.onZoomReset,
'\\': () => actions.onToggleRawEditor?.(),
}
}
export function createShiftCommandKeyMap(actions: KeyboardActions): ShortcutMap {
return {
f: () => {
trackEvent('search_used')
actions.onSearch()
},
i: () => actions.onToggleInspector?.(),
o: () => actions.onOpenInNewWindow?.(),
}
}
export function handleViewModeKey(e: KeyboardEvent, onSetViewMode: (mode: ViewMode) => void): boolean {
if (isCommandOrCtrlOnly(e) === false || e.shiftKey) return false
const mode = VIEW_MODE_KEYS[e.key]
if (mode === undefined) return false
e.preventDefault()
onSetViewMode(mode)
return true
}
export function handleCommandKey(e: KeyboardEvent, keyMap: ShortcutMap): boolean {
if (isCommandOrCtrlOnly(e) === false || e.shiftKey) return false
const handler = keyMap[e.key]
if (handler === undefined) return false
if (TEXT_EDITING_KEYS.has(e.key) && isTextInputFocused()) return false
e.preventDefault()
handler()
return true
}
export function handleAiPanelKey(e: KeyboardEvent, onToggleAIChat?: () => void): boolean {
const matchesAiPanelShortcut = e.code === 'KeyL' || e.key.toLowerCase() === 'l'
if (isCommandShiftOnly(e) === false || matchesAiPanelShortcut === false || onToggleAIChat === undefined) return false
e.preventDefault()
onToggleAIChat()
return true
}
export function handleShiftCommandKey(e: KeyboardEvent, keyMap: ShortcutMap): boolean {
if (isCommandOrCtrlShiftOnly(e) === false) return false
const handler = keyMap[e.key.toLowerCase()]
if (handler === undefined) return false
e.preventDefault()
handler()
return true
}
export function handleAppKeyboardEvent(actions: KeyboardActions, event: KeyboardEvent) {
if (handleAiPanelKey(event, actions.onToggleAIChat)) return
const shiftKeyMap = createShiftCommandKeyMap(actions)
if (handleShiftCommandKey(event, shiftKeyMap)) return
if (handleViewModeKey(event, actions.onSetViewMode)) return
const cmdKeyMap = createCommandKeyMap(actions)
handleCommandKey(event, cmdKeyMap)
const commandId = findShortcutCommandIdForEvent(event)
if (commandId === null) return
if (TEXT_EDITING_KEYS.has(event.key) && isTextInputFocused()) return
event.preventDefault()
if (commandId === APP_COMMAND_IDS.editFindInVault) {
trackEvent('search_used')
}
executeAppCommand(commandId, actions, 'renderer-keyboard')
}

View File

@@ -35,7 +35,7 @@ export function buildNoteCommands(config: NoteCommandsConfig): CommandAction[] {
} = config
return [
{ id: 'create-note', label: 'Create New Note', group: 'Note', shortcut: '⌘N', keywords: ['new', 'add'], enabled: true, execute: onCreateNote },
{ id: 'create-note', label: 'New Note', group: 'Note', shortcut: '⌘N', keywords: ['new', 'create', 'add'], enabled: true, execute: onCreateNote },
{ id: 'create-type', label: 'New Type', group: 'Note', keywords: ['new', 'create', 'type', 'template'], enabled: !!onCreateType, execute: () => onCreateType?.() },
{ id: 'open-daily-note', label: "Open Today's Note", group: 'Note', shortcut: '⌘J', keywords: ['daily', 'journal', 'today'], enabled: true, execute: onOpenDailyNote },
{ id: 'save-note', label: 'Save Note', group: 'Note', shortcut: '⌘S', keywords: ['write'], enabled: hasActiveNote, execute: onSave },

View File

@@ -7,6 +7,15 @@ const PLURAL_OVERRIDES: Record<string, string> = {
}
const DEFAULT_TYPES = ['Event', 'Person', 'Project', 'Note']
const DEFAULT_TYPE_CANONICAL_CASE = new Map(
DEFAULT_TYPES.map(type => [type.toLowerCase(), type] as const),
)
function canonicalizeTypeName(type: string): string | null {
const trimmedType = type.trim()
if (!trimmedType) return null
return DEFAULT_TYPE_CANONICAL_CASE.get(trimmedType.toLowerCase()) ?? trimmedType
}
export function pluralizeType(type: string): string {
if (PLURAL_OVERRIDES[type]) return PLURAL_OVERRIDES[type]
@@ -16,16 +25,26 @@ export function pluralizeType(type: string): string {
}
export function extractVaultTypes(entries: VaultEntry[]): string[] {
const typeSet = new Set<string>()
const typeMap = new Map<string, string>()
for (const e of entries) {
if (e.isA === 'Type' && e.title) {
typeSet.add(e.title)
} else if (e.isA && e.isA !== 'Type') {
typeSet.add(e.isA)
const rawType =
e.isA === 'Type'
? e.title
: e.isA && e.isA !== 'Type'
? e.isA
: null
if (!rawType) continue
const canonicalType = canonicalizeTypeName(rawType)
if (!canonicalType) continue
const typeKey = canonicalType.toLowerCase()
if (!typeMap.has(typeKey)) {
typeMap.set(typeKey, canonicalType)
}
}
if (typeSet.size === 0) return DEFAULT_TYPES
return Array.from(typeSet).sort()
if (typeMap.size === 0) return DEFAULT_TYPES
return Array.from(typeMap.values()).sort()
}
export function buildTypeCommands(
@@ -34,19 +53,27 @@ export function buildTypeCommands(
onSelect: (sel: SidebarSelection) => void,
): CommandAction[] {
return types.flatMap((type) => {
const slug = type.toLowerCase().replace(/\s+/g, '-')
const plural = pluralizeType(type)
return [
{
id: `new-${slug}`, label: `New ${type}`, group: 'Note' as const,
keywords: ['new', 'create', type.toLowerCase()],
enabled: true, execute: () => onCreateNoteOfType(type),
},
{
id: `list-${slug}`, label: `List ${plural}`, group: 'Navigation' as const,
keywords: ['list', 'show', 'filter', type.toLowerCase(), plural.toLowerCase()],
enabled: true, execute: () => onSelect({ kind: 'sectionGroup', type }),
},
]
const canonicalType = canonicalizeTypeName(type)
if (!canonicalType) return []
const slug = canonicalType.toLowerCase().replace(/\s+/g, '-')
const plural = pluralizeType(canonicalType)
const commands: CommandAction[] = []
if (canonicalType.toLowerCase() !== 'note') {
commands.push({
id: `new-${slug}`, label: `New ${canonicalType}`, group: 'Note' as const,
keywords: ['new', 'create', canonicalType.toLowerCase()],
enabled: true, execute: () => onCreateNoteOfType(canonicalType),
})
}
commands.push({
id: `list-${slug}`, label: `List ${plural}`, group: 'Navigation' as const,
keywords: ['list', 'show', 'filter', canonicalType.toLowerCase(), plural.toLowerCase()],
enabled: true, execute: () => onSelect({ kind: 'sectionGroup', type: canonicalType }),
})
return commands
})
}

View File

@@ -0,0 +1,118 @@
const ROOT_EDITABLE_SELECTOR = '.ProseMirror[contenteditable="true"]'
const FALLBACK_EDITABLE_SELECTOR = '.bn-editor [contenteditable="true"]'
const MAX_FOCUS_ATTEMPTS = 12
interface TiptapChain {
setTextSelection: (pos: { from: number; to: number }) => TiptapChain
run: () => void
}
export interface TiptapEditor {
state: { doc: { descendants: (cb: (node: { type: { name: string }; nodeSize: number }, pos: number) => boolean | void) => void } }
chain: () => TiptapChain
}
export interface FocusableEditor {
focus: () => void
_tiptapEditor?: TiptapEditor
}
/** Select all text in the first heading block via the TipTap chain API. */
function selectFirstHeading(editor: FocusableEditor): void {
const tiptap = editor._tiptapEditor
if (!tiptap?.state?.doc) return
let from = -1
let to = -1
tiptap.state.doc.descendants((node, pos) => {
if (from !== -1) return false
if (node.type.name === 'heading') {
from = pos + 1
to = pos + node.nodeSize - 1
return false
}
})
if (from === -1 || to === -1 || from > to) return
tiptap.chain().setTextSelection({ from, to }).run()
}
function hasEditableFocus(): boolean {
const active = document.activeElement as HTMLElement | null
return Boolean(active?.isContentEditable || active?.closest('[contenteditable="true"]'))
}
function canFocusWindow(): boolean {
return !navigator.userAgent.toLowerCase().includes('jsdom')
}
function focusEditableCandidate(editable: HTMLElement): boolean {
if (canFocusWindow()) {
window.focus?.()
}
editable.focus()
if (hasEditableFocus()) return true
const selection = window.getSelection()
if (selection && editable.isContentEditable) {
const range = document.createRange()
range.selectNodeContents(editable)
range.collapse(true)
selection.removeAllRanges()
selection.addRange(range)
editable.focus()
}
return hasEditableFocus()
}
function focusEditableNode(): boolean {
const rootEditable = document.querySelector<HTMLElement>(ROOT_EDITABLE_SELECTOR)
if (rootEditable && focusEditableCandidate(rootEditable)) {
return true
}
const fallbackEditable = document.querySelector<HTMLElement>(FALLBACK_EDITABLE_SELECTOR)
if (fallbackEditable && focusEditableCandidate(fallbackEditable)) {
return true
}
return false
}
function logFocusTiming(t0: number | undefined, label: 'focus' | 'focus+select'): void {
if (!t0) return
console.debug(`[perf] createNote → ${label}: ${(performance.now() - t0).toFixed(1)}ms`)
}
export function focusEditorWithRetries(
editor: FocusableEditor,
selectTitle: boolean,
t0: number | undefined,
attempt = 0,
): void {
editor.focus()
if (!hasEditableFocus()) {
focusEditableNode()
}
if (!hasEditableFocus() && attempt < MAX_FOCUS_ATTEMPTS) {
requestAnimationFrame(() => focusEditorWithRetries(editor, selectTitle, t0, attempt + 1))
return
}
if (!selectTitle) {
logFocusTiming(t0, 'focus')
return
}
// Defer selection to the next animation frame so the new note's content
// (applied via queueMicrotask inside a React effect triggered by the tab
// change) is in the document before we try to select the heading.
// Between two rAF callbacks, all pending macrotasks — including React's
// MessageChannel re-render and the subsequent queueMicrotask content swap
// — complete, so the heading block is guaranteed to exist by rAF 2.
requestAnimationFrame(() => {
selectFirstHeading(editor)
logFocusTiming(t0, 'focus+select')
})
}

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,
@@ -48,7 +49,11 @@ function makeActions() {
}
describe('useAppKeyboard', () => {
afterEach(() => vi.restoreAllMocks())
afterEach(() => {
delete (window as typeof window & { __TAURI__?: unknown }).__TAURI__
resetAppCommandDispatchStateForTests()
vi.restoreAllMocks()
})
it('Cmd+1 sets view mode to editor-only', () => {
const actions = makeActions()
@@ -92,6 +97,41 @@ describe('useAppKeyboard', () => {
expect(actions.onCreateNote).toHaveBeenCalled()
})
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).toHaveBeenCalled()
})
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).toHaveBeenCalled()
})
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).toHaveBeenCalled()
})
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).toHaveBeenCalled()
})
it('Cmd+D triggers toggle favorite on active note', () => {
const actions = makeActions()
actions.onToggleFavorite = vi.fn()
@@ -100,6 +140,15 @@ describe('useAppKeyboard', () => {
expect(actions.onToggleFavorite).toHaveBeenCalledWith('/vault/test.md')
})
it('Cmd+D still works in Tauri mode', () => {
const actions = makeActions()
actions.onToggleFavorite = vi.fn()
;(window as typeof window & { __TAURI__?: object }).__TAURI__ = {}
renderHook(() => useAppKeyboard(actions))
fireKey('d', { metaKey: true })
expect(actions.onToggleFavorite).toHaveBeenCalledWith('/vault/test.md')
})
it('Cmd+E triggers toggle organized on active note, not archive', () => {
const actions = makeActions()
renderHook(() => useAppKeyboard(actions))
@@ -108,6 +157,18 @@ describe('useAppKeyboard', () => {
expect(actions.onArchiveNote).not.toHaveBeenCalled()
})
it('Cmd+E still works when editor focus stops propagation', () => {
const actions = makeActions()
const onToggleOrganized = vi.fn()
renderHook(() => useAppKeyboard({ ...actions, onToggleOrganized }))
withFocusedContentEditable((editable) => {
editable.addEventListener('keydown', (event) => event.stopPropagation())
fireKeyOnTarget(editable, 'e', { metaKey: true })
expect(onToggleOrganized).toHaveBeenCalledWith('/vault/test.md')
expect(actions.onArchiveNote).not.toHaveBeenCalled()
})
})
it('Cmd+J triggers open daily note', () => {
const actions = makeActions()
renderHook(() => useAppKeyboard(actions))

View File

@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import type { SetStateAction } from 'react'
import { useAppSave } from './useAppSave'
import type { VaultEntry } from '../types'
import { isTauri } from '../mock-tauri'
@@ -22,6 +23,7 @@ describe('useAppSave', () => {
const deps = {
updateEntry: vi.fn(),
setTabs: vi.fn(),
handleSwitchTab: vi.fn(),
setToastMessage: vi.fn(),
loadModifiedFiles: vi.fn(),
clearUnsaved: vi.fn(),
@@ -147,6 +149,44 @@ describe('useAppSave', () => {
)
})
it('switches the active tab to the renamed path after untitled H1 auto-rename', async () => {
vi.useFakeTimers()
vi.mocked(isTauri).mockReturnValue(true)
const oldPath = '/vault/untitled-note-123.md'
const newPath = '/vault/fresh-title.md'
const entry = makeEntry(oldPath, 'Untitled Note 123', 'untitled-note-123.md')
let tabsState = [{ entry, content: '# Fresh Title\n\nBody' }]
const setTabs = vi.fn((updater: SetStateAction<typeof tabsState>) => {
tabsState = typeof updater === 'function' ? updater(tabsState) : updater
})
vi.mocked(invoke).mockImplementation(async (command: string, args?: Record<string, unknown>) => {
if (command === 'save_note_content') return undefined
if (command === 'auto_rename_untitled') return { new_path: newPath, updated_files: 0 }
if (command === 'reload_vault_entry') return makeEntry(newPath, 'Fresh Title', 'fresh-title.md')
if (command === 'get_note_content' && args?.path === newPath) return '# Fresh Title\n\nBody'
return undefined
})
const { result } = renderSave({
setTabs,
tabs: tabsState,
activeTabPath: oldPath,
unsavedPaths: new Set([oldPath]),
})
await act(async () => {
result.current.handleContentChange(oldPath, '# Fresh Title\n\nBody')
await vi.advanceTimersByTimeAsync(3_000)
})
expect(deps.handleSwitchTab).toHaveBeenCalledWith(newPath)
expect(tabsState[0].entry.path).toBe(newPath)
expect(tabsState[0].entry.filename).toBe('fresh-title.md')
expect(tabsState[0].content).toBe('# Fresh Title\n\nBody')
})
it('cancels a pending untitled auto-rename when the user navigates away', async () => {
vi.useFakeTimers()
vi.mocked(isTauri).mockReturnValue(true)

View File

@@ -92,6 +92,10 @@ function pendingRenameOutsideActiveTab(
async function reloadAutoRenamedNote(
oldPath: string,
newPath: string,
tabs: TabState[],
activeTabPath: string | null,
setTabs: AppSaveDeps['setTabs'],
handleSwitchTab: AppSaveDeps['handleSwitchTab'],
replaceEntry: AppSaveDeps['replaceEntry'],
loadModifiedFiles: AppSaveDeps['loadModifiedFiles'],
): Promise<void> {
@@ -99,13 +103,31 @@ async function reloadAutoRenamedNote(
invoke<VaultEntry>('reload_vault_entry', { path: newPath }),
invoke<string>('get_note_content', { path: newPath }),
])
const otherTabPaths = tabs
.filter((tab) => tab.entry.path !== oldPath && tab.entry.path !== newPath)
.map((tab) => tab.entry.path)
setTabs((prev: TabState[]) => prev.map((tab) => (
tab.entry.path === oldPath
? { entry: { ...tab.entry, ...newEntry, path: newPath }, content: newContent }
: tab
)))
if (activeTabPath === oldPath) handleSwitchTab(newPath)
replaceEntry(oldPath, { ...newEntry, path: newPath }, newContent)
await Promise.all(otherTabPaths.map(async (path) => {
const content = await invoke<string>('get_note_content', { path })
setTabs((prev: TabState[]) => prev.map((tab) => (
tab.entry.path === path ? { ...tab, content } : tab
)))
}))
loadModifiedFiles()
}
interface AppSaveDeps {
updateEntry: (path: string, patch: Partial<VaultEntry>) => void
setTabs: Parameters<typeof useEditorSaveWithLinks>[0]['setTabs']
handleSwitchTab: (path: string) => void
setToastMessage: (msg: string | null) => void
loadModifiedFiles: () => void
reloadViews?: () => Promise<void>
@@ -119,7 +141,7 @@ interface AppSaveDeps {
}
export function useAppSave({
updateEntry, setTabs, setToastMessage,
updateEntry, setTabs, handleSwitchTab, setToastMessage,
loadModifiedFiles, reloadViews, clearUnsaved, unsavedPaths,
tabs, activeTabPath,
handleRenameNote, replaceEntry, resolvedPath,
@@ -142,12 +164,21 @@ export function useAppSave({
notePath: path,
})
if (!result) return false
await reloadAutoRenamedNote(path, result.new_path, replaceEntry, loadModifiedFiles)
await reloadAutoRenamedNote(
path,
result.new_path,
tabs,
activeTabPath,
setTabs,
handleSwitchTab,
replaceEntry,
loadModifiedFiles,
)
return true
} catch {
return false
}
}, [resolvedPath, replaceEntry, loadModifiedFiles])
}, [resolvedPath, tabs, activeTabPath, setTabs, handleSwitchTab, replaceEntry, loadModifiedFiles])
const flushPendingUntitledRename = useCallback(async (path?: string) => {
const pending = takePendingRename(pendingUntitledRenameRef, path)

View File

@@ -219,6 +219,24 @@ describe('useCommandRegistry', () => {
cmd!.execute()
expect(onOpenFeedback).toHaveBeenCalledOnce()
})
it('keeps a single canonical New Note command when generic note types are present', () => {
const config = makeConfig({
entries: [
{ path: '/type-note.md', title: 'Note', isA: 'Type' },
{ path: '/lowercase-note.md', title: 'lowercase-note', isA: 'note' },
],
})
const { result } = renderHook(() => useCommandRegistry(config))
const newNoteCommands = result.current.filter(command => command.label.toLowerCase() === 'new note')
expect(newNoteCommands).toHaveLength(1)
expect(newNoteCommands[0]).toMatchObject({
id: 'create-note',
shortcut: '⌘N',
})
})
})
describe('pluralizeType', () => {
@@ -274,6 +292,15 @@ describe('extractVaultTypes', () => {
expect(types).toHaveLength(2)
})
it('deduplicates default types case-insensitively and keeps canonical casing', () => {
const entries = [
{ path: '/note-type.md', title: 'note', isA: 'Type' },
{ path: '/note-instance.md', title: 'Example', isA: 'Note' },
{ path: '/project-instance.md', title: 'Project Plan', isA: 'project' },
] as never[]
expect(extractVaultTypes(entries)).toEqual(['Note', 'Project'])
})
})
describe('groupSortKey', () => {
@@ -396,4 +423,16 @@ describe('buildTypeCommands', () => {
expect(commands[2].id).toBe('new-event')
expect(commands[3].id).toBe('list-event')
})
it('omits the generic Note create command while keeping navigation for notes', () => {
const onCreateNoteOfType = vi.fn()
const onSelect = vi.fn()
const commands = buildTypeCommands(['Note', 'Project'], onCreateNoteOfType, onSelect)
expect(commands.map(command => command.id)).toEqual([
'list-note',
'new-project',
'list-project',
])
})
})

Some files were not shown because too many files have changed in this diff Show More