From bdc15e952db73e4f9460016e9a6aa050472e8520 Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Sat, 26 Sep 2026 01:25:42 -0700 Subject: [PATCH] Initial RuneStone project --- .gitignore | 14 + .vscode/extensions.json | 7 + .vscode/settings.json | 3 + AGENTS.md | 63 + README.md | 73 + docs/development.md | 72 + docs/installation.md | 47 + docs/product-scope.md | 87 + docs/releases.md | 69 + docs/roadmap.md | 59 + docs/user-guide.md | 145 + fixtures/reader-showcase.md | 63 + fixtures/sample/.runestone/marks.json | 31 + fixtures/sample/notes/inbox.md | 5 + fixtures/sample/notes/projects/alpha.md | 3 + fixtures/sample/src/hello.py | 6 + fixtures/sample/tools/setup.sh | 3 + package.json | 58 + pnpm-lock.yaml | 2678 ++++++++ scripts/chrome.spec.ts | 41 + scripts/documents.spec.ts | 348 ++ scripts/headingMarks.spec.ts | 15 + scripts/imageNavigation.smoke.mjs | 209 + scripts/images.smoke.mjs | 248 + scripts/images.spec.ts | 55 + scripts/languageFor.spec.ts | 18 + scripts/markdownBlocks.spec.ts | 56 + scripts/markdownCommands.spec.ts | 60 + scripts/markdownLinks.spec.ts | 37 + scripts/markdownMenu.smoke.mjs | 207 + scripts/markdownTable.spec.ts | 93 + scripts/media.spec.ts | 36 + scripts/noteHtml.spec.ts | 60 + scripts/reader.spec.ts | 103 + scripts/renamePath.spec.ts | 66 + scripts/renameTitle.smoke.mjs | 158 + scripts/tabScroll.smoke.mjs | 148 + scripts/tableDrag.smoke.mjs | 234 + scripts/tableFormulas.smoke.mjs | 187 + scripts/tableFormulas.spec.ts | 92 + scripts/tableNavigation.smoke.mjs | 324 + scripts/tableSelection.spec.ts | 56 + scripts/tableStructure.spec.ts | 69 + scripts/terminal.smoke.mjs | 195 + scripts/terminal.spec.ts | 39 + scripts/treeDrop.spec.ts | 120 + scripts/treeSelection.smoke.mjs | 122 + scripts/treeSelection.spec.ts | 87 + scripts/windowControls.smoke.mjs | 84 + scripts/workbench.smoke.mjs | 798 +++ scripts/workspaces.smoke.mjs | 122 + scripts/writerMenu.spec.ts | 244 + src-tauri/.gitignore | 7 + src-tauri/Cargo.lock | 5395 +++++++++++++++++ src-tauri/Cargo.toml | 36 + src-tauri/build.rs | 33 + src-tauri/capabilities/default.json | 41 + src-tauri/icons/128x128.png | Bin 0 -> 1593 bytes src-tauri/icons/128x128@2x.png | Bin 0 -> 2861 bytes src-tauri/icons/32x32.png | Bin 0 -> 567 bytes src-tauri/icons/Square107x107Logo.png | Bin 0 -> 1340 bytes src-tauri/icons/Square142x142Logo.png | Bin 0 -> 1691 bytes src-tauri/icons/Square150x150Logo.png | Bin 0 -> 1738 bytes src-tauri/icons/Square284x284Logo.png | Bin 0 -> 3115 bytes src-tauri/icons/Square30x30Logo.png | Bin 0 -> 536 bytes src-tauri/icons/Square310x310Logo.png | Bin 0 -> 3447 bytes src-tauri/icons/Square44x44Logo.png | Bin 0 -> 777 bytes src-tauri/icons/Square71x71Logo.png | Bin 0 -> 1020 bytes src-tauri/icons/Square89x89Logo.png | Bin 0 -> 1181 bytes src-tauri/icons/StoreLogo.png | Bin 0 -> 848 bytes src-tauri/icons/icon.icns | Bin 0 -> 98451 bytes src-tauri/icons/icon.ico | Bin 0 -> 37710 bytes src-tauri/icons/icon.png | Bin 0 -> 5664 bytes .../permissions/autogenerated/pty_close.toml | 11 + .../autogenerated/pty_dictation.toml | 11 + .../autogenerated/pty_new_window.toml | 11 + .../permissions/autogenerated/pty_open.toml | 11 + .../autogenerated/pty_profiles.toml | 11 + .../permissions/autogenerated/pty_resize.toml | 11 + .../permissions/autogenerated/pty_write.toml | 11 + .../autogenerated/workspace_abs_path.toml | 11 + .../autogenerated/workspace_copy.toml | 11 + .../autogenerated/workspace_create.toml | 11 + .../autogenerated/workspace_delete.toml | 11 + .../autogenerated/workspace_last_path.toml | 11 + .../autogenerated/workspace_list.toml | 11 + .../autogenerated/workspace_new.toml | 11 + .../autogenerated/workspace_open.toml | 11 + .../autogenerated/workspace_open_window.toml | 11 + .../autogenerated/workspace_read.toml | 11 + .../workspace_read_data_url.toml | 11 + .../autogenerated/workspace_recent.toml | 11 + .../autogenerated/workspace_rename.toml | 11 + .../autogenerated/workspace_reveal.toml | 11 + .../autogenerated/workspace_search.toml | 11 + .../autogenerated/workspace_write.toml | 11 + .../autogenerated/workspace_write_bytes.toml | 11 + src-tauri/src/lib.rs | 52 + src-tauri/src/main.rs | 6 + src-tauri/src/pty.rs | 503 ++ src-tauri/src/workspace.rs | 1027 ++++ src-tauri/tauri.conf.json | 39 + src-tauri/tauri.windows.conf.json | 19 + src/app.css | 394 ++ src/app.html | 13 + src/lib/editor/EditorHost.svelte | 240 + src/lib/editor/LiveWriter.svelte | 356 ++ src/lib/editor/WriterHost.svelte | 283 + src/lib/editor/headingMarks.ts | 90 + src/lib/editor/imageControls.ts | 170 + src/lib/editor/imageDrop.ts | 18 + src/lib/editor/imagePreview.ts | 76 + src/lib/editor/imageSource.ts | 22 + src/lib/editor/languageFor.ts | 39 + src/lib/editor/liveMarkdown.ts | 173 + src/lib/editor/markdownCommands.ts | 93 + src/lib/editor/markdownMenu.ts | 122 + src/lib/editor/markdownTable.ts | 74 + src/lib/editor/monaco-css.d.ts | 1 + src/lib/editor/monacoChrome.ts | 30 + src/lib/editor/monacoEnv.ts | 32 + src/lib/editor/noteTitle.ts | 99 + src/lib/editor/selection.ts | 10 + src/lib/editor/sessions.ts | 30 + src/lib/editor/tableCellActions.ts | 98 + src/lib/editor/tableCellMarkdown.ts | 63 + src/lib/editor/tableControls.ts | 386 ++ src/lib/editor/tableDragControls.ts | 226 + src/lib/editor/tableFormulas.ts | 151 + src/lib/editor/tableNavigation.ts | 32 + src/lib/editor/tableSelection.ts | 119 + src/lib/editor/tableSelectionControls.ts | 225 + src/lib/editor/tableStructure.ts | 69 + src/lib/editor/workspaceImageDrop.ts | 26 + src/lib/editor/writerMarks.ts | 21 + src/lib/editor/writerMenu.ts | 143 + src/lib/layout/BookmarksPane.svelte | 90 + src/lib/layout/ContextMenu.svelte | 167 + src/lib/layout/EditorPane.svelte | 228 + src/lib/layout/FileTree.svelte | 748 +++ src/lib/layout/ImageViewer.svelte | 32 + src/lib/layout/MarkdownView.svelte | 161 + src/lib/layout/OutlinePane.svelte | 74 + src/lib/layout/QuickOpen.svelte | 60 + src/lib/layout/SearchPane.svelte | 147 + src/lib/layout/TabBar.svelte | 114 + src/lib/layout/TerminalDock.svelte | 260 + src/lib/layout/TerminalPane.svelte | 218 + src/lib/layout/TextDialog.svelte | 29 + src/lib/layout/TreeNode.svelte | 345 ++ src/lib/layout/Workbench.svelte | 1017 ++++ src/lib/layout/WorkspacePicker.svelte | 158 + src/lib/layout/menuTypes.ts | 16 + src/lib/terminal/TerminalPicker.svelte | 43 + src/lib/terminal/TerminalSettings.svelte | 30 + src/lib/terminal/TerminalWindow.svelte | 19 + src/lib/terminal/model.ts | 70 + src/lib/theme/tokens.css | 56 + src/lib/ui/Icon.svelte | 121 + src/lib/ui/IconButton.svelte | 140 + src/lib/ui/ModeSwitcher.svelte | 190 + src/lib/ui/WindowControls.svelte | 61 + src/lib/ui/actionIcons.ts | 63 + src/lib/ui/actionMenu.ts | 66 + src/lib/workspace/api.ts | 128 + src/lib/workspace/chrome.ts | 27 + src/lib/workspace/diagrams.ts | 34 + src/lib/workspace/dialogs.svelte.ts | 13 + src/lib/workspace/documents.ts | 191 + src/lib/workspace/htmlToMarkdown.ts | 331 + src/lib/workspace/markdownBlocks.ts | 70 + src/lib/workspace/markdownLinks.ts | 74 + src/lib/workspace/marks.ts | 39 + src/lib/workspace/media.ts | 121 + src/lib/workspace/noteHtml.ts | 231 + src/lib/workspace/outline.ts | 31 + src/lib/workspace/renamePath.ts | 53 + src/lib/workspace/treeDrop.ts | 151 + src/lib/workspace/treeSelection.ts | 61 + src/lib/workspace/types.ts | 35 + src/routes/+layout.svelte | 7 + src/routes/+layout.ts | 5 + src/routes/+page.svelte | 7 + static/favicon.png | Bin 0 -> 1571 bytes static/svelte.svg | 1 + static/tauri.svg | 6 + static/vite.svg | 1 + svelte.config.js | 18 + tsconfig.json | 20 + vite.config.js | 45 + 190 files changed, 25986 insertions(+) create mode 100644 .gitignore create mode 100644 .vscode/extensions.json create mode 100644 .vscode/settings.json create mode 100644 AGENTS.md create mode 100644 README.md create mode 100644 docs/development.md create mode 100644 docs/installation.md create mode 100644 docs/product-scope.md create mode 100644 docs/releases.md create mode 100644 docs/roadmap.md create mode 100644 docs/user-guide.md create mode 100644 fixtures/reader-showcase.md create mode 100644 fixtures/sample/.runestone/marks.json create mode 100644 fixtures/sample/notes/inbox.md create mode 100644 fixtures/sample/notes/projects/alpha.md create mode 100644 fixtures/sample/src/hello.py create mode 100644 fixtures/sample/tools/setup.sh create mode 100644 package.json create mode 100644 pnpm-lock.yaml create mode 100644 scripts/chrome.spec.ts create mode 100644 scripts/documents.spec.ts create mode 100644 scripts/headingMarks.spec.ts create mode 100644 scripts/imageNavigation.smoke.mjs create mode 100644 scripts/images.smoke.mjs create mode 100644 scripts/images.spec.ts create mode 100644 scripts/languageFor.spec.ts create mode 100644 scripts/markdownBlocks.spec.ts create mode 100644 scripts/markdownCommands.spec.ts create mode 100644 scripts/markdownLinks.spec.ts create mode 100644 scripts/markdownMenu.smoke.mjs create mode 100644 scripts/markdownTable.spec.ts create mode 100644 scripts/media.spec.ts create mode 100644 scripts/noteHtml.spec.ts create mode 100644 scripts/reader.spec.ts create mode 100644 scripts/renamePath.spec.ts create mode 100644 scripts/renameTitle.smoke.mjs create mode 100644 scripts/tabScroll.smoke.mjs create mode 100644 scripts/tableDrag.smoke.mjs create mode 100644 scripts/tableFormulas.smoke.mjs create mode 100644 scripts/tableFormulas.spec.ts create mode 100644 scripts/tableNavigation.smoke.mjs create mode 100644 scripts/tableSelection.spec.ts create mode 100644 scripts/tableStructure.spec.ts create mode 100644 scripts/terminal.smoke.mjs create mode 100644 scripts/terminal.spec.ts create mode 100644 scripts/treeDrop.spec.ts create mode 100644 scripts/treeSelection.smoke.mjs create mode 100644 scripts/treeSelection.spec.ts create mode 100644 scripts/windowControls.smoke.mjs create mode 100644 scripts/workbench.smoke.mjs create mode 100644 scripts/workspaces.smoke.mjs create mode 100644 scripts/writerMenu.spec.ts create mode 100644 src-tauri/.gitignore create mode 100644 src-tauri/Cargo.lock create mode 100644 src-tauri/Cargo.toml create mode 100644 src-tauri/build.rs create mode 100644 src-tauri/capabilities/default.json create mode 100644 src-tauri/icons/128x128.png create mode 100644 src-tauri/icons/128x128@2x.png create mode 100644 src-tauri/icons/32x32.png create mode 100644 src-tauri/icons/Square107x107Logo.png create mode 100644 src-tauri/icons/Square142x142Logo.png create mode 100644 src-tauri/icons/Square150x150Logo.png create mode 100644 src-tauri/icons/Square284x284Logo.png create mode 100644 src-tauri/icons/Square30x30Logo.png create mode 100644 src-tauri/icons/Square310x310Logo.png create mode 100644 src-tauri/icons/Square44x44Logo.png create mode 100644 src-tauri/icons/Square71x71Logo.png create mode 100644 src-tauri/icons/Square89x89Logo.png create mode 100644 src-tauri/icons/StoreLogo.png create mode 100644 src-tauri/icons/icon.icns create mode 100644 src-tauri/icons/icon.ico create mode 100644 src-tauri/icons/icon.png create mode 100644 src-tauri/permissions/autogenerated/pty_close.toml create mode 100644 src-tauri/permissions/autogenerated/pty_dictation.toml create mode 100644 src-tauri/permissions/autogenerated/pty_new_window.toml create mode 100644 src-tauri/permissions/autogenerated/pty_open.toml create mode 100644 src-tauri/permissions/autogenerated/pty_profiles.toml create mode 100644 src-tauri/permissions/autogenerated/pty_resize.toml create mode 100644 src-tauri/permissions/autogenerated/pty_write.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_abs_path.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_copy.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_create.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_delete.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_last_path.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_list.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_new.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_open.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_open_window.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_read.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_read_data_url.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_recent.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_rename.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_reveal.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_search.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_write.toml create mode 100644 src-tauri/permissions/autogenerated/workspace_write_bytes.toml create mode 100644 src-tauri/src/lib.rs create mode 100644 src-tauri/src/main.rs create mode 100644 src-tauri/src/pty.rs create mode 100644 src-tauri/src/workspace.rs create mode 100644 src-tauri/tauri.conf.json create mode 100644 src-tauri/tauri.windows.conf.json create mode 100644 src/app.css create mode 100644 src/app.html create mode 100644 src/lib/editor/EditorHost.svelte create mode 100644 src/lib/editor/LiveWriter.svelte create mode 100644 src/lib/editor/WriterHost.svelte create mode 100644 src/lib/editor/headingMarks.ts create mode 100644 src/lib/editor/imageControls.ts create mode 100644 src/lib/editor/imageDrop.ts create mode 100644 src/lib/editor/imagePreview.ts create mode 100644 src/lib/editor/imageSource.ts create mode 100644 src/lib/editor/languageFor.ts create mode 100644 src/lib/editor/liveMarkdown.ts create mode 100644 src/lib/editor/markdownCommands.ts create mode 100644 src/lib/editor/markdownMenu.ts create mode 100644 src/lib/editor/markdownTable.ts create mode 100644 src/lib/editor/monaco-css.d.ts create mode 100644 src/lib/editor/monacoChrome.ts create mode 100644 src/lib/editor/monacoEnv.ts create mode 100644 src/lib/editor/noteTitle.ts create mode 100644 src/lib/editor/selection.ts create mode 100644 src/lib/editor/sessions.ts create mode 100644 src/lib/editor/tableCellActions.ts create mode 100644 src/lib/editor/tableCellMarkdown.ts create mode 100644 src/lib/editor/tableControls.ts create mode 100644 src/lib/editor/tableDragControls.ts create mode 100644 src/lib/editor/tableFormulas.ts create mode 100644 src/lib/editor/tableNavigation.ts create mode 100644 src/lib/editor/tableSelection.ts create mode 100644 src/lib/editor/tableSelectionControls.ts create mode 100644 src/lib/editor/tableStructure.ts create mode 100644 src/lib/editor/workspaceImageDrop.ts create mode 100644 src/lib/editor/writerMarks.ts create mode 100644 src/lib/editor/writerMenu.ts create mode 100644 src/lib/layout/BookmarksPane.svelte create mode 100644 src/lib/layout/ContextMenu.svelte create mode 100644 src/lib/layout/EditorPane.svelte create mode 100644 src/lib/layout/FileTree.svelte create mode 100644 src/lib/layout/ImageViewer.svelte create mode 100644 src/lib/layout/MarkdownView.svelte create mode 100644 src/lib/layout/OutlinePane.svelte create mode 100644 src/lib/layout/QuickOpen.svelte create mode 100644 src/lib/layout/SearchPane.svelte create mode 100644 src/lib/layout/TabBar.svelte create mode 100644 src/lib/layout/TerminalDock.svelte create mode 100644 src/lib/layout/TerminalPane.svelte create mode 100644 src/lib/layout/TextDialog.svelte create mode 100644 src/lib/layout/TreeNode.svelte create mode 100644 src/lib/layout/Workbench.svelte create mode 100644 src/lib/layout/WorkspacePicker.svelte create mode 100644 src/lib/layout/menuTypes.ts create mode 100644 src/lib/terminal/TerminalPicker.svelte create mode 100644 src/lib/terminal/TerminalSettings.svelte create mode 100644 src/lib/terminal/TerminalWindow.svelte create mode 100644 src/lib/terminal/model.ts create mode 100644 src/lib/theme/tokens.css create mode 100644 src/lib/ui/Icon.svelte create mode 100644 src/lib/ui/IconButton.svelte create mode 100644 src/lib/ui/ModeSwitcher.svelte create mode 100644 src/lib/ui/WindowControls.svelte create mode 100644 src/lib/ui/actionIcons.ts create mode 100644 src/lib/ui/actionMenu.ts create mode 100644 src/lib/workspace/api.ts create mode 100644 src/lib/workspace/chrome.ts create mode 100644 src/lib/workspace/diagrams.ts create mode 100644 src/lib/workspace/dialogs.svelte.ts create mode 100644 src/lib/workspace/documents.ts create mode 100644 src/lib/workspace/htmlToMarkdown.ts create mode 100644 src/lib/workspace/markdownBlocks.ts create mode 100644 src/lib/workspace/markdownLinks.ts create mode 100644 src/lib/workspace/marks.ts create mode 100644 src/lib/workspace/media.ts create mode 100644 src/lib/workspace/noteHtml.ts create mode 100644 src/lib/workspace/outline.ts create mode 100644 src/lib/workspace/renamePath.ts create mode 100644 src/lib/workspace/treeDrop.ts create mode 100644 src/lib/workspace/treeSelection.ts create mode 100644 src/lib/workspace/types.ts create mode 100644 src/routes/+layout.svelte create mode 100644 src/routes/+layout.ts create mode 100644 src/routes/+page.svelte create mode 100644 static/favicon.png create mode 100644 static/svelte.svg create mode 100644 static/tauri.svg create mode 100644 static/vite.svg create mode 100644 svelte.config.js create mode 100644 tsconfig.json create mode 100644 vite.config.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f12849a --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.DS_Store +node_modules +/build +/.svelte-kit +/package +.env +.env.* +!.env.example +vite.config.js.timestamp-* +vite.config.ts.timestamp-* +src-tauri/target +src-tauri/gen +.idea +/.audit diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..61343e9 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + "recommendations": [ + "svelte.svelte-vscode", + "tauri-apps.tauri-vscode", + "rust-lang.rust-analyzer" + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..2f86c50 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "svelte.enable-ts-plugin": true +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4ad5f15 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,63 @@ +# RuneStone project instructions + +## Documentation + +Keep the README focused on the project, its usefulness, setup, help, and maintainers. +Keep agent instructions in this file. Put detailed usage, development notes, and +product plans in `docs/`, with links from the README. +Keep the roadmap visual and organized around goals, user outcomes, and milestones. +Keep detailed capability lists and design constraints in the product scope reference. + +## UI work: prefer meaningful icons + +Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI. +Apply them automatically without requiring the user to repeat them. + +- Favor recognizable icons for actions, navigation, menus, and settings categories. + Help users recognize functions without relying only on English vocabulary. + Use icons to save space and reduce clutter. +- Pair icons with concise visible labels when the meaning could be ambiguous. + Keep labels that help users learn or distinguish functions. +- Use icon-only controls for familiar actions in compact spaces. + Give them accessible names, tooltips on hover and keyboard focus, and comfortable click targets. +- Reuse existing icon components and artwork. Keep the same icon for the same function. + Maintain consistent sizing and stroke weight. +- Do not force icons onto every setting, label, or explanation. + Use text alone when no clear icon exists. Omit decoration that does not improve understanding. + Recognition and accessibility take priority over fitting more controls on screen. +- Use Obsidian's settings pattern as a reference: icons with labels in navigation, + readable text and ordinary controls in detailed settings. + +For UI reviews, check changed controls against these rules. + +## UI work: use rounded corners + +Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI. +Apply them automatically without requiring the user to repeat them. + +- Use rounded corners consistently for controls and navigation highlights, including file and folder selections. + Compact controls and navigation rows share `--rs-control-radius`. + Selection outlines use `--rs-item-selection-radius`. +- Round exposed selection corners while keeping adjacent selected rows joined. + Do not add rounded gaps or selection borders on shared edges. +- Apply the same treatment to hover, active, and selected navigation states. +- Tables inside documents are the exception: keep grids, cells, and cell selection outlines square. + Table toolbar and menu controls still use rounded corners. + +## UI work: outline only the outer boundary of a selection + +Apply these rules whenever designing, implementing, modifying, or reviewing selection UI. +Apply them automatically without requiring the user to repeat them. + +- Adjacent selected rows or cells share one highlighted region. + Highlight only its exposed perimeter. Omit selection borders on shared internal edges. + Apply this to navigation rows, table cells, lists, and grids. +- Use the shared `--rs-item-selection-*` theme values for fill, border color, and border width. + Use table-cell selection as the fill and outline reference, with rounded exposed corners outside document tables. +- Separate groups, divided by unselected items or physical gaps, retain separate outlines. + A single selected item gets a complete outline. +- Determine adjacency from visible layout order, including sorting and expanded tree branches. + At indentation changes, preserve exposed edges and omit the portions shared by selected rows. +- Keep the fill continuous within each selected region. + Ordinary table grid lines can remain, but must not become highlighted selection borders inside the region. +- Check single items, contiguous ranges, separated selections, and nested rows. diff --git a/README.md b/README.md new file mode 100644 index 0000000..699ee10 --- /dev/null +++ b/README.md @@ -0,0 +1,73 @@ +# RuneStone + +A desktop workspace for writing and code. + +RuneStone brings Markdown notes, scripts, images, and a terminal into one window. +Open a folder and work with the files already inside it. + +## Why RuneStone? + +Notes and code often belong to the same project. RuneStone keeps them together, +so you can write an explanation, edit a script, and run it in the same workspace. + +Your documents stay as ordinary files on disk. You can open them in other editors +and use your own tools to manage them. Workspace settings live separately in `.runestone/`. + +## Features + +- **Markdown writing:** Live formatting, source editing, split view, and read view. +- **Code editing:** A source editor for scripts, with file navigation and workspace search. +- **Images and diagrams:** Image insertion and previews, plus Mermaid diagrams. +- **Tables:** Editable Markdown tables with formulas for calculations. +- **Terminals:** Multiple shell sessions, split panes, and commands beside your documents. +- **File handling:** Autosave every five seconds and controls to resolve changes from other tools. + +## Project status + +RuneStone is under development, with Windows as its first target. +**Plugin support is planned and is not available yet.** Git controls, language servers, +session restoration, and crash recovery are also pending. + +The [roadmap](docs/roadmap.md) shows the proposed direction, goals, and milestones. +The [user guide](docs/user-guide.md) covers current features and limitations. + +## Get started + +RuneStone runs on Windows 10 and 11 (64-bit). There is no public installer download yet. +If you have a supplied installer: + +1. Open `RuneStone__x64-setup.exe`. +2. Follow the setup steps. +3. Open **RuneStone** from the Windows Start menu. +4. Use the folder button to open a workspace or create one. + +The installer sets up RuneStone for your Windows account. You do not need a terminal or developer tools. +If Microsoft Edge WebView2 is missing, setup downloads and installs it, which needs an internet connection. + +Press Ctrl+N to create a note or script, Ctrl+P to find a file, and Ctrl+S to save. + +See the [installation guide](docs/installation.md) for setup help, updates, and removal. +To run from source, see the [development guide](docs/development.md#run-from-source). + +## Documentation + +Documentation lives in this repository: + +- [User guide](docs/user-guide.md): Editing, images, tables, terminals, and shortcuts. +- [Installation guide](docs/installation.md): Windows setup and troubleshooting. +- [Development guide](docs/development.md): Build tools, source setup, and tests. +- [Release guide](docs/releases.md): Build and package the Windows installer. +- [Roadmap](docs/roadmap.md): Product direction, goals, and milestones. + +## Contributing + +Contributions can include code, documentation, reproducible bug reports, and feature proposals. +Read the [development guide](docs/development.md) for the build and test workflow, +and the [product scope](docs/product-scope.md) for detailed capabilities and boundaries. + +Bug reports should include the operating system, steps to reproduce the problem, +the expected result, and any error message. + +## Maintainer + +[kwyvern-gh](https://github.com/kwyvern-gh) diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..1001e1a --- /dev/null +++ b/docs/development.md @@ -0,0 +1,72 @@ +# Development guide + +[Back to RuneStone](../README.md) + +## Stack + +RuneStone uses Tauri 2 and Rust for the desktop host. +The interface uses Svelte 5, TypeScript, and Vite. +CodeMirror handles live Markdown editing, Monaco handles source editing, and xterm handles terminals. +Windows is the first target. The older WriterHost component remains unused. + +See the setup steps below to install dependencies and run the desktop app. +See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints. +Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md). + +## Run from source + +These steps are for developers. App users can use the [Windows installer](installation.md). + +### Requirements + +- Node.js 22.12 or later and pnpm +- A current stable Rust toolchain +- Microsoft C++ Build Tools and Microsoft Edge WebView2 on Windows + +Use the [Tauri prerequisites guide](https://v2.tauri.app/start/prerequisites/) to install the Windows build tools and Rust toolchain. + +1. Download or clone this repository. +2. Open a terminal in the repository folder. +3. Run `pnpm install --frozen-lockfile`. +4. Run `pnpm tauri dev`. +5. Use the folder button in the app to open a workspace or create one. + +See the [release guide](releases.md) to build a Windows installer. + +## Checks + +Run these commands from the repository folder: + +```sh +pnpm check +pnpm test +pnpm build +cargo test --manifest-path src-tauri/Cargo.toml --lib --offline +``` + +The offline Rust command requires cached dependencies. Omit `--offline` if Cargo needs to download them. +`pnpm build` builds the frontend. Use `pnpm tauri build` to build the desktop app. + +The Rust tests cover real terminal shells, working directories, Unicode output, +resizing, exit status, and session termination. Native terminal tests launch each +detected shell profile and check shell prompt integration. + +## Browser smoke tests + +The browser tests use the real interface with mocked desktop communication. +They do not replace native desktop tests. + +1. Install Playwright, or set `PLAYWRIGHT_MODULE` to a shared Playwright package. +2. Start the frontend with `pnpm dev`. +3. In a second terminal, run a smoke script, such as `node scripts/workbench.smoke.mjs`. + +Set `CHROME_PATH` if you need to select an installed browser executable. + +| Script | Coverage | +| --- | --- | +| `scripts/workbench.smoke.mjs` | The Svelte, Monaco, and xterm interface | +| `scripts/terminal.smoke.mjs` | Terminal groups, single-session layout, menus, profiles, history, tasks, settings, and editor actions | +| `scripts/images.smoke.mjs` | Image drops, clipboard imports, source editing, zoom, undo, failed writes, and tab changes during imports | +| `scripts/imageNavigation.smoke.mjs` | Navigator pointer drags, hidden image source, selection, context actions, inline/reference images, and drag cancellation | + +Additional smoke scripts live in `scripts/`. diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..0dae8a9 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,47 @@ +# Installation guide + +[Back to RuneStone](../README.md) + +## Install on Windows + +RuneStone supports Windows 10 and 11 on 64-bit Intel and AMD computers. +The installer contains the app and its interface. You do not need developer tools or a terminal. +There is no public download yet. Get the setup file from the maintainer who supplied your release. + +1. Save `RuneStone__x64-setup.exe` to your Downloads folder. +2. Double-click the file. +3. Follow the setup steps. +4. Open **RuneStone** from the Windows Start menu. +5. Use the folder button to open a workspace or create one. + +Keep the default installation folder unless you need a different location. +Setup installs the app for your Windows account and adds a Start menu shortcut. +If WebView2 is missing, setup downloads and installs it. Keep your internet connection active until setup finishes. + +## Update RuneStone + +1. Save your open documents. +2. Close all RuneStone windows. +3. Open the installer for the newer version. +4. Follow the setup steps. + +The installer replaces the app. Your workspace files stay in their current folders. +Setup blocks older versions from replacing a newer version. + +## Remove RuneStone + +1. Open **Settings > Apps > Installed apps** in Windows 11, or **Apps & features** in Windows 10. +2. Find **RuneStone**. +3. Select **Uninstall**. + +Your workspace folders contain your notes, scripts, images, and workspace settings. +Keep these folders outside the app installation folder. Removing the app leaves these separate folders in place. + +## Setup help + +- **WebView2 download fails:** Restore your internet connection, then run the installer again. +- **Windows shows an unknown publisher:** Current local builds are unsigned. Check the file source with the maintainer before you proceed. +- **The app cannot open a workspace:** Use the folder button to choose a folder that your Windows account can access. + +The [user guide](user-guide.md) explains the app controls. +The [release guide](releases.md) explains how maintainers build and distribute installers. diff --git a/docs/product-scope.md b/docs/product-scope.md new file mode 100644 index 0000000..48d1bd8 --- /dev/null +++ b/docs/product-scope.md @@ -0,0 +1,87 @@ +# Product scope + +[Back to RuneStone](../README.md) + +This reference preserves intended capabilities and design constraints. Some features already exist. +See the [roadmap](roadmap.md) for goals and milestones, and the [user guide](user-guide.md) for current behavior and limitations. + +The planned design keeps the core active and adds optional features through first-party plugins. Plugin support is not implemented yet. + +## Workspace and files + +- Open one folder as the workspace. +- Keep notes, scripts, and images in the same tree. +- Honor `.gitignore` in the navigator. +- Watch the folder for changes. Poll when the path is a network drive. +- Prefer a local Git clone. Do not treat a live network share as the sync path. +- Store display order, pins, bookmarks, and plugin settings in `.runestone/`. +- Open an existing Obsidian folder as files plus wiki links. Ignore `.obsidian`. + +## Writer and IDE + +- Use one editor engine for notes and code. +- Switch chrome between Writer and IDE. Autodetect from the file type. Allow a per-file override. +- Writer chrome uses wrapped text, a document preview, and image hover previews. +- IDE chrome uses line numbers, a minimap, and a terminal dock. +- Left-click a file in the navigation pane to open it in the current tab; middle-click to open it in a new tab. Tabs with unsaved edits stay open. Already-open files select their existing tab. Close a tab with the close control or the middle mouse button. +- Support Markdown, Python, JavaScript, TypeScript, JSON, YAML, TOML, and shell at first. +- Parse CommonMark, GFM tasks and tables, YAML frontmatter, wiki links, and tags. + +## Navigator + +- Show a left activity bar with Files, Search, and Bookmarks. +- Click the active item again to hide the sidebar. +- Right-click empty space to create a folder or a note. +- Right-click a file for copy, bookmark, path copy, reveal, pin, rename, and delete. +- Drag files and folders to move them or to set display order. +- Save display order. Do not reorder inodes for sort. +- Show a ribbon with new file, new folder, sort, and collapse all or expand all. + +## Panes + +- Show an outline of headings and symbols on the right. Allow collapse. +- Show a minimap of the open buffer. +- Open a terminal whose working directory is the workspace root. +- Allow more than one terminal. Add a session and kill that session from a rail on the right of the dock. +- Show a document preview that renders Markdown images. + +## Plugins + +Plugin support is pending. The plan is to ship extra features as first-party plugins with an on or off toggle. A marketplace is outside the planned scope. + +Planned plugins enabled by default: + +- Git. Status, stage, commit, pull, push, log, and diff. Use the system `git` binary. +- Sort. Per-folder order, pin, and hide. Flexplorer is a reference for behavior, not a source of code. + +Planned plugins disabled by default: + +- Projects. Kanban is the first view. Calendar and Gantt share the same task index. +- Graph. Draw wiki-link edges from the file index. +- Canvas. Store `.canvas` files in JSON Canvas 1.0. +- Browser. Open a page in an in-app webview. Block ads with EasyList and EasyPrivacy. + +Kanban boards are Markdown files. Headings are columns. Task list items are cards. + +## Later work + +- Background Git for people who do not want to run Git by hand. Timed commit, pull, and push. A history limit is not designed yet. +- Extend the existing live Markdown preview. See the [user guide](user-guide.md) for current behavior. +- Language servers for diagnostics and go-to-definition. +- Wiki-link jump and backlinks from a rebuildable index. +- A command palette for every command. + +## Out of scope + +- A plugin marketplace or third-party loader +- Obsidian or VS Code plugin compatibility +- Cloud sync, live collaboration, or mobile +- A debugger or a full IDE +- Auto-commit on save + +## Architecture goals + +Dark is the primary theme. + +Privileged operations belong in Rust: disk access, file watching, search, Git, terminal sessions, and adblock matching. +Git and adblock matching belong to planned plugins. diff --git a/docs/releases.md b/docs/releases.md new file mode 100644 index 0000000..7259dfa --- /dev/null +++ b/docs/releases.md @@ -0,0 +1,69 @@ +# Release guide + +[Back to RuneStone](../README.md) + +## Build the Windows installer + +Build on 64-bit Windows with the tools in the [development guide](development.md#run-from-source). +The commands below use the checked-in dependency versions. + +```sh +pnpm install --frozen-lockfile +pnpm check +pnpm test +pnpm build:installer +``` + +The last command builds the interface, compiles the release app, and creates an NSIS setup executable. +The first build needs internet access to download the packaging tools and the WebView2 bootstrapper. +Find the installer in: + +```text +src-tauri/target/release/bundle/nsis/RuneStone__x64-setup.exe +``` + +Distribute this setup file. Users do not need the repository, a local server, or build tools. +Build output stays outside version control. + +## Installer settings + +Tauri automatically merges `src-tauri/tauri.windows.conf.json` into the base configuration on Windows. +This file selects NSIS for ordinary `pnpm tauri build` commands too. +It uses the existing RuneStone icon and installs the app for the current Windows account. +Tauri supplies the setup screens, Start menu shortcut, launch option, and uninstaller. + +The installer includes the WebView2 bootstrapper. +If WebView2 is missing, setup downloads the runtime. An existing runtime needs no setup download. +The configuration blocks version downgrades. +It does not register document types or start RuneStone when Windows starts. + +See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for the packaging options. + +## Prepare a release + +1. Set the same version in `package.json`, `src-tauri/Cargo.toml`, and `src-tauri/tauri.conf.json`. +2. Update `src-tauri/Cargo.lock` with Cargo if the package version changed. +3. Run the checks and build command above. +4. Test the installer on a clean Windows account with the checks below. +5. Attach the setup file and release notes to the repository release or your chosen download page. + +Keep `com.runestone.app` as the app identifier so upgrades retain the same app identity. +No public download location or automatic release upload is configured yet. +After you publish an installer, add its download link to the README. + +Local installers are unsigned until the maintainer configures Windows code signing. +Use [Tauri's signing guide](https://v2.tauri.app/distribute/sign/windows/) before public distribution. + +## Installer checks + +| Check | Expected result | +| --- | --- | +| Install on an account without Node.js or Rust | Setup completes and RuneStone opens | +| Install without WebView2, with internet access | Setup installs the runtime and RuneStone opens | +| Open RuneStone from the Start menu | The app opens without a terminal or development server | +| Create a workspace outside the installation folder | Notes save and reopen | +| Install a newer version | Setup updates the app and preserves workspace files | +| Try to install an older version | Setup blocks the downgrade | +| Remove RuneStone through Windows Settings | The app and shortcuts disappear, and the separate workspace remains | + +These checks require a Windows test account or virtual machine. A successful build alone does not confirm them. diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..f09092e --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,59 @@ +# Product roadmap + +[Back to RuneStone](../README.md) + +**Goal:** Make RuneStone a dependable place to write, understand, and run a project +while keeping its files portable and under the user's control. + +## Direction + +This is a proposed progression from the existing editor to a broader workspace. +No release dates are assigned. + +```mermaid +flowchart LR + accTitle: RuneStone product direction + accDescr: First make daily work dependable, then help users understand connected projects, then let users choose optional workflows. + daily("1. Trust daily work
Write, run, and resume") + understand("2. Understand the project
Follow ideas and code") + adapt("3. Choose your workflow
Add only the tools you need") + daily --> understand --> adapt +``` + +## 1. Trust daily work + +**Objective:** Make RuneStone dependable enough to serve as the everyday home for notes and scripts. + +The current editor, local files, autosave, and terminals provide the foundation. +Session restoration and crash recovery would let users resume work after an interruption. + +**Milestone:** A user can write a note, run its companion script, restart the app, +and resume the workspace with recoverable edits. + +## 2. Understand the project + +**Objective:** Help users move from a question to the related notes and code without losing context. + +Reliable note links and backlinks would connect explanations. +Code navigation and diagnostics would help users understand the scripts those explanations describe. + +**Milestone:** A user can follow a note to related material, locate a code definition, +and identify a reported code problem within the workspace. + +## 3. Choose your workflow + +**Objective:** Support different ways of working while keeping the core editor simple. + +Plugin support is pending. A first-party plugin foundation would let users choose +optional tools for version history, organization, planning, and visual exploration. + +**Milestone:** A user can enable a first-party plugin, use it with workspace files, +and disable it while retaining access to those files in the core editor. + +## Why this order? + +Reliable daily work establishes trust. Better navigation then helps users understand larger projects. +Optional workflows build on that foundation while preserving a focused core. + +Detailed capabilities and boundaries live in the [product scope](product-scope.md). +The [user guide](user-guide.md) describes what works today. diff --git a/docs/user-guide.md b/docs/user-guide.md new file mode 100644 index 0000000..bea6521 --- /dev/null +++ b/docs/user-guide.md @@ -0,0 +1,145 @@ +# User guide + +[Back to RuneStone](../README.md) + +Current features and limitations as of September 2026. + +## Workspace, editing, and terminals + +- The folder button and Ctrl+O open recent workspaces, with the current workspace + marked and full paths shown. The list remembers the 20 most recently opened + folders across restarts. Open another folder from the bottom of the menu, or + choose New workspace to create and open a named folder in a chosen location. + Existing folders are never overwritten. Opening or creating a workspace opens + a new window, keeping the current window's documents and terminals in place. +- Markdown's writing layout is one continuous document with live formatting. + Type freely, press Enter to continue, and use arrow keys or select across lines. + The active line reveals its raw Markdown, including link destinations and task + markers. Other lines show formatting. Checkboxes stay beside their item text. Clicking one updates the Markdown and completed items are struck through. + Ctrl+click follows links. There is no formatting toolbar. + Ctrl+E switches to the IDE source editor; Split and Read remain available. + Writing edits update the shared source model without converting through HTML, + preserving Markdown syntax, frontmatter and Windows line endings. Mermaid code, + tables and images preview inline. Table cells can be edited directly. +- Click a note's title in Writing to rename its file. Enter or leaving the field + saves the name; Escape cancels. The folder and Markdown extension are preserved, + and renaming keeps the note's contents and editing history. +- Drag a workspace image from the navigator into a Markdown editor to insert a + relative link to the existing file. An “Insert image” hint marks the editor; + Escape cancels the drag. Dropping files from the system file explorer or pasting + images copies them into `attachments/` with unique filenames. Undo removes the + inserted links while keeping the image files. + In Writing, image Markdown stays hidden until **Edit image source** is pressed. The image remains visible while editing. Hide it again with the same button, + Escape, or by moving the cursor away. Click an image to select it, then + right-click or press Shift+F10 for copy image, copy Markdown, swap image, remove + image, zoom, edit source, open in a new tab, copy path, and show in Explorer. + Remove image or Delete removes only that embed from the note and supports undo. + Zoom supports fit, magnification and Escape to close, including in Split and Read. +- Right-click Markdown text in writing or source mode (or press Shift+F10) for + note/external links, selection search, extraction, formatting, and clipboard + actions. Format includes bold, italic, strike, highlight, code, math, comments, + and clear formatting. Paragraph applies lists, tasks, headings 1–6, body text, + or quotes to the selected lines. Insert adds footnotes, tables, callouts, + horizontal rules, code blocks, and math blocks as Markdown source. Use arrow + keys to navigate submenus and Escape to return to editing. Obsidian Bases are + not supported. +- Tables keep readable column widths and render `
` as cell line breaks. + Hover beside a table's right edge to add a column, or below its bottom edge to + add a row. Clicking a cell edits its contents. Wide tables scroll within the document. + Grips appear on hover or keyboard focus above columns and beside body rows. + Drag a grip to reorder: a preview follows the pointer, the source row/column + stays highlighted, and a line marks the drop position. Drag near an edge + to scroll, or press Escape to cancel. Focus a grip and use arrow keys to move it. + Row moves keep the Markdown header fixed. Columns carry their alignment with them. + Drag across cells or Shift+click to select a rectangle, then right-click for + cut/copy/paste, bold, italic, strikethrough, highlight, code, math, comment, + clear formatting, alignment, clear cells, and delete cells. Clipboard shortcuts, + Ctrl+B/I, Shift+arrow selection, and undo/redo work on the selected cells. + TSV or Markdown tables paste as a grid and expand the table when needed. + Alignment applies to selected columns, as required by Markdown. Clear empties + contents; Delete removes complete selected rows/columns, or shifts a partial + selection left. Math stores inline `$…$` syntax. Comments use `%%…%%` and are + hidden in Read mode. Each operation can be undone in one step. + Right-clicking text within a cell preserves the selected words and offers note + links, external links, workspace search, extraction to a new note, formatting, + rich/plain-text paste, and Select all. Extraction saves the selected Markdown + in a new file and replaces the selection with a note link. Undo restores the + original text without deleting the new note. Row and Column submenus insert, + move, duplicate, and delete at the clicked cell. Column moves keep alignment. Sorting is stable and natural (2 before 10), leaves blanks last, and keeps the + header fixed. Context-menu actions and table edge buttons have matching icons. +- Table formulas start with `=`: for example, `=B2+C2`, `=AVERAGE(B2:C2)`, + `=SUM(B2:B10)`, or `=ROUND(B2/3, 2)`. Columns use A, B, …, AA. Row 1 is + the header, so the first data row is 2. References stay inside the current table. + Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`. + Functions include SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND. + Separate function arguments with commas: `=AVERAGE(B2,C2)` averages two cells. + A colon selects a range: `=AVERAGE(B2:C2)`. + Aggregates ignore text and blank cells. Arithmetic treats blank cells as zero. + Results recalculate in Writing, Split, and Read. Click a result to edit its + formula; Enter commits it and Tab moves to the next cell. The Formulas control + below each table explains the syntax, and the active cell shows its address. + Invalid formulas, missing cells, and circular references display error labels. + Markdown stores the formula itself, so other apps display readable source. + Use code formatting or `\=` to keep formula-like text literal. References are + positional: copying, inserting, deleting, sorting, or moving cells does not + rewrite addresses. Cross-table references and automatic fill are not supported. +- Tabs retain their editor models, undo history, cursor and scroll state while open. +- Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file. +- Changed notes and scripts autosave every 5 seconds, including background tabs. + Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts + and unavailable files preserve your edits for resolution instead of overwriting. +- The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks, + code blocks and reference images. Frontmatter sits in a collapsed Properties + section. Wiki links, note callouts and locally rendered Mermaid diagrams are + supported in Writing, Split and Read. Diagram source remains available to copy. Invalid diagrams show a message and their source. Toolbar icons show tooltips + on hover or keyboard focus; Split view stacks vertically in narrow panes. +- Ctrl+P finds files by path. Ctrl+N creates a note or script at a workspace-relative + path. Ctrl+S saves. Ctrl+Shift+F opens workspace search; Ctrl+F searches the editor. +- Ctrl+` or Ctrl+J shows or hides the terminal, preserving sessions and scrollback. + New Terminal (Ctrl+Shift+`) creates an independent shell; Split (Ctrl+Shift+5) + adds a resizable pane in the active group and inherits its current directory/profile. + The terminal list appears only when multiple sessions exist. Kill terminates a + session; Delete does the same while a terminal-list entry has focus. Maximize + and Restore change the panel size without restarting shells. +- The dropdown immediately beside New Terminal offers installed PowerShell, + PowerShell 7, Git Bash, Command Prompt, and Bash profiles, a default-profile + picker, terminal settings, tasks, and separate terminal windows + (Ctrl+Shift+Alt+`). Font size, scrollback, cursor blinking, and default profile + persist locally. New terminals inherit the app environment, including PATH. +- More terminal actions clears scrollback, runs selected editor text, or saves + and runs the active script. Supported runners include Python, JavaScript, + PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes + must be installed. Recent-command (Ctrl+Alt+R) and directory (Ctrl+G) pickers + work while the terminal is focused. Ctrl+Up/Down navigates prompt markers. + History is kept in memory for the current dock; PowerShell/Bash report commands + after completion, while Command Prompt captures submitted text at its prompt. +- Configure Tasks creates/opens `.runestone/tasks.json`. Its `tasks` array contains + objects with `label`, `command`, and an optional `profile` ID (`powershell`, + `pwsh`, `git-bash`, `cmd`, or `bash`). Run Task starts the chosen command in its + own terminal at the workspace root. Tasks run only when explicitly selected. +- JavaScript Debug Terminal starts a Node.js REPL with a local inspector on an + available port. Attach an external debugger using the printed address. + RuneStone does not provide VS Code's debugger or automatic debug attachment. + Start Dictation invokes Windows voice typing (Win+H) in the focused terminal; + Windows microphone/voice-typing configuration is required. Other platforms + use their operating system's dictation shortcut. +- Closing a detached terminal window terminates its sessions. Switching workspace + closes detached terminal windows and ends the old workspace's sessions. +- File watching reloads clean buffers after an agent or another application changes + them. Dirty buffers display a conflict with the disk version and explicit choices + to use it, keep local edits, or save a copy. Missing files retain their open buffer. +- Saves compare the current disk text with the saved baseline, prepare a complete + temporary file, then replace the destination. This prevents known stale saves and + truncation on failed writes. It does not lock out other processes. Concurrent tools + can still write between the last comparison and replacement. +- Closing a dirty tab, switching workspaces, and closing the desktop window prompt + before discarding edits or terminating terminal sessions. +- `.git`, `.obsidian`, `.runestone`, and temporary save files are hidden from the + navigator/search. Directory symlinks are not traversed by the navigator. + +## Limitations + +Vault-wide wiki-link resolution, backlinks and math rendering still need work. +Git UI, language servers, plugins, persistent tab restoration and crash recovery +are not implemented. Unsaved buffers and terminals last for the current app +session only. diff --git a/fixtures/reader-showcase.md b/fixtures/reader-showcase.md new file mode 100644 index 0000000..87a30f7 --- /dev/null +++ b/fixtures/reader-showcase.md @@ -0,0 +1,63 @@ +--- +title: Project field notes +tags: [workspace, design] +--- + +# Project field notes + +A place for the thinking that happens around the code. Keep your research, +implementation notes, and scripts together, with room to read and a terminal +close at hand. + +## A calmer place to work + +Good notes need a clear rhythm: **strong headings**, comfortable paragraphs, +and enough space to see how ideas relate. Use `project/config.ts` for a small +code reference, or follow a [[notes/welcome|related note]] without losing context. + +> [!tip] Keep context close +> Write down the reason for a change alongside the script that implements it. +> Your future self gets both the decision and the details. + +### From idea to implementation + +1. Capture the question in a note. + - Link the relevant research. + - Keep examples beside the explanation. +2. Open the script and try the smallest useful change. +3. Run it in the project terminal. + +## Working checklist + +- [x] Keep notes and code in the same workspace +- [x] Preserve Markdown exactly as written +- [ ] Review the next iteration + - [ ] Check a narrow split view + - [ ] Record what changed + +## At a glance + +| Surface | Purpose | Shortcut | +| :--- | :--- | ---: | +| Notes | Decisions, research, and working drafts | `Ctrl N` | +| Editor | Scripts and source files | `Ctrl P` | +| Terminal | Run commands in the project directory | `Ctrl` + backtick | + +### A small example + +```python +from pathlib import Path + +workspace = Path.cwd() +for note in workspace.rglob("*.md"): + print(note.relative_to(workspace)) +``` + +Code keeps its indentation and punctuation. Text such as `**bold**` inside a +code span stays literal, while **bold** in a paragraph is formatted. + +> The best workspace helps you return to a thought as easily as you return to a file. + +--- + +One project, with room for both the explanation and the implementation. diff --git a/fixtures/sample/.runestone/marks.json b/fixtures/sample/.runestone/marks.json new file mode 100644 index 0000000..e08c80e --- /dev/null +++ b/fixtures/sample/.runestone/marks.json @@ -0,0 +1,31 @@ +{ + "pins": [], + "bookmarks": [], + "order": { + "notes": [ + "inbox.md", + "projects" + ], + "notes/projects": [], + "": [ + ".runestone", + "src", + "notes", + "tools", + "folder" + ], + "folder": [ + "screenshot10.png", + "screenshot11.png", + "screenshot12.png", + "screenshot7.png", + "test.md", + "screenshot6.png", + "screenshot5.png", + "screenshot4.png", + "screenshot8.png", + "screenshot3.png", + "screenshot2.png" + ] + } +} diff --git a/fixtures/sample/notes/inbox.md b/fixtures/sample/notes/inbox.md new file mode 100644 index 0000000..3ddd8ba --- /dev/null +++ b/fixtures/sample/notes/inbox.md @@ -0,0 +1,5 @@ +# Inbox + +This is a sample note. Link to [[projects/alpha]]. + +- [ ] First task diff --git a/fixtures/sample/notes/projects/alpha.md b/fixtures/sample/notes/projects/alpha.md new file mode 100644 index 0000000..e4c3090 --- /dev/null +++ b/fixtures/sample/notes/projects/alpha.md @@ -0,0 +1,3 @@ +# Alpha + +Back to [[inbox]]. diff --git a/fixtures/sample/src/hello.py b/fixtures/sample/src/hello.py new file mode 100644 index 0000000..10bc09a --- /dev/null +++ b/fixtures/sample/src/hello.py @@ -0,0 +1,6 @@ +def greet(name: str) -> str: + return f"hello, {name}" + + +if __name__ == "__main__": + print(greet("runestone")) diff --git a/fixtures/sample/tools/setup.sh b/fixtures/sample/tools/setup.sh new file mode 100644 index 0000000..f153714 --- /dev/null +++ b/fixtures/sample/tools/setup.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +echo "workspace ready" diff --git a/package.json b/package.json new file mode 100644 index 0000000..5e69d51 --- /dev/null +++ b/package.json @@ -0,0 +1,58 @@ +{ + "name": "runestone", + "version": "0.1.0", + "description": "Desktop editor for a local workspace", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "build:installer": "tauri build --bundles nsis -- --locked", + "preview": "vite preview", + "prepare": "svelte-kit sync || echo ''", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", + "tauri": "tauri", + "test": "node --experimental-strip-types --test scripts/*.spec.ts" + }, + "license": "MIT", + "dependencies": { + "@codemirror/commands": "^6.11.1", + "@codemirror/lang-markdown": "^6.5.2", + "@codemirror/language": "^6.12.4", + "@codemirror/search": "^6.7.2", + "@codemirror/state": "^6.7.5", + "@codemirror/view": "^6.43.12", + "@tauri-apps/api": "^2", + "@tauri-apps/plugin-dialog": "^2.7.3", + "@tauri-apps/plugin-opener": "^2", + "@tiptap/core": "^3.31.3", + "@tiptap/extension-highlight": "^3.31.3", + "@tiptap/extension-image": "^3.31.3", + "@tiptap/extension-link": "^3.31.3", + "@tiptap/extension-subscript": "^3.31.3", + "@tiptap/extension-superscript": "^3.31.3", + "@tiptap/extension-table": "^3.31.3", + "@tiptap/extension-table-cell": "^3.31.3", + "@tiptap/extension-table-header": "^3.31.3", + "@tiptap/extension-table-row": "^3.31.3", + "@tiptap/extension-task-item": "^3.31.3", + "@tiptap/extension-task-list": "^3.31.3", + "@tiptap/pm": "^3.31.3", + "@tiptap/starter-kit": "^3.31.3", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", + "markdown-it": "^15.0.2", + "mermaid": "^12.0.0", + "monaco-editor": "^0.56.0" + }, + "devDependencies": { + "@sveltejs/adapter-static": "^3.0.10", + "@sveltejs/kit": "^2.65.1", + "@sveltejs/vite-plugin-svelte": "^7.1.2", + "@tauri-apps/cli": "^2", + "svelte": "^5.56.3", + "svelte-check": "^4.6.0", + "typescript": "~6.0.3", + "vite": "^8.0.16" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..43ca55f --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,2678 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@codemirror/commands': + specifier: ^6.11.1 + version: 6.11.1 + '@codemirror/lang-markdown': + specifier: ^6.5.2 + version: 6.5.2 + '@codemirror/language': + specifier: ^6.12.4 + version: 6.12.4 + '@codemirror/search': + specifier: ^6.7.2 + version: 6.7.2 + '@codemirror/state': + specifier: ^6.7.5 + version: 6.7.5 + '@codemirror/view': + specifier: ^6.43.12 + version: 6.43.12 + '@tauri-apps/api': + specifier: ^2 + version: 2.11.1 + '@tauri-apps/plugin-dialog': + specifier: ^2.7.3 + version: 2.7.3 + '@tauri-apps/plugin-opener': + specifier: ^2 + version: 2.5.5 + '@tiptap/core': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/extension-highlight': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-image': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-link': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-subscript': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-superscript': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-table': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-table-cell': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-table-header': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-table-row': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-task-item': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-task-list': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/pm': + specifier: ^3.31.3 + version: 3.31.3 + '@tiptap/starter-kit': + specifier: ^3.31.3 + version: 3.31.3 + '@xterm/addon-fit': + specifier: ^0.11.0 + version: 0.11.0 + '@xterm/xterm': + specifier: ^6.0.0 + version: 6.0.0 + markdown-it: + specifier: ^15.0.2 + version: 15.0.2 + mermaid: + specifier: ^12.0.0 + version: 12.0.0 + monaco-editor: + specifier: ^0.56.0 + version: 0.56.0 + devDependencies: + '@sveltejs/adapter-static': + specifier: ^3.0.10 + version: 3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0)) + '@sveltejs/kit': + specifier: ^2.65.1 + version: 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0) + '@sveltejs/vite-plugin-svelte': + specifier: ^7.1.2 + version: 7.3.0(svelte@5.57.1)(vite@8.3.0) + '@tauri-apps/cli': + specifier: ^2 + version: 2.11.4 + svelte: + specifier: ^5.56.3 + version: 5.57.1 + svelte-check: + specifier: ^4.6.0 + version: 4.7.6(picomatch@4.0.7)(svelte@5.57.1)(typescript@6.0.3) + typescript: + specifier: ~6.0.3 + version: 6.0.3 + vite: + specifier: ^8.0.16 + version: 8.3.0 + +packages: + + '@antfu/install-pkg@2.1.0': + resolution: {integrity: sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==} + + '@braintree/sanitize-url@7.1.2': + resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==} + + '@chevrotain/cst-dts-gen@11.1.2': + resolution: {integrity: sha512-XTsjvDVB5nDZBQB8o0o/0ozNelQtn2KrUVteIHSlPd2VAV2utEb6JzyCJaJ8tGxACR4RiBNWy5uYUHX2eji88Q==} + + '@chevrotain/gast@11.1.2': + resolution: {integrity: sha512-Z9zfXR5jNZb1Hlsd/p+4XWeUFugrHirq36bKzPWDSIacV+GPSVXdk+ahVWZTwjhNwofAWg/sZg58fyucKSQx5g==} + + '@chevrotain/regexp-to-ast@11.1.2': + resolution: {integrity: sha512-nMU3Uj8naWer7xpZTYJdxbAs6RIv/dxYzkYU8GSwgUtcAAlzjcPfX1w+RKRcYG8POlzMeayOQ/znfwxEGo5ulw==} + + '@chevrotain/types@11.1.2': + resolution: {integrity: sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==} + + '@chevrotain/utils@11.1.2': + resolution: {integrity: sha512-4mudFAQ6H+MqBTfqLmU7G1ZwRzCLfJEooL/fsF6rCX5eePMbGhoy5n4g+G4vlh2muDcsCTJtL+uKbOzWxs5LHA==} + + '@codemirror/autocomplete@6.20.3': + resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==} + + '@codemirror/commands@6.11.1': + resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==} + + '@codemirror/lang-css@6.3.1': + resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==} + + '@codemirror/lang-html@6.4.12': + resolution: {integrity: sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==} + + '@codemirror/lang-javascript@6.2.5': + resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==} + + '@codemirror/lang-markdown@6.5.2': + resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==} + + '@codemirror/language@6.12.4': + resolution: {integrity: sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==} + + '@codemirror/lint@6.9.7': + resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==} + + '@codemirror/search@6.7.2': + resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==} + + '@codemirror/state@6.7.5': + resolution: {integrity: sha512-QjLbZmY1Au3JiRrDVYFLRD0BZ3SOKS9pR3yjIkd7u27YY8TFD9/Q9fhPnLV5l1mHFSo3hHU/N31vpwEJOx4owQ==} + + '@codemirror/view@6.43.12': + resolution: {integrity: sha512-Nv0vxQ19NAqvB/c2pFzjIzFlzzJl7jmdtNkwOwGbn0Ks9mFAzibvumz7cQem5cRsFA2cEw2fg+uHZGbcHupLQQ==} + + '@iconify/types@2.0.0': + resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==} + + '@iconify/utils@3.1.7': + resolution: {integrity: sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w==} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@lezer/common@1.5.2': + resolution: {integrity: sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==} + + '@lezer/css@1.3.6': + resolution: {integrity: sha512-YJE78Wcg+zX8f10hiHWQ4Az48Qr/c13eId0VtRQYLBpxHDmDeSrXIlkbl+fJGW42rWC/uoUco9mhBZeVWP/A1g==} + + '@lezer/highlight@1.2.3': + resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==} + + '@lezer/html@1.3.13': + resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==} + + '@lezer/javascript@1.5.4': + resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==} + + '@lezer/lr@1.4.10': + resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==} + + '@lezer/markdown@1.7.2': + resolution: {integrity: sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==} + + '@marijn/find-cluster-break@1.0.4': + resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==} + + '@mermaid-js/parser@2.0.0': + resolution: {integrity: sha512-K8BeapFUfrfxbRAUQAG5oBOCwo1+bNWzaVnPxTCutkfrTBn6T/j91FIhqxWJ32SUeQ9T3iy1zcmPZ5ROZEvDrg==} + engines: {node: '>=22.12.0'} + + '@oxc-project/types@0.150.0': + resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==} + + '@polka/url@1.0.0-next.29': + resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} + + '@rolldown/binding-android-arm-eabi@1.2.9': + resolution: {integrity: sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.9': + resolution: {integrity: sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.9': + resolution: {integrity: sha512-IwhlH3qK5urrY8hZiEgGkHKEFN901p/p2bjxCxJlr4GyNnF7wYpUvK+Y43uaRYuC4hpfjzbR3SJC3arX1jGvmw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.9': + resolution: {integrity: sha512-XxpJfVzFh+jilRxIXUqcfYAYcunIc/XEzIizsOL1fcJee5Sf7H3mH8WlLmfHfluz5amqR88QQo9izKtmMlavAw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.9': + resolution: {integrity: sha512-kSfvhmgeWyfkbT3p/1s5vSgboogoah2zkm9fX2zjg2hHxSV7T4KhMWRUUaRk4OXNqoD3QAUeRqLcs1aZOK4U1g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.9': + resolution: {integrity: sha512-1RVzG17pxqbTfYLC352JlLt6kKLG+6Hr30n8DlIJqsnV5luUDd2Qdx9Ayw1Cabfyb1K9k0jXEZ7evxkRoT+uiw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.9': + resolution: {integrity: sha512-BXqPvZ2drqVD+/Z8UpKwcs4Mp7grM+eGFku4CAEKrEtcbAsUpzREphK1sogCRZGreVPiMkiiBtw0n3TPteuqvw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.9': + resolution: {integrity: sha512-11vWvo8YDwLzukt27J3aYDWU+gg2P7J+ZOmiJ0hkF5BXZDW7pVya7r40MXDy6ya0i9KamoENSVKIugvJNgFXIA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.9': + resolution: {integrity: sha512-a1tijMkdwsIARtc0F39ApURROkf3NwqinI6TOiSSWCTR7dT96dffNvMUtDHnq64wKNTIZOIlzKrFvvFUznJiyw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.9': + resolution: {integrity: sha512-x6SQNdAvv4c3hWqTMaWuawzMX9myaCs/yEmlGsxJzkdClnHW7FbrjQuSiRDhuSYzEYoEMhsaJy9qHG/XNemJPQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.9': + resolution: {integrity: sha512-9s0AZ8BFK5/n7B/TBoa2yJE3gI3KURrbXcPBlsAsvjU4VeJKgE90y1YtNxyEUIcHPQkg6/yfF3qihUrcM/Kf0Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.9': + resolution: {integrity: sha512-P7VWAmV+WdJluH7ovnRGoiv2i8To7GAZ+kGzfGup635cyL7SyYl3lSUaA3Gp5THf0n/Co5EyEqb2zbqq+nMOHQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.9': + resolution: {integrity: sha512-1qixtsE4BK8h+yS3BfmZ09UhA7O/N4IACva6YBr7EBvCJraByTuRcgOTaiA62Tm0vey3UcKXLOaoGHtYmNGEVg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.9': + resolution: {integrity: sha512-ok8IQjcEPs1AKZfuEUznVBrJw+gK4soq+bx8b1X2XoMqVClarc1q5JDmVtWXY1xfr6ZuHTAsPXHTgTrqKTZeww==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.9': + resolution: {integrity: sha512-Ip2mXoU0hM0boq3Rf+ekuT653OROSo6aSYcPT1VHE4q52KvyxgFkQgrgb/IEsxOuvQ2fZZbs8khJAyCEPM24/g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@sveltejs/acorn-typescript@1.0.13': + resolution: {integrity: sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==} + peerDependencies: + acorn: ^8.9.0 + + '@sveltejs/adapter-static@3.0.10': + resolution: {integrity: sha512-7D9lYFWJmB7zxZyTE/qxjksvMqzMuYrrsyh1f4AlZqeZeACPRySjbC3aFiY55wb1tWUaKOQG9PVbm74JcN2Iew==} + peerDependencies: + '@sveltejs/kit': ^2.0.0 + + '@sveltejs/kit@2.70.3': + resolution: {integrity: sha512-UDvEYuZqAMbfB/oXIoqKvbKcb7YczK5zYrzmsGV1zRJk03jntwp8dXiYoIJotxAndsKvcPFtx9H1GRSKFdSHgg==} + engines: {node: '>=18.13'} + hasBin: true + peerDependencies: + '@opentelemetry/api': ^1.0.0 + '@sveltejs/vite-plugin-svelte': ^3.0.0 || ^4.0.0-next.1 || ^5.0.0 || ^6.0.0-next.0 || ^7.0.0 + svelte: ^4.0.0 || ^5.0.0-next.0 + typescript: ^5.3.3 || ^6.0.0 + vite: ^5.0.3 || ^6.0.0 || ^7.0.0-beta.0 || ^8.0.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + typescript: + optional: true + + '@sveltejs/load-config@0.2.3': + resolution: {integrity: sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==} + engines: {node: '>= 18.0.0'} + + '@sveltejs/vite-plugin-svelte@7.3.0': + resolution: {integrity: sha512-QbRoJyD92e9R0ufeQIWRHrCC0ObcqSv/aBDdrQMoU+sypav3cDx5wytdQ6GLdXjEMO6xjrXGzfkUygng8JMv0A==} + engines: {node: ^20.19 || ^22.12 || >=24} + peerDependencies: + svelte: ^5.46.4 + vite: ^8.0.0-beta.7 || ^8.0.0 + + '@tauri-apps/api@2.11.1': + resolution: {integrity: sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==} + + '@tauri-apps/cli-darwin-arm64@2.11.4': + resolution: {integrity: sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@tauri-apps/cli-darwin-x64@2.11.4': + resolution: {integrity: sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@tauri-apps/cli-linux-arm-gnueabihf@2.11.4': + resolution: {integrity: sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ==} + engines: {node: '>= 10'} + cpu: [arm] + os: [linux] + + '@tauri-apps/cli-linux-arm64-gnu@2.11.4': + resolution: {integrity: sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@tauri-apps/cli-linux-arm64-musl@2.11.4': + resolution: {integrity: sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@tauri-apps/cli-linux-riscv64-gnu@2.11.4': + resolution: {integrity: sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ==} + engines: {node: '>= 10'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@tauri-apps/cli-linux-x64-gnu@2.11.4': + resolution: {integrity: sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@tauri-apps/cli-linux-x64-musl@2.11.4': + resolution: {integrity: sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@tauri-apps/cli-win32-arm64-msvc@2.11.4': + resolution: {integrity: sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@tauri-apps/cli-win32-ia32-msvc@2.11.4': + resolution: {integrity: sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA==} + engines: {node: '>= 10'} + cpu: [ia32] + os: [win32] + + '@tauri-apps/cli-win32-x64-msvc@2.11.4': + resolution: {integrity: sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@tauri-apps/cli@2.11.4': + resolution: {integrity: sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ==} + engines: {node: '>= 10'} + hasBin: true + + '@tauri-apps/plugin-dialog@2.7.3': + resolution: {integrity: sha512-CRgE+7TP4tvq9MjBU6f04NLTFIqVMLKHk3hAqlhil00ngK9ACTrXPH3oHpKMProxILodd3YjBoKbMwSI4IEcfA==} + + '@tauri-apps/plugin-opener@2.5.5': + resolution: {integrity: sha512-xvzGai5aQds8j8R8RsUK/lW6pGG50YgOYIPLzvkqmkwAj7dfySOD7sGtejRzvVdMmv1EQfKVEFh1MvmDp8QR0g==} + + '@tiptap/core@3.31.3': + resolution: {integrity: sha512-Cz50pvciQrxdSxgTkHOVz0uD0Yl/8Xt0QatGD6ILm47jW8EzyHR9RkUGs/D5IqzXKuVPntfw1ttaT926vXfiRg==} + peerDependencies: + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-blockquote@3.31.3': + resolution: {integrity: sha512-fyY2XMbyDDDfOTQ1Qdrnqa1qwC9DWE4n7AfE0EKQI0G8MfLV8RaDlLDcOZDJ9JbMPY7/Gx7EjyK4NKxSW9n2hQ==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-bold@3.31.3': + resolution: {integrity: sha512-dIuYhKk8TitKU/FeDpoTeWZhU42YgDN5npgWNjAmMmRktPdoxnH3/wGSiwXlqZgJWjehN7kPWDePWpJeAImGpQ==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-bullet-list@3.31.3': + resolution: {integrity: sha512-qEyyoPapPef4LO8XKaN83bxtaNzkJ4kFn/IxLnEKd4BJ3Mvi4MH2yJYlyDqwFnMoev4pMA1zBHRAt/C0THRmZw==} + peerDependencies: + '@tiptap/extension-list': 3.31.3 + + '@tiptap/extension-code-block@3.31.3': + resolution: {integrity: sha512-nvknt4FhyJQjYcvxptmeUlFsIAc8ibua3E5BN4Pim374/9RWepH4cdE9X0/qUTtguHElLx0iKtSIY3rW2qGTFA==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-code@3.31.3': + resolution: {integrity: sha512-SzxOqchrD2AcN3uT67PjKmRFEMOU3vNNiwNaamZJUbZrI6Hmy+bvdHJrc3jrIddyyCrAtsnAfRI0cmorW1jGfg==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-document@3.31.3': + resolution: {integrity: sha512-EexgmqnyDNyGlISxo7SMrp5MygpJYmqD+0cY5jB6L1U6L4CpKKRWUt8OO1sWzEHDE1+TTvwt+WIFoIWAziOtEA==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-dropcursor@3.31.3': + resolution: {integrity: sha512-NWomSfu5CSC7VacnMSDzKT8qm66SzMfZwVPEtwY5bPpRTJgTiT1rNK0neDrrzfMN27MfylGyKWWf7Q5Qf8w/fg==} + peerDependencies: + '@tiptap/extensions': 3.31.3 + + '@tiptap/extension-gapcursor@3.31.3': + resolution: {integrity: sha512-EBXKb1FrVStsNYCcRGtd9jmzveCvR+eqgg1rVqoONrqFK6U7bga6LN+1dMKroP1kliDVgveYkP3vRYxqw+rFqg==} + peerDependencies: + '@tiptap/extensions': 3.31.3 + + '@tiptap/extension-hard-break@3.31.3': + resolution: {integrity: sha512-QAdCvNO4+yW9ATwsrej11NTkDYFqPLIEQr3ARNrKOK1qaiS7A0fia2SEukb/hrkP3A6mbozhoQt2r2RGUf/DpQ==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-heading@3.31.3': + resolution: {integrity: sha512-rk5VHMAeQcg06SLauN6EGdD2jc0O2qY8QkZYPd0LxNvLblw2BxBx+lxUQSYwLAT9Ie5914gKIK2YbRyO2Ts3ig==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-highlight@3.31.3': + resolution: {integrity: sha512-97m1nDzTAjJaJZWe5hVOBMC2rjBZvEwTXA39zhjnaE/snb8Cy4H9A3+/sw9HQJBXMoG7tdOPG9kUlM3weYtLcQ==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-horizontal-rule@3.31.3': + resolution: {integrity: sha512-YnHGy2KShRwvCseAmmxl9VP7R0qaj8QMp3DA6DJWZqp7r5gLGvDkAqhedxqqefqsE4Y43hjkBdjtB9Ce78LkIw==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-image@3.31.3': + resolution: {integrity: sha512-wWNG9BOtx2Cg4vwxPVGDIJ5DGX+ETkldeoaFJLB1NXUL4OPUiVTf8cHZ+hdYgJWP704BEB7jQgjlpvdi6VigTg==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-italic@3.31.3': + resolution: {integrity: sha512-ibGvdvAPyfxBMUVNRI43eb9h2/Jka1MRG5GtnGqbcCX/2+Y/y0EOfFrPQPkuYphiWQYyu9+FzPKMB/pjuaLuKQ==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-link@3.31.3': + resolution: {integrity: sha512-986wOQzTL9Zr5lf84LCLpm+YOms8A0K39/8DVoqRfebqcOe0/eq4bnztmAlfabOd+kJY92g3AgZERFUx/w+dcw==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-list-item@3.31.3': + resolution: {integrity: sha512-4QlKOriJJMvg95QJTEsy9BUYPBQ6UvJyb8WURRwdUtQUkkqb8h32lg/eyQUv2FzW9IT1AdUyNZfVaxH64kRfQA==} + peerDependencies: + '@tiptap/extension-list': 3.31.3 + + '@tiptap/extension-list-keymap@3.31.3': + resolution: {integrity: sha512-If8UOEdDZbPJU6iYTvLtH6DOp2KBy6BKxg9UELL1AevVetGHEF/7lW8hP50Gn1tHMVpPRqmhSzVrJRpEJJgb/Q==} + peerDependencies: + '@tiptap/extension-list': 3.31.3 + + '@tiptap/extension-list@3.31.3': + resolution: {integrity: sha512-LoveGnC0FVdCV4jUNBaG1ZA+KWE07+adzV3kGy6uUYFcJEjbVUHTnPDrBOob3IwOSO3sCwIkvQb6EVYeXn/4yg==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-ordered-list@3.31.3': + resolution: {integrity: sha512-mp3g11NgA/PYu8rj7J7Ez3l4qBy6WfTSmHIG4PZvEGG5w2oUAIkgb9DU7nPPzjmeme27oazFYZw+AtZA0+u4tw==} + peerDependencies: + '@tiptap/extension-list': 3.31.3 + + '@tiptap/extension-paragraph@3.31.3': + resolution: {integrity: sha512-+iPku7wJfy5hbNDNLX8dveFtYVsZMmh7vztjuq8hT3mipSC4IByDehDbU8fzUCjfXiEzmI7mQn7c8LGmHULuzA==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-strike@3.31.3': + resolution: {integrity: sha512-G29bhKttYwcKHT+BI6emWVFol3RO/gUXxQVcmr/iT8LXXy7j8J6HFUnsKM+Kg5YlP1rxMRgsa65dbrQVahZi0A==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-subscript@3.31.3': + resolution: {integrity: sha512-jUMMtg4QF7wIXIvsgBmgJjdQMETOX4KMF+Nl/0nuCKs59lEi1StOJzkiEdm+UbFhxvvY9B30uLVgzogGIlHHyg==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-superscript@3.31.3': + resolution: {integrity: sha512-WzM84fb8akg1Ni2b1DcE1pE2kkWLbkEVxN2DKElzCVk/kuSNp+VKqOjunHGTnO+kJhXdcmXTVqAO4Vp2kiDxMQ==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-table-cell@3.31.3': + resolution: {integrity: sha512-5nueKR/p/IX6B4etWqHjyRsjNfDf6dJZaRgfw1/1l90CJe2h3tTZk4JbUKWN3Mo4FzZuYKzmU3fxcZ8pSVOeJQ==} + peerDependencies: + '@tiptap/extension-table': 3.31.3 + + '@tiptap/extension-table-header@3.31.3': + resolution: {integrity: sha512-sstVtNQiBYX4P16vlhwBYPsthxDnodHWQfGq0EUQM40Z7H796Lgh9t1qYtu8yARQuHKzvINRwJCSy6DZ8YTDtQ==} + peerDependencies: + '@tiptap/extension-table': 3.31.3 + + '@tiptap/extension-table-row@3.31.3': + resolution: {integrity: sha512-up6tDK+hYVTFDeJ3XqKO0WJqBzyXNfGxMoimo5h83jrq9dcNh0oPCOzglZ7rdo8GH9I3VJ2fNKxxU2Eg2HcMoQ==} + peerDependencies: + '@tiptap/extension-table': 3.31.3 + + '@tiptap/extension-table@3.31.3': + resolution: {integrity: sha512-7cnVPHhdiGGeauYqca6JVyPLTqZbqFEEk9nn2e2E8+fBo6zVtV07AktJBqth/XEzjZxcUmGxjoeuWYAisWjUHg==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-task-item@3.31.3': + resolution: {integrity: sha512-gCWvvXsCzi9tVFXPqKlkbU81XxtIdfjGy7FM9QFRKiWAvq5uv+Q5nvwrCyMVyP4bA7zRGWFaPzwjL68djgzoBw==} + peerDependencies: + '@tiptap/extension-list': 3.31.3 + + '@tiptap/extension-task-list@3.31.3': + resolution: {integrity: sha512-3WgVzmfEnDbmxbjUBlvTiKpT53KSBnnYhXUVQxM0nz1vpoWG8QifhsnCVsNI6TZmhgR0x/jY+UW9Hc/WLF8DkQ==} + peerDependencies: + '@tiptap/extension-list': 3.31.3 + + '@tiptap/extension-text@3.31.3': + resolution: {integrity: sha512-gdsWtF+taeaCu6V+5Ct10fGo0ACUy1GnYtbb+mcathBt8OqbT+Ws60p/yEmKesBDz2Hn+B5IcWy6+2BBZl5ZTg==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extension-underline@3.31.3': + resolution: {integrity: sha512-HghdJaOwRqYzsAxqSyNyb+IWyOMcdCl8IoiBETA9BZCJAqdXzFLcuWp7CqCqJPam9dgkWosSoHqTCAO4nTBfpw==} + peerDependencies: + '@tiptap/core': 3.31.3 + + '@tiptap/extensions@3.31.3': + resolution: {integrity: sha512-8sJNPGGUe8f3aDojcOW5cfVL7I5NrBbE0UWxG08qoi9Tea6qWbvQJsCR9tsrOapr/DaLr3kpbGZ9s1gEEfcNcA==} + peerDependencies: + '@tiptap/core': 3.31.3 + '@tiptap/pm': 3.31.3 + + '@tiptap/pm@3.31.3': + resolution: {integrity: sha512-sZime0SWsz/k62W2WvHx5Ig7G2h7kVhrrmnqy+wEgIHfDwEfOlelRjaWCiBCFlF7dxGUntJusCh9FxlLhni0Ag==} + + '@tiptap/starter-kit@3.31.3': + resolution: {integrity: sha512-WKof9RewdmGHvWJ1wn0/HVNG2mV+HOgVRyJkKekuM9fgr6BZAAH/xZsWE1eon+94JnQ+KtK2ThydXQM/qc6b2A==} + + '@types/cookie@0.6.0': + resolution: {integrity: sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==} + + '@types/d3-array@3.2.2': + resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==} + + '@types/d3-axis@3.0.6': + resolution: {integrity: sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==} + + '@types/d3-brush@3.0.6': + resolution: {integrity: sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==} + + '@types/d3-chord@3.0.6': + resolution: {integrity: sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==} + + '@types/d3-color@3.1.3': + resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==} + + '@types/d3-contour@3.0.6': + resolution: {integrity: sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==} + + '@types/d3-delaunay@6.0.4': + resolution: {integrity: sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==} + + '@types/d3-dispatch@3.0.7': + resolution: {integrity: sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==} + + '@types/d3-drag@3.0.7': + resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==} + + '@types/d3-dsv@3.0.7': + resolution: {integrity: sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==} + + '@types/d3-ease@3.0.2': + resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==} + + '@types/d3-fetch@3.0.7': + resolution: {integrity: sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==} + + '@types/d3-force@3.0.10': + resolution: {integrity: sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==} + + '@types/d3-format@3.0.4': + resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==} + + '@types/d3-geo@3.1.1': + resolution: {integrity: sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==} + + '@types/d3-hierarchy@3.1.7': + resolution: {integrity: sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==} + + '@types/d3-interpolate@3.0.4': + resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==} + + '@types/d3-path@3.1.1': + resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==} + + '@types/d3-polygon@3.0.2': + resolution: {integrity: sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==} + + '@types/d3-quadtree@3.0.6': + resolution: {integrity: sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==} + + '@types/d3-random@3.0.4': + resolution: {integrity: sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==} + + '@types/d3-scale-chromatic@3.1.0': + resolution: {integrity: sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==} + + '@types/d3-scale@4.0.9': + resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==} + + '@types/d3-selection@3.0.12': + resolution: {integrity: sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==} + + '@types/d3-shape@3.2.0': + resolution: {integrity: sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==} + + '@types/d3-time-format@4.0.3': + resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==} + + '@types/d3-time@3.0.4': + resolution: {integrity: sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==} + + '@types/d3-timer@3.0.2': + resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==} + + '@types/d3-transition@3.0.9': + resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==} + + '@types/d3-zoom@3.0.8': + resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==} + + '@types/d3@7.4.3': + resolution: {integrity: sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/geojson@7946.0.16': + resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} + + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + + '@upsetjs/venn.js@2.0.0': + resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} + + '@xterm/addon-fit@0.11.0': + resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==} + + '@xterm/xterm@6.0.0': + resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==} + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + argparse@3.0.2: + resolution: {integrity: sha512-mFdDM6WqWKraGLsVb+C9CahPnzTXOefAOLq3jYcca2YZ8bEWpr++Tzj+zSaKW9+X9L5uSxcm1AZ3Y6aZJ09OhQ==} + + aria-query@5.3.1: + resolution: {integrity: sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==} + engines: {node: '>= 0.4'} + + axobject-query@4.1.0: + resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} + engines: {node: '>= 0.4'} + + chevrotain@11.1.2: + resolution: {integrity: sha512-opLQzEVriiH1uUQ4Kctsd49bRoFDXGGSC4GUqj7pGyxM3RehRhvTlZJc1FL/Flew2p5uwxa1tUDWKzI4wNM8pg==} + + chokidar@4.0.3: + resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} + engines: {node: '>= 14.16.0'} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + commander@7.2.0: + resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} + engines: {node: '>= 10'} + + commander@8.3.0: + resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} + engines: {node: '>= 12'} + + cookie@0.6.0: + resolution: {integrity: sha512-U71cyTamuh1CRNCfpGY6to28lxvNwPG4Guz/EVjgf3Jmzv0vlDp1atT9eS5dDjMYHucpHbWns6Lwf3BKz6svdw==} + engines: {node: '>= 0.6'} + + cose-base@1.0.3: + resolution: {integrity: sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==} + + cose-base@2.2.0: + resolution: {integrity: sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==} + + crelt@1.0.7: + resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==} + + cytoscape-cose-bilkent@4.1.0: + resolution: {integrity: sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==} + peerDependencies: + cytoscape: ^3.2.0 + + cytoscape-fcose@2.2.0: + resolution: {integrity: sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==} + peerDependencies: + cytoscape: ^3.2.0 + + cytoscape@3.34.3: + resolution: {integrity: sha512-yfYGhRcGAntq6YBD583j4n0Eg3jIxvWmZtz/5uz9UYkeIStSlMxuUja+ec5j3iBD8nv1rwaOAYMW09tBdkSeaQ==} + engines: {node: '>=0.10'} + + d3-array@2.12.1: + resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==} + + d3-array@3.2.4: + resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==} + engines: {node: '>=12'} + + d3-axis@3.0.0: + resolution: {integrity: sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==} + engines: {node: '>=12'} + + d3-brush@3.0.0: + resolution: {integrity: sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==} + engines: {node: '>=12'} + + d3-chord@3.0.1: + resolution: {integrity: sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==} + engines: {node: '>=12'} + + d3-color@3.1.0: + resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==} + engines: {node: '>=12'} + + d3-contour@4.0.2: + resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==} + engines: {node: '>=12'} + + d3-delaunay@6.0.4: + resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==} + engines: {node: '>=12'} + + d3-dispatch@3.0.1: + resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==} + engines: {node: '>=12'} + + d3-drag@3.0.0: + resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==} + engines: {node: '>=12'} + + d3-dsv@3.0.1: + resolution: {integrity: sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==} + engines: {node: '>=12'} + hasBin: true + + d3-ease@3.0.1: + resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==} + engines: {node: '>=12'} + + d3-fetch@3.0.1: + resolution: {integrity: sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==} + engines: {node: '>=12'} + + d3-force@3.0.0: + resolution: {integrity: sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==} + engines: {node: '>=12'} + + d3-format@3.1.2: + resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==} + engines: {node: '>=12'} + + d3-geo@3.1.1: + resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==} + engines: {node: '>=12'} + + d3-hierarchy@3.1.2: + resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==} + engines: {node: '>=12'} + + d3-interpolate@3.0.1: + resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==} + engines: {node: '>=12'} + + d3-path@1.0.9: + resolution: {integrity: sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==} + + d3-path@3.1.0: + resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==} + engines: {node: '>=12'} + + d3-polygon@3.0.1: + resolution: {integrity: sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==} + engines: {node: '>=12'} + + d3-quadtree@3.0.1: + resolution: {integrity: sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==} + engines: {node: '>=12'} + + d3-random@3.0.1: + resolution: {integrity: sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==} + engines: {node: '>=12'} + + d3-sankey@0.12.3: + resolution: {integrity: sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==} + + d3-scale-chromatic@3.1.0: + resolution: {integrity: sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==} + engines: {node: '>=12'} + + d3-scale@4.0.2: + resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==} + engines: {node: '>=12'} + + d3-selection@3.0.0: + resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==} + engines: {node: '>=12'} + + d3-shape@1.3.7: + resolution: {integrity: sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==} + + d3-shape@3.2.0: + resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==} + engines: {node: '>=12'} + + d3-time-format@4.1.0: + resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==} + engines: {node: '>=12'} + + d3-time@3.1.0: + resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==} + engines: {node: '>=12'} + + d3-timer@3.0.1: + resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==} + engines: {node: '>=12'} + + d3-transition@3.0.1: + resolution: {integrity: sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==} + engines: {node: '>=12'} + peerDependencies: + d3-selection: 2 - 3 + + d3-zoom@3.0.0: + resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==} + engines: {node: '>=12'} + + d3@7.9.0: + resolution: {integrity: sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==} + engines: {node: '>=12'} + + dagre-d3-es@7.0.14: + resolution: {integrity: sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==} + + dayjs@1.11.23: + resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==} + + deepmerge@4.3.1: + resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} + engines: {node: '>=0.10.0'} + + delaunator@5.1.0: + resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + devalue@5.9.4: + resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==} + + dompurify@3.4.16: + resolution: {integrity: sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==} + + dompurify@3.4.8: + resolution: {integrity: sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ==} + + elkjs@0.9.3: + resolution: {integrity: sha512-f/ZeWvW/BCXbhGEf1Ujp29EASo/lk1FDnETgNKwJrsVvGZhUWCZyg3xLJjAsxfOmt8KjswHmI5EwCQcPMpOYhQ==} + + entities@8.1.0: + resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} + engines: {node: '>=20.19.0'} + + es-toolkit@1.52.0: + resolution: {integrity: sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==} + + esm-env@1.2.2: + resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==} + + esrap@2.3.7: + resolution: {integrity: sha512-n2nf7fZR3c9yXf0BPEuHuXqT+KW0SJVj4cN5FMEkpCZ3scLjOQWpiccyCxVzCC2q1wubTghuEGzngJY/7Ah0Ow==} + peerDependencies: + '@typescript-eslint/types': ^8.2.0 + peerDependenciesMeta: + '@typescript-eslint/types': + optional: true + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + hachure-fill@0.5.2: + resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==} + + iconv-lite@0.6.3: + resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} + engines: {node: '>=0.10.0'} + + import-meta-resolve@4.2.0: + resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} + + internmap@1.0.1: + resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==} + + internmap@2.0.3: + resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==} + engines: {node: '>=12'} + + is-reference@3.0.3: + resolution: {integrity: sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==} + + katex@0.16.47: + resolution: {integrity: sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg==} + hasBin: true + + khroma@2.1.0: + resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==} + + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + + layout-base@1.0.2: + resolution: {integrity: sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==} + + layout-base@2.0.1: + resolution: {integrity: sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + linkify-it@6.1.0: + resolution: {integrity: sha512-wJ/TwpSDTLepCrQoYWYIExIKg5Zchex2Nn5yk2mFnB+6PtdkHtyLx742md9csRjjOnGkKIS/RrbY7l8D6gT9Vw==} + + linkifyjs@4.3.3: + resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==} + + locate-character@3.0.0: + resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==} + + lodash-es@4.17.23: + resolution: {integrity: sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==} + + lodash-es@4.18.1: + resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + magic-string@1.4.1: + resolution: {integrity: sha512-8lyCu36ErXR0J9uaGKlKQoiLZKmtI63YGLE8G2o9jyRPdr4X47LusSOwgOJOzcVtp81fTAAjxR7BwKz682Jhow==} + + markdown-it@15.0.2: + resolution: {integrity: sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw==} + hasBin: true + + marked@14.0.0: + resolution: {integrity: sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==} + engines: {node: '>= 18'} + hasBin: true + + marked@16.4.2: + resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==} + engines: {node: '>= 20'} + hasBin: true + + mdurl@2.1.0: + resolution: {integrity: sha512-1+HBaOx0zi/dQWht8rNv9MYf9qqpqL/kxI0hXImU6Y547zM6Sni8BQibt7ifgMcYtQg41ao3Ivd6cnSM86inpg==} + + mermaid@12.0.0: + resolution: {integrity: sha512-/wQXC9iBxoGV8p3erbvaXs9h77VyLDBH6GdayVjj3hEcSQhFU4N1WUhUppotCEqlIxI2pRMwjwBSwTB1MfZBgQ==} + engines: {node: '>=22.12.0'} + + monaco-editor@0.56.0: + resolution: {integrity: sha512-sXboRm3BeBeLm938eaiyLMe0OxzfXIlZvbv4ir/jVgQy1zDhWjgmny0WoN45fuDKhCCQsYMbBJrv/A6jd8aCUg==} + + mri@1.2.0: + resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} + engines: {node: '>=4'} + + mrmime@2.0.1: + resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==} + engines: {node: '>=10'} + + nanoid@3.3.19: + resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + orderedmap@2.1.1: + resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==} + + package-manager-detector@1.8.0: + resolution: {integrity: sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A==} + + path-data-parser@0.1.0: + resolution: {integrity: sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + points-on-curve@0.2.0: + resolution: {integrity: sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==} + + points-on-path@0.2.1: + resolution: {integrity: sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==} + + postcss@8.5.28: + resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} + engines: {node: ^10 || ^12 || >=14} + + prosemirror-changeset@2.4.3: + resolution: {integrity: sha512-J8jqUZ1xybXKY44v3K0c8m8ZTIqJPVT34t2UVyxv4VEWoNd5C9t5Y52GNuMriRJ3IpNxOSE2R60vN4qBrTMcyQ==} + + prosemirror-commands@1.7.2: + resolution: {integrity: sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==} + + prosemirror-dropcursor@1.8.3: + resolution: {integrity: sha512-FoYbsJR8gK+DGlqhNoE29Loa38eIZPzQRIb1VMaDNBoo4OLP6vVof/jR8qFY/6XvUd6Dhug8MDCHl2a/h8RTfQ==} + + prosemirror-gapcursor@1.4.1: + resolution: {integrity: sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==} + + prosemirror-history@1.5.0: + resolution: {integrity: sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==} + + prosemirror-inputrules@1.5.1: + resolution: {integrity: sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==} + + prosemirror-keymap@1.2.3: + resolution: {integrity: sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==} + + prosemirror-model@1.25.11: + resolution: {integrity: sha512-QWg9RhnpLlogAmp3p96uEFrE5txQpFynd4vhBAELkwgOCWQs/X0yCzB3/hrHqiPwf91RG5KyWq6553zs9JqIOQ==} + + prosemirror-schema-list@1.5.1: + resolution: {integrity: sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==} + + prosemirror-state@1.4.4: + resolution: {integrity: sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==} + + prosemirror-tables@1.8.5: + resolution: {integrity: sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==} + + prosemirror-transform@1.12.1: + resolution: {integrity: sha512-t4F5615FycnCqsX7ShTUs8+jfnwcf46kuFRvSl/3qFx2QTZ4DjgowesLHQXcFP7G//TjesqZG3WtgL7vdyVJyA==} + + prosemirror-view@1.42.4: + resolution: {integrity: sha512-H/LErnE8Vms1GYkvhfj6G3K9rc2p+o5EHGmTwvPOl0f21wPPxlMVRB8ICOseH+COb2oPKFEoufbgY6yet/dR4w==} + + punycode.js@2.3.1: + resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==} + engines: {node: '>=6'} + + readdirp@4.1.2: + resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} + engines: {node: '>= 14.18.0'} + + robust-predicates@3.0.3: + resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} + + rolldown@1.2.9: + resolution: {integrity: sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rope-sequence@1.3.4: + resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==} + + roughjs@4.6.6: + resolution: {integrity: sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==} + + rw@1.3.3: + resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} + + sade@1.8.1: + resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==} + engines: {node: '>=6'} + + safer-buffer@2.1.2: + resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + + set-cookie-parser@3.1.2: + resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} + + sirv@3.0.2: + resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} + engines: {node: '>=18'} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + style-mod@4.1.4: + resolution: {integrity: sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==} + + stylis@4.4.0: + resolution: {integrity: sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==} + + svelte-check@4.7.6: + resolution: {integrity: sha512-t2scM//ZuVbSY/T2w6FSBw1v9s2NEmh/g+sy1lqtosW5ylBV5AF4wFb1Ts9Kf3MbfPDUDJDZ9L436YT0SPTdvw==} + engines: {node: '>= 18.0.0'} + hasBin: true + peerDependencies: + svelte: ^4.0.0 || ^5.0.0-next.0 + typescript: ^5.0.0 || ^6.0.0 + + svelte@5.57.1: + resolution: {integrity: sha512-Uqj49lWKB+iSSnneuwiYYJ7MZgkB+eXr0LXBhv4uDuAkXqnWmq65Sxflfvp0Lc6MdKjMUxGaeOKWJqz5SNiVIA==} + engines: {node: '>=18'} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + totalist@3.0.1: + resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==} + engines: {node: '>=6'} + + ts-dedent@2.3.0: + resolution: {integrity: sha512-JfJeIHke7y2egdGGgRAvpCwYFUsHlM2gPcrVOxFkznt/4uzQ7HFmvE63iFHVLBJNDuyDOQgijDK/tXH/f6Msjg==} + engines: {node: '>=6.10'} + + typescript@6.0.3: + resolution: {integrity: sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==} + engines: {node: '>=14.17'} + hasBin: true + + uc.micro@3.0.0: + resolution: {integrity: sha512-U3PppEkleoTnIfi8BozMx3yju3qc/L6SwqWo2Sw+54PX+PX0q9I+r1Um5HCmqD7n9VDX5/v3vQH/AjA6deDdtw==} + + uuid@14.0.2: + resolution: {integrity: sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ==} + hasBin: true + + vite@8.3.0: + resolution: {integrity: sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitefu@1.1.3: + resolution: {integrity: sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==} + peerDependencies: + vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + vite: + optional: true + + w3c-keyname@2.2.8: + resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==} + + zimmerframe@1.1.5: + resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==} + +snapshots: + + '@antfu/install-pkg@2.1.0': + dependencies: + package-manager-detector: 1.8.0 + tinyexec: 1.3.1 + + '@braintree/sanitize-url@7.1.2': {} + + '@chevrotain/cst-dts-gen@11.1.2': + dependencies: + '@chevrotain/gast': 11.1.2 + '@chevrotain/types': 11.1.2 + lodash-es: 4.17.23 + + '@chevrotain/gast@11.1.2': + dependencies: + '@chevrotain/types': 11.1.2 + lodash-es: 4.17.23 + + '@chevrotain/regexp-to-ast@11.1.2': {} + + '@chevrotain/types@11.1.2': {} + + '@chevrotain/utils@11.1.2': {} + + '@codemirror/autocomplete@6.20.3': + dependencies: + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + '@lezer/common': 1.5.2 + + '@codemirror/commands@6.11.1': + dependencies: + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + '@lezer/common': 1.5.2 + + '@codemirror/lang-css@6.3.1': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.5 + '@lezer/common': 1.5.2 + '@lezer/css': 1.3.6 + + '@codemirror/lang-html@6.4.12': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/lang-css': 6.3.1 + '@codemirror/lang-javascript': 6.2.5 + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + '@lezer/common': 1.5.2 + '@lezer/css': 1.3.6 + '@lezer/html': 1.3.13 + + '@codemirror/lang-javascript@6.2.5': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/language': 6.12.4 + '@codemirror/lint': 6.9.7 + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + '@lezer/common': 1.5.2 + '@lezer/javascript': 1.5.4 + + '@codemirror/lang-markdown@6.5.2': + dependencies: + '@codemirror/autocomplete': 6.20.3 + '@codemirror/lang-html': 6.4.12 + '@codemirror/language': 6.12.4 + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + '@lezer/common': 1.5.2 + '@lezer/markdown': 1.7.2 + + '@codemirror/language@6.12.4': + dependencies: + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + style-mod: 4.1.4 + + '@codemirror/lint@6.9.7': + dependencies: + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + crelt: 1.0.7 + + '@codemirror/search@6.7.2': + dependencies: + '@codemirror/state': 6.7.5 + '@codemirror/view': 6.43.12 + crelt: 1.0.7 + + '@codemirror/state@6.7.5': + dependencies: + '@marijn/find-cluster-break': 1.0.4 + + '@codemirror/view@6.43.12': + dependencies: + '@codemirror/state': 6.7.5 + crelt: 1.0.7 + style-mod: 4.1.4 + w3c-keyname: 2.2.8 + + '@iconify/types@2.0.0': {} + + '@iconify/utils@3.1.7': + dependencies: + '@antfu/install-pkg': 2.1.0 + '@iconify/types': 2.0.0 + import-meta-resolve: 4.2.0 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@lezer/common@1.5.2': {} + + '@lezer/css@1.3.6': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + + '@lezer/highlight@1.2.3': + dependencies: + '@lezer/common': 1.5.2 + + '@lezer/html@1.3.13': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + + '@lezer/javascript@1.5.4': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + '@lezer/lr': 1.4.10 + + '@lezer/lr@1.4.10': + dependencies: + '@lezer/common': 1.5.2 + + '@lezer/markdown@1.7.2': + dependencies: + '@lezer/common': 1.5.2 + '@lezer/highlight': 1.2.3 + + '@marijn/find-cluster-break@1.0.4': {} + + '@mermaid-js/parser@2.0.0': + dependencies: + '@chevrotain/types': 11.1.2 + + '@oxc-project/types@0.150.0': {} + + '@polka/url@1.0.0-next.29': {} + + '@rolldown/binding-android-arm-eabi@1.2.9': + optional: true + + '@rolldown/binding-android-arm64@1.2.9': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.9': + optional: true + + '@rolldown/binding-darwin-x64@1.2.9': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.9': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.9': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.9': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.9': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.9': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.9': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.9': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.9': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.9': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.9': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.9': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@sveltejs/acorn-typescript@1.0.13(acorn@8.18.0)': + dependencies: + acorn: 8.18.0 + + '@sveltejs/adapter-static@3.0.10(@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0))': + dependencies: + '@sveltejs/kit': 2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0) + + '@sveltejs/kit@2.70.3(@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0))(svelte@5.57.1)(typescript@6.0.3)(vite@8.3.0)': + dependencies: + '@standard-schema/spec': 1.1.0 + '@sveltejs/acorn-typescript': 1.0.13(acorn@8.18.0) + '@sveltejs/vite-plugin-svelte': 7.3.0(svelte@5.57.1)(vite@8.3.0) + '@types/cookie': 0.6.0 + acorn: 8.18.0 + cookie: 0.6.0 + devalue: 5.9.4 + esm-env: 1.2.2 + kleur: 4.1.5 + magic-string: 0.30.21 + mrmime: 2.0.1 + set-cookie-parser: 3.1.2 + sirv: 3.0.2 + svelte: 5.57.1 + vite: 8.3.0 + optionalDependencies: + typescript: 6.0.3 + + '@sveltejs/load-config@0.2.3': {} + + '@sveltejs/vite-plugin-svelte@7.3.0(svelte@5.57.1)(vite@8.3.0)': + dependencies: + deepmerge: 4.3.1 + magic-string: 1.4.1 + obug: 2.2.1 + svelte: 5.57.1 + vite: 8.3.0 + vitefu: 1.1.3(vite@8.3.0) + + '@tauri-apps/api@2.11.1': {} + + '@tauri-apps/cli-darwin-arm64@2.11.4': + optional: true + + '@tauri-apps/cli-darwin-x64@2.11.4': + optional: true + + '@tauri-apps/cli-linux-arm-gnueabihf@2.11.4': + optional: true + + '@tauri-apps/cli-linux-arm64-gnu@2.11.4': + optional: true + + '@tauri-apps/cli-linux-arm64-musl@2.11.4': + optional: true + + '@tauri-apps/cli-linux-riscv64-gnu@2.11.4': + optional: true + + '@tauri-apps/cli-linux-x64-gnu@2.11.4': + optional: true + + '@tauri-apps/cli-linux-x64-musl@2.11.4': + optional: true + + '@tauri-apps/cli-win32-arm64-msvc@2.11.4': + optional: true + + '@tauri-apps/cli-win32-ia32-msvc@2.11.4': + optional: true + + '@tauri-apps/cli-win32-x64-msvc@2.11.4': + optional: true + + '@tauri-apps/cli@2.11.4': + optionalDependencies: + '@tauri-apps/cli-darwin-arm64': 2.11.4 + '@tauri-apps/cli-darwin-x64': 2.11.4 + '@tauri-apps/cli-linux-arm-gnueabihf': 2.11.4 + '@tauri-apps/cli-linux-arm64-gnu': 2.11.4 + '@tauri-apps/cli-linux-arm64-musl': 2.11.4 + '@tauri-apps/cli-linux-riscv64-gnu': 2.11.4 + '@tauri-apps/cli-linux-x64-gnu': 2.11.4 + '@tauri-apps/cli-linux-x64-musl': 2.11.4 + '@tauri-apps/cli-win32-arm64-msvc': 2.11.4 + '@tauri-apps/cli-win32-ia32-msvc': 2.11.4 + '@tauri-apps/cli-win32-x64-msvc': 2.11.4 + + '@tauri-apps/plugin-dialog@2.7.3': + dependencies: + '@tauri-apps/api': 2.11.1 + + '@tauri-apps/plugin-opener@2.5.5': + dependencies: + '@tauri-apps/api': 2.11.1 + + '@tiptap/core@3.31.3(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-blockquote@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-bold@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-bullet-list@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-code-block@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-code@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-document@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-dropcursor@3.31.3(@tiptap/extensions@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extensions': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-gapcursor@3.31.3(@tiptap/extensions@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extensions': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-hard-break@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-heading@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-highlight@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-horizontal-rule@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-image@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-italic@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-link@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + linkifyjs: 4.3.3 + + '@tiptap/extension-list-item@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-list-keymap@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-ordered-list@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-paragraph@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-strike@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-subscript@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-superscript@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-table-cell@3.31.3(@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-table': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-table-header@3.31.3(@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-table': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-table-row@3.31.3(@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-table': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-table@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/extension-task-item@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-task-list@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + + '@tiptap/extension-text@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extension-underline@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + + '@tiptap/extensions@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@tiptap/pm@3.31.3': + dependencies: + prosemirror-changeset: 2.4.3 + prosemirror-commands: 1.7.2 + prosemirror-dropcursor: 1.8.3 + prosemirror-gapcursor: 1.4.1 + prosemirror-history: 1.5.0 + prosemirror-inputrules: 1.5.1 + prosemirror-keymap: 1.2.3 + prosemirror-model: 1.25.11 + prosemirror-schema-list: 1.5.1 + prosemirror-state: 1.4.4 + prosemirror-tables: 1.8.5 + prosemirror-transform: 1.12.1 + prosemirror-view: 1.42.4 + + '@tiptap/starter-kit@3.31.3': + dependencies: + '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) + '@tiptap/extension-blockquote': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-bold': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-bullet-list': 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-code': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-code-block': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-document': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-dropcursor': 3.31.3(@tiptap/extensions@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-gapcursor': 3.31.3(@tiptap/extensions@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-hard-break': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-heading': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-horizontal-rule': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-italic': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-link': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-list': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-list-item': 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-list-keymap': 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-ordered-list': 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) + '@tiptap/extension-paragraph': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-strike': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-text': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extension-underline': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) + '@tiptap/extensions': 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/pm': 3.31.3 + + '@types/cookie@0.6.0': {} + + '@types/d3-array@3.2.2': {} + + '@types/d3-axis@3.0.6': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-brush@3.0.6': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-chord@3.0.6': {} + + '@types/d3-color@3.1.3': {} + + '@types/d3-contour@3.0.6': + dependencies: + '@types/d3-array': 3.2.2 + '@types/geojson': 7946.0.16 + + '@types/d3-delaunay@6.0.4': {} + + '@types/d3-dispatch@3.0.7': {} + + '@types/d3-drag@3.0.7': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-dsv@3.0.7': {} + + '@types/d3-ease@3.0.2': {} + + '@types/d3-fetch@3.0.7': + dependencies: + '@types/d3-dsv': 3.0.7 + + '@types/d3-force@3.0.10': {} + + '@types/d3-format@3.0.4': {} + + '@types/d3-geo@3.1.1': + dependencies: + '@types/geojson': 7946.0.16 + + '@types/d3-hierarchy@3.1.7': {} + + '@types/d3-interpolate@3.0.4': + dependencies: + '@types/d3-color': 3.1.3 + + '@types/d3-path@3.1.1': {} + + '@types/d3-polygon@3.0.2': {} + + '@types/d3-quadtree@3.0.6': {} + + '@types/d3-random@3.0.4': {} + + '@types/d3-scale-chromatic@3.1.0': {} + + '@types/d3-scale@4.0.9': + dependencies: + '@types/d3-time': 3.0.4 + + '@types/d3-selection@3.0.12': {} + + '@types/d3-shape@3.2.0': + dependencies: + '@types/d3-path': 3.1.1 + + '@types/d3-time-format@4.0.3': {} + + '@types/d3-time@3.0.4': {} + + '@types/d3-timer@3.0.2': {} + + '@types/d3-transition@3.0.9': + dependencies: + '@types/d3-selection': 3.0.12 + + '@types/d3-zoom@3.0.8': + dependencies: + '@types/d3-interpolate': 3.0.4 + '@types/d3-selection': 3.0.12 + + '@types/d3@7.4.3': + dependencies: + '@types/d3-array': 3.2.2 + '@types/d3-axis': 3.0.6 + '@types/d3-brush': 3.0.6 + '@types/d3-chord': 3.0.6 + '@types/d3-color': 3.1.3 + '@types/d3-contour': 3.0.6 + '@types/d3-delaunay': 6.0.4 + '@types/d3-dispatch': 3.0.7 + '@types/d3-drag': 3.0.7 + '@types/d3-dsv': 3.0.7 + '@types/d3-ease': 3.0.2 + '@types/d3-fetch': 3.0.7 + '@types/d3-force': 3.0.10 + '@types/d3-format': 3.0.4 + '@types/d3-geo': 3.1.1 + '@types/d3-hierarchy': 3.1.7 + '@types/d3-interpolate': 3.0.4 + '@types/d3-path': 3.1.1 + '@types/d3-polygon': 3.0.2 + '@types/d3-quadtree': 3.0.6 + '@types/d3-random': 3.0.4 + '@types/d3-scale': 4.0.9 + '@types/d3-scale-chromatic': 3.1.0 + '@types/d3-selection': 3.0.12 + '@types/d3-shape': 3.2.0 + '@types/d3-time': 3.0.4 + '@types/d3-time-format': 4.0.3 + '@types/d3-timer': 3.0.2 + '@types/d3-transition': 3.0.9 + '@types/d3-zoom': 3.0.8 + + '@types/estree@1.0.9': {} + + '@types/geojson@7946.0.16': {} + + '@types/trusted-types@2.0.7': + optional: true + + '@upsetjs/venn.js@2.0.0': + optionalDependencies: + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + '@xterm/addon-fit@0.11.0': {} + + '@xterm/xterm@6.0.0': {} + + acorn@8.18.0: {} + + argparse@3.0.2: {} + + aria-query@5.3.1: {} + + axobject-query@4.1.0: {} + + chevrotain@11.1.2: + dependencies: + '@chevrotain/cst-dts-gen': 11.1.2 + '@chevrotain/gast': 11.1.2 + '@chevrotain/regexp-to-ast': 11.1.2 + '@chevrotain/types': 11.1.2 + '@chevrotain/utils': 11.1.2 + lodash-es: 4.17.23 + + chokidar@4.0.3: + dependencies: + readdirp: 4.1.2 + + clsx@2.1.1: {} + + commander@7.2.0: {} + + commander@8.3.0: {} + + cookie@0.6.0: {} + + cose-base@1.0.3: + dependencies: + layout-base: 1.0.2 + + cose-base@2.2.0: + dependencies: + layout-base: 2.0.1 + + crelt@1.0.7: {} + + cytoscape-cose-bilkent@4.1.0(cytoscape@3.34.3): + dependencies: + cose-base: 1.0.3 + cytoscape: 3.34.3 + + cytoscape-fcose@2.2.0(cytoscape@3.34.3): + dependencies: + cose-base: 2.2.0 + cytoscape: 3.34.3 + + cytoscape@3.34.3: {} + + d3-array@2.12.1: + dependencies: + internmap: 1.0.1 + + d3-array@3.2.4: + dependencies: + internmap: 2.0.3 + + d3-axis@3.0.0: {} + + d3-brush@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + d3-chord@3.0.1: + dependencies: + d3-path: 3.1.0 + + d3-color@3.1.0: {} + + d3-contour@4.0.2: + dependencies: + d3-array: 3.2.4 + + d3-delaunay@6.0.4: + dependencies: + delaunator: 5.1.0 + + d3-dispatch@3.0.1: {} + + d3-drag@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-selection: 3.0.0 + + d3-dsv@3.0.1: + dependencies: + commander: 7.2.0 + iconv-lite: 0.6.3 + rw: 1.3.3 + + d3-ease@3.0.1: {} + + d3-fetch@3.0.1: + dependencies: + d3-dsv: 3.0.1 + + d3-force@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-quadtree: 3.0.1 + d3-timer: 3.0.1 + + d3-format@3.1.2: {} + + d3-geo@3.1.1: + dependencies: + d3-array: 3.2.4 + + d3-hierarchy@3.1.2: {} + + d3-interpolate@3.0.1: + dependencies: + d3-color: 3.1.0 + + d3-path@1.0.9: {} + + d3-path@3.1.0: {} + + d3-polygon@3.0.1: {} + + d3-quadtree@3.0.1: {} + + d3-random@3.0.1: {} + + d3-sankey@0.12.3: + dependencies: + d3-array: 2.12.1 + d3-shape: 1.3.7 + + d3-scale-chromatic@3.1.0: + dependencies: + d3-color: 3.1.0 + d3-interpolate: 3.0.1 + + d3-scale@4.0.2: + dependencies: + d3-array: 3.2.4 + d3-format: 3.1.2 + d3-interpolate: 3.0.1 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + + d3-selection@3.0.0: {} + + d3-shape@1.3.7: + dependencies: + d3-path: 1.0.9 + + d3-shape@3.2.0: + dependencies: + d3-path: 3.1.0 + + d3-time-format@4.1.0: + dependencies: + d3-time: 3.1.0 + + d3-time@3.1.0: + dependencies: + d3-array: 3.2.4 + + d3-timer@3.0.1: {} + + d3-transition@3.0.1(d3-selection@3.0.0): + dependencies: + d3-color: 3.1.0 + d3-dispatch: 3.0.1 + d3-ease: 3.0.1 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-timer: 3.0.1 + + d3-zoom@3.0.0: + dependencies: + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-interpolate: 3.0.1 + d3-selection: 3.0.0 + d3-transition: 3.0.1(d3-selection@3.0.0) + + d3@7.9.0: + dependencies: + d3-array: 3.2.4 + d3-axis: 3.0.0 + d3-brush: 3.0.0 + d3-chord: 3.0.1 + d3-color: 3.1.0 + d3-contour: 4.0.2 + d3-delaunay: 6.0.4 + d3-dispatch: 3.0.1 + d3-drag: 3.0.0 + d3-dsv: 3.0.1 + d3-ease: 3.0.1 + d3-fetch: 3.0.1 + d3-force: 3.0.0 + d3-format: 3.1.2 + d3-geo: 3.1.1 + d3-hierarchy: 3.1.2 + d3-interpolate: 3.0.1 + d3-path: 3.1.0 + d3-polygon: 3.0.1 + d3-quadtree: 3.0.1 + d3-random: 3.0.1 + d3-scale: 4.0.2 + d3-scale-chromatic: 3.1.0 + d3-selection: 3.0.0 + d3-shape: 3.2.0 + d3-time: 3.1.0 + d3-time-format: 4.1.0 + d3-timer: 3.0.1 + d3-transition: 3.0.1(d3-selection@3.0.0) + d3-zoom: 3.0.0 + + dagre-d3-es@7.0.14: + dependencies: + d3: 7.9.0 + lodash-es: 4.18.1 + + dayjs@1.11.23: {} + + deepmerge@4.3.1: {} + + delaunator@5.1.0: + dependencies: + robust-predicates: 3.0.3 + + detect-libc@2.1.2: {} + + devalue@5.9.4: {} + + dompurify@3.4.16: + optionalDependencies: + '@types/trusted-types': 2.0.7 + + dompurify@3.4.8: + optionalDependencies: + '@types/trusted-types': 2.0.7 + + elkjs@0.9.3: {} + + entities@8.1.0: {} + + es-toolkit@1.52.0: {} + + esm-env@1.2.2: {} + + esrap@2.3.7: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + hachure-fill@0.5.2: {} + + iconv-lite@0.6.3: + dependencies: + safer-buffer: 2.1.2 + + import-meta-resolve@4.2.0: {} + + internmap@1.0.1: {} + + internmap@2.0.3: {} + + is-reference@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + katex@0.16.47: + dependencies: + commander: 8.3.0 + + khroma@2.1.0: {} + + kleur@4.1.5: {} + + layout-base@1.0.2: {} + + layout-base@2.0.1: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + linkify-it@6.1.0: + dependencies: + uc.micro: 3.0.0 + + linkifyjs@4.3.3: {} + + locate-character@3.0.0: {} + + lodash-es@4.17.23: {} + + lodash-es@4.18.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + magic-string@1.4.1: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + markdown-it@15.0.2: + dependencies: + argparse: 3.0.2 + entities: 8.1.0 + linkify-it: 6.1.0 + mdurl: 2.1.0 + punycode.js: 2.3.1 + uc.micro: 3.0.0 + + marked@14.0.0: {} + + marked@16.4.2: {} + + mdurl@2.1.0: {} + + mermaid@12.0.0: + dependencies: + '@braintree/sanitize-url': 7.1.2 + '@iconify/utils': 3.1.7 + '@mermaid-js/parser': 2.0.0 + '@types/d3': 7.4.3 + '@upsetjs/venn.js': 2.0.0 + chevrotain: 11.1.2 + cytoscape: 3.34.3 + cytoscape-cose-bilkent: 4.1.0(cytoscape@3.34.3) + cytoscape-fcose: 2.2.0(cytoscape@3.34.3) + d3: 7.9.0 + d3-sankey: 0.12.3 + dagre-d3-es: 7.0.14 + dayjs: 1.11.23 + dompurify: 3.4.16 + elkjs: 0.9.3 + es-toolkit: 1.52.0 + katex: 0.16.47 + khroma: 2.1.0 + marked: 16.4.2 + roughjs: 4.6.6 + stylis: 4.4.0 + ts-dedent: 2.3.0 + uuid: 14.0.2 + + monaco-editor@0.56.0: + dependencies: + dompurify: 3.4.8 + marked: 14.0.0 + + mri@1.2.0: {} + + mrmime@2.0.1: {} + + nanoid@3.3.19: {} + + obug@2.2.1: {} + + orderedmap@2.1.1: {} + + package-manager-detector@1.8.0: {} + + path-data-parser@0.1.0: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + points-on-curve@0.2.0: {} + + points-on-path@0.2.1: + dependencies: + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + + postcss@8.5.28: + dependencies: + nanoid: 3.3.19 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prosemirror-changeset@2.4.3: + dependencies: + prosemirror-transform: 1.12.1 + + prosemirror-commands@1.7.2: + dependencies: + prosemirror-model: 1.25.11 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + + prosemirror-dropcursor@1.8.3: + dependencies: + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + prosemirror-view: 1.42.4 + + prosemirror-gapcursor@1.4.1: + dependencies: + prosemirror-keymap: 1.2.3 + prosemirror-model: 1.25.11 + prosemirror-state: 1.4.4 + prosemirror-view: 1.42.4 + + prosemirror-history@1.5.0: + dependencies: + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + prosemirror-view: 1.42.4 + rope-sequence: 1.3.4 + + prosemirror-inputrules@1.5.1: + dependencies: + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + + prosemirror-keymap@1.2.3: + dependencies: + prosemirror-state: 1.4.4 + w3c-keyname: 2.2.8 + + prosemirror-model@1.25.11: + dependencies: + orderedmap: 2.1.1 + + prosemirror-schema-list@1.5.1: + dependencies: + prosemirror-model: 1.25.11 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + + prosemirror-state@1.4.4: + dependencies: + prosemirror-model: 1.25.11 + prosemirror-transform: 1.12.1 + prosemirror-view: 1.42.4 + + prosemirror-tables@1.8.5: + dependencies: + prosemirror-keymap: 1.2.3 + prosemirror-model: 1.25.11 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + prosemirror-view: 1.42.4 + + prosemirror-transform@1.12.1: + dependencies: + prosemirror-model: 1.25.11 + + prosemirror-view@1.42.4: + dependencies: + prosemirror-model: 1.25.11 + prosemirror-state: 1.4.4 + prosemirror-transform: 1.12.1 + + punycode.js@2.3.1: {} + + readdirp@4.1.2: {} + + robust-predicates@3.0.3: {} + + rolldown@1.2.9: + dependencies: + '@oxc-project/types': 0.150.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.9 + '@rolldown/binding-android-arm64': 1.2.9 + '@rolldown/binding-darwin-arm64': 1.2.9 + '@rolldown/binding-darwin-x64': 1.2.9 + '@rolldown/binding-freebsd-x64': 1.2.9 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.9 + '@rolldown/binding-linux-arm64-gnu': 1.2.9 + '@rolldown/binding-linux-arm64-musl': 1.2.9 + '@rolldown/binding-linux-ppc64-gnu': 1.2.9 + '@rolldown/binding-linux-s390x-gnu': 1.2.9 + '@rolldown/binding-linux-x64-gnu': 1.2.9 + '@rolldown/binding-linux-x64-musl': 1.2.9 + '@rolldown/binding-openharmony-arm64': 1.2.9 + '@rolldown/binding-win32-arm64-msvc': 1.2.9 + '@rolldown/binding-win32-x64-msvc': 1.2.9 + + rope-sequence@1.3.4: {} + + roughjs@4.6.6: + dependencies: + hachure-fill: 0.5.2 + path-data-parser: 0.1.0 + points-on-curve: 0.2.0 + points-on-path: 0.2.1 + + rw@1.3.3: {} + + sade@1.8.1: + dependencies: + mri: 1.2.0 + + safer-buffer@2.1.2: {} + + set-cookie-parser@3.1.2: {} + + sirv@3.0.2: + dependencies: + '@polka/url': 1.0.0-next.29 + mrmime: 2.0.1 + totalist: 3.0.1 + + source-map-js@1.2.1: {} + + style-mod@4.1.4: {} + + stylis@4.4.0: {} + + svelte-check@4.7.6(picomatch@4.0.7)(svelte@5.57.1)(typescript@6.0.3): + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@sveltejs/load-config': 0.2.3 + chokidar: 4.0.3 + fdir: 6.5.0(picomatch@4.0.7) + picocolors: 1.1.1 + sade: 1.8.1 + svelte: 5.57.1 + typescript: 6.0.3 + transitivePeerDependencies: + - picomatch + + svelte@5.57.1: + dependencies: + '@jridgewell/remapping': 2.3.5 + '@jridgewell/sourcemap-codec': 1.6.0 + '@sveltejs/acorn-typescript': 1.0.13(acorn@8.18.0) + '@types/estree': 1.0.9 + acorn: 8.18.0 + aria-query: 5.3.1 + axobject-query: 4.1.0 + clsx: 2.1.1 + devalue: 5.9.4 + esm-env: 1.2.2 + esrap: 2.3.7 + is-reference: 3.0.3 + locate-character: 3.0.0 + magic-string: 0.30.21 + zimmerframe: 1.1.5 + transitivePeerDependencies: + - '@typescript-eslint/types' + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + totalist@3.0.1: {} + + ts-dedent@2.3.0: {} + + typescript@6.0.3: {} + + uc.micro@3.0.0: {} + + uuid@14.0.2: {} + + vite@8.3.0: + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.9 + tinyglobby: 0.2.17 + optionalDependencies: + fsevents: 2.3.3 + + vitefu@1.1.3(vite@8.3.0): + optionalDependencies: + vite: 8.3.0 + + w3c-keyname@2.2.8: {} + + zimmerframe@1.1.5: {} diff --git a/scripts/chrome.spec.ts b/scripts/chrome.spec.ts new file mode 100644 index 0000000..735f750 --- /dev/null +++ b/scripts/chrome.spec.ts @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { detectChrome, extensionOf, treeFileParts } from "../src/lib/workspace/chrome.ts"; +import { monacoChrome } from "../src/lib/editor/monacoChrome.ts"; + +test("markdown files open in writing chrome", () => { + assert.equal(detectChrome("notes/inbox.md"), "Writing"); + assert.equal(detectChrome("README.markdown"), "Writing"); +}); + +test("scripts open in ide chrome", () => { + assert.equal(detectChrome("src/hello.py"), "Ide"); + assert.equal(detectChrome("tools/setup.sh"), "Ide"); + assert.equal(detectChrome("Makefile"), "Ide"); +}); + +test("writing chrome wraps and hides line numbers", () => { + assert.equal(monacoChrome("Writing").wordWrap, "on"); + assert.equal(monacoChrome("Writing").lineNumbers, "off"); + assert.equal(monacoChrome("Writing").minimap.enabled, false); +}); + +test("ide chrome shows line numbers and no wrap", () => { + assert.equal(monacoChrome("Ide").wordWrap, "off"); + assert.equal(monacoChrome("Ide").lineNumbers, "on"); + assert.equal(monacoChrome("Ide").minimap.enabled, true); +}); + +test("extensionOf reads the last suffix", () => { + assert.equal(extensionOf("a/b.c.py"), "py"); + assert.equal(extensionOf(".gitignore"), ""); +}); + +test("treeFileParts splits a display name from its extension", () => { + assert.deepEqual(treeFileParts("inbox.md"), { label: "inbox", ext: "md" }); + assert.deepEqual(treeFileParts("chrome_extensions.json"), { + label: "chrome_extensions", + ext: "json", + }); + assert.deepEqual(treeFileParts(".gitignore"), { label: ".gitignore", ext: "" }); +}); diff --git a/scripts/documents.spec.ts b/scripts/documents.spec.ts new file mode 100644 index 0000000..2f97706 --- /dev/null +++ b/scripts/documents.spec.ts @@ -0,0 +1,348 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { Documents } from "../src/lib/workspace/documents.ts"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => resolve = done); + return { promise, resolve }; +} +const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const }); +function setup() { + const disk = new Map([["note.md", "original"], ["script.py", "print('hello')"]]); + const io = { + read: async (path: string) => { if (!disk.has(path)) throw new Error("missing"); return disk.get(path)!; }, + write: async (path: string, contents: string, expected: string) => { + if (disk.get(path) !== expected) throw new Error("conflict"); + disk.set(path, contents); + }, + image: async () => "data:image/png;base64,", + kind: () => "text" as const, + chrome: () => "Writing" as const, + }; + const docs = new Documents(io, () => {}); + return { docs, disk, io }; +} + +test("empty tabs are independent, preserve dirty documents, and never access disk", async () => { + const { docs, io } = setup(); + await docs.open(entry("note.md")); + const note = docs.active!; + docs.edit(note.id, "keep my edits"); + docs.newTab(); + const first = docs.active!; + docs.newTab(); + const second = docs.active!; + assert.equal(first.kind, "empty"); + assert.equal(second.kind, "empty"); + assert.notEqual(first.relPath, second.relPath); + assert.equal(note.contents, "keep my edits"); + docs.select(first.relPath); + docs.close(first.relPath); + assert.equal(docs.active, second); + docs.close(note.relPath); + io.read = io.image = async () => { assert.fail("empty tabs must not read disk"); }; + io.write = async () => { assert.fail("empty tabs must not write disk"); }; + docs.edit(second.id, "ignored"); + await docs.refresh(); + await docs.save(second.id); + assert.deepEqual(await docs.autosave(), { saved: [], failed: [] }); + assert.equal(docs.dirty, false); + assert.equal(second.diskError, undefined); + docs.close(second.relPath); + assert.equal(docs.activePath, null); +}); + +test("opening a file fills the active empty tab in place and failed reads preserve it", async () => { + const { docs } = setup(); + docs.newTab(); + const first = docs.active!; + docs.newTab(); + const second = docs.active!; + docs.select(first.relPath); + await assert.rejects(docs.open(entry("missing.md")), /missing/); + assert.equal(docs.active, first); + await docs.open(entry("note.md")); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", second.relPath]); + docs.select(second.relPath); + await docs.open(entry("note.md")); + assert.equal(docs.buffers.length, 2); + assert.equal(docs.activePath, "note.md"); +}); + +test("a new empty tab stays selected when an earlier file read finishes", async () => { + const { docs, io } = setup(); + const gate = deferred(); + io.read = () => gate.promise; + const pending = docs.open(entry("note.md")); + docs.newTab(); + const blank = docs.active!; + gate.resolve("note"); + await pending; + assert.equal(docs.active, blank); + assert.equal(docs.buffers.length, 2); +}); + +test("clean buffers follow agent edits; dirty buffers retain both versions", async () => { + const { docs, disk } = setup(); + await docs.open(entry("note.md")); + disk.set("note.md", "agent version"); + await docs.refresh(); + assert.equal(docs.active?.contents, "agent version"); + docs.edit(docs.active!.id, "my version"); + disk.set("note.md", "agent version 2"); + await docs.refresh(); + assert.equal(docs.active?.contents, "my version"); + assert.equal(docs.active?.diskContents, "agent version 2"); + await assert.rejects(docs.save(docs.active!.id), /Resolve/); + docs.resolve(docs.active!.id, false); + await docs.save(docs.active!.id); + assert.equal(disk.get("note.md"), "my version"); +}); + +test("typing during a save remains unsaved", async () => { + const { docs, io, disk } = setup(); + await docs.open(entry("note.md")); + const gate = deferred(); + const write = io.write; + io.write = async (...args) => { await gate.promise; return write(...args); }; + docs.edit(docs.active!.id, "first edit"); + const pending = docs.save(docs.active!.id); + await Promise.resolve(); + docs.edit(docs.active!.id, "second edit"); + gate.resolve(); + await pending; + assert.equal(disk.get("note.md"), "first edit"); + assert.equal(docs.active!.saved, "first edit"); + assert.equal(docs.active!.contents, "second edit"); + assert.equal(docs.dirty, true); +}); + +test("concurrent saves serialize and finish at the latest edit", async () => { + const { docs, io, disk } = setup(); + await docs.open(entry("note.md")); + const gate = deferred(); + const write = io.write; + io.write = async (...args) => { await gate.promise; return write(...args); }; + docs.edit(docs.active!.id, "first"); + const first = docs.save(docs.active!.id); + await Promise.resolve(); + docs.edit(docs.active!.id, "latest"); + const second = docs.save(docs.active!.id); + const third = docs.save(docs.active!.id); + gate.resolve(); + await Promise.all([first, second, third]); + assert.equal(disk.get("note.md"), "latest"); + assert.equal(docs.dirty, false); +}); + +test("latest navigation wins even when earlier reads finish later", async () => { + const { docs, io } = setup(); + const gate = deferred(); + const read = io.read; + io.read = path => path === "note.md" ? gate.promise : read(path); + const first = docs.open(entry("note.md")); + await docs.open(entry("script.py")); + gate.resolve("note"); + await first; + assert.equal(docs.activePath, "script.py"); +}); + +test("duplicate opens share one document and do not lose edits", async () => { + const { docs } = setup(); + await Promise.all([docs.open(entry("note.md")), docs.open(entry("note.md"))]); + assert.equal(docs.buffers.length, 1); + docs.edit(docs.active!.id, "unsaved"); + await docs.open(entry("script.py")); + await docs.open(entry("note.md")); + assert.equal(docs.active!.contents, "unsaved"); +}); + +test("current-tab navigation replaces the selected tab in place; new-tab navigation keeps it", async () => { + const { docs, disk } = setup(); + disk.set("third.md", "third"); + await docs.open(entry("note.md")); + await docs.open(entry("script.py"), "new"); + docs.select("note.md"); + await docs.open(entry("third.md"), "current"); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]); + assert.equal(docs.activePath, "third.md"); + await docs.open(entry("script.py"), "current"); + assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]); + assert.equal(docs.activePath, "script.py"); +}); + +test("current-tab navigation preserves edits made while the next file is loading", async () => { + const { docs, io } = setup(); + await docs.open(entry("note.md")); + const note = docs.active!; + const gate = deferred(); + io.read = () => gate.promise; + const pending = docs.open(entry("script.py"), "current"); + docs.edit(note.id, "keep these edits"); + gate.resolve("script"); + await pending; + assert.equal(docs.buffers.length, 2); + assert.equal(note.contents, "keep these edits"); + assert.equal(docs.activePath, "script.py"); +}); + +test("failed current-tab navigation keeps the active document", async () => { + const { docs } = setup(); + await docs.open(entry("note.md"), "current"); + await assert.rejects(docs.open(entry("missing.md"), "current"), /missing/); + assert.equal(docs.buffers.length, 1); + assert.equal(docs.activePath, "note.md"); +}); + +test("a late current-tab read cannot replace a more recently selected tab", async () => { + const { docs, io } = setup(); + await docs.open(entry("note.md")); + const gate = deferred(); + io.read = () => gate.promise; + const pending = docs.open(entry("script.py"), "current"); + docs.select("note.md"); + gate.resolve("script"); + await pending; + assert.equal(docs.activePath, "note.md"); + assert.equal(docs.buffers[0].relPath, "note.md"); +}); + +test("removed files retain text and block accidental recreation", async () => { + const { docs, disk } = setup(); + await docs.open(entry("note.md")); + docs.edit(docs.active!.id, "precious text"); + disk.delete("note.md"); + await docs.refresh(); + assert.equal(docs.active!.contents, "precious text"); + assert.match(docs.active!.diskError!, /unavailable/); + await assert.rejects(docs.save(docs.active!.id)); +}); + +test("disposing a workspace ignores late open results", async () => { + const { docs, io } = setup(); + const gate = deferred(); + io.read = () => gate.promise; + const pending = docs.open(entry("note.md")); + docs.dispose(); gate.resolve("late"); + await pending; + assert.equal(docs.buffers.length, 0); +}); + +test("renaming a folder preserves document identity and dirty state", async () => { + const { docs } = setup(); + await docs.open(entry("note.md")); + const id = docs.active!.id; + docs.edit(id, "edits"); docs.rename("note.md", "notes/moved.md"); + assert.equal(docs.activePath, "notes/moved.md"); + assert.equal(docs.active!.id, id); + assert.equal(docs.dirty, true); +}); + +test("autosave writes changed background tabs once and skips clean or reverted text", async () => { + const { docs, io, disk } = setup(); + const writes: string[] = []; + const write = io.write; + io.write = async (...args) => { writes.push(args[0]); await write(...args); }; + await docs.open(entry("note.md")); + const note = docs.active!; + docs.edit(note.id, "background edit"); + await docs.open(entry("script.py")); + docs.edit(docs.active!.id, "temporary edit"); + docs.edit(docs.active!.id, docs.active!.saved); + assert.deepEqual(await docs.autosave(), { saved: ["note.md"], failed: [] }); + assert.equal(disk.get("note.md"), "background edit"); + await docs.autosave(); + await docs.save(note.id); + assert.deepEqual(writes, ["note.md"]); +}); + +test("autosave skips in-flight saves and preserves edits for the next pass", async () => { + const { docs, io, disk } = setup(); + await docs.open(entry("note.md")); + const gate = deferred(); + const write = io.write; + let writes = 0; + io.write = async (...args) => { writes++; await gate.promise; await write(...args); }; + docs.edit(docs.active!.id, "first"); + const pending = docs.autosave(); + await Promise.resolve(); + docs.edit(docs.active!.id, "still typing"); + assert.deepEqual(await docs.autosave(), { saved: [], failed: [] }); + gate.resolve(); + await pending; + assert.equal(writes, 1); + assert.equal(disk.get("note.md"), "first"); + assert.equal(docs.dirty, true); + await docs.autosave(); + assert.equal(writes, 2); + assert.equal(disk.get("note.md"), "still typing"); +}); + +test("autosave skips known conflicts and unavailable files", async () => { + const { docs, io, disk } = setup(); + await docs.open(entry("note.md")); + const note = docs.active!; + docs.edit(note.id, "my note"); + await docs.open(entry("script.py")); + docs.edit(docs.active!.id, "my script"); + disk.set("note.md", "external edit"); + disk.delete("script.py"); + await docs.refresh(); + io.write = async () => { assert.fail("blocked files must not be written"); }; + assert.deepEqual(await docs.autosave(), { saved: [], failed: [] }); + assert.equal(note.contents, "my note"); + assert.equal(note.diskContents, "external edit"); + assert.equal(docs.active!.contents, "my script"); + assert.equal(docs.dirty, true); +}); + +test("an autosave failure preserves edits, saves other files, and can be retried", async () => { + const { docs, io, disk } = setup(); + await docs.open(entry("note.md")); + const note = docs.active!; + docs.edit(note.id, "my note"); + await docs.open(entry("script.py")); + docs.edit(docs.active!.id, "my script"); + const write = io.write; + io.write = async (...args) => { + if (args[0] === "note.md") throw new Error("disk full"); + await write(...args); + }; + const result = await docs.autosave(); + assert.deepEqual(result.saved, ["script.py"]); + assert.equal(result.failed[0].path, "note.md"); + assert.match(String(result.failed[0].error), /disk full/); + assert.equal(note.saved, "original"); + assert.equal(note.contents, "my note"); + assert.equal(disk.get("script.py"), "my script"); + io.write = write; + await docs.autosave(); + assert.equal(disk.get("note.md"), "my note"); + assert.equal(docs.dirty, false); +}); + +test("autosave cannot overwrite an external edit even before the watcher refreshes", async () => { + const { docs, disk } = setup(); + await docs.open(entry("note.md")); + docs.edit(docs.active!.id, "my note"); + disk.set("note.md", "external edit"); + const result = await docs.autosave(); + assert.equal(result.failed.length, 1); + assert.equal(disk.get("note.md"), "external edit"); + assert.equal(docs.active!.contents, "my note"); + assert.equal(docs.dirty, true); +}); + +test("closed documents and disposed workspaces are not autosaved", async () => { + const { docs, io } = setup(); + await docs.open(entry("note.md")); + docs.edit(docs.active!.id, "discarded"); + docs.close("note.md"); + io.write = async () => { assert.fail("discarded edits must not be written"); }; + assert.deepEqual(await docs.autosave(), { saved: [], failed: [] }); + await docs.open(entry("script.py")); + docs.edit(docs.active!.id, "disposed"); + docs.dispose(); + assert.deepEqual(await docs.autosave(), { saved: [], failed: [] }); +}); diff --git a/scripts/headingMarks.spec.ts b/scripts/headingMarks.spec.ts new file mode 100644 index 0000000..53ca610 --- /dev/null +++ b/scripts/headingMarks.spec.ts @@ -0,0 +1,15 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { fenceOpenText, headingMarkText } from "../src/lib/editor/headingMarks.ts"; + +test("heading marks match the heading level", () => { + assert.equal(headingMarkText(1), "#"); + assert.equal(headingMarkText(3), "###"); + assert.equal(headingMarkText(6), "######"); +}); + +test("fence open marks include the language", () => { + assert.equal(fenceOpenText(""), "```"); + assert.equal(fenceOpenText("js"), "```js"); + assert.equal(fenceOpenText(" pp "), "```pp"); +}); diff --git a/scripts/imageNavigation.smoke.mjs b/scripts/imageNavigation.smoke.mjs new file mode 100644 index 0000000..5d4598d --- /dev/null +++ b/scripts/imageNavigation.smoke.mjs @@ -0,0 +1,209 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(10000); +const errors = []; +page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); +page.on("pageerror", error => errors.push(error.message)); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\smoke-workspace"; + const files = new Map([ + ["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"], + ["notes/second.md", "# Second note\n"], + ["src/hello.py", "print('hello')\n"], + ]); + const svg = ''; + files.set("images/picture (#1).svg", btoa(svg)); + files.set("images/replacement.svg", btoa(svg)); + files.set("notes/welcome.md", "Above.\n\nBelow.\n"); + const callbacks = new Map(); + const listeners = new Map(); + let sequence = 0; + const calls = []; + const emit = (event, payload) => { + for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); + }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + calls.push({ command, args }); + if (command === "plugin:event|listen") { + const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; + } + if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } + if (command === "workspace_write_bytes") { + if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; }); + if (window.__TEST__.failWrite) throw new Error("Image write failed"); + files.set(args.rel, args.base64); return; + } + if (command === "workspace_read_data_url") { + if (!files.has(args.rel)) throw new Error("missing image"); + return "data:image/svg+xml;base64," + files.get(args.rel); + } + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } + if (command === "workspace_write") { + if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); + files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return; + } + if (command === "workspace_list") { + const prefix = args.rel ? args.rel + "/" : ""; + const entries = new Map(); + for (const path of files.keys()) { + if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue; + const tail = path.slice(prefix.length); const name = tail.split("/")[0]; + entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" }); + } + return [...entries.values()]; + } + if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; } + if (command === "workspace_reveal") return; + if (command === "workspace_search") return []; + if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }]; + if (command === "pty_open") { + const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")]; + emit("pty-data", { id: args.id, data: data.slice(0, 8) }); + emit("pty-data", { id: args.id, data: data.slice(8) }); + await new Promise(resolve => setTimeout(resolve, 50)); + return; + } + if (command.startsWith("pty_")) return; + if (command === "plugin:dialog|message") return "Cancel"; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; + window.__TEST__ = { files, calls, emit, root }; +}); + + + +async function writer() { + await page.locator(".cm-content").waitFor(); + await page.evaluate(async () => { + const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js"); + window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); + }); +} +async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); } +async function dragFromTree(selector = ".cm-content", cancel = false) { + const row = page.locator('[data-tree-rel="images/picture (#1).svg"]'); + const from = await row.boundingBox(), to = await page.locator(selector).boundingBox(); + await page.mouse.move(from.x + 60, from.y + from.height / 2); + await page.mouse.down(); + await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 }); + await page.getByText("Insert image", { exact: true }).waitFor(); + assert.equal(await page.locator(".image-drop-target").count(), 1); + if (cancel) await page.keyboard.press("Escape"); + await page.mouse.up(); +} +async function imageMenu() { + await page.locator(".md-image-frame").first().click({ button: "right" }); + await page.getByRole("menu", { name: "Image actions" }).waitFor(); +} +try { + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await page.getByText("smoke-workspace", { exact: true }).waitFor(); + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md"); + await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).click(); + await writer(); + await page.locator('[data-tree-rel="images"]').click(); + await dragFromTree(); + await page.locator(".md-image-frame img").waitFor(); + const linked = await source(); + assert.ok(linked.startsWith("![](../images/picture%20%28%231%29.svg)\n\nAbove."), linked); + assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => ["workspace_write_bytes", "workspace_rename"].includes(c.command)).length), 0); + assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0); + // Neither caret movement nor selection exposes an image's Markdown. + await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: 0, head: 38 } })); + assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0); + await page.locator(".md-image-frame img").click(); + assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1); + await page.keyboard.press("Shift+F10"); + await page.getByRole("menu", { name: "Image actions" }).waitFor(); + assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1); + await page.screenshot({ path: ".audit/image-context-menu.png" }); + await page.getByRole("menuitem", { name: "Copy Markdown", exact: true }).click(); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "![](../images/picture%20%28%231%29.svg)"); + await imageMenu(); + await page.getByRole("menuitem", { name: "Copy image", exact: true }).click(); + await page.waitForFunction(async () => (await navigator.clipboard.read()).some(item => item.types.includes("image/png"))); + await imageMenu(); + await page.getByRole("menuitem", { name: "Show in Explorer", exact: true }).click(); + await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "workspace_reveal" && c.args.rel === "images/picture (#1).svg")); + await imageMenu(); + await page.getByRole("menuitem", { name: "Remove image", exact: true }).click(); + assert.ok(!(await source()).includes("picture%20")); + assert.ok(await page.evaluate(() => window.__TEST__.files.has("images/picture (#1).svg"))); + await page.keyboard.press("Control+z"); + assert.equal(await source(), linked); + + await page.locator(".md-image-frame").hover(); + await page.getByRole("button", { name: "Edit image source", exact: true }).click(); + await page.locator(".cm-line").filter({ hasText: "picture%20" }).waitFor(); + assert.equal(await page.locator(".md-image-frame img").count(), 1); + await page.getByRole("button", { name: "Hide image source", exact: true }).click(); + assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0); + await imageMenu(); + await page.getByRole("menuitem", { name: "Swap image…", exact: true }).click(); + await page.getByRole("textbox", { name: "Image path relative to this note, or https URL" }).fill("../images/replacement.svg"); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + await page.waitForFunction(() => window.__CM__.state.doc.toString().includes("replacement.svg")); + assert.equal(await page.locator(".cm-line").filter({ hasText: "replacement.svg" }).count(), 0); + await imageMenu(); + await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click(); + await page.getByRole("tab", { name: "replacement.svg", exact: true }).waitFor(); + await page.getByRole("tab", { name: /welcome.md/ }).click(); + await writer(); + + const beforeCancel = await source(); + await dragFromTree(".cm-content", true); + assert.equal(await source(), beforeCancel); + assert.equal(await page.locator(".image-drop-target").count(), 0); + // Inline images remain independently selectable without hiding adjacent prose. + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "Before ![](../images/replacement.svg) between ![[../images/replacement.svg]] after.\n" }, selection: { anchor: 0 } }); + }); + await page.waitForFunction(() => document.querySelectorAll(".md-image-frame").length === 2); + assert.ok((await page.locator(".cm-content").innerText()).includes("Before")); + assert.ok(!(await page.locator(".cm-content").innerText()).includes("![]")); + await page.locator(".md-image-frame img").nth(1).click(); + await page.keyboard.press("Delete"); + assert.equal(await source(), "Before ![](../images/replacement.svg) between after.\n"); + await page.keyboard.press("Control+z"); + assert.ok((await source()).includes("![[../images/replacement.svg]]")); + // Reference-image editing affects only the selected embed, not its definition. + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "![Reference][pic]\n\nBelow.\n\n[pic]: ../images/replacement.svg\n" }, selection: { anchor: 0 } }); + }); + await page.locator(".md-image-frame").hover(); + assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0); + await page.getByRole("button", { name: "Edit image source", exact: true }).click(); + await page.locator(".cm-line").filter({ hasText: "![Reference]" }).waitFor(); + await page.keyboard.press("Escape"); + assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0); + // The same navigator drag works in the source editor. + await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); + await page.locator(".monaco-editor textarea").waitFor(); + await dragFromTree(".monaco-editor .view-lines"); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").includes("picture%20")); + assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_write_bytes").length), 0); + assert.deepEqual(errors, []); + console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed."); +} catch (error) { + await page.screenshot({ path: ".audit/image-navigation-failure.png" }); + console.error(errors); throw error; +} finally { await browser.close(); } diff --git a/scripts/images.smoke.mjs b/scripts/images.smoke.mjs new file mode 100644 index 0000000..48e2fe1 --- /dev/null +++ b/scripts/images.smoke.mjs @@ -0,0 +1,248 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(10000); +const errors = []; +page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); +page.on("pageerror", error => errors.push(error.message)); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\smoke-workspace"; + const files = new Map([ + ["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"], + ["notes/second.md", "# Second note\n"], + ["src/hello.py", "print('hello')\n"], + ]); + const callbacks = new Map(); + const listeners = new Map(); + let sequence = 0; + const calls = []; + const emit = (event, payload) => { + for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); + }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + calls.push({ command, args }); + if (command === "plugin:event|listen") { + const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; + } + if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } + if (command === "workspace_write_bytes") { + if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; }); + if (window.__TEST__.failWrite) throw new Error("Image write failed"); + files.set(args.rel, args.base64); return; + } + if (command === "workspace_read_data_url") { + if (!files.has(args.rel)) throw new Error("missing image"); + return "data:image/svg+xml;base64," + files.get(args.rel); + } + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } + if (command === "workspace_write") { + if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); + files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return; + } + if (command === "workspace_list") { + const prefix = args.rel ? args.rel + "/" : ""; + const entries = new Map(); + for (const path of files.keys()) { + if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue; + const tail = path.slice(prefix.length); const name = tail.split("/")[0]; + entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" }); + } + return [...entries.values()]; + } + if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; } + if (command === "workspace_search") return []; + if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }]; + if (command === "pty_open") { + const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")]; + emit("pty-data", { id: args.id, data: data.slice(0, 8) }); + emit("pty-data", { id: args.id, data: data.slice(8) }); + await new Promise(resolve => setTimeout(resolve, 50)); + return; + } + if (command.startsWith("pty_")) return; + if (command === "plugin:dialog|message") return "Cancel"; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; + window.__TEST__ = { files, calls, emit, root }; +}); + + +async function openNote(name = "welcome.md") { + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill(name); + await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click(); + await page.locator(".cm-content").waitFor(); +} +async function source() { + return page.evaluate(() => window.__CM__.state.doc.toString()); +} +async function save() { + await page.keyboard.press("Control+s"); + await page.waitForTimeout(100); + return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md")); +} +async function drop(count = 1, selector = ".cm-content") { + await page.locator(selector).evaluate((element, count) => { + const data = new DataTransfer(); + const svg = 'Image drop test'; + for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" })); + const rect = element.getBoundingClientRect(); + element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 })); + }, count); +} +try { + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await page.getByText("smoke-workspace", { exact: true }).waitFor(); + await openNote(); + await page.evaluate(async () => { + const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js"); + window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); + window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } }); + }); + const original = await source(); + const acceptsDrag = await page.locator(".cm-content").evaluate(element => { + const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg")); + const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data }); + element.dispatchEvent(event); return event.defaultPrevented; + }); + assert.ok(acceptsDrag); + await drop(2); + await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2); + await page.locator(".md-image-frame img").first().waitFor(); + assert.equal(await page.locator(".md-image-frame img").count(), 2); + const inserted = await source(); + assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor"); + const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]); + assert.notEqual(paths[0], paths[1]); + assert.ok(paths.every(path => path.startsWith("../attachments/"))); + assert.equal(await save(), inserted); + + // Selecting and editing Markdown leaves the image visible and updates its alt text. + await page.locator(".md-image-frame").first().hover(); + await page.getByRole("button", { name: "Edit image source", exact: true }).first().click(); + assert.equal(await page.locator(".md-image-frame img").count(), 2); + assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0]))); + await page.evaluate(() => { + const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2; + view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } }); + }); + await page.locator('img[alt="Edited alt"]').waitFor(); + await page.screenshot({ path: ".audit/images-editing.png" }); + await page.locator(".md-image-frame").first().hover(); + await page.getByRole("button", { name: "Zoom in", exact: true }).first().click(); + const zoom = page.getByRole("dialog", { name: "Image zoom" }); + await zoom.waitFor(); + await zoom.getByRole("button", { name: "Zoom in", exact: true }).click(); + assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%"); + await zoom.getByRole("button", { name: "Zoom in", exact: true }).click(); + assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%"); + await page.screenshot({ path: ".audit/images-zoom.png" }); + await zoom.getByRole("button", { name: "Fit image", exact: true }).click(); + await page.keyboard.press("Escape"); + assert.equal(await page.getByRole("dialog").count(), 0); + assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in"); + + // Undo the alt edit and the complete drop as separate operations. + await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click(); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Control+z"); + assert.equal(await source(), original); + await page.keyboard.press("Control+y"); + assert.equal(await source(), inserted); + + // Type and move the cursor during a slow import; the drop follows its original position. + await page.evaluate(() => { window.__TEST__.delay = true; }); + await drop(); + await page.waitForFunction(() => !!window.__TEST__.resume); + await page.evaluate(() => { + const view = window.__CM__; + view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } }); + window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null; + }); + await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3); + assert.ok((await source()).startsWith("Typed while saving.\n\n![]")); + + // Typed local image paths load without changing views, including wiki syntax. + await page.evaluate(path => { + window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]); + const view = window.__CM__; + view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } }); + }, "../attachments/typed.svg"); + await page.locator('img[alt="Wiki image"]').waitFor(); + await save(); + await page.getByRole("button", { name: "Read", exact: true }).click(); + await page.locator(".md-page .md-image-frame").first().hover(); + await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click(); + await page.getByRole("dialog", { name: "Image zoom" }).waitFor(); + await page.keyboard.press("Escape"); + + // Source mode uses the same drop flow; the batch is one undo step. + await page.getByRole("button", { name: "Edit", exact: true }).click(); + await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); + await page.locator(".monaco-editor textarea").waitFor(); + await page.evaluate(async () => { + const { monaco } = await import("/src/lib/editor/monacoEnv.ts"); + window.__MONACO__ = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected); + }); + const sourceBefore = await page.evaluate(() => window.__MONACO__.getValue()); + await drop(2, ".monaco-editor .view-lines"); + await page.waitForFunction(() => (window.__MONACO__.getValue().match(/!\[\]/g) || []).length === 5); + await page.keyboard.press("Control+z"); + assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), sourceBefore); + await page.keyboard.press("Control+y"); + assert.equal((await save()).match(/!\[\]/g).length, 5); + // A failed write leaves source unchanged and surfaces an error. + const beforeFailure = await page.evaluate(() => window.__MONACO__.getValue()); + await page.evaluate(() => { window.__TEST__.failWrite = true; }); + await drop(1, ".monaco-editor .view-lines"); + await page.getByText("Image write failed", { exact: true }).waitFor(); + assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), beforeFailure); + await page.evaluate(() => { window.__TEST__.failWrite = false; }); + + // File drops over a rendered widget are handled by the editor's capture listener. + await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); + await page.locator(".cm-content").waitFor(); + await page.evaluate(async () => { + const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js"); + window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); + }); + await drop(1, ".md-image-frame img >> nth=0"); + await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6); + + // Switching tabs while a write is pending cannot insert into the new document. + await page.evaluate(() => { window.__TEST__.delay = true; }); + await drop(); + await page.waitForFunction(() => !!window.__TEST__.resume); + await openNote("second.md"); + await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); }); + await page.waitForTimeout(100); + assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/")); + // Clipboard images are inserted and remain a single undo operation too. + await page.locator(".cm-content").evaluate(element => { + const data = new DataTransfer(); + data.items.add(new File([''], "pasted.svg", { type: "image/svg+xml" })); + element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data })); + }); + await page.waitForFunction(() => document.querySelector(".md-image-frame img")); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg")); + assert.deepEqual(errors, []); + console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed."); +} catch (error) { + await page.screenshot({ path: ".audit/images-failure.png" }); + console.error(errors); + throw error; +} finally { await browser.close(); } diff --git a/scripts/images.spec.ts b/scripts/images.spec.ts new file mode 100644 index 0000000..f013a33 --- /dev/null +++ b/scripts/images.spec.ts @@ -0,0 +1,55 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { EditorState } from "@codemirror/state"; +import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../src/lib/workspace/media.ts"; +import { imageSource, editImageSource, imageSourceRanges } from "../src/lib/editor/imageSource.ts"; +import { imageDrops, trackImageDrop } from "../src/lib/editor/imageDrop.ts"; + +test("same-name image imports receive distinct safe attachment paths", () => { + const paths = new Set(Array.from({ length: 100 }, () => attachmentRel("photo (1).PNG"))); + assert.equal(paths.size, 100); + assert.ok([...paths].every(path => /^attachments\/[\w.-]+\.PNG$/.test(path))); +}); + +test("protected file drags and files without MIME metadata are recognized", () => { + assert.equal(hasFileDrag({ types: ["Files"], files: [] } as unknown as DataTransfer), true); + assert.equal(hasFileDrag({ types: ["text/plain"] } as unknown as DataTransfer), false); + const files = [{ name: "PHOTO.PNG", type: "" }, { name: "note.md", type: "text/plain" }]; + assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]); +}); + +test("image batches form independent Markdown blocks without extra blank lines", () => { + assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n"); + assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n"); + assert.equal(imageInsertion("before\r\n\r\nafter", 10, 10, ["![](a.png)"]), "![](a.png)\n\n"); +}); + +test("pending image drops follow intervening edits instead of the current caret", () => { + let state = EditorState.create({ doc: "before\nafter", extensions: [imageDrops] }); + const id = Symbol(); + state = state.update({ effects: trackImageDrop.of({ id, from: 7, to: 7 }) }).state; + state = state.update({ changes: { from: 0, insert: "new\n" }, selection: { anchor: 0 } }).state; + assert.deepEqual(state.field(imageDrops).get(id), { from: 11, to: 11 }); +}); + +test("navigator image links are relative and encode Markdown and URL punctuation", () => { + assert.equal(workspaceImageLink("notes/drafts/note.md", "images/a (#1).png"), "![](../../images/a%20%28%231%29.png)"); + assert.equal(workspaceImageLink("notes/note.md", "notes/photo.png"), "![](photo.png)"); + assert.equal(workspaceImageLink("note.md", "日本語/photo%.png"), "![](%E6%97%A5%E6%9C%AC%E8%AA%9E/photo%25.png)"); +}); + +test("image source is explicitly activated, tracks edits, and hides on leaving", () => { + let state = EditorState.create({ doc: "![](a.png)\n\nText", extensions: [imageSource] }); + state = state.update({ selection: { anchor: 0, head: 10 } }).state; + assert.equal(state.field(imageSource), null); + state = state.update({ effects: editImageSource.of({ from: 0, to: 10 }) }).state; + state = state.update({ changes: { from: 2, insert: "Alt" } }).state; + assert.deepEqual(state.field(imageSource), { from: 0, to: 13 }); + state = state.update({ selection: { anchor: state.doc.length } }).state; + assert.equal(state.field(imageSource), null); +}); + +test("image ranges distinguish embeds from code and retain reference and wiki syntax", () => { + const source = "`![](code.png)`\n\nText ![alt]() and ![[a b.png|Photo]]\n\n![ref][photo]\n\n[photo]: x.png\n\n```\n![](code.png)\n```"; + assert.deepEqual(imageSourceRanges(source).map(range => source.slice(range.from, range.to)), ["![alt]()", "![[a b.png|Photo]]", "![ref][photo]"]); +}); diff --git a/scripts/languageFor.spec.ts b/scripts/languageFor.spec.ts new file mode 100644 index 0000000..fbf9284 --- /dev/null +++ b/scripts/languageFor.spec.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { languageFor } from "../src/lib/editor/languageFor.ts"; + +test("markdown files use the markdown language", () => { + assert.equal(languageFor("notes/inbox.md"), "markdown"); + assert.equal(languageFor("README.markdown"), "markdown"); +}); + +test("python and scripts use their languages", () => { + assert.equal(languageFor("src/hello.py"), "python"); + assert.equal(languageFor("tools/setup.sh"), "shell"); +}); + +test("unknown extensions are plaintext", () => { + assert.equal(languageFor("Makefile"), "plaintext"); + assert.equal(languageFor("notes/data.bin"), "plaintext"); +}); diff --git a/scripts/markdownBlocks.spec.ts b/scripts/markdownBlocks.spec.ts new file mode 100644 index 0000000..6ddf410 --- /dev/null +++ b/scripts/markdownBlocks.spec.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { markdownBlocks, markdownFences } from "../src/lib/workspace/markdownBlocks.ts"; + +test("fenced block with a language is one fence", () => { + assert.deepEqual(markdownBlocks("hi\n```js\nconst x = 1\n```\nbye"), [ + { type: "text", line: "hi" }, + { type: "fence", lang: "js", body: "const x = 1" }, + { type: "text", line: "bye" }, + ]); +}); + +test("fenced block without a language keeps an empty lang", () => { + assert.deepEqual(markdownBlocks("```\nHUGE\n```"), [ + { type: "fence", lang: "", body: "HUGE" }, + ]); +}); + +test("inline backticks stay on a text line", () => { + assert.deepEqual(markdownBlocks("say `HUGE` now"), [ + { type: "text", line: "say `HUGE` now" }, + ]); +}); + +test("a fence opened and closed on one line is a fence", () => { + assert.deepEqual(markdownBlocks("```this was a triumph```"), [ + { type: "fence", lang: "", body: "this was a triumph" }, + ]); +}); + +test("closed fence body is the copy payload", () => { + assert.deepEqual(markdownFences("```js\nconst x = 1\n```"), [ + { lang: "js", body: "const x = 1", openLine: 1, closeLine: 3 }, + ]); +}); + +test("one-line fence body excludes ticks", () => { + assert.deepEqual(markdownFences("```this was a triumph```"), [ + { lang: "", body: "this was a triumph", openLine: 1, closeLine: 1 }, + ]); +}); + +test("unclosed fence is not MdFence", () => { + assert.deepEqual(markdownFences("```js\nconst x = 1\n"), []); +}); + +test("markdownBlocks fence body matches markdownFences", () => { + const src = "hi\n```js\nconst x = 1\n```\nbye"; + const block = markdownBlocks(src).find((row) => row.type === "fence"); + const fence = markdownFences(src)[0]; + assert.equal(block && block.type === "fence" ? block.body : null, "const x = 1"); + assert.equal(fence.body, "const x = 1"); + assert.equal(fence.lang, "js"); + assert.equal(fence.openLine, 2); + assert.equal(fence.closeLine, 4); +}); diff --git a/scripts/markdownCommands.spec.ts b/scripts/markdownCommands.spec.ts new file mode 100644 index 0000000..8fef83d --- /dev/null +++ b/scripts/markdownCommands.spec.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { formatText, paragraphText, insertBlock, type MarkdownEdit, type InlineFormat } from "../src/lib/editor/markdownCommands.ts"; + +const apply = (source: string, edit: MarkdownEdit) => source.slice(0, edit.from) + edit.insert + source.slice(edit.to); + +test("inline formatting toggles without losing surrounding prose or the selected text", () => { + for (const format of ["bold", "italic", "strike", "highlight", "code", "math", "comment"] as InlineFormat[]) { + const source = "before words after", selection = { from: 7, to: 12 }; + const edit = formatText(source, selection, format), changed = apply(source, edit); + assert.equal(changed.slice(edit.anchor, edit.head), "words"); + assert.equal(apply(changed, formatText(changed, { from: edit.anchor, to: edit.head }, format)), source, format); + assert.equal(apply(changed, formatText(changed, { from: edit.from, to: edit.from + edit.insert.length }, format)), source, format); + } + assert.equal(apply("word ", formatText("word ", { from: 0, to: 5 }, "bold")), "**word** "); + assert.equal(apply("**bold**", formatText("**bold**", { from: 0, to: 8 }, "italic")), "***bold***"); + const empty = formatText("", { from: 0, to: 0 }, "bold"); + assert.equal(empty.insert, "****"); assert.equal(empty.anchor, 2); assert.equal(empty.head, 2); +}); + +test("code delimiters survive backticks and clear formatting preserves literal punctuation and newlines", () => { + const source = "a ` b", edit = formatText(source, { from: 0, to: source.length }, "code"); + assert.equal(edit.insert, "``a ` b``"); + assert.equal(apply(edit.insert, formatText(edit.insert, { from: edit.anchor, to: edit.head }, "code")), source); + assert.equal(apply(edit.insert, formatText(edit.insert, { from: 0, to: edit.insert.length }, "code")), source); + const rich = "**bold**\r\n==mark== and \\*literal\\*"; + assert.equal(formatText(rich, { from: 0, to: rich.length }, "clear").insert, "bold\r\nmark and \\*literal\\*"); + assert.equal(apply("***bold***", formatText("***bold***", { from: 3, to: 7 }, "clear")), "bold"); +}); + +test("paragraph commands cover selected lines, omit an unselected next line, and preserve indentation and CRLF", () => { + const source = "before\r\n - [x] first\r\n 2. second\r\nafter"; + const selected = { from: source.indexOf("first"), to: source.indexOf("after") }; + assert.equal(apply(source, paragraphText(source, selected, 3)), "before\r\n ### first\r\n ### second\r\nafter"); + assert.equal(apply(source, paragraphText(source, selected, "body")), "before\r\n first\r\n second\r\nafter"); + assert.equal(paragraphText("one\ntwo\n\nthree", { from: 0, to: 14 }, "number").insert, "1. one\n2. two\n\n1. three"); + assert.equal(paragraphText("", { from: 0, to: 0 }, "task").insert, "- [ ] "); + assert.equal(apply("one\ntwo", paragraphText("one\ntwo", { from: 4, to: 4 }, "quote")), "one\n> two"); +}); + +test("block inserts retain adjacent text, escape code fences, and select editable placeholders", () => { + const source = "left right", selection = { from: 5, to: 10 }; + for (const kind of ["table", "rule"] as const) { + const result = apply(source, insertBlock(source, selection, kind)); + assert.ok(result.startsWith(source + "\n\n")); + } + const code = insertBlock("```", { from: 0, to: 3 }, "code"); + assert.equal(code.insert, "````\n```\n````\n\n"); + const table = insertBlock("", { from: 0, to: 0 }, "table"); + assert.equal(table.insert.slice(table.anchor, table.head), "Column 1"); + assert.equal(insertBlock("a\r\nb", { from: 3, to: 4 }, "callout").insert, "\r\n> [!note]\r\n> b\r\n\r\n"); +}); + +test("footnotes get unique references, retain the document tail, and select the definition", () => { + const source = "One[^1] and words.\n\n[^1]: existing\n"; + const from = source.indexOf("words"), edit = insertBlock(source, { from, to: from + 5 }, "footnote"); + const changed = apply(source, edit); + assert.equal(changed, "One[^1] and [^2].\n\n[^1]: existing\n\n[^2]: words\n"); + assert.equal(changed.slice(edit.anchor, edit.head), "words"); +}); diff --git a/scripts/markdownLinks.spec.ts b/scripts/markdownLinks.spec.ts new file mode 100644 index 0000000..3059ed4 --- /dev/null +++ b/scripts/markdownLinks.spec.ts @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { findMarkdownLinks, wikiCandidates } from "../src/lib/workspace/markdownLinks.ts"; + +test("markdown links skip image embeds", () => { + const links = findMarkdownLinks("See [alpha](notes/a.md) and ![shot](pic.png)"); + assert.deepEqual(links, [ + { kind: "md", from: 4, to: 23, label: "alpha", target: "notes/a.md" }, + ]); +}); + +test("wikilinks skip image embeds", () => { + const links = findMarkdownLinks("Go [[projects/alpha|Alpha]] and ![[screenshot.png]]"); + assert.deepEqual(links, [ + { + kind: "wiki", + from: 3, + to: 27, + label: "Alpha", + target: "projects/alpha", + }, + ]); +}); + +test("wikiCandidates add .md for a bare name", () => { + assert.deepEqual(wikiCandidates("alpha"), ["alpha.md", "notes/alpha.md", "alpha"]); +}); + + +import { linkCandidates } from "../src/lib/workspace/markdownLinks.ts"; + +test("links resolve relative to notes, including parent paths and encoded spaces", () => { + assert.deepEqual(linkCandidates("notes/project/inbox.md", "../other%20note.md", "md"), ["notes/other note.md"]); + assert.deepEqual(linkCandidates("notes/inbox.md", "ideas", "wiki"), ["notes/ideas.md", "notes/ideas", "ideas.md", "ideas"]); + assert.deepEqual(linkCandidates("notes/inbox.md", "../../secret", "md"), []); + assert.deepEqual(linkCandidates("notes/inbox.md", "javascript:alert(1)", "md"), []); +}); diff --git a/scripts/markdownMenu.smoke.mjs b/scripts/markdownMenu.smoke.mjs new file mode 100644 index 0000000..c8a38c3 --- /dev/null +++ b/scripts/markdownMenu.smoke.mjs @@ -0,0 +1,207 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(10000); +const errors = []; +const showcase = await readFile(new URL("../fixtures/reader-showcase.md", import.meta.url), "utf8"); +page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); +page.on("pageerror", error => errors.push(error.message)); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\smoke-workspace"; + const files = new Map([ + ["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"], + ["notes/second.md", "# Second note\n"], + ["src/hello.py", "print('hello')\n"], + ]); + const callbacks = new Map(); + const listeners = new Map(); + let sequence = 0; + const calls = []; + const emit = (event, payload) => { + for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); + }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + calls.push({ command, args }); + if (command === "plugin:event|listen") { + const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; + } + if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } + if (command === "workspace_write") { + if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); + files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return; + } + if (command === "workspace_list") { + const prefix = args.rel ? args.rel + "/" : ""; + const entries = new Map(); + for (const path of files.keys()) { + if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue; + const tail = path.slice(prefix.length); const name = tail.split("/")[0]; + entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" }); + } + return [...entries.values()]; + } + if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; } + if (command === "workspace_search") return []; + if (command === "pty_open") { + const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")]; + emit("pty-data", { id: args.id, data: data.slice(0, 8) }); + emit("pty-data", { id: args.id, data: data.slice(8) }); + await new Promise(resolve => setTimeout(resolve, 50)); + return; + } + if (command.startsWith("pty_")) return; + if (command === "plugin:dialog|message") return "Cancel"; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; + window.__TEST__ = { files, calls, emit, root }; +}); + +async function quickOpen(name) { + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill(name); + await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click(); + if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) { + await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); + } + await page.locator(".monaco-editor textarea").waitFor(); +} +async function contents() { + return page.evaluate(async () => { + const { monaco } = await import("/src/lib/editor/monacoEnv.ts"); + return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue(); + }); +} +async function waitForText(text) { + await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; }); + await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text); +} +async function focusEditor() { + await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}}); +} + +try { + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await page.getByText("smoke-workspace", { exact: true }).waitFor(); + await quickOpen("welcome.md"); + const source = "First paragraph.\n\nSecond paragraph.\n"; + await page.evaluate(async value => { + const { monaco } = await import("/src/lib/editor/monacoEnv.ts"); + const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected); + editor.setValue(value); + editor.setSelection(new monaco.Selection(1, 1, 1, 6)); editor.focus(); + }, source); + const menu = page.getByRole("menu", { name: "Markdown text actions", exact: true }); + await page.keyboard.press("Shift+F10"); + await menu.waitFor(); + await menu.getByRole("menuitem", { name: "Format", exact: true }).hover(); + await menu.getByRole("menuitem", { name: "Bold", exact: true }).click(); + await waitForText("**First** paragraph.\n\nSecond paragraph.\n"); + await page.keyboard.press("Control+z"); await waitForText(source); + await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click(); + const writer = page.getByRole("textbox", { name: "Writing editor", exact: true }); + await writer.click(); await page.keyboard.press("Control+Home"); + await page.keyboard.press("Control+Shift+ArrowRight"); + await page.keyboard.press("Shift+F10"); await menu.waitFor(); + await menu.getByRole("menuitem", { name: "Format", exact: true }).hover(); + await menu.getByRole("menuitem", { name: "Italic", exact: true }).click(); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n"); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Control+Home"); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).hover(); + await menu.getByRole("menuitem", { name: "Heading 2", exact: true }).click(); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("## First paragraph.")); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Control+End"); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover(); + await menu.getByRole("menuitem", { name: "Table", exact: true }).click(); + await page.locator(".live-writer table").waitFor(); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Control+Home"); + await page.keyboard.press("Control+Shift+ArrowRight"); + // Mouse invocation must preserve the selection, too. + await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } }); + await menu.waitFor(); + await menu.getByRole("menuitem", { name: "Format", exact: true }).hover(); + await menu.getByRole("menuitem", { name: "Highlight", exact: true }).click(); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph.")); + await page.keyboard.press("Control+End"); + await page.locator(".writer-highlight").waitFor(); + assert.equal(await page.locator(".writer-highlight").textContent(), "First"); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Control+End"); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover(); + await page.screenshot({ path: ".audit/markdown-insert-menu.png" }); + await page.keyboard.press("Escape"); + await page.setViewportSize({ width: 760, height: 600 }); + await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + await writer.focus(); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).focus(); + await page.keyboard.press("ArrowRight"); + assert.equal(await page.evaluate(() => document.activeElement.textContent), "Bullet list"); + const rect = await menu.getByRole("menu", { name: "Paragraph", exact: true }).boundingBox(); + assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 760 && rect.y + rect.height <= 600); + await page.screenshot({ path: ".audit/markdown-paragraph-menu.png" }); + await page.keyboard.press("ArrowLeft"); + assert.equal(await page.evaluate(() => document.activeElement.textContent), "Paragraph"); + await page.keyboard.press("Escape"); + await page.keyboard.press("Control+Home"); + await page.keyboard.press("Control+Shift+ArrowRight"); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Add external link", exact: true }).click(); + await page.getByRole("textbox", { name: "External link URL" }).fill("https://example.com/a(b)"); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a%28b%29) paragraph.")); + await page.keyboard.press("Control+z"); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Extract current selection…", exact: true }).click(); + await page.getByRole("textbox", { name: "Extract selection to a new note (workspace relative path)" }).fill("notes/extracted.md"); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[[/notes/extracted.md|First]] paragraph.")); + assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/extracted.md")), "First\n"); + await page.keyboard.press("Control+z"); + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + await page.evaluate(() => navigator.clipboard.writeText("Pasted")); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click(); + await page.waitForFunction(() => document.querySelector(".cm-content")?.textContent.includes("Pasted paragraph.")); + await page.keyboard.press("Control+s"); + await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("Pasted paragraph.")); + await page.evaluate(() => { navigator.clipboard.readText = () => new Promise(resolve => { window.__finishPaste = resolve; }); }); + await page.keyboard.press("Shift+F10"); + await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click(); + await writer.focus(); await page.keyboard.press("End"); await page.keyboard.type(" kept"); + await page.evaluate(async () => { window.__finishPaste("STALE"); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); }); + assert.ok(!(await writer.textContent()).includes("STALE")); + assert.ok((await writer.textContent()).includes("kept")); + assert.deepEqual(errors, []); + console.log("PASS: Markdown menus in source/writing modes, selection retention, formatting, paragraph conversion, table insertion, undo, keyboard navigation, narrow viewport, links, extraction, clipboard and stale-selection guards."); +} catch (error) { + console.error("Browser errors:", errors); + console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000)); + await page.screenshot({ path: ".audit/markdown-menu-failure.png" }); + throw error; +} finally { await browser.close(); } diff --git a/scripts/markdownTable.spec.ts b/scripts/markdownTable.spec.ts new file mode 100644 index 0000000..c2e0d73 --- /dev/null +++ b/scripts/markdownTable.spec.ts @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../src/lib/editor/markdownTable.ts"; +import { tableCellMarkdown, extractedCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts"; +import { renderMarkdownHtml } from "../src/lib/workspace/noteHtml.ts"; + +const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First
Second |"; + +test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => { + assert.equal(extractedCellMarkdown([ + { type: "text", text: "Title", marks: [{ type: "bold" }] }, + { type: "hardBreak" }, + { type: "text", text: "
", marks: [{ type: "code" }] }, + ]), "**Title**\n`
`"); +}); + +test("table column insertion retains alignment and existing cell contents", () => { + assert.equal(appendTableColumn(table), "| Ticker | Notes | |\n| :--- | ---: | --- |\n| IBKR.US | First
Second | |"); +}); + +test("table row insertion keeps existing source byte-for-byte", () => { + assert.equal(appendTableRow(table + "\n\n"), table + "\n| | |\n\n"); +}); + +test("table edits preserve CRLF and optional outer pipes", () => { + const source = "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n"; + assert.equal(appendTableRow(source), "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n| | |\r\n"); + assert.equal(appendTableColumn(source), "| Name | Link | |\r\n| --- | :---: | --- |\r\n| One | [note](note.md) | |\r\n"); +}); + +test("escaped pipes in text, wiki aliases, and inline code stay inside cells", () => { + const source = "| One | Two |\n| --- | --- |\n| [[note\\|Alias]] | `a\\|b` and text\\|value |"; + const parsed = parseMarkdownTable(source)!; + assert.equal(parsed.rows[2].cells.length, 2); + const changed = appendTableColumn(source); + assert.ok(changed.includes("| [[note\\|Alias]] | `a\\|b` and text\\|value | |")); + for (const row of parsed.rows) for (const cell of row.cells) assert.equal(source.slice(cell.from, cell.to), cell.text); +}); + +test("adding columns pads short rows without losing extra source cells", () => { + const source = "| A | B |\n| --- | --- |\n| short |\n| a | b | extra |"; + assert.equal(appendTableColumn(source), "| A | B | |\n| --- | --- | --- |\n| short | | |\n| a | b | | extra |"); +}); + +test("table controls handle header-only and single-column tables", () => { + assert.equal(appendTableRow("| Header |\n| --- |"), "| Header |\n| --- |\n| |"); + assert.equal(parseMarkdownTable(appendTableColumn("| Header |\n| --- |"))?.columns, 2); +}); + +test("invalid tables are unchanged", () => { + for (const source of ["Just text", "| A | B |\n| --- |", "| A |\n| not a delimiter |"] ) { + assert.equal(parseMarkdownTable(source), null); + assert.equal(appendTableColumn(source), source); + assert.equal(appendTableRow(source), source); + } +}); + +test("editing one cell preserves padding, alignment, other cells and CRLF", () => { + const source = " | Name | Notes |\r\n | :--- | ---: |\r\n | One | first
~~old~~ |\r\n\r\nTail"; + assert.equal(replaceTableCell(source, 2, 1, "next
line\\|pipe"), source.replace("first
~~old~~", "next
line\\|pipe")); + assert.equal(replaceTableCell(source, 0, 0, "Title"), source.replace("Name", "Title")); + assert.equal(replaceTableCell(source, 1, 0, "bad"), source); + assert.equal(replaceTableCell(source, 2, 1, "break\nrow"), source); +}); + +test("editing an empty or omitted cell does not overwrite its neighbor", () => { + assert.equal(replaceTableCell("| A | B |\n| --- | --- |\n| short |", 2, 1, "new"), "| A | B |\n| --- | --- |\n| short | new |"); + const source = "| A | B |\n| --- | --- |\n| | value |"; + assert.equal(replaceTableCell(source, 2, 0, "new"), source.replace("| | value", "| new| value")); +}); + +test("rich cell serialization retains breaks, formatting, links and literal punctuation", () => { + const text = tableCellMarkdown({ type: "doc", content: [{ type: "paragraph", content: [ + { type: "text", text: "old", marks: [{ type: "strike" }] }, + { type: "hardBreak" }, + { type: "text", text: "bold", marks: [{ type: "bold" }] }, + { type: "text", text: " | *literal*
& value" }, + { type: "hardBreak" }, + { type: "text", text: "a|`b", marks: [{ type: "code" }] }, + { type: "text", text: "note", marks: [{ type: "link", attrs: { href: "note.md", "data-kind": "wiki" } }] }, + { type: "text", text: "web", marks: [{ type: "link", attrs: { href: "https://example.com/a(b)" } }] }, + ] }, { type: "paragraph", content: [{ type: "text", text: "Pasted paragraph" }] }] }); + const source = `| A |\n| --- |\n| ${text} |`; + assert.equal(parseMarkdownTable(source)?.rows[2].cells.length, 1); + const html = renderMarkdownHtml(source, new Map()); + assert.ok(html.includes("old")); + assert.ok(html.includes("bold")); + assert.ok(html.includes("| *literal* <br> & value")); + assert.ok(html.includes("a|`b")); + assert.ok(html.includes('href="note.md" data-kind="wiki"')); + assert.ok(html.includes('href="https://example.com/a(b)"')); + assert.equal((html.match(/
/g) || []).length, 3); +}); diff --git a/scripts/media.spec.ts b/scripts/media.spec.ts new file mode 100644 index 0000000..9f9aec2 --- /dev/null +++ b/scripts/media.spec.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + findMarkdownImages, + isImagePath, + isRemoteImage, + resolveImageRel, +} from "../src/lib/workspace/media.ts"; + +test("image paths are detected by extension", () => { + assert.equal(isImagePath("screenshot.png"), true); + assert.equal(isImagePath("notes/photo.JPEG"), true); + assert.equal(isImagePath("notes/inbox.md"), false); +}); + +test("markdown image syntax is parsed", () => { + const found = findMarkdownImages("See ![alt](../shot.png) and ![[screenshot.png|Hero]]"); + assert.equal(found.length, 2); + assert.equal(found[0].src, "../shot.png"); + assert.equal(found[0].kind, "md"); + assert.equal(found[1].src, "screenshot.png"); + assert.equal(found[1].alt, "Hero"); + assert.equal(found[1].kind, "wiki"); +}); + +test("image paths resolve from the note folder", () => { + assert.equal(resolveImageRel("notes/inbox.md", "pic.png"), "notes/pic.png"); + assert.equal(resolveImageRel("notes/inbox.md", "../screenshot.png"), "screenshot.png"); + assert.equal(resolveImageRel("notes/inbox.md", "screenshot.png"), "notes/screenshot.png"); + assert.equal(resolveImageRel("notes/inbox.md", "/assets/pic.png"), "assets/pic.png"); +}); + +test("remote images stay as URLs", () => { + assert.equal(isRemoteImage("https://example.com/a.png"), true); + assert.equal(isRemoteImage("screenshot.png"), false); +}); diff --git a/scripts/noteHtml.spec.ts b/scripts/noteHtml.spec.ts new file mode 100644 index 0000000..0c50f50 --- /dev/null +++ b/scripts/noteHtml.spec.ts @@ -0,0 +1,60 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts"; + +test("headings and inline marks become markdown", () => { + const html = + "

Heading 1

Heading 2

hello bold and code

"; + assert.equal(htmlToMarkdown(html), "# Heading 1\n## Heading 2\nhello **bold** and `code`"); +}); + +test("fences keep language and body", () => { + const html = '
const x = 1
'; + assert.equal(htmlToMarkdown(html), "```js\nconst x = 1\n```"); +}); + +test("wiki and markdown links become markdown", () => { + const html = + '

see projects/alpha and label

'; + assert.equal(htmlToMarkdown(html), "see [[projects/alpha]] and [label](notes/a.md)"); +}); + +test("wiki image uses data-md-kind", () => { + const html = + '

screenshot.png

'; + assert.equal(htmlToMarkdown(html), "![[screenshot.png]]"); +}); + +test("strike super and sub become markdown", () => { + const html = "

old x2 an

"; + assert.equal(htmlToMarkdown(html), "~~old~~ x^2^ a~n~"); +}); + +test("gfm table becomes markdown", () => { + const html = + "
AB
12
"; + assert.equal(htmlToMarkdown(html), "| A | B |\n| --- | --- |\n| 1 | 2 |"); +}); + +test("checked task item becomes a checkbox line", () => { + const html = + '
  • done

'; + assert.equal(htmlToMarkdown(html), "- [x] done"); +}); + +test("unchecked task item becomes an empty checkbox", () => { + const html = + '
  • todo

'; + assert.equal(htmlToMarkdown(html), "- [ ] todo"); +}); + +test("italic highlight math and comment become markdown", () => { + const html = + '

hi glow x^2 note

'; + assert.equal(htmlToMarkdown(html), "*hi* ==glow== $x^2$ %%note%%"); +}); + +test("blockquote and numbered list become markdown", () => { + const html = "

said

  1. one
  2. two
"; + assert.equal(htmlToMarkdown(html), "> said\n1. one\n2. two"); +}); diff --git a/scripts/reader.spec.ts b/scripts/reader.spec.ts new file mode 100644 index 0000000..a48bb24 --- /dev/null +++ b/scripts/reader.spec.ts @@ -0,0 +1,103 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { markdownImages, renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts"; + +const render = (text: string) => renderMarkdownHtml(text, new Map()); + +test("writing sections retain exact source ranges and document-wide references", () => { + const source = '\uFEFF---\r\ntitle: Draft\r\n---\r\n\r\n# Heading\r\n\r\n- Parent\r\n - Child\r\n\r\nA [reference][ref].\r\n\r\n[ref]: https://example.com\r\n'; + const sections = renderMarkdownSections(source, new Map()); + assert.equal(sections.map(section => source.slice(section.start, section.end)).join(""), source); + assert.equal(sections.length, 4); + assert.match(sections[2].html, /
    [\s\S]*
      /); + assert.match(sections[3].html, /href="https:\/\/example.com"/); + const paragraph = sections[3]; + const edited = source.slice(0, paragraph.start) + 'Changed paragraph.\r\n' + source.slice(paragraph.end); + assert.equal(edited.slice(0, paragraph.start), source.slice(0, paragraph.start)); +}); + +test("writing exposes empty and reference-only documents for editing", () => { + for (const source of ["", "\n\n", "[ref]: https://example.com\n"]) { + assert.deepEqual(renderMarkdownSections(source, new Map()), [{ start: 0, end: source.length, html: "" }]); + } +}); + +test("Mermaid fences render diagram containers with escaped, copyable source", () => { + const html = render('```mermaid\nflowchart LR\n A[""] --> B\n```'); + assert.match(html, /class="md-mermaid"/); + assert.match(html, /aria-label="Mermaid diagram"/); + assert.match(html, /Diagram source<\/summary>/); + assert.match(html, /<script>bad<\/script>/); + assert.doesNotMatch(html, /";\n```\n\n`[[literal]]`\n\n'); + assert.match(html, /aria-label="Copy code"/); + assert.match(html, /\[\[note\]\] \*\*bold\*\* <script>/); + assert.match(html, /\[\[literal\]\]<\/code>/); + assert.doesNotMatch(html, / + +
      { + if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) { + event.preventDefault(); + if (event.dataTransfer) event.dataTransfer.dropEffect = "copy"; + } + }} + ondropcapture={(event) => { + void takeImages(event, event.dataTransfer); + }} + onpastecapture={(event) => { + void takeImages(event, event.clipboardData); + }} +>
      +{#if loadError}{/if} + + diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte new file mode 100644 index 0000000..dbd83ae --- /dev/null +++ b/src/lib/editor/LiveWriter.svelte @@ -0,0 +1,356 @@ + + +
      { + if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return; + event.preventDefault(); + if (event.dataTransfer) event.dataTransfer.dropEffect = "copy"; + }} + ondropcapture={(event) => { if (editor) void insertImages(event, editor); }} +>
      +{#if error}{/if} + + diff --git a/src/lib/editor/WriterHost.svelte b/src/lib/editor/WriterHost.svelte new file mode 100644 index 0000000..39799d9 --- /dev/null +++ b/src/lib/editor/WriterHost.svelte @@ -0,0 +1,283 @@ + + +
      { + if (imageFiles(event.dataTransfer).length > 0) { + event.preventDefault(); + } + }} + ondrop={(event) => { + const files = imageFiles(event.dataTransfer); + if (files.length === 0 || !onInsertImage) { + return; + } + event.preventDefault(); + void (async () => { + for (const file of files) { + const snippet = await onInsertImage(file); + const rel = snippet ? /\(([^)]+)\)/.exec(snippet)?.[1] : null; + if (!rel || !editor) { + continue; + } + try { + const src = await workspaceReadDataUrl(rel); + editor.commands.insertContent( + `${file.name}`, + ); + } catch { + editor.commands.insertContent(snippet); + } + } + })(); + }} +>
      + +{#if menu} + (menu = null)} + /> +{/if} + + diff --git a/src/lib/editor/headingMarks.ts b/src/lib/editor/headingMarks.ts new file mode 100644 index 0000000..1b6cf96 --- /dev/null +++ b/src/lib/editor/headingMarks.ts @@ -0,0 +1,90 @@ +import { Extension } from "@tiptap/core"; +import type { Node as PmNode } from "@tiptap/pm/model"; +import { Plugin, PluginKey } from "@tiptap/pm/state"; +import { Decoration, DecorationSet } from "@tiptap/pm/view"; + +export function headingMarkText(level: number): string { + const n = Math.min(6, Math.max(1, Math.floor(level))); + return "#".repeat(n); +} + +export function fenceOpenText(lang: string): string { + const name = lang.trim(); + return name ? `\`\`\`${name}` : "```"; +} + +export function findInlineCodeRange(doc: PmNode, pos: number): { from: number; to: number } | null { + const $pos = doc.resolve(pos); + const type = doc.type.schema.marks.code; + if (!type || !$pos.parent.inlineContent) { + return null; + } + const parentStart = $pos.start(); + let runFrom = -1; + let runTo = -1; + let hit: { from: number; to: number } | null = null; + $pos.parent.forEach((child, offset) => { + const from = parentStart + offset; + const to = from + child.nodeSize; + if (type.isInSet(child.marks)) { + if (runFrom === -1) { + runFrom = from; + } + runTo = to; + return; + } + if (runFrom !== -1 && pos >= runFrom && pos <= runTo) { + hit = { from: runFrom, to: runTo }; + } + runFrom = -1; + runTo = -1; + }); + if (hit) { + return hit; + } + if (runFrom !== -1 && pos >= runFrom && pos <= runTo) { + return { from: runFrom, to: runTo }; + } + return null; +} + +export const HeadingMarks = Extension.create({ + name: "headingMarks", + addProseMirrorPlugins() { + return [ + new Plugin({ + key: new PluginKey("headingMarks"), + props: { + decorations(state) { + const { $from } = state.selection; + if ($from.parent.type.name === "codeBlock") { + const lang = String($from.parent.attrs.language ?? ""); + return DecorationSet.create(state.doc, [ + Decoration.node($from.before(), $from.after(), { + class: "is-editing", + "data-fence-open": fenceOpenText(lang), + }), + ]); + } + if ($from.parent.type.name === "heading") { + const level = Number($from.parent.attrs.level ?? 1); + return DecorationSet.create(state.doc, [ + Decoration.node($from.before(), $from.after(), { + class: "is-editing", + "data-heading-marks": headingMarkText(level), + }), + ]); + } + const range = findInlineCodeRange(state.doc, $from.pos); + if (!range) { + return DecorationSet.empty; + } + return DecorationSet.create(state.doc, [ + Decoration.inline(range.from, range.to, { class: "is-editing-ticks" }), + ]); + }, + }, + }), + ]; + }, +}); diff --git a/src/lib/editor/imageControls.ts b/src/lib/editor/imageControls.ts new file mode 100644 index 0000000..ee304f5 --- /dev/null +++ b/src/lib/editor/imageControls.ts @@ -0,0 +1,170 @@ +import { actionIcon, type ActionIcon } from "../ui/actionIcons"; +import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; + +export type ImageActions = { + edit?: () => void; + done?: () => void; + editing?: boolean; + select?: () => void; + remove?: () => void; + markdown?: () => string; + swap?: (image: HTMLImageElement) => Promise; + open?: (image: HTMLImageElement) => void; + reveal?: (image: HTMLImageElement) => Promise; + report?: (message: string) => void; +}; + +async function copyImage(image: HTMLImageElement) { + const png = (async () => { + await image.decode(); + const canvas = document.createElement("canvas"); + canvas.width = image.naturalWidth; canvas.height = image.naturalHeight; + const context = canvas.getContext("2d"); + if (!context) throw new Error("Image clipboard is unavailable."); + context.drawImage(image, 0, 0); + return await new Promise((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png")); + })(); + await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]); +} + +function button(label: string, icon: ActionIcon, action: () => void) { + const control = document.createElement("button"); + control.type = "button"; + control.className = "image-action"; + control.setAttribute("aria-label", label); + control.dataset.tooltip = label; + control.append(actionIcon(icon)); + control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); }); + return control; +} + +function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) { + const dialog = document.createElement("dialog"); + dialog.className = "image-lightbox"; + dialog.setAttribute("aria-label", "Image zoom"); + const header = document.createElement("div"); + header.className = "image-lightbox-toolbar"; + const name = document.createElement("span"); + name.className = "image-lightbox-name"; + name.textContent = original.dataset.mdSrc || original.alt || "Image"; + const viewport = document.createElement("div"); + viewport.className = "image-lightbox-viewport"; + const image = original.cloneNode() as HTMLImageElement; + image.removeAttribute("loading"); + image.draggable = false; + let scale = 0; + const status = document.createElement("span"); + status.className = "image-lightbox-scale"; + status.setAttribute("aria-live", "polite"); + function resize(next: number) { + scale = next; + image.style.width = scale ? `${image.naturalWidth * scale}px` : ""; + viewport.classList.toggle("is-zoomed", scale > 0); + status.textContent = scale ? `${Math.round(scale * 100)}%` : "Fit"; + zoomOut.disabled = scale === 0; + zoomIn.disabled = scale >= 4; + } + const zoomOut = button("Zoom out", "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2)); + const zoomIn = button("Zoom in", "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1)); + const fit = button("Fit image", "select", () => resize(0)); + const close = button("Close image", "close", () => dialog.close()); + header.append(name, zoomOut, status, zoomIn, fit, close); + viewport.append(image); + dialog.append(header, viewport); + dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); }); + // Escape and focus trapping are provided by the native modal dialog. + dialog.addEventListener("close", () => { dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true }); + image.addEventListener("load", () => resize(scale)); + document.body.append(dialog); + dialog.showModal(); + resize(0); + close.focus(); + return () => { if (dialog.isConnected) dialog.close(); }; +} + +export function imageControls(root: HTMLElement, actions: ImageActions = {}, measure?: () => void): () => void { + const cleanup: (() => void)[] = []; + for (const image of root.querySelectorAll("img[data-md-src]")) { + if (image.closest(".md-image-frame")) continue; + const frame = document.createElement("span"); + frame.className = "md-image-frame"; + frame.contentEditable = "false"; + frame.tabIndex = 0; + frame.setAttribute("role", "group"); + frame.setAttribute("aria-label", `Image: ${image.alt || image.dataset.mdSrc || "image"}`); + image.replaceWith(frame); + frame.append(image); + image.draggable = false; + const toolbar = document.createElement("span"); + toolbar.className = "md-image-actions"; + let closeZoom: (() => void) | undefined; + const zoom = button("Zoom in", "zoom-in", () => { closeZoom = zoomImage(image, zoom); }); + cleanup.push(() => closeZoom?.()); + toolbar.append(zoom); + if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit)); + frame.append(toolbar); + let menu: HTMLElement | undefined; + let openingMenu = false; + function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); } + async function run(action: () => void | Promise) { + closeMenu(false); + try { await action(); } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (actions.report) actions.report(message); + else { frame.dataset.error = message; frame.setAttribute("aria-description", message); } + } + } + function select() { + actions.select?.(); + frame.classList.add("is-selected"); + frame.focus({ preventScroll: true }); + } + function openMenu(x: number, y: number) { + closeMenu(false); select(); + const items: ActionMenuItem[] = [ + { label: "Copy image", icon: "copy", run: () => void run(() => copyImage(image)) }, + ...(actions.markdown ? [{ label: "Copy Markdown", icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []), + ...(actions.swap ? [{ label: "Swap image…", icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []), + ...(actions.remove ? [{ label: "Remove image", icon: "trash" as const, run: () => void run(actions.remove!) }] : []), + { separator: true }, + { label: "Zoom in", icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } }, + ...(actions.edit ? [{ label: "Edit image source", icon: "code" as const, run: () => void run(actions.edit!) }] : []), + ...(actions.open ? [{ label: "Open in new tab", icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []), + { label: "Copy path", icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) }, + ...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: "Show in Explorer", icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []), + ]; + openingMenu = true; + try { menu = actionMenu(x, y, items, closeMenu, "Image actions"); } + finally { openingMenu = false; } + } + frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } }); + frame.addEventListener("contextmenu", event => { event.preventDefault(); event.stopPropagation(); openMenu(event.clientX, event.clientY); }); + frame.addEventListener("keydown", event => { + if (event.target !== frame) return; + if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) { + event.preventDefault(); event.stopPropagation(); const rect = frame.getBoundingClientRect(); openMenu(rect.left + 16, rect.top + 16); + } else if ((event.key === "Delete" || event.key === "Backspace") && actions.remove) { + event.preventDefault(); event.stopPropagation(); actions.remove(); + } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c") { + event.preventDefault(); event.stopPropagation(); void run(() => copyImage(image)); + } else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); } + }); + const outside = (event: Event) => { + if (openingMenu) return; + if (event.target instanceof Node && !frame.contains(event.target) && !menu?.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); } + }; + const dismiss = () => closeMenu(false); + const scroll = (event: Event) => { if (menu && event.target instanceof Node && !menu.contains(event.target)) closeMenu(false); }; + document.addEventListener("mousedown", outside, true); + document.addEventListener("focusin", outside, true); + window.addEventListener("resize", dismiss); + document.addEventListener("scroll", scroll, true); + cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); window.removeEventListener("resize", dismiss); document.removeEventListener("scroll", scroll, true); }); + if (measure) { + image.addEventListener("load", measure); + image.addEventListener("error", measure); + cleanup.push(() => { image.removeEventListener("load", measure); image.removeEventListener("error", measure); }); + } + } + return () => cleanup.forEach(dispose => dispose()); +} diff --git a/src/lib/editor/imageDrop.ts b/src/lib/editor/imageDrop.ts new file mode 100644 index 0000000..f9d5e85 --- /dev/null +++ b/src/lib/editor/imageDrop.ts @@ -0,0 +1,18 @@ +import { StateEffect, StateField } from "@codemirror/state"; + +export const trackImageDrop = StateEffect.define<{ id: symbol; from: number; to: number }>(); +export const clearImageDrop = StateEffect.define(); +export const imageDrops = StateField.define>({ + create: () => new Map(), + update(value, transaction) { + const next = new Map([...value].map(([id, range]) => [id, { + from: transaction.changes.mapPos(range.from, 1), + to: transaction.changes.mapPos(range.to, 1), + }])); + for (const effect of transaction.effects) { + if (effect.is(trackImageDrop)) next.set(effect.value.id, effect.value); + if (effect.is(clearImageDrop)) next.delete(effect.value); + } + return next; + }, +}); diff --git a/src/lib/editor/imagePreview.ts b/src/lib/editor/imagePreview.ts new file mode 100644 index 0000000..4cf4c1e --- /dev/null +++ b/src/lib/editor/imagePreview.ts @@ -0,0 +1,76 @@ +import { EditorView, WidgetType } from "@codemirror/view"; +import { isolateHistory } from "@codemirror/commands"; +import { imageControls, type ImageActions } from "./imageControls"; +import { editImageSource } from "./imageSource"; +import { requestText } from "../workspace/dialogs.svelte"; +import { isRemoteImage } from "../workspace/media"; +import { actionIcon } from "../ui/actionIcons"; + +export type ImageContext = { + open?: (image: HTMLImageElement) => void; + reveal?: (image: HTMLImageElement) => Promise; + validate?: (source: string) => Promise; + report?: (message: string) => void; +}; +const cleanups = new WeakMap void>(); + +export class ImagePreview extends WidgetType { + constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); } + eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; } + toDOM(view: EditorView) { + const dom = document.createElement(this.block ? "div" : "span"); + dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`; + dom.innerHTML = this.html; + const range = () => { + const position = view.posAtDOM(dom); + const from = this.editing ? position - this.source.length : position; + return { from, to: from + this.source.length }; + }; + const replace = (insert: string) => { + if (!dom.isConnected) return; + const target = range(); + view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, effects: editImageSource.of(null), annotations: isolateHistory.of("full"), userEvent: "input.image" }); + view.focus(); + }; + const actions: ImageActions = { + editing: this.editing, + select: () => { const { from, to } = range(); view.dispatch({ selection: { anchor: from, head: to } }); }, + edit: () => { + const target = range(); + view.dispatch({ effects: [editImageSource.of(target), EditorView.scrollIntoView(target.from, { y: "nearest" })], selection: { anchor: target.from, head: target.to } }); + view.focus(); + }, + done: () => { view.dispatch({ effects: editImageSource.of(null) }); view.focus(); }, + remove: () => replace(""), + markdown: () => this.source, + open: this.context.open, + reveal: this.context.reveal, + report: this.context.report, + swap: async image => { + const before = view.state.doc; + const path = (await requestText("Image path relative to this note, or https URL", image.dataset.mdSrc || ""))?.trim(); + if (!path || !dom.isConnected || view.state.doc !== before) return; + if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error("Choose a workspace image path or an http/https URL."); + await this.context.validate?.(path); + if (!dom.isConnected || view.state.doc !== before) return; + const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char)); + const alt = image.alt.replace(/[\\\[\]]/g, "\\$&"); + replace(`![${alt}](<${target}>)`); + }, + }; + cleanups.set(dom, imageControls(dom, actions, () => { if (dom.isConnected) view.requestMeasure(); })); + // A missing attachment must still offer a way to repair its hidden source. + if (!dom.querySelector("img")) { + const edit = document.createElement("button"); + edit.type = "button"; edit.className = "image-action"; + const label = this.editing ? "Hide image source" : "Edit image source"; + edit.setAttribute("aria-label", label); edit.dataset.tooltip = label; + edit.append(actionIcon("code")); + edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); }); + dom.append(edit); + } + return dom; + } + destroy(dom: HTMLElement) { cleanups.get(dom)?.(); } + ignoreEvent() { return true; } +} diff --git a/src/lib/editor/imageSource.ts b/src/lib/editor/imageSource.ts new file mode 100644 index 0000000..fb5e7de --- /dev/null +++ b/src/lib/editor/imageSource.ts @@ -0,0 +1,22 @@ +import { StateEffect, StateField } from "@codemirror/state"; +import { markdownLanguage } from "@codemirror/lang-markdown"; + +export type ImageRange = { from: number; to: number }; +export function imageSourceRanges(source: string): ImageRange[] { + const ranges: ImageRange[] = []; + // Image controls must also work beyond CodeMirror's partially parsed viewport. + markdownLanguage.parser.parse(source).iterate({ enter(node) { + if (node.name === "Image") { ranges.push({ from: node.from, to: node.to }); return false; } + } }); + return ranges; +} +export const editImageSource = StateEffect.define(); +export const imageSource = StateField.define({ + create: () => null, + update(value, transaction) { + if (value) value = { from: transaction.changes.mapPos(value.from, -1), to: transaction.changes.mapPos(value.to, 1) }; + for (const effect of transaction.effects) if (effect.is(editImageSource)) value = effect.value; + if (value && transaction.selection && !transaction.selection.ranges.some(range => range.from <= value.to && range.to >= value.from)) return null; + return value; + }, +}); diff --git a/src/lib/editor/languageFor.ts b/src/lib/editor/languageFor.ts new file mode 100644 index 0000000..38566c9 --- /dev/null +++ b/src/lib/editor/languageFor.ts @@ -0,0 +1,39 @@ +const LANGUAGES: Record = { + md: "markdown", + markdown: "markdown", + mdown: "markdown", + txt: "plaintext", + py: "python", + js: "javascript", + mjs: "javascript", + cjs: "javascript", + ts: "typescript", + tsx: "typescript", + jsx: "javascript", + json: "json", + css: "css", + scss: "scss", + html: "html", + htm: "html", + rs: "rust", + sh: "shell", + bash: "shell", + yml: "yaml", + yaml: "yaml", + toml: "ini", + xml: "xml", + svg: "xml", +}; + +function fileExt(relPath: string): string { + const base = relPath.split("/").pop() ?? relPath; + const dot = base.lastIndexOf("."); + if (dot <= 0) { + return ""; + } + return base.slice(dot + 1).toLowerCase(); +} + +export function languageFor(relPath: string): string { + return LANGUAGES[fileExt(relPath)] ?? "plaintext"; +} diff --git a/src/lib/editor/liveMarkdown.ts b/src/lib/editor/liveMarkdown.ts new file mode 100644 index 0000000..8abf6f8 --- /dev/null +++ b/src/lib/editor/liveMarkdown.ts @@ -0,0 +1,173 @@ +import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state"; +import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view"; +import { syntaxTree } from "@codemirror/language"; +import { renderMarkdownSections } from "../workspace/noteHtml"; +import { renderDiagrams } from "../workspace/diagrams"; +import { tableControls, tableEditors } from "./tableControls"; +import { parseMarkdownTable } from "./markdownTable"; +import type { TableContextActions } from "./tableCellActions"; +import { imageControls } from "./imageControls"; +import { ImagePreview, type ImageContext } from "./imagePreview"; +import { imageSource, editImageSource, imageSourceRanges } from "./imageSource"; + +export const refreshImages = StateEffect.define(); +const imageCleanups = new WeakMap void>(); + +class Checkbox extends WidgetType { + constructor(readonly checked: boolean) { super(); } + eq(other: Checkbox) { return this.checked === other.checked; } + toDOM(view: EditorView) { + const box = document.createElement("input"); + box.type = "checkbox"; + box.checked = this.checked; + box.className = "writer-checkbox"; + box.setAttribute("aria-label", this.checked ? "Mark task incomplete" : "Mark task complete"); + box.addEventListener("mousedown", event => event.preventDefault()); + box.addEventListener("click", event => { + event.stopPropagation(); + const line = view.state.doc.lineAt(view.posAtDOM(box)); + const match = /^(\s*[-+*]\s+\[)([ xX])(\])/.exec(line.text); + if (!match) return; + const from = line.from + match[1].length; + view.dispatch({ changes: { from, to: from + 1, insert: this.checked ? " " : "x" }, userEvent: "input" }); + }); + return box; + } + ignoreEvent() { return true; } +} + +class Preview extends WidgetType { + constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false) { super(); } + eq(other: Preview) { return other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; } + updateDOM(dom: HTMLElement) { return tableEditors.get(dom)?.source === this.source; } + destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); } + toDOM(view: EditorView) { + const dom = document.createElement("div"); + dom.className = "reading writer-preview"; + dom.innerHTML = this.html; + tableControls(dom, view, this.source, this.actions); + imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); })); + dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove()); + dom.addEventListener("mousedown", event => { + if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return; + if (event.target instanceof Element && event.target.closest("summary, .md-image-frame")) return; + if (event.ctrlKey || event.metaKey) return; + event.preventDefault(); + view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true }); + view.focus(); + }); + requestAnimationFrame(() => { + if (dom.isConnected) { + void renderDiagrams(dom, () => !dom.isConnected).then(() => view.requestMeasure()); + view.requestMeasure(); + } + }); + return dom; + } + ignoreEvent() { return true; } +} + +export function liveMarkdown(urls: Map, actions: TableContextActions = {}, images: ImageContext = {}) { + function build(state: EditorState): DecorationSet { + const ranges: Range[] = []; + const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to })); + const selected = (from: number, to: number) => active.some(range => range.from <= to && range.to >= from); + const hiddenBlocks: { from: number; to: number }[] = []; + const source = state.doc.toString(); + const editing = state.field(imageSource); + const imageNodes = imageSourceRanges(source); + for (const section of renderMarkdownSections(source, urls)) { + if (!/(?:/.test(section.html)) section.start += /^(?:[ \t]*\r?\n)+/.exec(source.slice(section.start, section.end))?.[0].length ?? 0; + const end = section.end - (source.slice(section.start, section.end).match(/\n+$/)?.[0].length || 0); + const isTable = //.test(section.html) && parseMarkdownTable(source.slice(section.start, end)); + if (end <= section.start) continue; + const imageHtml = section.html.match(/]*>|]*>[\s\S]*?<\/span>/g) || []; + const nodes = imageNodes.filter(node => node.from >= section.start && node.to <= end); + if (!isTable && imageHtml.length && imageHtml.length === nodes.length && (!/md-callout/.test(section.html) || selected(section.start, end))) { + nodes.forEach((node, index) => { + const revealed = editing?.from === node.from; + const block = state.doc.lineAt(node.from).from === node.from && state.doc.lineAt(node.to).to === node.to; + const widget = new ImagePreview(imageHtml[index], source.slice(node.from, node.to), images, revealed, revealed || block); + if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to)); + else { + hiddenBlocks.push(node); + ranges.push(Decoration.replace({ widget, block }).range(node.from, node.to)); + } + }); + continue; + } + if (!isTable && selected(section.start, end)) { + // Keep images below the editable source, without duplicating surrounding prose. + const images = section.html.match(/]*>|]*>[\s\S]*?<\/span>/g)?.join(""); + if (images) ranges.push(Decoration.widget({ widget: new Preview(images, source.slice(section.start, end), actions, true), block: true, side: 1 }).range(end)); + continue; + } + hiddenBlocks.push({ from: section.start, to: end }); + ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions), block: true }).range(section.start, end)); + } + const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to); + const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({}).range(from, to)); }; + const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); }; + const codeRanges: { from: number; to: number }[] = []; + syntaxTree(state).iterate({ enter(node) { + if (hidden(node.from, node.to)) return false; + if (node.name === "FencedCode" || node.name === "CodeBlock") { + codeRanges.push({ from: node.from, to: node.to }); + mark(node.from, node.to, "writer-code-source"); + return false; + } + const line = state.doc.lineAt(node.from); + if (/^ATXHeading[1-6]$/.test(node.name)) { + ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from)); + } + if (selected(node.from, node.to)) return; + if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1)); + if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong"); + if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis"); + if (node.name === "Strikethrough") mark(node.from, node.to, "writer-strike"); + if (node.name === "InlineCode") mark(node.from, node.to, "writer-inline-code"); + if (node.name === "NoteHighlight") mark(node.from, node.to, "writer-highlight"); + if (node.name === "NoteMath") mark(node.from, node.to, "writer-math"); + if (node.name === "NoteComment") mark(node.from, node.to, "writer-comment"); + if (["EmphasisMark", "StrikethroughMark", "CodeMark", "NoteFormatMark"].includes(node.name)) replace(node.from, node.to); + if (node.name === "Link") { + // Wiki links are handled separately, because CommonMark sees their inner + // brackets as an incomplete reference link. + if (source[node.from - 1] === "[" && source[node.to] === "]") return false; + const text = source.slice(node.from, node.to); + const match = /^\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)$/.exec(text); + if (!match) return; + replace(node.from, node.from + 1); + replace(node.from + 1 + match[1].length, node.to); + ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", title: "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length)); + return false; + } + if (node.name === "TaskMarker") { + const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text); + if (!match) return; + ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x") }).range(line.from + match[1].length, line.from + match[0].length)); + if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed"); + } + } }); + for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) { + const from = match.index, to = from + match[0].length; + if (selected(from, to) || hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue; + const separator = match[1].indexOf("|"); + const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1); + replace(from, labelStart); + replace(to - 2, to); + ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0] } }).range(labelStart, to - 2)); + } + return Decoration.set(ranges, true); + } + return [imageSource, StateField.define({ + create: build, + update(value, transaction) { + return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state) : value; + }, + provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field))], + })]; +} diff --git a/src/lib/editor/markdownCommands.ts b/src/lib/editor/markdownCommands.ts new file mode 100644 index 0000000..8d86d75 --- /dev/null +++ b/src/lib/editor/markdownCommands.ts @@ -0,0 +1,93 @@ +import { plainInlineMarkdown } from "../workspace/noteHtml.ts"; + +export type TextSelection = { from: number; to: number }; +export type MarkdownEdit = TextSelection & { insert: string; anchor: number; head: number }; +export type InlineFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear"; +export type ParagraphStyle = "bullet" | "number" | "task" | "body" | "quote" | 1 | 2 | 3 | 4 | 5 | 6; +export type InsertBlock = "footnote" | "table" | "callout" | "rule" | "code" | "math"; + +export function replacement(selection: TextSelection, insert: string, start = 0, end = insert.length): MarkdownEdit { + return { ...selection, insert, anchor: selection.from + start, head: selection.from + end }; +} + +export function formatText(source: string, selection: TextSelection, format: InlineFormat): MarkdownEdit { + let { from, to } = selection; + const selected = source.slice(from, to); + if (format === "clear") { + let marker: string | undefined; + do { + marker = ["**", "__", "~~", "==", "%%", "*", "_", "$", "`"].find(value => source.slice(0, from).endsWith(value) && source.slice(to).startsWith(value)); + if (marker) { from -= marker.length; to += marker.length; } + } while (marker); + // The inline serializer uses
      in tables; retain real newlines in prose. + return replacement({ from, to }, plainInlineMarkdown(source.slice(from, to)).replace(/
      /g, source.includes("\r\n") ? "\r\n" : "\n")); + } + let marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format]; + // Ignore boundary whitespace so emphasis stays valid Markdown. + if (selected.trim()) { from += selected.length - selected.trimStart().length; to -= selected.length - selected.trimEnd().length; } + const text = source.slice(from, to); + if (format === "code") { + const wrapped = /^(`+)([\s\S]+)\1$/.exec(text); + if (wrapped && !wrapped[2].startsWith("`") && !wrapped[2].endsWith("`")) return replacement({ from, to }, wrapped[2].replace(/^ (.*) $/s, "$1")); + const before = /(`+) ?$/.exec(source.slice(0, from)), after = /^ ?(`+)/.exec(source.slice(to)); + if (before && after && before[1] === after[1]) return replacement({ from: from - before[0].length, to: to + after[0].length }, text); + } + const isWrapped = text.startsWith(marker) && text.endsWith(marker) && text.length >= marker.length * 2 + && !(format === "italic" && text.startsWith("**") && !text.startsWith("***")); + if (isWrapped) return replacement({ from, to }, text.slice(marker.length, -marker.length)); + const before = source.slice(0, from), after = source.slice(to); + const surrounds = before.endsWith(marker) && after.startsWith(marker) + && !(format === "italic" && before.endsWith("**") && !before.endsWith("***")); + if (surrounds) return replacement({ from: from - marker.length, to: to + marker.length }, text); + if (format === "code") marker = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1); + const padding = format === "code" && /^`|`$/.test(text) ? " " : ""; + return replacement({ from, to }, marker + padding + text + padding + marker, marker.length + padding.length, marker.length + padding.length + text.length); +} + +export function paragraphText(source: string, selection: TextSelection, style: ParagraphStyle): MarkdownEdit { + const from = selection.from === 0 ? 0 : source.lastIndexOf("\n", selection.from - 1) + 1; + // A selection ending at the start of the next line must not format that line. + const last = selection.to > selection.from && source[selection.to - 1] === "\n" ? selection.to - 1 : selection.to; + const newline = source.indexOf("\n", last); + const to = newline < 0 ? source.length : newline > 0 && source[newline - 1] === "\r" ? newline - 1 : newline; + const eol = source.includes("\r\n") ? "\r\n" : "\n"; + let number = 0; + const insert = source.slice(from, to).split(/\r?\n/).map(line => { + if (!line.trim() && from !== to) { number = 0; return line; } + const indent = /^[\t ]*/.exec(line)![0]; + const body = line.slice(indent.length).replace(/^(?:#{1,6}\s+|>\s?|(?:[-+*]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)/, ""); + const prefix = typeof style === "number" ? "#".repeat(style) + " " : { bullet: "- ", number: `${++number}. `, task: "- [ ] ", quote: "> ", body: "" }[style]; + return indent + prefix + body; + }).join(eol); + return replacement({ from, to }, insert, selection.from === selection.to ? insert.length : 0); +} + +export function insertBlock(source: string, selection: TextSelection, kind: InsertBlock): MarkdownEdit { + const eol = source.includes("\r\n") ? "\r\n" : "\n"; + const text = source.slice(selection.from, selection.to); + if (kind === "footnote") { + let id = 1; + while (source.includes(`[^${id}]`)) id++; + const reference = `[^${id}]`, definition = (text || "Footnote text").replace(/\r?\n/g, eol + " "); + const tail = source.slice(selection.to); + const beforeDefinition = reference + tail; + const gap = beforeDefinition.endsWith(eol + eol) ? "" : beforeDefinition.endsWith(eol) ? eol : eol + eol; + const insert = beforeDefinition + gap + reference + ": " + definition + eol; + const start = beforeDefinition.length + gap.length + reference.length + 2; + return replacement({ from: selection.from, to: source.length }, insert, start, start + definition.length); + } + const fence = "`".repeat(Math.max(2, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1); + const content = text || (kind === "code" ? "Code" : kind === "math" ? "equation" : "Callout text"); + let block = kind === "table" ? "| Column 1 | Column 2 |\n| --- | --- |\n| | |" + : kind === "rule" ? "---" : kind === "code" ? `${fence}\n${content}\n${fence}` + : kind === "math" ? `$$\n${content}\n$$` : `> [!note]\n> ${content.replace(/\r?\n/g, "\n> ")}`; + block = block.replace(/\r?\n/g, eol); + // Structural inserts should not delete selected prose. + const at = kind === "table" || kind === "rule" ? { from: selection.to, to: selection.to } : selection; + const before = source.slice(0, at.from), after = source.slice(at.to); + const leading = !before || before.endsWith(eol + eol) ? "" : before.endsWith(eol) ? eol : eol + eol; + const trailing = after.startsWith(eol + eol) ? "" : after.startsWith(eol) ? eol : eol + eol; + const start = kind === "table" ? block.indexOf("Column 1") : kind === "rule" ? block.length : block.indexOf(eol) + eol.length + (kind === "callout" ? 2 : 0); + const length = kind === "table" ? 8 : kind === "rule" ? 0 : content.length; + return replacement(at, leading + block + trailing, leading.length + start, leading.length + start + length); +} diff --git a/src/lib/editor/markdownMenu.ts b/src/lib/editor/markdownMenu.ts new file mode 100644 index 0000000..aff4ef8 --- /dev/null +++ b/src/lib/editor/markdownMenu.ts @@ -0,0 +1,122 @@ +import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; +import { requestText } from "../workspace/dialogs.svelte"; +import { htmlToMarkdown } from "../workspace/htmlToMarkdown"; +import { cellFormats, type TableContextActions } from "./tableCellActions"; +import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands"; + +export type MarkdownMenuEditor = { + snapshot: () => { source: string; selection: TextSelection; valid: () => boolean }; + apply: (edit: MarkdownEdit) => void; + selectAll: () => void; + focus: () => void; +}; + +// A shared controller keeps menus, async selection guards, and clipboard behavior +// identical in the writing editor and the source editor. +export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) { + let root: HTMLElement | undefined, destroyed = false; + function close(focus = true) { + root?.remove(); root = undefined; + if (focus && !destroyed) editor.focus(); + } + const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); }; + const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); }; + const resize = () => close(false); + document.addEventListener("mousedown", outside, true); + document.addEventListener("scroll", scroll, true); + window.addEventListener("resize", resize); + + function open(x: number, y: number) { + close(false); + const snapshot = editor.snapshot(), { source, selection } = snapshot; + const text = source.slice(selection.from, selection.to); + const valid = () => !destroyed && snapshot.valid(); + function apply(edit: MarkdownEdit) { + if (!valid()) return; + close(); editor.apply(edit); editor.focus(); + } + async function request(run: () => Promise) { + close(false); + try { await run(); } catch (error) { if (!destroyed) report(error instanceof Error ? error.message : String(error)); } + finally { if (valid()) editor.focus(); } + } + function link(external: boolean) { + void request(async () => { + const target = (await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text))?.trim(); + if (!target || !valid()) return; + if (external) { + try { + const url = new URL(target); + if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error(); + } catch { report("Enter a valid http, https, or mailto link."); return; } + const label = (text || target).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " "); + apply(replacement(selection, `[${label}](${target.replace(/[()<>]/g, char => encodeURIComponent(char).replace("(", "%28").replace(")", "%29"))})`)); + } else { + if (/[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; } + const label = text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim(); + apply(replacement(selection, `[[${target}${label && label !== target ? "|" + label : ""}]]`)); + } + }); + } + function clipboard(kind: "cut" | "copy" | "paste" | "plain") { + void request(async () => { + try { + if (kind === "cut" || kind === "copy") { + await navigator.clipboard.writeText(text); + if (kind === "cut") apply(replacement(selection, "")); + } else { + let value = ""; + if (kind === "paste" && navigator.clipboard.read) { + try { + const data = await navigator.clipboard.read(); + const rich = data.find(item => item.types.includes("text/html")); + if (rich) value = htmlToMarkdown(await (await rich.getType("text/html")).text()); + } catch { /* Fall back to the text clipboard on older WebViews. */ } + } + if (!value) value = await navigator.clipboard.readText(); + if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n"))); + } + } catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); } + }); + } + const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) }); + const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) }); + const items: ActionMenuItem[] = [ + { label: "Add link", icon: "link", run: () => link(false) }, + { label: "Add external link", icon: "external", run: () => link(true) }, + { separator: true }, + { label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } }, + { label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => { + const target = await actions.onExtract?.(text, text, valid); + if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`)); + }) }, + { label: "Format", icon: "format", children: cellFormats.flatMap(([label, kind]) => [ + ...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []), + { label, icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) }, + ]) }, + { label: "Paragraph", icon: "paragraph", children: [ + paragraph("Bullet list", "bullet", "bullet"), paragraph("Numbered list", "number", "number"), paragraph("Task list", "task", "task"), + { separator: true }, + ...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(`Heading ${level}`, level, "heading")), + paragraph("Body", "body", "paragraph"), { separator: true }, paragraph("Quote", "quote", "quote"), + ] }, + { label: "Insert", icon: "insert", children: [ + insert("Footnote", "footnote", "footnote"), insert("Table", "table", "table"), insert("Callout", "callout", "quote"), insert("Horizontal rule", "rule", "rule"), + { separator: true }, insert("Code block", "code", "code"), insert("Math block", "math", "math"), + ] }, + { separator: true }, + { label: "Cut", icon: "cut", disabled: !text, run: () => clipboard("cut") }, + { label: "Copy", icon: "copy", disabled: !text, run: () => clipboard("copy") }, + { label: "Paste", icon: "paste", run: () => clipboard("paste") }, + { label: "Paste as plain text", icon: "paste-text", run: () => clipboard("plain") }, + { label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } }, + ]; + root = actionMenu(x, y, items, close, "Markdown text actions"); + } + return { open, close, destroy() { + destroyed = true; close(false); + document.removeEventListener("mousedown", outside, true); + document.removeEventListener("scroll", scroll, true); + window.removeEventListener("resize", resize); + } }; +} diff --git a/src/lib/editor/markdownTable.ts b/src/lib/editor/markdownTable.ts new file mode 100644 index 0000000..6b22375 --- /dev/null +++ b/src/lib/editor/markdownTable.ts @@ -0,0 +1,74 @@ +export type TableCell = { text: string; from: number; to: number }; +export type TableRow = { from: number; to: number; indent: string; cells: TableCell[] }; +export type MarkdownTable = { rows: TableRow[]; columns: number; eol: string; end: number }; + +function row(text: string, from: number): TableRow { + const pipes: number[] = []; + for (let index = 0; index < text.length; index++) { + if (text[index] !== "|") continue; + let slashes = 0; + for (let before = index - 1; before >= 0 && text[before] === "\\"; before--) slashes++; + if (slashes % 2 === 0) pipes.push(index); + } + const start = text.search(/\S/); + const end = text.trimEnd().length; + const left = pipes[0] === start ? pipes.shift()! + 1 : 0; + const right = pipes.at(-1) === end - 1 ? pipes.pop()! : text.length; + const boundaries = [left - 1, ...pipes, right]; + const cells = boundaries.slice(0, -1).map((boundary, index) => { + const rawFrom = boundary + 1, rawTo = boundaries[index + 1]; + const raw = text.slice(rawFrom, rawTo); + const leading = raw.length - raw.trimStart().length; + const cellFrom = from + rawFrom + leading; + return { text: raw.trim(), from: cellFrom, to: Math.max(cellFrom, from + rawTo - (raw.length - raw.trimEnd().length)) }; + }); + return { from, to: from + text.length, indent: /^\s*/.exec(text)![0], cells }; +} + +export function parseMarkdownTable(source: string): MarkdownTable | null { + const rows: TableRow[] = []; + let offset = 0; + const eol = source.includes("\r\n") ? "\r\n" : "\n"; + for (const line of source.split(eol)) { + if (!line.trim()) break; + rows.push(row(line, offset)); + offset += line.length + eol.length; + } + if (rows.length < 2 || !source.slice(rows[0].from, rows[0].to).includes("|")) return null; + const columns = rows[0].cells.length; + if (rows[1].cells.length !== columns || !rows[1].cells.every(cell => /^:?-+:?$/.test(cell.text))) return null; + return { rows, columns, eol, end: rows.at(-1)!.to }; +} + +export function appendTableColumn(source: string): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const body = table.rows.map((row, index) => { + const cells = row.cells.map(cell => cell.text); + while (cells.length < table.columns) cells.push(""); + cells.splice(table.columns, 0, index === 1 ? "---" : ""); + return `${row.indent}| ${cells.join(" | ")} |`; + }).join(table.eol); + return body + source.slice(table.end); +} + +export function appendTableRow(source: string): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const row = `${table.rows[0].indent}| ${Array.from({ length: table.columns }, () => "").join(" | ")} |`; + return source.slice(0, table.end) + table.eol + row + source.slice(table.end); +} + +// Change only the selected cell: padding, alignment, and every other row stay intact. +export function replaceTableCell(source: string, rowIndex: number, column: number, text: string): string { + const table = parseMarkdownTable(source); + if (!table || rowIndex === 1 || column < 0 || column >= table.columns || /[\r\n]/.test(text)) return source; + const row = table.rows[rowIndex]; + if (!row) return source; + const cell = row.cells[column]; + if (cell) return source.slice(0, cell.from) + text + source.slice(cell.to); + const cells = row.cells.map(cell => cell.text); + while (cells.length <= column) cells.push(""); + cells[column] = text; + return source.slice(0, row.from) + `${row.indent}| ${cells.join(" | ")} |` + source.slice(row.to); +} diff --git a/src/lib/editor/monaco-css.d.ts b/src/lib/editor/monaco-css.d.ts new file mode 100644 index 0000000..50f3810 --- /dev/null +++ b/src/lib/editor/monaco-css.d.ts @@ -0,0 +1 @@ +declare module "monaco-editor-css"; diff --git a/src/lib/editor/monacoChrome.ts b/src/lib/editor/monacoChrome.ts new file mode 100644 index 0000000..ab74867 --- /dev/null +++ b/src/lib/editor/monacoChrome.ts @@ -0,0 +1,30 @@ +import type { Chrome } from "../workspace/types"; + +export function monacoChrome(mode: Chrome) { + if (mode === "Writing") { + return { + wordWrap: "on" as const, + lineNumbers: "off" as const, + minimap: { enabled: false }, + fontSize: 16, + lineHeight: 26, + folding: false, + glyphMargin: false, + lineDecorationsWidth: 24, + padding: { top: 16, bottom: 48 }, + renderLineHighlight: "none" as const, + }; + } + return { + wordWrap: "off" as const, + lineNumbers: "on" as const, + minimap: { enabled: true, scale: 1 }, + fontSize: 14, + lineHeight: 22, + folding: true, + glyphMargin: true, + lineDecorationsWidth: 10, + padding: { top: 8, bottom: 24 }, + renderLineHighlight: "line" as const, + }; +} diff --git a/src/lib/editor/monacoEnv.ts b/src/lib/editor/monacoEnv.ts new file mode 100644 index 0000000..0efb58a --- /dev/null +++ b/src/lib/editor/monacoEnv.ts @@ -0,0 +1,32 @@ +import * as monaco from "monaco-editor"; +import "monaco-editor-css"; +import editorWorkerUrl from "monaco-editor/editor/editor.worker.js?url"; + +self.MonacoEnvironment = { + getWorker() { + return new Worker(editorWorkerUrl, { type: "module" }); + }, +}; + +monaco.editor.defineTheme("runestone-dark", { + base: "vs-dark", + inherit: true, + rules: [], + colors: { + "editor.background": "#141414", + "editor.foreground": "#e6e6e6", + "editor.lineHighlightBackground": "#ffffff0d", + "editor.selectionBackground": "#264f78", + "editorCursor.foreground": "#82aaff", + "editorLineNumber.foreground": "#5a5a5a", + "editorLineNumber.activeForeground": "#c8c8c8", + "editorGutter.background": "#141414", + "editorWidget.background": "#1c1c1c", + "editorWidget.border": "#2e2e2e", + "minimap.background": "#1c1c1c", + "editorIndentGuide.background1": "#2e2e2e", + "editorIndentGuide.activeBackground1": "#3e3e3e", + }, +}); + +export { monaco }; diff --git a/src/lib/editor/noteTitle.ts b/src/lib/editor/noteTitle.ts new file mode 100644 index 0000000..fb1a8c0 --- /dev/null +++ b/src/lib/editor/noteTitle.ts @@ -0,0 +1,99 @@ +import { Decoration, EditorView, WidgetType } from "@codemirror/view"; +import { actionIcon } from "../ui/actionIcons"; + +type RenameTitle = (title: string) => Promise; + +class NoteTitle extends WidgetType { + constructor(readonly title: string, readonly rename?: RenameTitle) { super(); } + eq(other: NoteTitle) { return this.title === other.title && this.rename === other.rename; } + toDOM(view: EditorView) { + // Contain heading margins so CodeMirror measures the full block height. + const block = document.createElement("div"); + block.style.display = "flow-root"; + const heading = document.createElement("h1"); + heading.className = "document-title"; + heading.textContent = this.title; + block.append(heading); + if (!this.rename) return block; + + const button = document.createElement("button"); + button.type = "button"; + button.className = "note-title-button"; + button.setAttribute("aria-label", "Rename note"); + button.append(document.createTextNode(this.title), actionIcon("rename")); + const help = document.createElement("span"); + help.className = "note-title-help"; + help.textContent = "Rename note"; + help.setAttribute("role", "tooltip"); + button.append(help); + heading.replaceChildren(button); + + const input = document.createElement("input"); + input.className = "note-title-input"; + input.setAttribute("aria-label", "Note filename"); + input.autocomplete = "off"; + input.spellcheck = false; + input.hidden = true; + heading.append(input); + const message = document.createElement("p"); + message.className = "note-title-error"; + message.setAttribute("role", "alert"); + message.hidden = true; + block.append(message); + let editing = false, pending = false; + const finish = () => { + editing = false; + input.hidden = true; + button.hidden = false; + message.hidden = true; + input.removeAttribute("aria-invalid"); + view.requestMeasure(); + }; + const commit = async (focusEditor: boolean) => { + if (!editing || pending) return; + pending = true; + input.readOnly = true; + input.setAttribute("aria-busy", "true"); + try { + await this.rename!(input.value); + finish(); + if (focusEditor && view.dom.isConnected && (document.activeElement === input || document.activeElement === document.body)) view.focus(); + } catch (reason) { + if (!block.isConnected) return; + input.setAttribute("aria-invalid", "true"); + message.textContent = reason instanceof Error ? reason.message : String(reason); + message.hidden = false; + view.requestMeasure(); + } finally { + pending = false; + input.readOnly = false; + input.removeAttribute("aria-busy"); + } + }; + button.onclick = () => { + editing = true; + input.value = this.title; + button.hidden = true; + input.hidden = false; + input.focus(); + input.select(); + view.requestMeasure(); + }; + input.onblur = () => { void commit(false); }; + input.onkeydown = event => { + event.stopPropagation(); + if (event.isComposing) return; + if (event.key === "Enter") { event.preventDefault(); void commit(true); } + if (event.key === "Escape" && !pending) { event.preventDefault(); finish(); button.focus(); } + }; + return block; + } + ignoreEvent() { return true; } +} + +// Filename editing stays outside the Markdown and its undo history. +export function noteTitle(title: string, rename?: RenameTitle) { + return EditorView.decorations.of(Decoration.set([ + Decoration.widget({ widget: new NoteTitle(title, rename), block: true, side: -1 }).range(0), + ])); +} diff --git a/src/lib/editor/selection.ts b/src/lib/editor/selection.ts new file mode 100644 index 0000000..2619b8f --- /dev/null +++ b/src/lib/editor/selection.ts @@ -0,0 +1,10 @@ +// Readers retain editor selection when toolbar buttons take focus. +let current: { id: string; read: () => string } | undefined; +export function registerSelection(id: string, read: () => string): () => void { + const owner = { id, read }; + current = owner; + return () => { if (current === owner) current = undefined; }; +} +export function selectedEditorText(id?: string): string { + return current && current.id === id ? current.read() : ""; +} diff --git a/src/lib/editor/sessions.ts b/src/lib/editor/sessions.ts new file mode 100644 index 0000000..7b8fef7 --- /dev/null +++ b/src/lib/editor/sessions.ts @@ -0,0 +1,30 @@ +import type * as Monaco from "monaco-editor"; +import type { OpenBuffer } from "../workspace/types"; +import { languageFor } from "./languageFor"; + +type Session = { + model: Monaco.editor.ITextModel; + view: Monaco.editor.ICodeEditorViewState | null; + writer?: { source: string; state: ReturnType; scroll: ReturnType }; +}; +const sessions = new Map(); + +export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session { + let session = sessions.get(buffer.id); + if (!session) { + session = { + model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)), + view: null, + }; + sessions.set(buffer.id, session); + } + monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath)); + return session; +} + +export function retainEditorSessions(ids: string[]) { + const retained = new Set(ids); + for (const [id, session] of sessions) { + if (!retained.has(id)) { session.model.dispose(); sessions.delete(id); } + } +} diff --git a/src/lib/editor/tableCellActions.ts b/src/lib/editor/tableCellActions.ts new file mode 100644 index 0000000..6aa7a86 --- /dev/null +++ b/src/lib/editor/tableCellActions.ts @@ -0,0 +1,98 @@ +import type { Editor, JSONContent } from "@tiptap/core"; +import { requestText } from "../workspace/dialogs.svelte"; +import { extractedCellMarkdown } from "./tableCellMarkdown"; +import type { ActionMenuItem } from "../ui/actionMenu"; + +export type TableContextActions = { + onSearch?: (text: string) => void; + onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise; +}; + +export const cellFormats = [ + ["Bold", "bold"], ["Italic", "italic"], ["Strikethrough", "strike"], ["Highlight", "highlight"], + ["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"], +] as const; + +export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void): ActionMenuItem[] { + const selection = editor.state.selection, doc = editor.state.doc; + const text = doc.textBetween(selection.from, selection.to, "\n"); + const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection); + function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); } + async function request(command: () => Promise) { + pending(true); close(); + try { await command(); } catch (error) { report(error instanceof Error ? error.message : String(error)); } + finally { pending(false); if (!editor.isDestroyed) editor.view.focus(); } + } + function link(external: boolean) { + void request(async () => { + const target = await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text); + if (!target || !valid()) return; + if (external) { + try { + const url = new URL(target); + if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL"); + } catch { report("Enter a valid http, https, or mailto link."); return; } + } + if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; } + run(() => { + const attrs = { href: target, "data-kind": external ? "md" : "wiki" }; + if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] }); + else editor.commands.setMark("link", attrs); + }); + }); + } + async function clipboard(action: "cut" | "copy" | "paste" | "plain") { + await request(async () => { + try { + if (action === "copy" || action === "cut") { + await navigator.clipboard.writeText(text); + if (action === "cut") run(() => { editor.commands.deleteSelection(); }); + } else { + let html = "", value = ""; + if (action === "paste" && navigator.clipboard.read) { + try { + const data = await navigator.clipboard.read(); + const rich = data.find(item => item.types.includes("text/html")); + if (rich) html = await (await rich.getType("text/html")).text(); + const plain = data.find(item => item.types.includes("text/plain")); + if (plain) value = await (await plain.getType("text/plain")).text(); + } catch { /* Text clipboard is also supported on older WebViews. */ } + } + if (!html && !value) value = await navigator.clipboard.readText(); + if (!html && !value) return; + run(() => { + if (html) editor.commands.insertContent(html); + else { + const nodes: JSONContent[] = []; + value.replace(/\r\n?/g, "\n").split("\n").forEach((line, i) => { if (i) nodes.push({ type: "hardBreak" }); if (line) nodes.push({ type: "text", text: line, marks: [] }); }); + editor.commands.insertContent(nodes); + } + }); + } + } catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); } + }); + } + return [ + { label: "Add link", icon: "link", run: () => link(false) }, + { label: "Add external link", icon: "external", run: () => link(true) }, + { separator: true }, + { label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } }, + { label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => { + const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null; + const markdown = extractedCellMarkdown(selected || []); + const target = await actions.onExtract?.(markdown, text, valid); + if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); }); + }) }, + { label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, disabled: selection.empty, run: () => run(() => { + if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind); + }) })) }, + { label: "Paragraph", icon: "paragraph", disabled: true, title: "Markdown table cells contain inline text" }, + { label: "Insert", icon: "insert", disabled: true, title: "Use the Row and Column menus to change the table" }, + { separator: true }, + { label: "Cut", icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") }, + { label: "Copy", icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") }, + { label: "Paste", icon: "paste", run: () => void clipboard("paste") }, + { label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") }, + { label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } }, + ]; +} diff --git a/src/lib/editor/tableCellMarkdown.ts b/src/lib/editor/tableCellMarkdown.ts new file mode 100644 index 0000000..9070650 --- /dev/null +++ b/src/lib/editor/tableCellMarkdown.ts @@ -0,0 +1,63 @@ +import type { JSONContent } from "@tiptap/core"; +import { isTableFormula } from "./tableFormulas.ts"; + +// Extract inline content into a note without confusing literal
      in code +// with actual cell hard breaks. +export function extractedCellMarkdown(nodes: JSONContent[]): string { + return nodes.map(node => { + if (node.type === "hardBreak") return "\n"; + if (node.type === "paragraph") return extractedCellMarkdown(node.content || []); + return tableCellMarkdown(node); + }).join(""); +} + +function literal(text: string): string { + return text.replace(/&/g, "&").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`).replace(/\r?\n/g, "
      "); +} + +function wrap(text: string, marker: string): string { + const [, before, body, after] = /^(\s*)([\s\S]*?)(\s*)$/.exec(text)!; + return body ? `${before}${marker}${body}${marker}${after}` : text; +} + +// A cell is inline Markdown. Paragraphs from pasted text become safe table breaks. +export function tableCellMarkdown(node: JSONContent): string { + // Keep plain formula input as readable source. Formatted/code/escaped text + // still follows ordinary Markdown serialization and remains literal. + if (node.type === "doc" && node.content?.length === 1 && node.content[0].type === "paragraph") { + const children = node.content[0].content || []; + const text = children.map(child => child.text || "").join(""); + if (children.every(child => child.type === "text" && !child.marks?.length) && (isTableFormula(text) || /^\s*\\=(?!=)/.test(text))) return text.replace(/\|/g, "\\|"); + } + if (node.type === "hardBreak") return "
      "; + if (node.type === "image") { + const source = String(node.attrs?.["data-md-src"] || node.attrs?.src || ""); + const alt = String(node.attrs?.alt || ""); + return node.attrs?.["data-md-kind"] === "wiki" + ? `![[${literal(source)}${alt && alt !== source ? `\\|${literal(alt)}` : ""}]]` + : `![${literal(alt)}](<${source.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`; + } + let text = node.text === undefined + ? (node.content || []).map(tableCellMarkdown).join(node.type === "doc" ? "
      " : "") + : literal(node.text); + for (const mark of node.marks || []) { + if (mark.type === "code") { + const raw = node.text || ""; + const fence = "`".repeat(Math.max(0, ...[...raw.matchAll(/`+/g)].map(match => match[0].length)) + 1); + const padding = /^`|`$|^ .* $/.test(raw) ? " " : ""; + text = `${fence}${padding}${raw.replace(/\|/g, "\\|")}${padding}${fence}`; + } + if (mark.type === "bold") text = wrap(text, "**"); + if (mark.type === "italic") text = wrap(text, "*"); + if (mark.type === "strike") text = wrap(text, "~~"); + if (mark.type === "highlight") text = wrap(text, "=="); + if (mark.type === "math" || mark.type === "comment") text = wrap((node.text || "").replace(/\|/g, "\\|"), mark.type === "math" ? "$" : "%%"); + if (mark.type === "link") { + const href = String(mark.attrs?.href || ""); + text = mark.attrs?.["data-kind"] === "wiki" + ? `[[${literal(href)}\\|${text}]]` + : `[${text}](<${href.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>${mark.attrs?.title ? ` "${String(mark.attrs.title).replace(/"/g, """)}"` : ""})`; + } + } + return text; +} diff --git a/src/lib/editor/tableControls.ts b/src/lib/editor/tableControls.ts new file mode 100644 index 0000000..9a78c7a --- /dev/null +++ b/src/lib/editor/tableControls.ts @@ -0,0 +1,386 @@ +import { Editor, Mark } from "@tiptap/core"; +import Highlight from "@tiptap/extension-highlight"; +import StarterKit from "@tiptap/starter-kit"; +import Link from "@tiptap/extension-link"; +import Image from "@tiptap/extension-image"; +import type { EditorView } from "@codemirror/view"; +import { isolateHistory, undo, redo } from "@codemirror/commands"; +import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable"; +import { tableCellMarkdown } from "./tableCellMarkdown"; +import { tableSelectionControls } from "./tableSelectionControls"; +import { tableDragControls } from "./tableDragControls"; +import type { TableContextActions } from "./tableCellActions"; +import { actionIcon } from "../ui/actionIcons"; +import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./tableFormulas"; +import { tableFormulaHtml } from "../workspace/noteHtml"; + +const cellFormats = ["math", "comment"].map(name => Mark.create({ + name, + parseHTML: () => [{ tag: `span[data-cell-format="${name}"]` }], + renderHTML: () => ["span", { "data-cell-format": name, class: `md-inline-${name}` }, 0], +})); + +const CellLink = Link.extend({ + addAttributes() { return { ...this.parent?.(), "data-kind": { default: "md" } }; }, +}); +const CellImage = Image.extend({ + addAttributes() { return { ...this.parent?.(), "data-md-src": { default: null }, "data-md-kind": { default: "md" } }; }, + parseHTML() { return [...(this.parent?.() || []), { tag: "span.missing-image[data-md-src]" }]; }, + renderHTML({ HTMLAttributes }) { + return HTMLAttributes.src + ? ["img", HTMLAttributes] + : ["span", { ...HTMLAttributes, class: "missing-image" }, `Image unavailable: ${HTMLAttributes.alt || HTMLAttributes["data-md-src"] || ""}`]; + }, +}); + +export const tableEditors = new WeakMap void; destroy: () => void }>(); + +export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) { + const scroll = root.querySelector(".md-table-scroll"); + const table = scroll?.querySelector("table"); + if (!scroll || !table || !parseMarkdownTable(initialSource)) return; + const wrapper = document.createElement("div"); + wrapper.className = "writer-table"; + scroll.before(wrapper); + wrapper.append(scroll); + let editor: Editor | undefined; + let active: HTMLTableCellElement | undefined; + let firstEdit = true; + let selectionControls: ReturnType | undefined; + let dragControls: ReturnType | undefined; + const controller = { source: initialSource, enter, destroy: () => { dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } }; + tableEditors.set(root, controller); + + function enter(forward: boolean, x?: number) { + const row = table!.rows[forward ? 0 : table!.rows.length - 1]; + const cells = [...row.cells]; + let cell = cells[forward ? 0 : cells.length - 1]; + if (x !== undefined) { + const distance = (candidate: HTMLTableCellElement) => { + const rect = candidate.getBoundingClientRect(); + return Math.max(rect.left - x, x - rect.right, 0); + }; + cell = cells.reduce((nearest, candidate) => distance(candidate) < distance(nearest) ? candidate : nearest); + } + activate(cell); + const current = editor!; + let position = forward ? 1 : current.state.doc.content.size - 1; + if (x !== undefined) { + const edge = current.view.coordsAtPos(position); + position = current.view.posAtCoords({ left: x, top: (edge.top + edge.bottom) / 2 })?.pos ?? position; + } + current.commands.setTextSelection(position); + current.view.focus(); + cell.scrollIntoView({ block: "nearest", inline: "nearest" }); + } + + function refreshFormulas() { + const parsed = parseMarkdownTable(controller.source); + if (!parsed) return; + const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || "")); + const results = evaluateTableFormulas(grid); + for (const row of table!.rows) for (const cell of row.cells) { + const result = results[row.rowIndex]?.[cell.cellIndex]; + const address = cellAddress(row.rowIndex, cell.cellIndex); + cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`; + if (result && cell !== active) cell.innerHTML = tableFormulaHtml(result); + if (cell === active) { + formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`; + formulaHint.textContent = result?.error ? formulaErrors[result.error] : ""; + formulaHint.hidden = !formulaHint.textContent; + } + } + } + + function change(insert: string, structural = false) { + const source = controller.source; + const from = view.posAtDOM(root); + if (view.state.doc.sliceString(from, from + source.length) !== source || insert === source) return; + // Keep the same DOM/editor on typing, including composition and text selection. + if (!structural) controller.source = insert; + let start = 0, oldEnd = source.length, newEnd = insert.length; + while (start < oldEnd && start < newEnd && source[start] === insert[start]) start++; + while (oldEnd > start && newEnd > start && source[oldEnd - 1] === insert[newEnd - 1]) { oldEnd--; newEnd--; } + view.dispatch({ + changes: { from: from + start, to: from + oldEnd, insert: insert.slice(start, newEnd) }, + userEvent: structural ? "input" : editor?.view.composing ? "input.type.compose" : "input.type.table", + annotations: structural ? isolateHistory.of("full") : firstEdit ? isolateHistory.of("before") : [], + }); + firstEdit = false; + if (!structural) refreshFormulas(); + view.requestMeasure(); + } + + function finish() { + if (!editor || !active) return; + const cell = active; + const html = editor.getHTML(); + editor.destroy(); editor = undefined; active = undefined; + cell.innerHTML = html; + cell.classList.remove("is-editing"); + refreshFormulas(); + formulaStatus.textContent = "Type = in a cell to calculate"; + formulaHint.hidden = true; + view.requestMeasure(); + if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") }); + } + + function leave(after: boolean) { + const from = view.posAtDOM(root), to = from + controller.source.length; + finish(); + let anchor = after ? Math.min(view.state.doc.length, to + 1) : Math.max(0, from - 1); + if (after && to + 1 >= view.state.doc.length) { + view.dispatch({ changes: { from: view.state.doc.length, insert: to === view.state.doc.length ? "\n\n" : "\n" }, userEvent: "input" }); + anchor = to + 2; + } else if (after && view.state.doc.sliceString(to, to + 2) === "\n\n") { + // Leave the separator blank so typing below cannot become another row. + anchor = to + 2; + } else if (!after && from === 0) { + view.dispatch({ changes: { from: 0, insert: "\n\n" }, userEvent: "input" }); + anchor = 0; + } + view.dispatch({ selection: { anchor }, scrollIntoView: true }); + view.focus(); + } + + function activate(cell: HTMLTableCellElement) { + if (active === cell) return; + finish(); + active = cell; + firstEdit = true; + const row = (cell.parentElement as HTMLTableRowElement).rowIndex; + const column = cell.cellIndex; + const sourceRow = row === 0 ? 0 : row + 1; + const originalCell = parseMarkdownTable(controller.source)?.rows[sourceRow]?.cells[column]; + // The nested editor owns browser focus, but the outer editor also needs to + // leave its previous active line so its Markdown markers render again. + view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" }); + let contentFrom = originalCell?.from, contentTo = originalCell?.to; + const formula = originalCell && (isTableFormula(originalCell.text) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined; + const html = cell.innerHTML; + formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`; + cell.innerHTML = ""; + cell.classList.add("is-editing"); + editor = new Editor({ + element: cell, + extensions: [ + StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }), + CellLink.configure({ openOnClick: false, autolink: false }), + CellImage.configure({ inline: true, allowBase64: true }), + Highlight, ...cellFormats, + ], + content: formula ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: formula }] }] } : html, + enableInputRules: false, + enablePasteRules: false, + editorProps: { + attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" }, + handleKeyDown(_editorView, event) { + if (event.isComposing) return false; + if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) { + // The nested editor owns cursor movement, including word movement + // and selections. Never let an arrow reach the prose editor. + event.stopPropagation(); + // Native cursor movement can precede ProseMirror's selectionchange + // observer (especially during key repeat). Test the visible caret. + const native = document.getSelection(); + if (native?.anchorNode && native.focusNode && _editorView.dom.contains(native.anchorNode) && _editorView.dom.contains(native.focusNode)) { + const anchor = _editorView.posAtDOM(native.anchorNode, native.anchorOffset); + const head = _editorView.posAtDOM(native.focusNode, native.focusOffset); + if (anchor !== _editorView.state.selection.anchor || head !== _editorView.state.selection.head) editor!.commands.setTextSelection({ from: anchor, to: head }); + } + if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || !_editorView.state.selection.empty) return false; + const direction = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down"; + const horizontal = direction === "left" || direction === "right"; + const backwards = direction === "left" || direction === "up"; + const { $head } = _editorView.state.selection; + // Pasted rich text can have several paragraphs within one cell. + if ($head.depth && (backwards ? $head.before(1) > 0 : $head.after(1) < _editorView.state.doc.content.size)) return false; + if (!_editorView.endOfTextblock(direction)) return false; + event.preventDefault(); + const cells = [...table!.querySelectorAll("th, td")]; + const next = horizontal + ? cells[cells.indexOf(cell) + (backwards ? -1 : 1)] + : table!.rows[row + (backwards ? -1 : 1)]?.cells[column]; + // Once there are no more cells in this direction, return to prose. + if (!next) { leave(!backwards); return true; } + const caret = _editorView.coordsAtPos(_editorView.state.selection.head); + activate(next); + const current = editor!; + let position = backwards ? current.state.doc.content.size - 1 : 1; + if (!horizontal) { + // Enter the closest position on the first/last visual line, even + // when either cell wraps or contains a hard break. + const edge = current.view.coordsAtPos(position); + position = current.view.posAtCoords({ left: caret.left, top: (edge.top + edge.bottom) / 2 })?.pos ?? position; + } + current.commands.setTextSelection(position); + current.view.focus(); + next.scrollIntoView({ block: "nearest", inline: "nearest" }); + return true; + } + // Keep formatting shortcuts local; the workbench also binds Ctrl+B. + if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation(); + if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) { + event.preventDefault(); event.stopPropagation(); + const position = event.key === "Home" ? 1 : editor!.state.doc.content.size - 1; + editor?.commands.setTextSelection(event.shiftKey ? { from: editor.state.selection.anchor, to: position } : position); + return true; + } + if ((event.ctrlKey || event.metaKey) && ["z", "y"].includes(event.key.toLowerCase())) { + event.preventDefault(); event.stopPropagation(); + const from = view.posAtDOM(root); + (event.key.toLowerCase() === "y" || event.shiftKey ? redo : undo)(view); + requestAnimationFrame(() => { + const updated = [...view.dom.querySelectorAll(".writer-preview")].find(el => view.posAtDOM(el) === from); + (updated?.querySelector("table")?.rows[row]?.cells[column])?.focus(); + }); + return true; + } + if (event.key === "Escape") { event.preventDefault(); leave(true); return true; } + if (event.key === "Enter") { + event.preventDefault(); + if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); } + else if (event.ctrlKey || event.metaKey) leave(true); + else editor?.commands.setHardBreak(); + return true; + } + if (event.key === "Tab") { + event.preventDefault(); + const cells = [...table!.querySelectorAll("th, td")]; + const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)]; + if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); } + else if (event.shiftKey) leave(false); + else add("row", true); + return true; + } + return false; + }, + }, + onUpdate({ editor: current }) { + const text = tableCellMarkdown(current.getJSON()); + const source = controller.source; + // Track the full edited range, including typed spaces. Re-parsing the + // trimmed cell on each key would gradually turn those spaces into padding. + const insert = contentFrom === undefined || contentTo === undefined + ? replaceTableCell(source, sourceRow, column, text) + : source.slice(0, contentFrom) + text + source.slice(contentTo); + contentFrom ??= parseMarkdownTable(insert)?.rows[sourceRow]?.cells[column]?.from; + if (contentFrom !== undefined) contentTo = contentFrom + text.length; + change(insert); + }, + onBlur() { + // A toolbar click, another cell, or the prose editor can now take focus. + queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); }); + }, + }); + editor.commands.setTextSelection(editor.state.doc.content.size - 1); editor.view.focus(); + refreshFormulas(); + view.requestMeasure(); + } + + function add(kind: "row" | "column", focusNew = false) { + const from = view.posAtDOM(root); + finish(); + const current = controller.source; + change(kind === "column" ? appendTableColumn(current) : appendTableRow(current), true); + view.focus(); + requestAnimationFrame(() => { + const updated = [...view.dom.querySelectorAll(".writer-preview")].find(el => view.posAtDOM(el) === from); + if (!updated) return; + if (focusNew) updated.querySelector("tbody tr:last-child td")?.focus(); + if (kind === "column") { + const viewport = updated.querySelector(".md-table-scroll")!; + viewport.scrollLeft = viewport.scrollWidth; + } else updated.querySelector(".table-add-row")?.scrollIntoView({ block: "nearest", inline: "nearest" }); + view.requestMeasure(); + }); + } + + const help = document.createElement("div"); + help.className = "table-edit-help"; + help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table"; + const footer = document.createElement("div"); + footer.className = "table-footer"; + const formulaTools = document.createElement("div"); + formulaTools.className = "table-formula-tools"; + const formulaHelp = document.createElement("details"); + formulaHelp.className = "table-formula-help"; + const summary = document.createElement("summary"); + summary.append(actionIcon("math"), document.createTextNode("Formulas")); + summary.title = "How to calculate with table cells"; + // Committing a wrapped formula can shrink its row. Keep the click target in + // place until mouseup, then finish editing and give keyboard focus to help. + summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } }); + summary.addEventListener("click", () => { finish(); summary.focus(); }); + const instructions = document.createElement("div"); + instructions.className = "table-formula-instructions"; + const intro = document.createElement("p"); + intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2."; + const examples = document.createElement("dl"); + for (const [formula, description] of [ + ["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."], + ["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."], + ["=SUM(B2:B10)", "Add the values in a range."], + ["=(B2+C2)/2", "Add two values and divide by two."], + ["=ROUND(B2/3,2)", "Round to two decimal places."], + ]) { + const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd"); + code.textContent = formula; term.append(code); descriptionElement.textContent = description; + examples.append(term, descriptionElement); + } + const functions = document.createElement("p"); + functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range."; + const references = document.createElement("p"); + references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting."; + instructions.append(intro, examples, functions, references); + formulaHelp.append(summary, instructions); + formulaHelp.addEventListener("toggle", () => view.requestMeasure()); + const formulaStatus = document.createElement("span"); + formulaStatus.className = "table-formula-status"; + formulaStatus.textContent = "Type = in a cell to calculate"; + const formulaHint = document.createElement("div"); + formulaHint.className = "table-formula-hint"; + formulaHint.hidden = true; + formulaTools.append(formulaHelp, formulaStatus); + footer.append(help, formulaTools, formulaHint); + wrapper.after(footer); + for (const kind of ["column", "row"] as const) { + const button = document.createElement("button"); + const label = kind === "column" ? "Add column to the right" : "Add row below"; + button.type = "button"; + button.className = `table-add table-add-${kind}`; + button.title = label; + button.setAttribute("aria-label", label); + const plus = document.createElement("span"); + plus.append(actionIcon("plus")); + plus.setAttribute("aria-hidden", "true"); + button.append(plus); + button.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); }); + button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); add(kind); }); + button.addEventListener("pointermove", event => { + const rect = button.getBoundingClientRect(); + button.style.setProperty("--table-add-position", `${kind === "column" ? Math.max(12, Math.min(rect.height - 12, event.clientY - rect.top)) : Math.max(12, Math.min(rect.width - 12, event.clientX - rect.left))}px`); + }); + wrapper.append(button); + } + for (const row of table.rows) for (const cell of row.cells) { + cell.tabIndex = 0; + cell.setAttribute("aria-label", `${cellAddress(row.rowIndex, cell.cellIndex)} · Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`); + cell.addEventListener("focus", () => activate(cell)); + } + selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions); + dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change); + table.addEventListener("mousedown", event => { + if (event.button !== 0) return; + if (event.ctrlKey || event.metaKey || !(event.target instanceof Element)) return; + const cell = event.target.closest("td, th"); + if (!cell) return; + event.stopPropagation(); + if (active !== cell) { + event.preventDefault(); activate(cell); + const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY }); + if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); } + } + }); + refreshFormulas(); +} diff --git a/src/lib/editor/tableDragControls.ts b/src/lib/editor/tableDragControls.ts new file mode 100644 index 0000000..44bcdfc --- /dev/null +++ b/src/lib/editor/tableDragControls.ts @@ -0,0 +1,226 @@ +import type { EditorView } from "@codemirror/view"; +import { actionIcon } from "../ui/actionIcons"; +import { moveTableAxis, type TableAxis } from "./tableStructure"; +import type { CellRange } from "./tableSelection"; + +const controls = new WeakMap void>(); + +export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, scroll: HTMLElement, view: EditorView, source: () => string, select: (range: CellRange) => void, change: (text: string, structural: boolean) => void) { + const lifecycle = new AbortController(), options = { signal: lifecycle.signal }; + const handles: { axis: TableAxis; index: number; button: HTMLButtonElement }[] = []; + const layer = document.createElement("div"); + layer.className = "table-drag-layer"; + wrapper.append(layer); + const indicator = document.createElement("div"); + indicator.className = "table-drop-indicator"; + indicator.hidden = true; + layer.append(indicator); + let preview: HTMLElement | undefined, previewLabel: HTMLElement | undefined; + let drag: { axis: TableAxis; index: number; pointer: number; x: number; y: number; startX: number; startY: number; active: boolean; to?: number; before: string } | undefined; + let frame = 0, layoutFrame = 0; + + function selectAxis(axis: TableAxis, index: number) { + select(axis === "row" + ? { anchor: { row: index, column: 0 }, head: { row: index, column: table.rows[0].cells.length - 1 } } + : { anchor: { row: 0, column: index }, head: { row: table.rows.length - 1, column: index } }); + } + function focusAxis(axis: TableAxis, index: number, keyboard = true) { + selectAxis(axis, index); + const button = handles.find(handle => handle.axis === axis && handle.index === index)?.button; + button?.toggleAttribute("data-pointer-focus", !keyboard); + button?.focus({ preventScroll: true }); + } + controls.set(table, focusAxis); + + function commit(axis: TableAxis, index: number, to: number, keyboard = true) { + const before = source(), after = moveTableAxis(before, axis, index, to); + if (before === after) return; + const from = view.posAtDOM(root), left = scroll.scrollLeft; + change(after, true); + const updated = [...view.dom.querySelectorAll(".writer-preview")].find(el => view.posAtDOM(el) === from); + const next = updated?.querySelector("table"); + const viewport = updated?.querySelector(".md-table-scroll"); + if (viewport) viewport.scrollLeft = left; + if (next) controls.get(next)?.(axis, to, keyboard); + } + + function layout() { + layoutFrame = 0; + const origin = wrapper.getBoundingClientRect(), viewport = scroll.getBoundingClientRect(); + for (const { axis, index, button } of handles) { + const rect = (axis === "row" ? table.rows[index] : table.rows[0].cells[index]).getBoundingClientRect(); + const left = Math.max(viewport.left, rect.left), right = Math.min(viewport.right, rect.right); + button.hidden = axis === "column" && right <= left; + Object.assign(button.style, axis === "row" + ? { left: `${viewport.left - origin.left - 26}px`, top: `${rect.top - origin.top}px`, width: "26px", height: `${rect.height}px` } + : { left: `${left - origin.left}px`, top: `${viewport.top - origin.top - 26}px`, width: `${Math.max(0, right - left)}px`, height: "26px" }); + button.style.setProperty("--table-tooltip-left", `${axis === "row" ? 26 : viewport.left - left}px`); + button.style.setProperty("--table-tooltip-width", `${Math.min(260, viewport.width)}px`); + } + } + function scheduleLayout() { if (!layoutFrame) layoutFrame = requestAnimationFrame(layout); } + + function createPreview() { + if (!drag) return; + preview = document.createElement("div"); + preview.className = `reading table-drag-preview table-drag-preview-${drag.axis}`; + preview.setAttribute("aria-hidden", "true"); + preview.inert = true; + previewLabel = document.createElement("div"); + previewLabel.className = "table-drag-preview-label"; + preview.append(previewLabel); + const content = document.createElement("div"); + content.className = "table-drag-preview-content"; + const copy = document.createElement("table"); + const rows = drag.axis === "row" ? [table.rows[drag.index]] : [...table.rows]; + const width = drag.axis === "row" ? table.getBoundingClientRect().width : table.rows[0].cells[drag.index].getBoundingClientRect().width; + preview.style.width = `${Math.min(width, drag.axis === "row" ? 560 : 280, window.innerWidth - 24)}px`; + copy.style.font = getComputedStyle(table).font; + for (const row of rows) { + const clonedRow = document.createElement("tr"); + const cells = drag.axis === "row" ? [...row.cells] : [row.cells[drag.index]]; + for (const cell of cells) { + const clonedCell = cell.cloneNode(true) as HTMLTableCellElement; + // A visual snapshot must not duplicate focusable controls, document IDs, + // or selection styling from the real cells. + for (const element of [clonedCell, ...clonedCell.querySelectorAll("*")]) { + for (const attribute of ["id", "tabindex", "contenteditable", "aria-selected", "aria-label", "data-selection-edges", "title"]) element.removeAttribute(attribute); + element.classList.remove("is-cell-selected", "is-editing"); + } + clonedCell.style.width = `${cell.getBoundingClientRect().width / width * 100}%`; + clonedRow.append(clonedCell); + } + copy.append(clonedRow); + } + content.append(copy); preview.append(content); document.body.append(preview); + updatePreview(); + } + + function updatePreview() { + if (!preview || !previewLabel || !drag) return; + const valid = drag.to !== undefined; + preview.classList.toggle("is-invalid-drop", !valid); + previewLabel.textContent = `${drag.axis === "row" ? "Row" : "Column"} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : " · Release to cancel"}`; + const rect = preview.getBoundingClientRect(); + const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8)); + const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8)); + preview.style.transform = `translate3d(${x}px, ${y}px, 0)`; + } + + function updateTarget() { + if (!drag?.active) return; + const { axis, x, y, index } = drag; + const viewport = scroll.getBoundingClientRect(), origin = wrapper.getBoundingClientRect(); + drag.to = undefined; + indicator.hidden = true; + if (x < viewport.left - 32 || x > viewport.right + 32 || y < viewport.top - 32 || y > viewport.bottom + 32) return; + const items = axis === "row" ? [...table.rows].slice(1) : [...table.rows[0].cells]; + if (!items.length) return; + const coordinate = axis === "row" ? y : x; + let boundary = items.findIndex(item => { + const rect = item.getBoundingClientRect(); + return coordinate < (axis === "row" ? (rect.top + rect.bottom) / 2 : (rect.left + rect.right) / 2); + }); + if (boundary < 0) boundary = items.length; + const insertion = boundary + (axis === "row" ? 1 : 0); + drag.to = insertion > index ? insertion - 1 : insertion; + if (drag.to === index) return; + const edge = (items[boundary] || items[items.length - 1]).getBoundingClientRect(); + const position = axis === "row" ? (boundary === items.length ? edge.bottom : edge.top) : (boundary === items.length ? edge.right : edge.left); + if (axis === "column" && (position < viewport.left || position > viewport.right)) return; + indicator.hidden = false; + Object.assign(indicator.style, axis === "row" + ? { left: `${viewport.left - origin.left}px`, top: `${position - origin.top - 2}px`, width: `${viewport.width}px`, height: "4px" } + : { left: `${position - origin.left - 2}px`, top: `${viewport.top - origin.top}px`, width: "4px", height: `${table.getBoundingClientRect().height}px` }); + } + function tick() { + if (!drag?.active) return; + const viewport = scroll.getBoundingClientRect(), editor = view.scrollDOM.getBoundingClientRect(); + const speed = (coordinate: number, start: number, end: number) => coordinate < start + 36 ? -Math.min(18, (start + 36 - coordinate) / 3) : coordinate > end - 36 ? Math.min(18, (coordinate - end + 36) / 3) : 0; + if (drag.x >= viewport.left - 32 && drag.x <= viewport.right + 32) { + if (drag.axis === "column") scroll.scrollLeft += speed(drag.x, viewport.left, viewport.right); + // Stop at the table's ends so an edge drag cannot scroll its own drop + // target out from under the pointer after the last row becomes visible. + const vertical = speed(drag.y, editor.top, editor.bottom); + view.scrollDOM.scrollTop += vertical > 0 + ? Math.min(vertical, Math.max(0, viewport.bottom - editor.bottom + 36)) + : Math.max(vertical, Math.min(0, viewport.top - editor.top - 36)); + } + layout(); updateTarget(); updatePreview(); + frame = requestAnimationFrame(tick); + } + function cancel() { + const previous = drag; + drag = undefined; + cancelAnimationFrame(frame); + indicator.hidden = true; + preview?.remove(); preview = undefined; previewLabel = undefined; + wrapper.classList.remove("is-table-dragging"); + if (previous) { + const button = handles.find(handle => handle.axis === previous.axis && handle.index === previous.index)?.button; + if (button?.hasPointerCapture(previous.pointer)) button.releasePointerCapture(previous.pointer); + } + } + + for (const axis of ["column", "row"] as const) { + const length = axis === "row" ? table.rows.length : table.rows[0].cells.length; + for (let index = axis === "row" ? 1 : 0; index < length; index++) { + const button = document.createElement("button"); + button.type = "button"; + button.className = `table-drag-handle table-drag-${axis}`; + button.dataset.index = String(index); + const label = `Move ${axis} ${index + 1}`; + const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`; + button.setAttribute("aria-label", label); + button.title = tooltip; + button.dataset.tooltip = tooltip; + button.append(actionIcon("grip")); + layer.append(button); + handles.push({ axis, index, button }); + button.addEventListener("pointerdown", event => { + if (event.button !== 0 || drag) return; + event.preventDefault(); event.stopPropagation(); + focusAxis(axis, index, false); + drag = { axis, index, pointer: event.pointerId, x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY, active: false, before: source() }; + button.setPointerCapture(event.pointerId); + }, options); + button.addEventListener("lostpointercapture", () => { if (drag) cancel(); }, options); + button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); }, options); + button.addEventListener("blur", () => button.removeAttribute("data-pointer-focus"), options); + button.addEventListener("keydown", event => { + button.removeAttribute("data-pointer-focus"); + const previous = axis === "row" ? "ArrowUp" : "ArrowLeft", next = axis === "row" ? "ArrowDown" : "ArrowRight"; + if (![previous, next, " ", "Enter"].includes(event.key)) return; + event.preventDefault(); event.stopPropagation(); + if (drag) return; + if (event.key === previous || event.key === next) commit(axis, index, index + (event.key === previous ? -1 : 1)); + else focusAxis(axis, index); + }, options); + } + } + document.addEventListener("pointermove", event => { + if (!drag || event.pointerId !== drag.pointer) return; + drag.x = event.clientX; drag.y = event.clientY; + if (!drag.active && Math.hypot(drag.x - drag.startX, drag.y - drag.startY) >= 5) { + drag.active = true; wrapper.classList.add("is-table-dragging"); createPreview(); tick(); + } + if (drag.active) { event.preventDefault(); updateTarget(); updatePreview(); } + }, { ...options, passive: false }); + document.addEventListener("pointerup", event => { + if (!drag || event.pointerId !== drag.pointer) return; + drag.x = event.clientX; drag.y = event.clientY; updateTarget(); + const completed = drag; + cancel(); + if (completed.active && completed.to !== undefined && source() === completed.before) commit(completed.axis, completed.index, completed.to, false); + }, options); + document.addEventListener("pointercancel", cancel, options); + document.addEventListener("keydown", event => { + if (drag && event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); cancel(); } + }, { ...options, capture: true }); + window.addEventListener("blur", cancel, options); + scroll.addEventListener("scroll", scheduleLayout, options); + const observer = new ResizeObserver(scheduleLayout); + observer.observe(table); observer.observe(scroll); + scheduleLayout(); + return { destroy() { cancel(); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } }; +} diff --git a/src/lib/editor/tableFormulas.ts b/src/lib/editor/tableFormulas.ts new file mode 100644 index 0000000..8039643 --- /dev/null +++ b/src/lib/editor/tableFormulas.ts @@ -0,0 +1,151 @@ +// Formulas are plain Markdown cell text. No JavaScript evaluation or external data. +export const formulaErrors = { + "#ERROR!": "Invalid formula syntax or function arguments", + "#REF!": "Cell reference is outside this table", + "#VALUE!": "Expected a number", + "#NAME?": "Unknown function or cell name", + "#DIV/0!": "Cannot divide by zero or average an empty range", + "#CYCLE!": "Circular cell reference", + "#NUM!": "Result is not a finite number", + "#LIMIT!": "Formula is too complex", +} as const; +type ErrorCode = keyof typeof formulaErrors; +export type FormulaResult = { formula: string; text: string; value?: number; error?: ErrorCode }; +class FormulaError extends Error { + code: ErrorCode; + constructor(code: ErrorCode) { super(formulaErrors[code]); this.code = code; } +} +function fail(code: ErrorCode): never { throw new FormulaError(code); } +export const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim()); + +export function cellAddress(row: number, column: number): string { + let letters = ""; + for (let n = column + 1; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + (n - 1) % 26) + letters; + return letters + (row + 1); +} + +type Scalar = number | string | null; +type Value = Scalar | Scalar[]; +const number = (value: Value): number => typeof value === "number" ? value : value === null ? 0 : fail("#VALUE!"); +const finite = (value: number) => Number.isFinite(value) ? value : fail("#NUM!"); +const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; + +// Header is row 1; the Markdown separator is not a spreadsheet row. +export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[][] { + const cache = new Map(); + const visiting = new Set(); + let budget = 50000; + const spend = () => { if (--budget < 0) fail("#LIMIT!"); }; + function reference(address: string): [number, number] { + const match = /^\$?([A-Z]+)\$?([1-9]\d*)$/i.exec(address) || fail("#REF!"); + let column = 0; + for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64; + const row = Number(match[2]); + if (row > grid.length || column > (grid[0]?.length || 0)) fail("#REF!"); + return [row - 1, column - 1]; + } + function cell(row: number, column: number): Scalar { + spend(); + const key = `${row}:${column}`; + if (visiting.has(key)) fail("#CYCLE!"); + if (visiting.size >= 128) fail("#LIMIT!"); + const cached = cache.get(key); + if (cached instanceof FormulaError) throw cached; + if (cache.has(key)) return cached!; + const source = (grid[row]?.[column] || "").trim(); + if (!isTableFormula(source)) return source === "" ? null : numeric.test(source) ? finite(Number(source)) : source; + visiting.add(key); + try { + const value = parse(source.slice(1)); + cache.set(key, value); + return value; + } catch (error) { + const problem = error instanceof FormulaError ? error : new FormulaError("#LIMIT!"); + cache.set(key, problem); + throw problem; + } finally { visiting.delete(key); } + } + function parse(source: string): number { + if (source.length > 2048) fail("#LIMIT!"); + const tokens: string[] = []; + const pattern = /\s*(\$?[A-Za-z]+\$?\d+|[A-Za-z_]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+\-*/^%(),:])/y; + let offset = 0; + while (offset < source.trimEnd().length) { + pattern.lastIndex = offset; + const match = pattern.exec(source) || fail("#ERROR!"); + tokens.push(match[1]); offset = pattern.lastIndex; + } + let position = 0, depth = 0; + const peek = () => tokens[position]; + const take = () => { spend(); return tokens[position++]; }; + const expect = (token: string) => { if (take() !== token) fail("#ERROR!"); }; + function expression(min = 0): Value { + if (++depth > 64) fail("#LIMIT!"); + let left: Value; + const token = take(); + if (token === "+" || token === "-") left = number(expression(3)) * (token === "-" ? -1 : 1); + else if (token === "(") { left = expression(); expect(")"); } + else if (token && numeric.test(token)) left = finite(Number(token)); + else if (token && /^\$?[a-z]+\$?\d+$/i.test(token)) { + const [row, column] = reference(token); + if (peek() === ":") { + take(); const [endRow, endColumn] = reference(take() || ""); + const values: Scalar[] = []; + for (let r = Math.min(row, endRow); r <= Math.max(row, endRow); r++) { + for (let c = Math.min(column, endColumn); c <= Math.max(column, endColumn); c++) values.push(cell(r, c)); + } + left = values; + } else left = cell(row, column); + } else if (token && /^[a-z_]+$/i.test(token)) { + if (peek() !== "(") fail("#NAME?"); + take(); const args: Value[] = []; + if (peek() !== ")") { + do { args.push(expression()); if (peek() !== ",") break; take(); } while (true); + } + expect(")"); + left = call(token.toUpperCase(), args); + } else fail("#ERROR!"); + while (true) { + const op = peek(); + if (op === "%") { take(); left = number(left) / 100; continue; } + const precedence = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 3 : -1; + if (precedence < min) break; + take(); + const right = number(expression(precedence + (op === "^" ? 0 : 1))), a = number(left); + left = finite(op === "+" ? a + right : op === "-" ? a - right : op === "*" ? a * right : op === "/" ? (right === 0 ? fail("#DIV/0!") : a / right) : a ** right); + } + depth--; + return left; + } + const result = finite(number(expression())); + if (position !== tokens.length) fail("#ERROR!"); + return result; + } + function call(name: string, args: Value[]): number { + if (name === "ABS") return args.length === 1 ? Math.abs(number(args[0])) : fail("#ERROR!"); + if (name === "ROUND") { + if (args.length < 1 || args.length > 2) fail("#ERROR!"); + const value = number(args[0]), digits = args.length === 2 ? number(args[1]) : 0; + if (!Number.isInteger(digits) || Math.abs(digits) > 100) fail("#NUM!"); + const factor = 10 ** digits, scaled = Math.abs(value) * factor; + return finite(Math.sign(value) * Math.round(scaled + Number.EPSILON * scaled) / factor); + } + if (!["SUM", "AVERAGE", "MIN", "MAX", "COUNT"].includes(name)) fail("#NAME?"); + const values = args.flat().filter((value): value is number => typeof value === "number"); + if (name === "COUNT") return values.length; + if (name === "MIN" || name === "MAX") return values.length ? values.reduce((a, b) => name === "MIN" ? Math.min(a, b) : Math.max(a, b)) : 0; + const sum = finite(values.reduce((a, b) => a + b, 0)); + return name === "AVERAGE" ? (values.length ? sum / values.length : fail("#DIV/0!")) : sum; + } + return grid.map((row, r) => row.map((source, c) => { + if (!isTableFormula(source)) return null; + const formula = source.trim(); + try { + const value = number(cell(r, c)); + return { formula, value, text: String(Number(value.toPrecision(12))) }; + } catch (error) { + const code = error instanceof FormulaError ? error.code : "#LIMIT!"; + return { formula, text: code, error: code }; + } + })); +} diff --git a/src/lib/editor/tableNavigation.ts b/src/lib/editor/tableNavigation.ts new file mode 100644 index 0000000..dd1559e --- /dev/null +++ b/src/lib/editor/tableNavigation.ts @@ -0,0 +1,32 @@ +import { Prec } from "@codemirror/state"; +import { keymap } from "@codemirror/view"; +import { tableEditors } from "./tableControls"; + +// Tables are atomic in the prose editor. Intercept a movement that would cross +// one before CodeMirror skips the widget, and hand focus to its cell editor. +export const tableNavigation = Prec.high(keymap.of(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].map(key => ({ + key, + run(view) { + const selection = view.state.selection.main; + if (!view.hasFocus || !selection.empty || view.state.selection.ranges.length !== 1) return false; + const forward = key === "ArrowRight" || key === "ArrowDown"; + const vertical = key === "ArrowUp" || key === "ArrowDown"; + const next = vertical ? view.moveVertically(selection, forward) : view.moveByChar(selection, forward); + const previews = [...view.dom.querySelectorAll(".writer-preview")]; + if (!forward) previews.reverse(); + for (const root of previews) { + const table = tableEditors.get(root); + if (!table) continue; + const from = view.posAtDOM(root), to = from + table.source.length; + const crosses = forward + ? selection.head <= from && next.head >= from + : selection.head >= to && next.head <= to; + if (!crosses) continue; + const goal = selection.goalColumn ?? next.goalColumn; + const x = goal === undefined ? view.coordsAtPos(selection.head)?.left : view.contentDOM.getBoundingClientRect().left + goal; + table.enter(forward, vertical ? x : undefined); + return true; + } + return false; + }, +})))); diff --git a/src/lib/editor/tableSelection.ts b/src/lib/editor/tableSelection.ts new file mode 100644 index 0000000..48ac5e6 --- /dev/null +++ b/src/lib/editor/tableSelection.ts @@ -0,0 +1,119 @@ +import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable.ts"; +import { plainInlineMarkdown } from "../workspace/noteHtml.ts"; + +export type CellPoint = { row: number; column: number }; +export type CellRange = { anchor: CellPoint; head: CellPoint }; +export type CellFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear"; + +export function bounds(range: CellRange) { + return { top: Math.min(range.anchor.row, range.head.row), bottom: Math.max(range.anchor.row, range.head.row), left: Math.min(range.anchor.column, range.head.column), right: Math.max(range.anchor.column, range.head.column) }; +} +const sourceRow = (row: number) => row === 0 ? 0 : row + 1; + +export function mapTableCells(source: string, range: CellRange, transform: (text: string) => string): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const { top, bottom, left, right } = bounds(range); + for (let r = Math.max(0, top); r <= Math.min(bottom, table.rows.length - 2); r++) { + for (let c = Math.max(0, left); c <= Math.min(right, table.columns - 1); c++) { + source = replaceTableCell(source, sourceRow(r), c, transform(table.rows[sourceRow(r)].cells[c]?.text || "")); + } + } + return source; +} + +export function formatTableCells(source: string, range: CellRange, format: CellFormat): string { + if (format === "clear") return mapTableCells(source, range, plainInlineMarkdown); + const marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format]; + const wrapped = (text: string) => format === "code" ? /^(`+)(?!`)([\s\S]*[^`])\1(?!`)$/.test(text) + : text.startsWith(marker) && text.endsWith(marker) && text.length > marker.length * 2 && !(format === "italic" && text.startsWith("**") && !text.startsWith("***")); + let allWrapped = true; + mapTableCells(source, range, text => { if (text.trim() && !wrapped(text)) allWrapped = false; return text; }); + return mapTableCells(source, range, text => { + if (!text.trim()) return text; + if (wrapped(text)) return allWrapped ? (format === "code" ? plainInlineMarkdown(text) : text.slice(marker.length, -marker.length)) : text; + if (format === "code") { + const fence = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(m => m[0].length)) + 1); + return `${fence} ${text} ${fence}`; + } + return marker + text + marker; + }); +} + +export function alignTableCells(source: string, range: CellRange, alignment: "left" | "center" | "right"): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const { left, right } = bounds(range); + const marker = { left: ":---", center: ":---:", right: "---:" }[alignment]; + for (let c = Math.min(right, table.columns - 1); c >= Math.max(0, left); c--) { + const cell = table.rows[1].cells[c]; + source = source.slice(0, cell.from) + marker + source.slice(cell.to); + } + return source; +} + +export function copyTableCells(source: string, range: CellRange): string { + const table = parseMarkdownTable(source); + if (!table) return ""; + const { top, bottom, left, right } = bounds(range); + const quote = (value: string) => /[\t\r\n"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value; + return Array.from({ length: bottom - top + 1 }, (_, r) => Array.from({ length: right - left + 1 }, (_, c) => quote(table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "")).join("\t")).join("\n"); +} + +// Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table. +export function clipboardCells(text: string): string[][] { + const table = parseMarkdownTable(text); + if (table) return table.rows.filter((_, i) => i !== 1).map(row => row.cells.map(cell => cell.text)); + const rows: string[][] = [[]]; + let cell = "", quoted = false; + text = text.replace(/\r\n?/g, "\n").replace(/\n$/, ""); + for (let i = 0; i < text.length; i++) { + const char = text[i]; + if (char === '"' && (quoted || !cell)) { + if (quoted && text[i + 1] === '"') { cell += '"'; i++; } + else quoted = !quoted; + } else if (!quoted && (char === "\t" || char === "\n")) { + rows.at(-1)!.push(cell); cell = ""; + if (char === "\n") rows.push([]); + } else cell += char; + } + rows.at(-1)!.push(cell); + return rows.map(row => row.map(value => value.replace(/\n/g, "
      ").replace(/(\\*)\|/g, (match, slashes: string) => slashes.length % 2 ? match : `${slashes}\\|`))); +} + +export function pasteTableCells(source: string, range: CellRange, text: string): string { + if (!parseMarkdownTable(source)) return source; + const cells = clipboardCells(text), { top, bottom, left, right } = bounds(range); + if (cells.length === 1 && cells[0].length === 1) return mapTableCells(source, range, () => cells[0][0]); + const gridWidth = Math.max(...cells.map(row => row.length)); + const height = Math.max(bottom - top + 1, cells.length), width = Math.max(right - left + 1, gridWidth); + while (parseMarkdownTable(source)!.columns < left + width) source = appendTableColumn(source); + while (parseMarkdownTable(source)!.rows.length - 1 < top + height) source = appendTableRow(source); + for (let r = 0; r < height; r++) for (let c = 0; c < width; c++) { + source = replaceTableCell(source, sourceRow(top + r), left + c, cells[r % cells.length][c % gridWidth] ?? ""); + } + return source; +} + +// Whole rows/columns are removed structurally; a partial rectangle shifts cells left. +export function deleteTableCells(source: string, range: CellRange): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const { top, bottom, left, right } = bounds(range); + const allRows = top === 0 && bottom >= table.rows.length - 2; + const allColumns = left === 0 && right >= table.columns - 1; + if (allRows && allColumns) return source.slice(table.end); + const rows = table.rows.flatMap((row, i) => { + const r = i === 0 ? 0 : i - 1; + if (allColumns && i !== 1 && r >= top && r <= bottom) return []; + const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || ""); + if (allRows || (i !== 1 && r >= top && r <= bottom)) { + cells.splice(left, right - left + 1); + if (!allRows) while (cells.length < table.columns) cells.push(""); + } + return [{ ...row, cells }]; + }); + // Deleting the header promotes the first remaining body row. + if (allColumns && top === 0) [rows[0], rows[1]] = [rows[1], rows[0]]; + return rows.map(row => `${row.indent}| ${row.cells.join(" | ")} |`).join(table.eol) + source.slice(table.end); +} diff --git a/src/lib/editor/tableSelectionControls.ts b/src/lib/editor/tableSelectionControls.ts new file mode 100644 index 0000000..8640f87 --- /dev/null +++ b/src/lib/editor/tableSelectionControls.ts @@ -0,0 +1,225 @@ +import type { EditorView } from "@codemirror/view"; +import { undo, redo, isolateHistory } from "@codemirror/commands"; +import type { Editor } from "@tiptap/core"; +import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure"; +import { actionMenu, type ActionMenuItem } from "../ui/actionMenu"; +import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions"; +import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection"; + +const selections = new WeakMap void>(); + +export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void }, actions: TableContextActions) { + const lifecycle = new AbortController(), options = { signal: lifecycle.signal }; + let range: CellRange | undefined, down: CellPoint | undefined, dragging = false; + let menu: HTMLElement | undefined; + let pending = false; + wrapper.tabIndex = -1; + wrapper.contentEditable = "false"; + const point = (cell: HTMLTableCellElement): CellPoint => ({ row: (cell.parentElement as HTMLTableRowElement).rowIndex, column: cell.cellIndex }); + function cellAt(target: EventTarget | null) { + const cell = target instanceof Element ? target.closest("td, th") : null; + return cell?.closest("table") === table ? cell : null; + } + function closeMenu() { menu?.remove(); menu = undefined; } + function clear() { + range = undefined; closeMenu(); + wrapper.classList.remove("has-cell-selection"); + for (const cell of table.querySelectorAll("th, td")) { cell.classList.remove("is-cell-selected"); cell.removeAttribute("aria-selected"); cell.removeAttribute("data-selection-edges"); } + } + function select(next: CellRange) { + finish(); + const clamp = (p: CellPoint) => ({ row: Math.max(0, Math.min(table.rows.length - 1, p.row)), column: Math.max(0, Math.min(table.rows[0].cells.length - 1, p.column)) }); + range = { anchor: clamp(next.anchor), head: clamp(next.head) }; + const { top, bottom, left, right } = bounds(range); + wrapper.classList.add("has-cell-selection"); + for (const row of table.rows) for (const cell of row.cells) { + const selected = row.rowIndex >= top && row.rowIndex <= bottom && cell.cellIndex >= left && cell.cellIndex <= right; + cell.classList.toggle("is-cell-selected", selected); + cell.setAttribute("aria-selected", String(selected)); + if (selected) cell.setAttribute("data-selection-edges", [ + row.rowIndex === top && "top", row.rowIndex === bottom && "bottom", + cell.cellIndex === left && "left", cell.cellIndex === right && "right", + ].filter(Boolean).join(" ")); + else cell.removeAttribute("data-selection-edges"); + } + document.getSelection()?.removeAllRanges(); + wrapper.focus({ preventScroll: true }); + } + selections.set(table, select); + function apply(transform: (text: string, selected: CellRange) => string, restore?: CellRange) { + if (!range) return; + const selected = range, from = view.posAtDOM(root); + closeMenu(); finish(); + change(transform(source(), selected), true); + const updated = [...view.dom.querySelectorAll(".writer-preview")].find(el => view.posAtDOM(el) === from); + const nextTable = updated?.querySelector("table"); + if (nextTable) selections.get(nextTable)?.(restore || selected); + else view.focus(); + } + const clearCells = () => apply((text, selected) => mapTableCells(text, selected, () => "")); + const format = (kind: CellFormat) => apply((text, selected) => formatTableCells(text, selected, kind)); + async function clipboard(action: "copy" | "cut" | "paste") { + if (!range) return; + const before = source(), selected = range; + closeMenu(); wrapper.focus({ preventScroll: true }); + try { + if (action === "paste") { + const text = await navigator.clipboard.readText(); + if (root.isConnected && source() === before && range === selected) apply((value, target) => pasteTableCells(value, target, text)); + } else { + await navigator.clipboard.writeText(copyTableCells(before, selected)); + if (action === "cut" && root.isConnected && source() === before && range === selected) clearCells(); + } + } catch { + const status = root.querySelector(".table-edit-help"); + if (status) { status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; } + } + } + function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) { + if (!at) return; + closeMenu(); + const cellRange = { anchor: at, head: at }; + const returnFocus = () => { closeMenu(); if (textEditor && !textEditor.isDestroyed) textEditor.view.focus(); else wrapper.focus(); }; + function structural(axis: TableAxis, operation: TableOperation) { + range ??= cellRange; + const index = axis === "row" ? at!.row : at!.column; + const next = { ...at! }; + if (operation === "previous") next[axis]--; + if (operation === "next" || operation === "after" || operation === "duplicate") next[axis]++; + apply(text => changeTableStructure(text, axis, index, operation), { anchor: next, head: next }); + } + const row = at.row, column = at.column, lastRow = table.rows.length - 1, lastColumn = table.rows[0].cells.length - 1; + const sep: ActionMenuItem = { separator: true }; + const align = (alignment: "left" | "center" | "right") => { + range ??= cellRange; + apply((text, selected) => alignTableCells(text, selected, alignment)); + }; + const alignmentItems: ActionMenuItem[] = [ + { label: "Align left", icon: "left", run: () => align("left") }, + { label: "Align centre", icon: "center", run: () => align("center") }, + { label: "Align right", icon: "right", run: () => align("right") }, + ].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem)); + const report = (message: string) => { + const status = root.querySelector(".table-edit-help"); + if (status) { status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; } + }; + const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => { + view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") }); + }, value => { pending = value; }, report) : [ + ...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })), + sep, + { label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) }, + ...alignmentItems, + sep, { label: "Clear cells", icon: "clear", run: clearCells }, + { label: "Delete cells", icon: "trash", run: () => apply(deleteTableCells), title: "Remove selected rows/columns; otherwise shift cells left" }, + ]; + items.push(sep, + { label: "Row", icon: "row", children: [ + { label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") }, + { label: "Add row below", icon: "row-after", run: () => structural("row", "after") }, sep, + { label: "Move row up", icon: "up", disabled: row <= 1, run: () => structural("row", "previous") }, + { label: "Move row down", icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep, + { label: "Duplicate row", icon: "copy", run: () => structural("row", "duplicate") }, + { label: "Delete row", icon: "trash", run: () => structural("row", "delete") }, + ] }, + { label: "Column", icon: "column", children: [ + { label: "Add column to the left", icon: "column-before", run: () => structural("column", "before") }, + { label: "Add column to the right", icon: "column-after", run: () => structural("column", "after") }, sep, + { label: "Move column left", icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") }, + { label: "Move column right", icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep, + ...alignmentItems, sep, + { label: "Duplicate column", icon: "copy", run: () => structural("column", "duplicate") }, + { label: "Delete column", icon: "trash", run: () => structural("column", "delete") }, + ] }, sep, + { label: "Sort by column (A to Z)", icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } }, + { label: "Sort by column (Z to A)", icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } }, + ); + menu = actionMenu(x, y, items, returnFocus); + } + table.addEventListener("mousedown", event => { + const cell = cellAt(event.target); + if (cell && event.button === 2) { event.preventDefault(); return; } + if (!cell || event.button !== 0 || event.ctrlKey || event.metaKey) return; + closeMenu(); down = point(cell); dragging = false; + if (event.shiftKey) { + event.preventDefault(); event.stopImmediatePropagation(); + const active = table.querySelector(".is-editing"); + select({ anchor: range?.anchor || (active ? point(active) : down), head: down }); dragging = true; + } else clear(); + }, { ...options, capture: true }); + document.addEventListener("mousemove", event => { + if (!down || !(event.buttons & 1)) return; + const cell = cellAt(document.elementFromPoint(event.clientX, event.clientY)); + if (!cell) return; + const head = point(cell); + if (dragging || head.row !== down.row || head.column !== down.column) { + event.preventDefault(); dragging = true; + select({ anchor: range?.anchor || down, head }); + } + }, options); + document.addEventListener("mouseup", () => { down = undefined; }, options); + table.addEventListener("dragstart", event => event.preventDefault(), options); + table.addEventListener("focus", event => { if (range && cellAt(event.target)) clear(); }, { ...options, capture: true }); + table.addEventListener("click", event => { if (dragging) { event.preventDefault(); event.stopPropagation(); dragging = false; } }, { ...options, capture: true }); + table.addEventListener("contextmenu", event => { + const cell = cellAt(event.target); if (!cell) return; + event.preventDefault(); event.stopPropagation(); + if (cell.classList.contains("is-cell-selected")) showMenu(event.clientX, event.clientY, point(cell)); + else { + clear(); rich.activate(cell); + const current = rich.get(); + // A context click can arrive before the browser's selectionchange event. + // Read the visible word selection before moving focus into the menu. + const native = document.getSelection(); + if (current && native && !native.isCollapsed && native.anchorNode && native.focusNode && current.view.dom.contains(native.anchorNode) && current.view.dom.contains(native.focusNode)) { + current.commands.setTextSelection({ from: current.view.posAtDOM(native.anchorNode, native.anchorOffset), to: current.view.posAtDOM(native.focusNode, native.focusOffset) }); + } + if (current?.state.selection.empty) { + const hit = current.view.posAtCoords({ left: event.clientX, top: event.clientY }); + if (hit) current.commands.setTextSelection(hit.pos); + } + showMenu(event.clientX, event.clientY, point(cell), current); + } + }, options); + document.addEventListener("mousedown", event => { if (!wrapper.contains(event.target as Node) && !menu?.contains(event.target as Node)) { clear(); if (!pending) finish(); } }, options); + document.addEventListener("scroll", event => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }, { ...options, capture: true }); + window.addEventListener("resize", closeMenu, options); + wrapper.addEventListener("keydown", event => { + if (!range) return; + const mod = event.ctrlKey || event.metaKey, key = event.key.toLowerCase(); + const handled = ["Escape", "Delete", "Backspace", "Enter", "ContextMenu", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) || (event.shiftKey && event.key === "F10") || (mod && ["b", "i", "z", "y", "a"].includes(key)); + if (!handled) return; + event.preventDefault(); event.stopPropagation(); + if (mod && ["z", "y"].includes(key)) { closeMenu(); (key === "y" || event.shiftKey ? redo : undo)(view); view.focus(); } + else if (mod && key === "a") select({ anchor: { row: 0, column: 0 }, head: { row: table.rows.length - 1, column: table.rows[0].cells.length - 1 } }); + else if (mod && ["b", "i"].includes(key)) format(key === "b" ? "bold" : "italic"); + else if (event.key === "Escape") { clear(); view.focus(); } + else if (event.key === "Delete" || event.key === "Backspace") clearCells(); + else if (event.key === "Enter") { const target = table.rows[range.head.row].cells[range.head.column]; clear(); target.focus(); } + else if (event.key === "ContextMenu" || event.key === "F10") { const rect = table.rows[range.head.row].cells[range.head.column].getBoundingClientRect(); showMenu(rect.left, rect.bottom); } + else { + const head = { ...range.head }; + if (event.key === "ArrowLeft") head.column--; if (event.key === "ArrowRight") head.column++; + if (event.key === "ArrowUp") head.row--; if (event.key === "ArrowDown") head.row++; + select({ anchor: event.shiftKey ? range.anchor : head, head }); + table.rows[range!.head.row].cells[range!.head.column].scrollIntoView({ block: "nearest", inline: "nearest" }); + } + }, options); + for (const action of ["copy", "cut", "paste"] as const) wrapper.addEventListener(action, event => { + if (!range || !event.clipboardData) return; + if (action === "paste" && !event.clipboardData.types.includes("text/plain")) return; + event.preventDefault(); event.stopPropagation(); + if (action === "paste") apply((text, selected) => pasteTableCells(text, selected, event.clipboardData!.getData("text/plain"))); + else { event.clipboardData.setData("text/plain", copyTableCells(source(), range)); if (action === "cut") clearCells(); } + }, { ...options, capture: true }); + // Spreadsheet data pasted while editing one cell becomes a grid operation. + wrapper.addEventListener("paste", event => { + if (range) return; + const text = event.clipboardData?.getData("text/plain") || ""; + const cell = cellAt(event.target); + if (!cell || !text.includes("\t")) return; + event.preventDefault(); event.stopPropagation(); select({ anchor: point(cell), head: point(cell) }); + apply((value, selected) => pasteTableCells(value, selected, text)); + }, { ...options, capture: true }); + return { select, keepEditing: () => !!menu || pending, destroy: () => { lifecycle.abort(); closeMenu(); selections.delete(table); } }; +} diff --git a/src/lib/editor/tableStructure.ts b/src/lib/editor/tableStructure.ts new file mode 100644 index 0000000..1ece344 --- /dev/null +++ b/src/lib/editor/tableStructure.ts @@ -0,0 +1,69 @@ +import { parseMarkdownTable } from "./markdownTable.ts"; +import { deleteTableCells } from "./tableSelection.ts"; +import { plainInlineMarkdown } from "../workspace/noteHtml.ts"; + +export type TableAxis = "row" | "column"; +export type TableOperation = "before" | "after" | "previous" | "next" | "duplicate" | "delete"; + +// Indices refer to rendered rows (header = 0), or columns. `to` is the +// final position, after removing the source item. +export function moveTableAxis(source: string, axis: TableAxis, from: number, to: number): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const size = axis === "row" ? table.rows.length - 1 : table.columns; + const first = axis === "row" ? 1 : 0; + if (![from, to].every(index => Number.isInteger(index) && index >= first && index < size) || from === to) return source; + function move(items: T[], start: number, end: number) { + items.splice(end, 0, items.splice(start, 1)[0]); + return items; + } + const rows = axis === "row" + ? move(table.rows.map(row => source.slice(row.from, row.to)), from + 1, to + 1) + : table.rows.map(row => { + const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, i) => row.cells[i]?.text || ""); + return `${row.indent}| ${move(cells, from, to).join(" | ")} |`; + }); + return rows.join(table.eol) + source.slice(table.end); +} + +export function changeTableStructure(source: string, axis: TableAxis, index: number, operation: TableOperation): string { + const table = parseMarkdownTable(source); + if (!table) return source; + const size = axis === "row" ? table.rows.length - 1 : table.columns; + if (index < 0 || index >= size) return source; + if (operation === "delete") return deleteTableCells(source, axis === "row" + ? { anchor: { row: index, column: 0 }, head: { row: index, column: table.columns - 1 } } + : { anchor: { row: 0, column: index }, head: { row: table.rows.length - 2, column: index } }); + const moving = operation === "previous" || operation === "next"; + const other = index + (operation === "previous" ? -1 : 1); + // The Markdown header stays a header; row movement and sorting affect the body. + if (moving && (other < (axis === "row" ? 1 : 0) || other >= size || (axis === "row" && index === 0))) return source; + if (axis === "row") { + if (index === 0 && operation === "before") return source; + const rows = table.rows.map(row => source.slice(row.from, row.to)); + const at = index === 0 ? 0 : index + 1; + if (moving) [rows[at], rows[other + 1]] = [rows[other + 1], rows[at]]; + else { + const value = operation === "duplicate" ? rows[at] : `${table.rows[0].indent}| ${Array(table.columns).fill("").join(" | ")} |`; + rows.splice(index === 0 ? 2 : at + (operation === "before" ? 0 : 1), 0, value); + } + return rows.join(table.eol) + source.slice(table.end); + } + const rows = table.rows.map((row, r) => { + const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || ""); + if (moving) [cells[index], cells[other]] = [cells[other], cells[index]]; + else cells.splice(index + (operation === "before" ? 0 : 1), 0, operation === "duplicate" ? cells[index] : r === 1 ? "---" : ""); + return `${row.indent}| ${cells.join(" | ")} |`; + }); + return rows.join(table.eol) + source.slice(table.end); +} + +export function sortTableColumn(source: string, column: number, descending = false): string { + const table = parseMarkdownTable(source); + if (!table || column < 0 || column >= table.columns) return source; + const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }); + const key = (text: string) => plainInlineMarkdown(text).replace(/
      /g, " ").replace(/\\([\\`*_[\]~<>!|=$%])/g, "$1").trim(); + const rows = table.rows.slice(2).map(row => ({ row, key: key(row.cells[column]?.text || "") })); + rows.sort((a, b) => !a.key ? (b.key ? 1 : 0) : !b.key ? -1 : collator.compare(a.key, b.key) * (descending ? -1 : 1)); + return [...table.rows.slice(0, 2), ...rows.map(item => item.row)].map(row => source.slice(row.from, row.to)).join(table.eol) + source.slice(table.end); +} diff --git a/src/lib/editor/workspaceImageDrop.ts b/src/lib/editor/workspaceImageDrop.ts new file mode 100644 index 0000000..e676cac --- /dev/null +++ b/src/lib/editor/workspaceImageDrop.ts @@ -0,0 +1,26 @@ +import { isImagePath } from "../workspace/media"; + +type Point = { x: number; y: number }; +const targets = new Map void>(); +let highlighted: HTMLElement | undefined; +export function registerImageDropTarget(element: HTMLElement, drop: (path: string, point: Point) => void) { + targets.set(element, drop); + return () => { targets.delete(element); element.classList.remove("image-drop-target"); }; +} +function targetAt(path: string, point: Point) { + if (!isImagePath(path)) return; + const hit = document.elementFromPoint(point.x, point.y); + return [...targets].find(([element]) => element.isConnected && hit && element.contains(hit)); +} +export function highlightImageDrop(path?: string, point?: Point): boolean { + highlighted?.classList.remove("image-drop-target"); + highlighted = path && point ? targetAt(path, point)?.[0] : undefined; + highlighted?.classList.add("image-drop-target"); + return !!highlighted; +} +export function dropWorkspaceImage(path: string, point: Point): boolean { + const target = targetAt(path, point); + highlightImageDrop(); + target?.[1](path, point); + return !!target; +} diff --git a/src/lib/editor/writerMarks.ts b/src/lib/editor/writerMarks.ts new file mode 100644 index 0000000..eb32c56 --- /dev/null +++ b/src/lib/editor/writerMarks.ts @@ -0,0 +1,21 @@ +import { Mark } from "@tiptap/core"; + +export const MathMark = Mark.create({ + name: "math", + parseHTML() { + return [{ tag: "span[data-math]" }]; + }, + renderHTML() { + return ["span", { "data-math": "1", class: "md-math" }, 0]; + }, +}); + +export const CommentMark = Mark.create({ + name: "comment", + parseHTML() { + return [{ tag: "span[data-comment]" }]; + }, + renderHTML() { + return ["span", { "data-comment": "1", class: "md-comment" }, 0]; + }, +}); diff --git a/src/lib/editor/writerMenu.ts b/src/lib/editor/writerMenu.ts new file mode 100644 index 0000000..e54e802 --- /dev/null +++ b/src/lib/editor/writerMenu.ts @@ -0,0 +1,143 @@ +import type { Editor } from "@tiptap/core"; +import type { MenuItem } from "../layout/menuTypes"; + +function selectedText(editor: Editor): string { + const { from, to } = editor.state.selection; + return editor.state.doc.textBetween(from, to, "\n"); +} + +async function writeClipboard(text: string): Promise { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + return false; + } +} + +export async function cutSelection(editor: Editor): Promise { + const text = selectedText(editor); + if (text && !(await writeClipboard(text))) { + return; + } + editor.chain().focus().deleteSelection().run(); +} + +export async function copySelection(editor: Editor): Promise { + const text = selectedText(editor); + if (text) { + await writeClipboard(text); + } +} + +export async function pasteClipboard(editor: Editor): Promise { + let text = ""; + try { + text = await navigator.clipboard.readText(); + } catch { + return; + } + if (!text) { + return; + } + editor.chain().focus().run(); + editor.view.dispatch(editor.state.tr.insertText(text)); +} + +export function writerContextItems(editor: Editor): MenuItem[] { + const inTable = editor.isActive("table"); + return [ + { kind: "action", label: "Cut", run: () => void cutSelection(editor) }, + { kind: "action", label: "Copy", run: () => void copySelection(editor) }, + { kind: "action", label: "Paste", run: () => void pasteClipboard(editor) }, + { kind: "sep" }, + { + kind: "group", + label: "Style", + items: [ + { kind: "action", label: "Heading 1", run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() }, + { kind: "action", label: "Heading 2", run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() }, + { kind: "action", label: "Heading 3", run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() }, + { kind: "action", label: "Heading 4", run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() }, + { kind: "action", label: "Heading 5", run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() }, + { kind: "action", label: "Heading 6", run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() }, + { kind: "action", label: "Body", run: () => editor.chain().focus().setParagraph().run() }, + { kind: "action", label: "Quote", run: () => editor.chain().focus().toggleBlockquote().run() }, + { kind: "sep" }, + { kind: "action", label: "Bullet list", run: () => editor.chain().focus().toggleBulletList().run() }, + { kind: "action", label: "Numbered list", run: () => editor.chain().focus().toggleOrderedList().run() }, + { kind: "action", label: "Task list", run: () => editor.chain().focus().toggleTaskList().run() }, + ], + }, + { + kind: "group", + label: "Format", + items: [ + { kind: "action", label: "Bold", run: () => editor.chain().focus().toggleBold().run() }, + { kind: "action", label: "Italic", run: () => editor.chain().focus().toggleItalic().run() }, + { kind: "action", label: "Strikethrough", run: () => editor.chain().focus().toggleStrike().run() }, + { kind: "action", label: "Highlight", run: () => editor.chain().focus().toggleHighlight().run() }, + { kind: "action", label: "Code", run: () => editor.chain().focus().toggleCode().run() }, + { kind: "action", label: "Math", run: () => editor.chain().focus().toggleMark("math").run() }, + { kind: "action", label: "Comment", run: () => editor.chain().focus().toggleMark("comment").run() }, + { kind: "sep" }, + { kind: "action", label: "Clear formatting", run: () => editor.chain().focus().unsetAllMarks().run() }, + ], + }, + { + kind: "group", + label: "Table", + items: [ + { + kind: "action", + label: "Insert table", + run: () => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(), + }, + { kind: "sep" }, + { + kind: "action", + label: "Add row above", + disabled: !inTable, + run: () => editor.chain().focus().addRowBefore().run(), + }, + { + kind: "action", + label: "Add row below", + disabled: !inTable, + run: () => editor.chain().focus().addRowAfter().run(), + }, + { + kind: "action", + label: "Delete row", + disabled: !inTable, + run: () => editor.chain().focus().deleteRow().run(), + }, + { kind: "sep" }, + { + kind: "action", + label: "Add column left", + disabled: !inTable, + run: () => editor.chain().focus().addColumnBefore().run(), + }, + { + kind: "action", + label: "Add column right", + disabled: !inTable, + run: () => editor.chain().focus().addColumnAfter().run(), + }, + { + kind: "action", + label: "Delete column", + disabled: !inTable, + run: () => editor.chain().focus().deleteColumn().run(), + }, + { + kind: "action", + label: "Delete table", + disabled: !inTable, + run: () => editor.chain().focus().deleteTable().run(), + }, + ], + }, + ]; +} diff --git a/src/lib/layout/BookmarksPane.svelte b/src/lib/layout/BookmarksPane.svelte new file mode 100644 index 0000000..bcdbd9f --- /dev/null +++ b/src/lib/layout/BookmarksPane.svelte @@ -0,0 +1,90 @@ + + +
      +
      Bookmarks
      + {#if bookmarks.length === 0} +

      Right-click a file and choose Bookmark.

      + {:else} +
        + {#each bookmarks as rel (rel)} +
      • + +
      • + {/each} +
      + {/if} +
      + + diff --git a/src/lib/layout/ContextMenu.svelte b/src/lib/layout/ContextMenu.svelte new file mode 100644 index 0000000..a7e11d4 --- /dev/null +++ b/src/lib/layout/ContextMenu.svelte @@ -0,0 +1,167 @@ + + + + + + + diff --git a/src/lib/layout/EditorPane.svelte b/src/lib/layout/EditorPane.svelte new file mode 100644 index 0000000..467fbca --- /dev/null +++ b/src/lib/layout/EditorPane.svelte @@ -0,0 +1,228 @@ + + +{#if !buffer || buffer.kind === "empty"} +
      +

      {buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}

      +

      {hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}

      +
      + + {#if hasWorkspace} + + + {/if} +
      +

      Save · Ctrl S   Terminal · Ctrl `   Find in file · Ctrl F

      +
      +{:else} +
      +
      + {buffer.relPath} +
      + {#if canPreview} + + {/if} + { if (mode !== chrome) onToggleChrome?.(); }} + /> +
      +
      +
      + {#if isImage && buffer.imageUrl} + + {:else} +
      + {#key buffer.id} + {#if !isIde && canPreview && !reading} + + {:else} + + {/if} + {/key} +
      + {#if reading && canPreview} + {#key buffer.id} +
      + +
      + {/key} + {/if} + {/if} +
      +
      +{/if} + + diff --git a/src/lib/layout/FileTree.svelte b/src/lib/layout/FileTree.svelte new file mode 100644 index 0000000..04f83b8 --- /dev/null +++ b/src/lib/layout/FileTree.svelte @@ -0,0 +1,748 @@ + + + + +
      +
      + void createIn("", "note")} /> + void createIn("", "folder")} /> + + { + if (allCollapsed) { + void expandAll(); + } else { + collapseAll(); + } + }} + /> +
      + +
      + +{#if dragRel && dragPoint} + {@const landing = dropTarget ? findEntry(dropTarget.rel) : null} +
      + {dragRel.split("/").pop()} + {#if imageLanding} + Insert image + {:else if landing && dropTarget} + {dropHint(landing.name, dropTarget.place)} + {/if} +
      +{/if} + +{#if menu} + (menu = null)} + /> +{/if} + + diff --git a/src/lib/layout/ImageViewer.svelte b/src/lib/layout/ImageViewer.svelte new file mode 100644 index 0000000..ff3f478 --- /dev/null +++ b/src/lib/layout/ImageViewer.svelte @@ -0,0 +1,32 @@ + + +
      + {name} +
      + + diff --git a/src/lib/layout/MarkdownView.svelte b/src/lib/layout/MarkdownView.svelte new file mode 100644 index 0000000..ff4de13 --- /dev/null +++ b/src/lib/layout/MarkdownView.svelte @@ -0,0 +1,161 @@ + + + + +
      { + if (event.target instanceof HTMLElement && event.target.classList.contains("md-edit-block") && (event.key === "Enter" || event.key === " ")) { + event.preventDefault(); + onEditBlock?.(Number(event.target.dataset.start), Number(event.target.dataset.end)); + } + }} + onclick={(event) => { + const copy = event.target instanceof Element ? event.target.closest("button.rs-fence-copy") : null; + if (copy instanceof HTMLButtonElement) { + event.preventDefault(); + const pre = copy.closest("pre.md-code") ?? copy.closest("pre"); + const body = pre?.querySelector("code")?.textContent ?? ""; + void copyFence(copy, body); + return; + } + const node = event.target instanceof Element ? event.target.closest("a") : null; + if (!node) { + const target = event.target instanceof Element ? event.target : null; + if (target?.closest("textarea, button, summary")) return; + const block = target?.closest(".md-edit-block"); + if (block) onEditBlock?.(Number(block.dataset.start), Number(block.dataset.end)); + return; + } + const href = node.getAttribute("href") ?? ""; + const kind = node.getAttribute("data-kind"); + if (kind === "wiki") { + event.preventDefault(); + onOpenLink?.("wiki", href); + return; + } + if (kind === "md") { + event.preventDefault(); + onOpenLink?.("md", href); + } + }} +> +

      {markdownTitle(noteRel)}

      + {#if onEditBlock} + {#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)} +
      {@html section.html}
      + {/each} + {#if editing && blockEditor} + {@render blockEditor()} + {#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)} +
      {@html section.html}
      + {/each} + {/if} + {:else} + {@html html} + {/if} +
      diff --git a/src/lib/layout/OutlinePane.svelte b/src/lib/layout/OutlinePane.svelte new file mode 100644 index 0000000..dc98695 --- /dev/null +++ b/src/lib/layout/OutlinePane.svelte @@ -0,0 +1,74 @@ + + +
      +
      Outline
      + {#if items.length === 0} +

      No headings or symbols in this file.

      + {:else} +
        + {#each items as item (item.line + item.text)} +
      • + +
      • + {/each} +
      + {/if} +
      + + diff --git a/src/lib/layout/QuickOpen.svelte b/src/lib/layout/QuickOpen.svelte new file mode 100644 index 0000000..30b07dc --- /dev/null +++ b/src/lib/layout/QuickOpen.svelte @@ -0,0 +1,60 @@ + + + + selected = 0} aria-label="Find a file" placeholder="Find a note or code file…" onkeydown={(event) => { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1))); + dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" }); + } + if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]); } + }} /> +
      + {#each matches as entry, index (entry.rel_path)} + + {/each} + {#if !matches.length}

      {loading ? "Finding files…" : "No matching files."}

      {/if} +
      +
      {error || `${files.length} files${loading ? " · indexing…" : ""}`} ↑ ↓ select · Enter open · Esc close
      +
      + + diff --git a/src/lib/layout/SearchPane.svelte b/src/lib/layout/SearchPane.svelte new file mode 100644 index 0000000..1a6a327 --- /dev/null +++ b/src/lib/layout/SearchPane.svelte @@ -0,0 +1,147 @@ + + +
      +
      Search
      +
      { + event.preventDefault(); + void run(); + }} + > + + + + {#if error} +

      {error}

      + {/if} +
        + {#each hits as hit (hit.rel_path + hit.line + hit.text)} +
      • + +
      • + {/each} +
      +
      + + diff --git a/src/lib/layout/TabBar.svelte b/src/lib/layout/TabBar.svelte new file mode 100644 index 0000000..61e3f77 --- /dev/null +++ b/src/lib/layout/TabBar.svelte @@ -0,0 +1,114 @@ + + +
      + {#each tabs as tab (tab.relPath)} +
      + + +
      + {/each} +
      + + diff --git a/src/lib/layout/TerminalDock.svelte b/src/lib/layout/TerminalDock.svelte new file mode 100644 index 0000000..ad6fdc4 --- /dev/null +++ b/src/lib/layout/TerminalDock.svelte @@ -0,0 +1,260 @@ + + +
      +
      + Terminal{active?.directory || cwd} +
      + {#if sessions.length === 1}{active?.profile.title}{/if} + addSession()} /> +
      + addSession(active?.profile, true)} /> +
      + killSession(activeId)} /> + {#if !standalone}{/if} + +
      +
      + {#if error}{/if} +
      +
      + {#each sessions as session (session.id)} +
      + {#if group.length > 1 && session.group === active?.group}
      {session.title}
      {/if} + activeId = session.id} + onState={state => { session.state = state; if (state === "Running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }} + onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }} + onCommand={command => recentCommands = remember(recentCommands, command)} + onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} /> + {#if session.group === active?.group && group.indexOf(session) > 0} + + {/if} +
      + {/each} + {#if !sessions.length}

      {loading ? "Detecting terminal profiles…" : "No terminal sessions."}

      {/if} +
      + {#if sessions.length > 1} + + + {/if} +
      +
      +{#if picker} picker = null} />{/if} +{#if showSettings} showSettings = false} />{/if} + diff --git a/src/lib/layout/TerminalPane.svelte b/src/lib/layout/TerminalPane.svelte new file mode 100644 index 0000000..996406d --- /dev/null +++ b/src/lib/layout/TerminalPane.svelte @@ -0,0 +1,218 @@ + + +
      + + diff --git a/src/lib/layout/TextDialog.svelte b/src/lib/layout/TextDialog.svelte new file mode 100644 index 0000000..55626fa --- /dev/null +++ b/src/lib/layout/TextDialog.svelte @@ -0,0 +1,29 @@ + + +{#if dialogs.text} + { event.preventDefault(); finishText(null); }}> +
      { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}> + + +
      + +
      +{/if} + + diff --git a/src/lib/layout/TreeNode.svelte b/src/lib/layout/TreeNode.svelte new file mode 100644 index 0000000..fdde77f --- /dev/null +++ b/src/lib/layout/TreeNode.svelte @@ -0,0 +1,345 @@ + + +
    • +
      { + if (event.button === 1) event.preventDefault(); + onDragPointerDown(entry, event); + }} + onclick={(event) => onRowClick(entry, event)} + onauxclick={(event) => { + if (event.button !== 1) return; + event.preventDefault(); + if (!isRenaming && entry.kind === "file") onRowClick(entry, {}, true); + }} + onkeydown={(event) => { + if (isRenaming) { + return; + } + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onRowClick(entry, event); + } + }} + oncontextmenu={(event) => { + event.preventDefault(); + event.stopPropagation(); + onContextMenu(entry, event.clientX, event.clientY); + }} + > + {#if isSelected} + + {/if} + + {#if isRenaming} + event.stopPropagation()} + onpointerdown={(event) => event.stopPropagation()} + oninput={(event) => onRenameDraft(event.currentTarget.value)} + onkeydown={(event) => { + if (event.key === "Enter") { + event.preventDefault(); + event.stopPropagation(); + onRenameCommit(); + } + if (event.key === "Escape") { + event.preventDefault(); + event.stopPropagation(); + onRenameCancel(); + } + }} + onblur={() => onRenameCommit()} + /> + {:else} + {label} + {/if} + {#if ext} + {ext} + {/if} +
      + {#if entry.kind === "folder" && isOpen} +
        + {#each nested as child (child.rel_path)} + + {/each} +
      + {/if} +
    • + + diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte new file mode 100644 index 0000000..a2d9f70 --- /dev/null +++ b/src/lib/layout/Workbench.svelte @@ -0,0 +1,1017 @@ + + + { if (hasDirty) { event.preventDefault(); event.returnValue = ""; } }} /> + + +{#if quickOpen && workspace} void openFile(entry)} onClose={() => quickOpen = false} />{/if} + +
      (dragging = null)} + onpointerleave={() => (dragging = null)} +> +
      +
      + selectLeft("files")} + /> + selectLeft("search")} + /> + selectLeft("bookmarks")} + /> +
      +
      + {#if tabs.length > 0} + + {/if} + + {#if desktop}
      {/if} +
      +
      + void save()} /> + + (rightOpen = !rightOpen)} + /> + {#if desktop} error = message} />{/if} +
      +
      + + {#if leftOpen} + + + + {/if} + +
      +
      +
      + {#if buffer?.diskError} + + {:else if buffer?.diskContents != null} + +
      View disk version
      {buffer.diskContents}
      + {/if} + void chooseWorkspace()} + onNewFile={() => void newFile()} + onQuickOpen={() => quickOpen = true} + {buffer} + chrome={view} + {reading} + {focusLine} + {onChange} + onInsertImage={insertImage} + onRenameTitle={renameNoteTitle} + tableActions={{ onSearch: searchSelection, onExtract: extractSelection }} + onToggleReading={() => (reading = !reading)} + onToggleChrome={toggleChrome} + onOpenLink={(kind, target) => void openLink(kind, target)} + /> +
      +
      + {#if terminalStarted} + +
      + {#if workspace} + {#key workspace.root} + terminalMaximized = !terminalMaximized} + activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile} + getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} /> + {/key} + {:else} +

      Open a workspace to start the terminal.

      + {/if} +
      + {/if} +
      + + {#if rightOpen} + + + {/if} + +
      + {error ?? status} + {#if workspace} + {workspace.watch_mode} watch + {/if} + {isIde ? "IDE" : "Writer"} +
      +
      + + diff --git a/src/lib/layout/WorkspacePicker.svelte b/src/lib/layout/WorkspacePicker.svelte new file mode 100644 index 0000000..f785775 --- /dev/null +++ b/src/lib/layout/WorkspacePicker.svelte @@ -0,0 +1,158 @@ + + + { if (menu?.matches(":popover-open")) position(); }} /> + + +{#if creating} + { event.preventDefault(); cancel(); }}> +
      { event.preventDefault(); void create(); }}> +

      New workspace

      +

      Create a folder for your notes and files, then open it in a new window.

      + + error = ""} placeholder="My workspace" autocomplete="off" required disabled={busy} /> +
      + + {parent ? "Will create: " : ""}{destination} + {#if error}{/if} +
      + +
      +{/if} + + diff --git a/src/lib/layout/menuTypes.ts b/src/lib/layout/menuTypes.ts new file mode 100644 index 0000000..269bf3f --- /dev/null +++ b/src/lib/layout/menuTypes.ts @@ -0,0 +1,16 @@ +export type MenuAction = { + kind: "action"; + label: string; + run: () => void; + disabled?: boolean; +}; + +export type MenuSep = { kind: "sep" }; + +export type MenuGroup = { + kind: "group"; + label: string; + items: MenuItem[]; +}; + +export type MenuItem = MenuAction | MenuSep | MenuGroup; diff --git a/src/lib/terminal/TerminalPicker.svelte b/src/lib/terminal/TerminalPicker.svelte new file mode 100644 index 0000000..549e5a7 --- /dev/null +++ b/src/lib/terminal/TerminalPicker.svelte @@ -0,0 +1,43 @@ + + +
      {title}
      + selected = 0} onkeydown={event => { + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1))); + dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" }); + } + if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]?.value); } + }} /> +
      + {#each matches as item, index} + + {/each} + {#if !matches.length}

      {query ? "No matching entries." : empty}

      {/if} +
      +
      ↑ ↓ select · Enter choose · Esc close
      +
      + diff --git a/src/lib/terminal/TerminalSettings.svelte b/src/lib/terminal/TerminalSettings.svelte new file mode 100644 index 0000000..76d4014 --- /dev/null +++ b/src/lib/terminal/TerminalSettings.svelte @@ -0,0 +1,30 @@ + + +
      { event.preventDefault(); onSave(value); onClose(); }}> +

      Terminal settings

      + + + + +

      Appearance applies to open sessions. The default profile applies to new terminals.

      +
      + +
      + diff --git a/src/lib/terminal/TerminalWindow.svelte b/src/lib/terminal/TerminalWindow.svelte new file mode 100644 index 0000000..6d2c1e6 --- /dev/null +++ b/src/lib/terminal/TerminalWindow.svelte @@ -0,0 +1,19 @@ + + +
      + {#if error}

      {error}

      {/if} + void getCurrentWindow().destroy().catch(reason => error = String(reason))} /> +
      + diff --git a/src/lib/terminal/model.ts b/src/lib/terminal/model.ts new file mode 100644 index 0000000..6e8c662 --- /dev/null +++ b/src/lib/terminal/model.ts @@ -0,0 +1,70 @@ +export type ShellProfile = { id: string; title: string; kind: "powershell" | "bash" | "cmd" | "node" }; +export type TerminalSettings = { defaultProfile: string; fontSize: number; scrollback: number; cursorBlink: boolean }; +export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void }; +export type TerminalTask = { label: string; command: string; profile?: string }; +export const defaultSettings: TerminalSettings = { defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true }; + +export function readSettings(): TerminalSettings { + try { + const value = JSON.parse(localStorage.getItem("runestone.terminal") || "{}"); + return { defaultProfile: typeof value.defaultProfile === "string" ? value.defaultProfile : "", + fontSize: Number.isFinite(value.fontSize) ? Math.min(28, Math.max(9, value.fontSize)) : 13, + scrollback: Number.isFinite(value.scrollback) ? Math.min(100000, Math.max(100, value.scrollback)) : 10000, + cursorBlink: typeof value.cursorBlink === "boolean" ? value.cursorBlink : true }; + } catch { return { ...defaultSettings }; } +} + +export function quoteShell(value: string, kind: ShellProfile["kind"]): string { + if (/[\r\n\0]/.test(value)) throw new Error("Paths cannot contain line breaks or null characters."); + if (kind === "cmd") { + // Expansion happens even inside cmd quotes. Reject rather than execute a different path. + if (/["%!]/.test(value)) throw new Error("Use PowerShell for paths containing quotes, % or !."); + return `"${value}"`; + } + if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`; + return `'${value.replaceAll("'", "''")}'`; +} + +export function directoryCommand(path: string, kind: ShellProfile["kind"]): string { + if (kind === "node") return `process.chdir(${JSON.stringify(path)})`; + const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path; + return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`; +} + +export function fileCommand(path: string, kind: ShellProfile["kind"]): string { + if (kind === "node") throw new Error("Choose a shell terminal to run files. The debug terminal is a Node.js REPL."); + const ext = path.split(".").pop()?.toLowerCase(); + const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind); + const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node" + : ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby" + : ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null; + if (runner === null) throw new Error("No runner for this file type. Use Run Selected Text or configure a task."); + return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`; +} + +export function parseTasks(text: string): TerminalTask[] { + const value = JSON.parse(text); + if (!Array.isArray(value.tasks)) throw new Error('Tasks must contain a "tasks" array.'); + return value.tasks.map((task: unknown) => { + if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim() + || !("command" in task) || typeof task.command !== "string" || !task.command.trim() + || ("profile" in task && typeof task.profile !== "string")) throw new Error("Each task needs a label, command, and optional profile ID."); + return task as TerminalTask; + }); +} + +export function remember(items: string[], value: string): string[] { + return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items; +} + +export function terminalShortcut(event: Pick): "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories" | null { + if (!event.ctrlKey && !event.metaKey) return null; + if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle"; + if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split"; + if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle"; + if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous"; + if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next"; + if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands"; + if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories"; + return null; +} diff --git a/src/lib/theme/tokens.css b/src/lib/theme/tokens.css new file mode 100644 index 0000000..01f1478 --- /dev/null +++ b/src/lib/theme/tokens.css @@ -0,0 +1,56 @@ +:root { + --rs-control-radius: 5px; + --rs-item-selection-radius: var(--rs-control-radius); + --rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent); + --rs-item-selection-border: var(--rs-accent); + --rs-item-selection-width: 2px; + --rs-bg: #141414; + --rs-bg-elevated: #1c1c1c; + --rs-bg-active: #2a2a2a; + --rs-border: #2e2e2e; + --rs-text-dim: #9a9a9a; + --rs-text: #e6e6e6; + --rs-text-strong: #f3f3f3; + --rs-accent-2: #89ddff; + --rs-accent: #82aaff; + --rs-accent-dim: #6b8cce; + --rs-accent-deep: #4d6aa8; + --rs-error: #f44747; + --rs-warn-hot: #d68a00; + --rs-warn: #cca700; + --rs-ok: #89d185; + --rs-special: #c792ea; + + --rs-font-ui: "Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif; + --rs-font-prose: "Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif; + --rs-font-mono: "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace; + --rs-prose-size: 16px; + --rs-prose-line: 1.65; + --rs-code-size: 13px; + --rs-h1-size: 1.6em; + --rs-h2-size: 1.4em; + --rs-h3-size: 1.25em; + --rs-h4-size: 1.15em; + --rs-h5-size: 1.08em; + --rs-h6-size: 1em; + --rs-selection: #264f78; + --rs-line-highlight: #ffffff0d; + --rs-h1: var(--rs-text-strong); + --rs-h2: var(--rs-text-strong); + --rs-h3: var(--rs-text); + --rs-h4: var(--rs-text); + --rs-h5: var(--rs-text-dim); + --rs-h6: var(--rs-text-dim); +} + +[data-theme="light"] { + --rs-bg: #f3f3f3; + --rs-bg-elevated: #ffffff; + --rs-bg-active: #e8e8e8; + --rs-border: #d4d4d4; + --rs-text-dim: #6b6b6b; + --rs-text: #1e1e1e; + --rs-text-strong: #111111; + --rs-selection: #add6ff; + --rs-line-highlight: #0000000d; +} diff --git a/src/lib/ui/Icon.svelte b/src/lib/ui/Icon.svelte new file mode 100644 index 0000000..70430b0 --- /dev/null +++ b/src/lib/ui/Icon.svelte @@ -0,0 +1,121 @@ + + + diff --git a/src/lib/ui/IconButton.svelte b/src/lib/ui/IconButton.svelte new file mode 100644 index 0000000..a11a32c --- /dev/null +++ b/src/lib/ui/IconButton.svelte @@ -0,0 +1,140 @@ + + + { if (event.key === "Escape") onLeave(); }} /> + + +{label} + + diff --git a/src/lib/ui/ModeSwitcher.svelte b/src/lib/ui/ModeSwitcher.svelte new file mode 100644 index 0000000..d04b4ea --- /dev/null +++ b/src/lib/ui/ModeSwitcher.svelte @@ -0,0 +1,190 @@ + + +
      { hovered = true; scheduleExpansion(); }} + onmouseleave={leave} + onfocusin={(event) => { + if ((event.target as HTMLElement).matches(":focus-visible") && !group.contains(event.relatedTarget as Node)) { + keyboardFocus = true; + scheduleExpansion(); + } + }} + onfocusout={(event) => { + if (!group.contains(event.relatedTarget as Node)) { + keyboardFocus = false; + if (!hovered) collapse(); + } + }} +> + + {#each options as option, index (option.value)} + + {/each} +
      + + diff --git a/src/lib/ui/WindowControls.svelte b/src/lib/ui/WindowControls.svelte new file mode 100644 index 0000000..76326e7 --- /dev/null +++ b/src/lib/ui/WindowControls.svelte @@ -0,0 +1,61 @@ + + +
      + void run("minimize")} /> + void run("toggleMaximize")} /> +
      + void run("close")} /> +
      +
      + + diff --git a/src/lib/ui/actionIcons.ts b/src/lib/ui/actionIcons.ts new file mode 100644 index 0000000..839f504 --- /dev/null +++ b/src/lib/ui/actionIcons.ts @@ -0,0 +1,63 @@ +// Stroke icons share the same 24px grid and weight as IconButton. +export const actionIcons = { + rename: '', + 'zoom-in': '', + 'zoom-out': '', + close: '', + swap: '', + bullet: '', + number: '', + task: '', + heading: '', + quote: '', + table: '', + rule: '', + footnote: '', + cut: '', + copy: '', + paste: '', + 'paste-text': '', + format: '', + bold: '', + italic: '', + strike: '', + highlight: '', + code: '', + math: '', + comment: '', + clear: '', + left: '', + center: '', + right: '', + row: '', + column: '', + 'row-before': '', + 'row-after': '', + 'column-before': '', + 'column-after': '', + up: '', + down: '', + 'move-left': '', + 'move-right': '', + trash: '', + 'sort-asc': '', + 'sort-desc': '', + link: '', + external: '', + search: '', + extract: '', + select: '', + paragraph: '', + insert: '', + chevron: '', + plus: '', + grip: '', +} as const; +export type ActionIcon = keyof typeof actionIcons; + +export function actionIcon(name: ActionIcon): SVGSVGElement { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); + svg.classList.add("action-icon"); svg.innerHTML = actionIcons[name]; + return svg; +} diff --git a/src/lib/ui/actionMenu.ts b/src/lib/ui/actionMenu.ts new file mode 100644 index 0000000..6f6fef6 --- /dev/null +++ b/src/lib/ui/actionMenu.ts @@ -0,0 +1,66 @@ +import { actionIcon, type ActionIcon } from "./actionIcons"; + +export type ActionMenuItem = { label: string; icon: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true }; + +export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions") { + const root = document.createElement("div"); root.className = "table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label); + let opened: HTMLElement | undefined, owner: HTMLButtonElement | undefined; + if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))"; + const submenus = new Map(); + function hideSubmenu() { if (opened) opened.hidden = true; owner?.setAttribute("aria-expanded", "false"); opened = undefined; owner = undefined; } + function positionSubmenu(button: HTMLButtonElement, panel: HTMLElement) { + const rect = button.getBoundingClientRect(), size = panel.getBoundingClientRect(), main = root.getBoundingClientRect(); + panel.style.left = `${Math.max(8, main.right + size.width < innerWidth - 8 ? main.right - 2 : main.left - size.width + 2)}px`; + panel.style.top = `${Math.max(8, Math.min(rect.top - 5, innerHeight - size.height - 8))}px`; + } + function reveal(button: HTMLButtonElement, panel: HTMLElement, focus = false) { + if (opened !== panel) hideSubmenu(); + opened = panel; owner = button; panel.hidden = false; button.setAttribute("aria-expanded", "true"); + positionSubmenu(button, panel); + if (focus) panel.querySelector("button:not(:disabled)")?.focus({ preventScroll: true }); + } + function populate(panel: HTMLElement, entries: ActionMenuItem[]) { + for (const item of entries) { + if ("separator" in item) { const hr = document.createElement("hr"); hr.setAttribute("role", "separator"); panel.append(hr); continue; } + const button = document.createElement("button"); button.type = "button"; button.setAttribute("role", "menuitem"); button.disabled = !!item.disabled; + if (item.title) button.title = item.title; + const label = document.createElement("span"); label.className = "action-label"; label.textContent = item.label; + button.append(actionIcon(item.icon), label); panel.append(button); + if (item.shortcut) { const shortcut = document.createElement("span"); shortcut.textContent = item.shortcut; shortcut.style.cssText = "margin-left:auto;color:var(--rs-text-dim);font-size:12px;white-space:nowrap"; button.append(shortcut); } + if (item.children) { + button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false"); + const arrow = actionIcon("chevron"); arrow.classList.add("action-chevron"); button.append(arrow); + const submenu = document.createElement("div"); submenu.className = "table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true; + populate(submenu, item.children); root.append(submenu); submenus.set(button, submenu); + button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); }); + button.addEventListener("click", () => reveal(button, submenu, true)); + } else { + if (panel === root) button.addEventListener("mousemove", hideSubmenu); + button.addEventListener("click", event => { event.stopPropagation(); item.run?.(); }); + } + } + } + populate(root, items); + root.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); }); + root.addEventListener("focusin", event => { + const button = event.target as HTMLElement; + if (button.parentElement === root && button !== owner) hideSubmenu(); + }); + root.addEventListener("keydown", event => { + event.stopPropagation(); + if (event.key === "Escape" || event.key === "Tab") { event.preventDefault(); onClose(); return; } + const focused = document.activeElement as HTMLButtonElement, panel = focused.parentElement || root; + const buttons = [...panel.querySelectorAll(":scope > button:not(:disabled)")], index = buttons.indexOf(focused); + if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) { + event.preventDefault(); buttons[event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length]?.focus(); + } + if (event.key === "ArrowRight" && submenus.has(focused)) { event.preventDefault(); reveal(focused, submenus.get(focused)!, true); } + if (event.key === "ArrowLeft" && opened?.contains(focused)) { event.preventDefault(); const previous = owner; hideSubmenu(); previous?.focus(); } + }); + root.addEventListener("scroll", event => { if (event.target === root && opened && owner) positionSubmenu(owner, opened); }); + document.body.append(root); + root.style.left = `${Math.max(8, Math.min(x, innerWidth - root.offsetWidth - 8))}px`; + root.style.top = `${Math.max(8, Math.min(y, innerHeight - root.offsetHeight - 8))}px`; + root.querySelector(":scope > button:not(:disabled)")?.focus(); + return root; +} diff --git a/src/lib/workspace/api.ts b/src/lib/workspace/api.ts new file mode 100644 index 0000000..5fba468 --- /dev/null +++ b/src/lib/workspace/api.ts @@ -0,0 +1,128 @@ +import { invoke } from "@tauri-apps/api/core"; +import { listen, type UnlistenFn } from "@tauri-apps/api/event"; +import { open as openDialog } from "@tauri-apps/plugin-dialog"; +import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types"; + +export async function pickWorkspaceFolder(title = "Open workspace"): Promise { + const selected = await openDialog({ + directory: true, + multiple: false, + title, + }); + if (selected === null || Array.isArray(selected)) { + return null; + } + return selected; +} + +export function workspaceOpen(path: string): Promise { + return invoke("workspace_open", { path }); +} + +export function workspaceOpenWindow(path: string): Promise { + return invoke("workspace_open_window", { path }); +} + +export function workspaceLastPath(): Promise { + return invoke("workspace_last_path"); +} + +export function workspaceRecent(): Promise { + return invoke("workspace_recent"); +} + +export function workspaceNew(parent: string, name: string): Promise { + return invoke("workspace_new", { parent, name }); +} + +export function workspaceList(rel: string): Promise { + return invoke("workspace_list", { rel }); +} + +export function workspaceRead(rel: string): Promise { + return invoke("workspace_read", { rel }); +} + +export function workspaceWrite(rel: string, contents: string, expected?: string): Promise { + return invoke("workspace_write", { rel, contents, expected }); +} + +export function workspaceCreate(rel: string, kind: "file" | "folder"): Promise { + return invoke("workspace_create", { rel, kind }); +} + +export function workspaceRename(from: string, to: string): Promise { + return invoke("workspace_rename", { from, to }); +} + +export function workspaceDelete(rel: string): Promise { + return invoke("workspace_delete", { rel }); +} + +export function workspaceReadDataUrl(rel: string): Promise { + return invoke("workspace_read_data_url", { rel }); +} + +export function workspaceWriteBytes(rel: string, base64: string): Promise { + return invoke("workspace_write_bytes", { rel, base64 }); +} + +export type CopyResult = { + name: string; + rel_path: string; + kind: "file" | "folder"; +}; + +export function workspaceCopy(rel: string): Promise { + return invoke("workspace_copy", { rel }); +} + +export function workspaceAbsPath(rel: string): Promise { + return invoke("workspace_abs_path", { rel }); +} + +export function workspaceReveal(rel: string): Promise { + return invoke("workspace_reveal", { rel }); +} + +export type SearchHit = { + rel_path: string; + line: number; + text: string; +}; + +export function workspaceSearch(query: string): Promise { + return invoke("workspace_search", { query }); +} + +export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise { + return invoke("pty_open", { id, cols, rows, cwd, profile, directory }); +} + +export function ptyProfiles(): Promise { + return invoke("pty_profiles"); +} +export function ptyNewWindow(): Promise { + return invoke("pty_new_window", { id: crypto.randomUUID() }); +} +export function ptyDictation(): Promise { return invoke("pty_dictation"); } + +export function ptyWrite(id: string, data: string): Promise { + return invoke("pty_write", { id, data }); +} + +export function ptyResize(id: string, cols: number, rows: number): Promise { + return invoke("pty_resize", { id, cols, rows }); +} + +export function ptyClose(id: string): Promise { + return invoke("pty_close", { id }); +} + +export function onWorkspaceEvent( + handler: (event: WorkspaceEvent) => void, +): Promise { + return listen("workspace-event", (event) => { + handler(event.payload); + }); +} diff --git a/src/lib/workspace/chrome.ts b/src/lib/workspace/chrome.ts new file mode 100644 index 0000000..28cdfe5 --- /dev/null +++ b/src/lib/workspace/chrome.ts @@ -0,0 +1,27 @@ +import type { Chrome } from "./types"; + +const WRITING_EXT = new Set(["md", "markdown", "mdown", "txt"]); + +export function extensionOf(relPath: string): string { + const base = relPath.split("/").pop() ?? relPath; + const dot = base.lastIndexOf("."); + if (dot <= 0) { + return ""; + } + return base.slice(dot + 1).toLowerCase(); +} + +export function treeFileParts(name: string): { label: string; ext: string } { + const ext = extensionOf(name); + if (!ext || !name.toLowerCase().endsWith(`.${ext}`)) { + return { label: name, ext: "" }; + } + return { label: name.slice(0, name.length - ext.length - 1), ext }; +} + +export function detectChrome(relPath: string): Chrome { + if (WRITING_EXT.has(extensionOf(relPath))) { + return "Writing"; + } + return "Ide"; +} diff --git a/src/lib/workspace/diagrams.ts b/src/lib/workspace/diagrams.ts new file mode 100644 index 0000000..632c711 --- /dev/null +++ b/src/lib/workspace/diagrams.ts @@ -0,0 +1,34 @@ +let engine: Promise | undefined; +let sequence = 0; + +function loadMermaid() { + return engine ??= import("mermaid").then(({ default: mermaid }) => { + mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "dark", suppressErrorRendering: true }); + return mermaid; + }).catch(error => { engine = undefined; throw error; }); +} + +export async function renderDiagrams(root: HTMLElement, cancelled: () => boolean) { + if (cancelled()) return; + const diagrams = [...root.querySelectorAll(".md-mermaid")]; + if (!diagrams.length) return; + for (const block of diagrams) { + const target = block.querySelector(".md-diagram"); + const source = block.querySelector("code")?.textContent ?? ""; + if (!target || target.dataset.rendered) continue; + target.dataset.rendered = "pending"; + try { + const mermaid = await loadMermaid(); + if (!block.isConnected) continue; + const { svg } = await mermaid.render(`rs-diagram-${++sequence}`, source); + if (!block.isConnected) continue; + target.innerHTML = svg; + target.dataset.rendered = "true"; + } catch { + if (!block.isConnected) continue; + target.textContent = "Diagram could not render. Check the Mermaid source below."; + target.setAttribute("role", "status"); + block.querySelector("details")?.setAttribute("open", ""); + } + } +} diff --git a/src/lib/workspace/dialogs.svelte.ts b/src/lib/workspace/dialogs.svelte.ts new file mode 100644 index 0000000..9c58ba1 --- /dev/null +++ b/src/lib/workspace/dialogs.svelte.ts @@ -0,0 +1,13 @@ +type TextRequest = { title: string; value: string; resolve: (value: string | null) => void }; +export const dialogs = $state<{ text: TextRequest | null }>({ text: null }); + +export function requestText(title: string, value = ""): Promise { + dialogs.text?.resolve(null); + return new Promise(resolve => { dialogs.text = { title, value, resolve }; }); +} + +export function finishText(value: string | null) { + const request = dialogs.text; + dialogs.text = null; + request?.resolve(value); +} diff --git a/src/lib/workspace/documents.ts b/src/lib/workspace/documents.ts new file mode 100644 index 0000000..63dab3b --- /dev/null +++ b/src/lib/workspace/documents.ts @@ -0,0 +1,191 @@ +import type { OpenBuffer, TreeEntry } from "./types"; + +export type DocumentIO = { + read: (path: string) => Promise; + write: (path: string, contents: string, expected: string) => Promise; + image: (path: string) => Promise; + kind: (path: string) => "image" | "text"; + chrome: (path: string) => OpenBuffer["chrome"]; +}; + +/** One workspace's documents. UI components never own the saved baseline. */ +export class Documents { + buffers: OpenBuffer[] = []; + activePath: string | null = null; + private opening = new Map>(); + private saving = new Map>(); + private selection = 0; + private refreshVersion = 0; + private disposed = false; + + private io: DocumentIO; + private changed: () => void; + constructor(io: DocumentIO, changed: () => void) { this.io = io; this.changed = changed; } + + dispose() { this.disposed = true; this.selection++; this.refreshVersion++; } + get dirty() { return this.buffers.some(b => b.contents !== b.saved); } + get active() { return this.buffers.find(b => b.relPath === this.activePath); } + private emit() { if (!this.disposed) this.changed(); } + + select(path: string) { + this.selection++; + if (this.buffers.some(b => b.relPath === path)) { this.activePath = path; this.emit(); } + } + + newTab() { + if (this.disposed) return; + this.selection++; + const id = crypto.randomUUID(); + // Empty tabs have an identity but no corresponding workspace file. + const relPath = `empty:${id}`; + this.buffers.push({ + id, relPath, name: "New tab", kind: "empty", imageUrl: null, + contents: "", saved: "", chrome: "Writing", chromeOverride: null, + }); + this.activePath = relPath; + this.emit(); + } + + async open(entry: TreeEntry, target: "current" | "new" = "new") { + const request = ++this.selection; + const previous = target === "current" || this.active?.kind === "empty" ? this.active : undefined; + const alreadyOpen = this.buffers.some(b => b.relPath === entry.rel_path); + if (!this.buffers.some(b => b.relPath === entry.rel_path)) { + let pending = this.opening.get(entry.rel_path); + if (!pending) { + pending = (async () => { + const kind = this.io.kind(entry.rel_path); + const value = await (kind === "image" ? this.io.image(entry.rel_path) : this.io.read(entry.rel_path)); + if (this.disposed) return; + this.buffers.push({ + id: crypto.randomUUID(), relPath: entry.rel_path, name: entry.name, + kind, imageUrl: kind === "image" ? value : null, + contents: kind === "text" ? value : "", saved: kind === "text" ? value : "", + chrome: this.io.chrome(entry.rel_path), chromeOverride: null, + }); + this.emit(); + })(); + this.opening.set(entry.rel_path, pending); + } + try { await pending; } finally { this.opening.delete(entry.rel_path); } + } + if (!this.disposed && request === this.selection) { + // Replace only after a successful read, and never discard edits or disk conflicts. + if (!alreadyOpen && previous && previous.contents === previous.saved + && previous.diskContents === undefined && !previous.diskError) { + const index = this.buffers.indexOf(previous); + const opened = this.buffers.find(b => b.relPath === entry.rel_path); + if (index !== -1 && opened) { + this.buffers = this.buffers.filter(b => b !== opened); + this.buffers.splice(this.buffers.indexOf(previous), 1, opened); + } + } + this.activePath = entry.rel_path; + this.emit(); + } + } + + edit(id: string, contents: string) { + const buffer = this.buffers.find(b => b.id === id); + if (buffer?.kind === "text") { buffer.contents = contents; this.emit(); } + } + + setChrome(chrome: OpenBuffer["chrome"]) { + if (this.active) { this.active.chromeOverride = chrome; this.emit(); } + } + + close(path: string) { + this.selection++; + const index = this.buffers.findIndex(b => b.relPath === path); + this.buffers = this.buffers.filter(b => b.relPath !== path); + if (this.activePath === path) this.activePath = (this.buffers[index] ?? this.buffers[index - 1])?.relPath ?? null; + this.emit(); + } + + rename(from: string, to: string) { + for (const b of this.buffers) { + if (b.kind === "empty") continue; + if (b.relPath === from || b.relPath.startsWith(`${from}/`)) { + const next = to + b.relPath.slice(from.length); + if (this.activePath === b.relPath) this.activePath = next; + b.relPath = next; + b.name = next.split("/").pop()!; + b.chrome = this.io.chrome(next); + } + } + this.emit(); + } + + save(id: string): Promise { + const prior = this.saving.get(id) ?? Promise.resolve(); + const pending = prior.then(() => this.write(id)); + this.saving.set(id, pending); + return pending.finally(() => { if (this.saving.get(id) === pending) this.saving.delete(id); }); + } + + async autosave() { + const saved: string[] = []; + const failed: { path: string; error: unknown }[] = []; + if (this.disposed) return { saved, failed }; + await Promise.all(this.buffers.map(async b => { + if (b.kind !== "text" || b.contents === b.saved || this.saving.has(b.id) + || b.diskContents !== undefined || b.diskError) return; + const path = b.relPath; + try { await this.save(b.id); saved.push(path); } + catch (error) { failed.push({ path, error }); } + })); + return { saved, failed }; + } + + private async write(id: string) { + // Serialize saves of a document, and capture the exact text being written. + // Typing while disk I/O is pending must still leave the document dirty. + if (this.disposed) return; + const b = this.buffers.find(b => b.id === id); + if (!b || b.kind !== "text") return; + if (b.diskContents !== undefined || b.diskError) throw new Error("Resolve the disk changes before saving."); + if (b.contents === b.saved) return; + const contents = b.contents; + const path = b.relPath; + await this.io.write(path, contents, b.saved).then(() => { + b.saved = contents; + if (b.diskContents === contents) b.diskContents = undefined; + this.emit(); + }); + } + + async refresh() { + const version = ++this.refreshVersion; + await Promise.all(this.buffers.map(async b => { + if (b.kind === "empty" || this.saving.has(b.id)) return; + const baseline = b.saved; + const path = b.relPath; + try { + const disk = await (b.kind === "image" ? this.io.image(path) : this.io.read(path)); + if (this.disposed || version !== this.refreshVersion || !this.buffers.includes(b) || b.relPath !== path || this.saving.has(b.id) || b.saved !== baseline) return; + b.diskError = null; + if (b.kind === "image") { b.imageUrl = disk; return; } + if (disk === b.saved) { b.diskContents = undefined; return; } + if (b.contents === b.saved || b.contents === disk) { + b.contents = disk; b.saved = disk; b.diskContents = undefined; + } else { + b.diskContents = disk; + } + } catch (error) { + if (!this.disposed && version === this.refreshVersion && this.buffers.includes(b) && b.relPath === path && b.saved === baseline && !this.saving.has(b.id)) { + b.diskError = `File unavailable on disk. Your buffer is preserved. ${String(error)}`; + } + } + })); + this.emit(); + } + + resolve(id: string, useDisk: boolean) { + const b = this.buffers.find(b => b.id === id); + if (!b || b.diskContents == null) return; + if (useDisk) b.contents = b.diskContents; + b.saved = b.diskContents; + b.diskContents = undefined; + this.emit(); + } +} diff --git a/src/lib/workspace/htmlToMarkdown.ts b/src/lib/workspace/htmlToMarkdown.ts new file mode 100644 index 0000000..a21adc4 --- /dev/null +++ b/src/lib/workspace/htmlToMarkdown.ts @@ -0,0 +1,331 @@ +export function unescapeHtml(text: string): string { + return text + .replaceAll(""", '"') + .replaceAll(">", ">") + .replaceAll("<", "<") + .replaceAll("&", "&"); +} + +function parseAttrs(raw: string): Record { + const attrs: Record = {}; + const re = /([:\w-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g; + let match: RegExpExecArray | null = re.exec(raw); + while (match) { + attrs[match[1]] = match[2] ?? match[3] ?? ""; + match = re.exec(raw); + } + return attrs; +} + +export function htmlToMarkdown(html: string): string { + const tokens = html.match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? []; + const out: string[] = []; + const list: string[] = []; + let inPre = false; + let preLang = ""; + let preBody = ""; + let inline = ""; + let heading = 0; + let inLi = false; + let liTask: boolean | null = null; + let liChecked = false; + let skipButton = false; + let inCell = false; + let tableRows: string[][] | null = null; + let tableRow: string[] | null = null; + let inQuote = false; + let inOl = false; + let olN = 1; + const spanKind: string[] = []; + + function flushInline(): string { + const text = unescapeHtml(inline.replace(/\s+/g, " ").trim()); + inline = ""; + return text; + } + + for (const token of tokens) { + if (token.startsWith(" ${text}`); + } else if (text) { + out.push(text); + } + continue; + } + if (tag === "blockquote") { + inQuote = false; + continue; + } + if (tag === "ol") { + inOl = false; + continue; + } + if (tag === "span") { + const kind = spanKind.pop(); + if (kind === "math") { + inline += "$"; + } + if (kind === "comment") { + inline += "%%"; + } + continue; + } + if (tag === "mark") { + inline += "=="; + continue; + } + if (tag === "em" || tag === "i") { + inline += "*"; + continue; + } + if (tag === "td" || tag === "th") { + if (tableRow) { + tableRow.push(flushInline()); + } + inCell = false; + continue; + } + if (tag === "tr") { + if (tableRows && tableRow) { + tableRows.push(tableRow); + } + tableRow = null; + continue; + } + if (tag === "table") { + if (tableRows && tableRows.length > 0) { + const width = Math.max(...tableRows.map((row) => row.length)); + const pad = (row: string[]) => { + const cells = [...row]; + while (cells.length < width) { + cells.push(""); + } + return `| ${cells.join(" | ")} |`; + }; + const sep = `| ${Array.from({ length: width }, () => "---").join(" | ")} |`; + out.push(pad(tableRows[0])); + out.push(sep); + for (const row of tableRows.slice(1)) { + out.push(pad(row)); + } + } + tableRows = null; + continue; + } + if (tag === "li") { + const text = flushInline(); + const item = text || list.pop() || ""; + if (liTask !== null) { + out.push(`- [${liChecked ? "x" : " "}] ${item}`); + } else if (inOl) { + out.push(`${olN}. ${item}`); + olN += 1; + } else { + out.push(`- ${item}`); + } + inLi = false; + liTask = null; + continue; + } + if (tag === "button") { + skipButton = false; + continue; + } + if (tag === "strong" || tag === "b") { + inline += "**"; + continue; + } + if (tag === "s" || tag === "del" || tag === "strike") { + inline += "~~"; + continue; + } + if (tag === "sup") { + inline += "^"; + continue; + } + if (tag === "sub") { + inline += "~"; + continue; + } + if (tag === "code" && !inPre) { + inline += "`"; + continue; + } + continue; + } + if (token.startsWith("<")) { + const selfClose = token.endsWith("/>"); + const body = token.slice(1, token.length - (selfClose ? 2 : 1)).trim(); + const space = body.indexOf(" "); + const tag = (space === -1 ? body : body.slice(0, space)).toLowerCase(); + const attrs = space === -1 ? {} : parseAttrs(body.slice(space + 1)); + if (tag === "br") { + inline += "\n"; + continue; + } + if (tag === "img") { + const src = attrs["data-md-src"] ?? ""; + const alt = attrs.alt ?? ""; + const kind = attrs["data-md-kind"] ?? "md"; + if (kind === "wiki") { + inline += alt && alt !== src ? `![[${src}|${alt}]]` : `![[${src}]]`; + } else { + inline += `![${alt}](${src})`; + } + continue; + } + if (tag === "input") { + liTask = true; + liChecked = Object.prototype.hasOwnProperty.call(attrs, "checked"); + continue; + } + if (tag === "button") { + skipButton = true; + continue; + } + if (tag === "pre") { + inPre = true; + preLang = attrs["data-lang"] ?? ""; + preBody = ""; + continue; + } + if (tag === "code") { + const langClass = (attrs.class ?? "").split(/\s+/).find((c) => c.startsWith("language-")); + if (inPre) { + if (langClass) { + preLang = langClass.slice("language-".length); + } + continue; + } + inline += "`"; + continue; + } + if (tag === "h1" || tag === "h2" || tag === "h3" || tag === "h4" || tag === "h5" || tag === "h6") { + heading = Number(tag.slice(1)); + continue; + } + if (tag === "blockquote") { + inQuote = true; + continue; + } + if (tag === "ol") { + inOl = true; + olN = 1; + continue; + } + if (tag === "span") { + if ("data-math" in attrs || /data-math/.test(token)) { + inline += "$"; + spanKind.push("math"); + } else if ("data-comment" in attrs || /data-comment/.test(token)) { + inline += "%%"; + spanKind.push("comment"); + } else { + spanKind.push(""); + } + continue; + } + if (tag === "mark") { + inline += "=="; + continue; + } + if (tag === "em" || tag === "i") { + inline += "*"; + continue; + } + if (tag === "table") { + tableRows = []; + continue; + } + if (tag === "tr") { + tableRow = []; + continue; + } + if (tag === "td" || tag === "th") { + inCell = true; + continue; + } + if (tag === "li") { + inLi = true; + const taskItem = attrs["data-type"] === "taskItem" || attrs["data-task"] === "1" || "data-checked" in attrs; + liTask = taskItem ? true : null; + liChecked = attrs["data-checked"] === "true"; + continue; + } + if (tag === "strong" || tag === "b") { + inline += "**"; + continue; + } + if (tag === "s" || tag === "del" || tag === "strike") { + inline += "~~"; + continue; + } + if (tag === "sup") { + inline += "^"; + continue; + } + if (tag === "sub") { + inline += "~"; + continue; + } + if (tag === "a") { + const href = attrs.href ?? ""; + const kind = /wiki/.test(token) ? "wiki" : "md"; + inline += `<>`; + continue; + } + continue; + } + if (skipButton) { + continue; + } + if (inPre) { + preBody += unescapeHtml(token); + continue; + } + const linkMark = inline.match(/<]*)>>$/); + if (linkMark) { + const kind = linkMark[1]; + const href = linkMark[2]; + const label = unescapeHtml(token).trim(); + inline = inline.slice(0, -linkMark[0].length); + if (kind === "wiki") { + inline += label && label !== href ? `[[${href}|${label}]]` : `[[${href}]]`; + } else { + inline += `[${label}](${href})`; + } + continue; + } + inline += token; + } + const trailing = flushInline(); + if (trailing) { + out.push(trailing); + } + return out.join("\n"); +} diff --git a/src/lib/workspace/markdownBlocks.ts b/src/lib/workspace/markdownBlocks.ts new file mode 100644 index 0000000..a74e7a3 --- /dev/null +++ b/src/lib/workspace/markdownBlocks.ts @@ -0,0 +1,70 @@ +export type MdBlock = + | { type: "fence"; lang: string; body: string } + | { type: "text"; line: string }; + +export type MdFence = { + lang: string; + body: string; + openLine: number; + closeLine: number; +}; + +type Scan = { + blocks: MdBlock[]; + fences: MdFence[]; +}; + +function scanMarkdown(contents: string): Scan { + const lines = contents.split(/\r?\n/); + const blocks: MdBlock[] = []; + const fences: MdFence[] = []; + let fence: { lang: string; body: string[]; openLine: number } | null = null; + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i]; + const lineNo = i + 1; + if (line.startsWith("```")) { + const rest = line.slice(3); + if (!fence) { + const closeAt = rest.indexOf("```"); + if (closeAt >= 0) { + const body = rest.slice(0, closeAt); + blocks.push({ type: "fence", lang: "", body }); + fences.push({ lang: "", body, openLine: lineNo, closeLine: lineNo }); + continue; + } + fence = { lang: rest.trim(), body: [], openLine: lineNo }; + } else { + const body = fence.body.join("\n"); + blocks.push({ type: "fence", lang: fence.lang, body }); + fences.push({ + lang: fence.lang, + body, + openLine: fence.openLine, + closeLine: lineNo, + }); + fence = null; + } + continue; + } + if (fence) { + fence.body.push(line); + continue; + } + blocks.push({ type: "text", line }); + } + if (fence) { + blocks.push({ type: "text", line: `\`\`\`${fence.lang}` }); + for (const line of fence.body) { + blocks.push({ type: "text", line }); + } + } + return { blocks, fences }; +} + +export function markdownBlocks(contents: string): MdBlock[] { + return scanMarkdown(contents).blocks; +} + +export function markdownFences(contents: string): MdFence[] { + return scanMarkdown(contents).fences; +} diff --git a/src/lib/workspace/markdownLinks.ts b/src/lib/workspace/markdownLinks.ts new file mode 100644 index 0000000..3d62b54 --- /dev/null +++ b/src/lib/workspace/markdownLinks.ts @@ -0,0 +1,74 @@ +export type MdLink = { + kind: "md" | "wiki"; + from: number; + to: number; + label: string; + target: string; +}; + +export function findMarkdownLinks(line: string): MdLink[] { + const found: MdLink[] = []; + const md = /(!?)\[([^\]]+)\]\(([^)]+)\)/g; + let match: RegExpExecArray | null = md.exec(line); + while (match) { + if (match[1] !== "!") { + found.push({ + kind: "md", + from: match.index, + to: match.index + match[0].length, + label: match[2], + target: match[3].trim(), + }); + } + match = md.exec(line); + } + const wiki = /(!?)\[\[([^\]|#]+)(?:\|([^\]]+))?\]\]/g; + match = wiki.exec(line); + while (match) { + if (match[1] !== "!") { + found.push({ + kind: "wiki", + from: match.index, + to: match.index + match[0].length, + label: match[3] ?? match[2], + target: match[2].trim(), + }); + } + match = wiki.exec(line); + } + found.sort((a, b) => a.from - b.from); + return found; +} + +export function wikiCandidates(target: string): string[] { + const trimmed = target.replaceAll("\\", "/").replace(/^\/+/, ""); + if (trimmed.includes(".") || trimmed.includes("/")) { + return [trimmed, `${trimmed}.md`]; + } + return [`${trimmed}.md`, `notes/${trimmed}.md`, trimmed]; +} + +export function linkCandidates(notePath: string, target: string, kind: "md" | "wiki"): string[] { + let path = target.split("#")[0]; + try { path = decodeURIComponent(path); } catch { /* Literal percent in a file name. */ } + path = path.replaceAll("\\", "/"); + if (!path) return [notePath]; + if (/^[a-z][a-z\d+.-]*:/i.test(path)) return []; + const folder = notePath.split("/").slice(0, -1).join("/"); + const normalize = (value: string) => { + const parts: string[] = []; + for (const part of value.split("/")) { + if (!part || part === ".") continue; + if (part === "..") { if (!parts.length) return null; parts.pop(); } + else parts.push(part); + } + return parts.join("/"); + }; + const bases = path.startsWith("/") ? [path.slice(1)] : [`${folder}/${path}`, path]; + const candidates = bases.flatMap(base => { + const normalized = normalize(base); + if (normalized === null) return []; + return kind === "wiki" && !/\.[^/]+$/.test(normalized) ? [`${normalized}.md`, normalized] : [normalized]; + }); + return [...new Set(candidates)]; +} diff --git a/src/lib/workspace/marks.ts b/src/lib/workspace/marks.ts new file mode 100644 index 0000000..10425fc --- /dev/null +++ b/src/lib/workspace/marks.ts @@ -0,0 +1,39 @@ +import { workspaceRead, workspaceWrite } from "./api"; + +const MARKS_PATH = ".runestone/marks.json"; + +export type Marks = { + pins: string[]; + bookmarks: string[]; + order: Record; +}; + +const EMPTY: Marks = { pins: [], bookmarks: [], order: {} }; + +export async function loadMarks(): Promise { + try { + const raw = await workspaceRead(MARKS_PATH); + const parsed = JSON.parse(raw) as Partial; + return { + pins: Array.isArray(parsed.pins) ? parsed.pins : [], + bookmarks: Array.isArray(parsed.bookmarks) ? parsed.bookmarks : [], + order: + parsed.order && typeof parsed.order === "object" && !Array.isArray(parsed.order) + ? parsed.order + : {}, + }; + } catch { + return { pins: [], bookmarks: [], order: {} }; + } +} + +export async function saveMarks(marks: Marks): Promise { + await workspaceWrite(MARKS_PATH, `${JSON.stringify(marks, null, 2)}\n`); +} + +export function togglePath(list: string[], rel: string): string[] { + if (list.includes(rel)) { + return list.filter((item) => item !== rel); + } + return [...list, rel]; +} diff --git a/src/lib/workspace/media.ts b/src/lib/workspace/media.ts new file mode 100644 index 0000000..d7cf07f --- /dev/null +++ b/src/lib/workspace/media.ts @@ -0,0 +1,121 @@ +export const IMAGE_EXT = new Set([ + "png", + "jpg", + "jpeg", + "gif", + "webp", + "svg", + "bmp", + "ico", + "avif", +]); + +function fileExt(relPath: string): string { + const base = relPath.split("/").pop() ?? relPath; + const dot = base.lastIndexOf("."); + if (dot <= 0) { + return ""; + } + return base.slice(dot + 1).toLowerCase(); +} + +export function isImagePath(relPath: string): boolean { + return IMAGE_EXT.has(fileExt(relPath)); +} + +export function isMarkdownPath(relPath: string): boolean { + const ext = fileExt(relPath); + return ext === "md" || ext === "markdown" || ext === "mdown"; +} + +export function markdownTitle(relPath: string): string { + return (relPath.replaceAll("\\", "/").split("/").pop() || "Untitled").replace(/\.(?:md|markdown|mdown)$/i, ""); +} + +export function dirnameOf(relPath: string): string { + const idx = relPath.replaceAll("\\", "/").lastIndexOf("/"); + if (idx <= 0) { + return ""; + } + return relPath.slice(0, idx); +} + +export function resolveImageRel(noteRel: string, raw: string): string { + let path = raw.trim().replaceAll("\\", "/").replace(/^<|>$/g, ""); + path = path.replace(/^\.\//, ""); + if (path.startsWith("/")) { + return path.replace(/^\/+/, ""); + } + const noteDir = dirnameOf(noteRel.replaceAll("\\", "/")); + if (path.startsWith("../")) { + const parts = [...noteDir.split("/").filter(Boolean), ...path.split("/")]; + const out: string[] = []; + for (const part of parts) { + if (part === "..") { + out.pop(); + } else if (part !== "." && part) { + out.push(part); + } + } + return out.join("/"); + } + if (noteDir) { + return `${noteDir}/${path}`; + } + return path; +} + +export function isRemoteImage(raw: string): boolean { + return /^https?:\/\//i.test(raw.trim()); +} + +export type MarkdownImage = { + alt: string; + src: string; + kind: "md" | "wiki"; +}; + +export function findMarkdownImages(line: string): MarkdownImage[] { + const found: MarkdownImage[] = []; + const md = /!\[([^\]]*)\]\(([^)]+)\)/g; + const wiki = /!\[\[([^\]|#]+)(?:\|([^\]]+))?\]\]/g; + let match: RegExpExecArray | null; + while ((match = md.exec(line))) { + found.push({ alt: match[1], src: match[2].trim(), kind: "md" }); + } + while ((match = wiki.exec(line))) { + found.push({ alt: match[2] ?? match[1], src: match[1].trim(), kind: "wiki" }); + } + return found; +} + +export function attachmentRel(fileName: string): string { + const raw = fileName || "image.png"; + const safe = raw.replace(/[^\w.\-]+/g, "-"); + const stamp = new Date().toISOString().replace(/[:.]/g, "").replace("T", "-").slice(0, 15); + return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`; +} + +export function imageFiles(data: DataTransfer | null): File[] { + return [...(data?.files ?? [])].filter(file => isImagePath(file.name)); +} + +// File contents and names are protected during dragover; files is usually empty. +export function hasFileDrag(data: DataTransfer | null): boolean { + return !!data && [...data.types].includes("Files"); +} + +export function imageInsertion(source: string, from: number, to: number, snippets: string[]): string { + const before = source.slice(0, from), after = source.slice(to); + const prefix = !before || /(?:\r?\n){2}$/.test(before) ? "" : before.endsWith("\n") ? "\n" : "\n\n"; + const suffix = /^(?:\r?\n){2}/.test(after) ? "" : /^\r?\n/.test(after) ? "\n" : "\n\n"; + return prefix + snippets.join("\n\n") + suffix; +} + +export function workspaceImageLink(notePath: string, imagePath: string): string { + const from = notePath.replaceAll("\\", "/").split("/").slice(0, -1); + const to = imagePath.replaceAll("\\", "/").split("/"); + while (from.length && to.length && from[0] === to[0]) { from.shift(); to.shift(); } + const relative = [...from.map(() => ".."), ...to].map(part => encodeURIComponent(part).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)).join("/"); + return `![](${relative})`; +} diff --git a/src/lib/workspace/noteHtml.ts b/src/lib/workspace/noteHtml.ts new file mode 100644 index 0000000..761fa5c --- /dev/null +++ b/src/lib/workspace/noteHtml.ts @@ -0,0 +1,231 @@ +import MarkdownIt from "markdown-it"; +import type { Token } from "markdown-it"; +import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "../editor/tableFormulas.ts"; + +const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false }); +export const escapeHtml = markdown.utils.escapeHtml; + +// Inline note formats also round-trip through the table cell editor. +markdown.inline.ruler.before("emphasis", "note_formats", (state, silent) => { + const marker = ["==", "%%", "$"].find(value => state.src.startsWith(value, state.pos)); + if (!marker || (marker === "$" && state.src.startsWith("$$", state.pos))) return false; + let end = state.pos + marker.length; + for (; end < state.posMax; end++) { + if (state.src[end] === "\\") { end++; continue; } + if (state.src.startsWith(marker, end)) break; + } + if (end >= state.posMax || end === state.pos + marker.length) return false; + if (!silent) { + const kind = marker === "==" ? "highlight" : marker === "$" ? "math" : "comment"; + const token = state.push(`note_${kind}`, "", 0); + token.content = state.src.slice(state.pos + marker.length, end); + } + state.pos = end + marker.length; + return true; +}); +for (const kind of ["highlight", "math", "comment"]) { + markdown.renderer.rules[`note_${kind}`] = (tokens, index, _options, env) => { + const content = tokens[index].content; + return kind === "highlight" ? `${markdown.renderInline(content, env)}` : `${escapeHtml(content)}`; + }; +} + +export function plainInlineMarkdown(source: string): string { + const literal = (text: string) => text.replace(/&/g, "&").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`); + function plain(tokens: Token[]): string { + return tokens.map(token => { + if (token.type === "note_highlight") return plain(markdown.parseInline(token.content, {})); + if (token.type === "hardbreak" || token.type === "softbreak") return "
      "; + if (token.type === "image") { + const target = String(token.attrGet("src") || ""); + const label = plain(token.children || []); + return token.attrGet("data-md-kind") === "wiki" ? `![[${literal(target)}\\|${label}]]` : `![${label}](<${target.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`; + } + if (token.children) return plain(token.children); + return token.nesting === 0 ? literal(token.content) : ""; + }).join(""); + } + return plain(markdown.parseInline(source, {})); +} + +// Obsidian-style table cells use
      for line breaks. Recognize only this +// attribute-free tag; arbitrary HTML remains escaped, including inside cells. +markdown.inline.ruler.before("html_inline", "note_line_break", (state, silent) => { + const match = /^/i.exec(state.src.slice(state.pos)); + if (!match) return false; + if (!silent) state.push("hardbreak", "br", 0); + state.pos += match[0].length; + return true; +}); + +const copyIcon = ''; + +// Parse wiki links as inline tokens, so code spans and fenced code stay literal. +markdown.inline.ruler.before("link", "wiki_link", (state, silent) => { + const match = /^(!?)\[\[([^\]\n]+)\]\]/.exec(state.src.slice(state.pos)); + if (!match) return false; + const [target, ...alias] = match[2].split("|"); + const label = alias.join("|") || target; + if (!target.trim() || !markdown.validateLink(target)) return false; + if (!silent) { + if (match[1]) { + const image = state.push("image", "img", 0); + image.attrs = [["src", target.trim()], ["alt", label], ["data-md-kind", "wiki"]]; + image.content = label; + const text = new MarkdownIt.Token("text", "", 0); + text.content = label; + image.children = [text]; + } else { + const open = state.push("link_open", "a", 1); + open.attrs = [["href", target.trim()], ["data-kind", "wiki"], ["class", "wiki"]]; + state.push("text", "", 0).content = label; + state.push("link_close", "a", -1); + } + } + state.pos += match[0].length; + return true; +}); + +markdown.core.ruler.after("inline", "note_blocks", state => { + for (let i = 0; i < state.tokens.length; i++) { + const token = state.tokens[i]; + if (token.type !== "inline" || !token.children?.length) continue; + const first = token.children[0]; + if (first.type !== "text") continue; + const item = state.tokens[i - 2]; + const task = /^\[([ xX])\]\s+/.exec(first.content); + if (task && item?.type === "list_item_open") { + const checked = task[1].toLowerCase() === "x"; + item.attrJoin("class", `task-list-item${checked ? " is-checked" : ""}`); + first.content = first.content.slice(task[0].length); + const checkbox = new MarkdownIt.Token("html_inline", "", 0); + checkbox.content = ` `; + token.children.unshift(checkbox); + for (let parent = i - 3; parent >= 0; parent--) { + const ancestor = state.tokens[parent]; + if ((ancestor.type === "bullet_list_open" || ancestor.type === "ordered_list_open") && ancestor.level < item.level) { + ancestor.attrJoin("class", "contains-task-list"); + break; + } + } + } + const callout = /^\[!(note|tip|info|warning|danger|important|success|question)\][+-]?(?:[ \t]+([^\n]*))?(?:\n|$)/i.exec(first.content); + if (callout && item?.type === "blockquote_open") { + item.attrJoin("class", "md-callout"); + item.attrSet("data-callout", callout[1].toLowerCase()); + const title = callout[2] || callout[1].charAt(0).toUpperCase() + callout[1].slice(1).toLowerCase(); + first.content = first.content.slice(callout[0].length); + if (!first.content && token.children[1]?.type === "softbreak") token.children.splice(1, 1); + const heading = new MarkdownIt.Token("html_inline", "", 0); + heading.content = `${escapeHtml(title)}`; + token.children.unshift(heading); + } + } +}); + +markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => { + if (!tokens[index].attrGet("data-kind")) tokens[index].attrSet("data-kind", "md"); + return renderer.renderToken(tokens, index, options); +}; + +markdown.renderer.rules.fence = (tokens, index) => { + const token = tokens[index]; + const language = token.info.trim().split(/\s+/)[0]; + const code = `
      ${escapeHtml(token.content)}
      \n`; + return language.toLowerCase() === "mermaid" + ? `
      Diagram source${code}
      \n` + : code; +}; + +markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => { + const token = tokens[index]; + const original = String(token.attrGet("src") || ""); + const urls = env?.urls as Map | undefined; + const resolved = urls?.get(original) || (/^https?:\/\//i.test(original) ? original : ""); + const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env); + // Only app-resolved image data or HTTP(S) URLs become image sources. + if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `Image unavailable: ${escapeHtml(alt || original)}`; + return `${escapeHtml(alt)}`; +}; +markdown.renderer.rules.table_open = () => '
      \n'; +markdown.renderer.rules.table_close = () => '
      \n'; + +export function tableFormulaHtml(result: FormulaResult): string { + const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`; + return `${escapeHtml(result.text)}`; +} + +// Work from raw inline content, before Markdown formatting can interpret * or $. +// Each table gets its own reference scope, including in nested lists/callouts. +markdown.core.ruler.after("inline", "table_formulas", state => { + let rows: Token[][] | undefined; + for (const token of state.tokens) { + if (token.type === "table_open") rows = []; + else if (rows && token.type === "tr_open") rows.push([]); + else if (rows && token.type === "inline") rows.at(-1)?.push(token); + else if (rows && token.type === "table_close") { + const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content))); + rows.forEach((row, r) => row.forEach((cell, c) => { + const result = results[r][c]; + if (!result) return; + const output = new MarkdownIt.Token("html_inline", "", 0); + output.content = tableFormulaHtml(result); + cell.children = [output]; + })); + rows = undefined; + } + } +}); + +function documentParts(contents: string) { + const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(contents); + return match ? { body: contents.slice(match[0].length), properties: match[1] } : { body: contents, properties: "" }; +} + +export function markdownImages(contents: string): string[] { + const paths = new Set(); + function visit(tokens: Token[]) { + for (const token of tokens) { + if (token.type === "image") paths.add(String(token.attrGet("src") || "")); + if (token.children) visit(token.children); + } + } + visit(markdown.parse(documentParts(contents).body, {})); + return [...paths]; +} + +export function renderMarkdownHtml(contents: string, urls: Map): string { + const { body, properties } = documentParts(contents); + const metadata = properties ? `
      Properties
      ${escapeHtml(properties)}
      \n` : ""; + return metadata + markdown.render(body, { urls }); +} + +export type MarkdownSection = { start: number; end: number; html: string }; + +// Render with the entire document's reference environment, retaining exact source +// offsets so editing one block never serializes the rest of the document. +export function renderMarkdownSections(contents: string, urls: Map): MarkdownSection[] { + const { body, properties } = documentParts(contents); + const offset = contents.length - body.length; + const lines = [offset]; + for (const match of body.matchAll(/\n/g)) lines.push(offset + match.index + 1); + const env = { urls }; + const tokens = markdown.parse(body, env); + const sections: MarkdownSection[] = []; + if (offset) sections.push({ start: 0, end: offset, html: `
      Properties
      ${escapeHtml(properties)}
      ` }); + for (let i = 0; i < tokens.length;) { + const token = tokens[i]; + const start = token.map ? (lines[token.map[0]] ?? contents.length) : offset; + let end = i + 1; + if (token.nesting === 1) { + let depth = 1; + while (end < tokens.length && depth) depth += tokens[end++].nesting; + } + sections.push({ start, end: contents.length, html: markdown.renderer.render(tokens.slice(i, end), markdown.options, env) }); + i = end; + } + if (!sections.length) sections.push({ start: 0, end: contents.length, html: "" }); + sections[0].start = 0; + for (let i = 0; i < sections.length - 1; i++) sections[i].end = sections[i + 1].start; + return sections; +} diff --git a/src/lib/workspace/outline.ts b/src/lib/workspace/outline.ts new file mode 100644 index 0000000..52efe51 --- /dev/null +++ b/src/lib/workspace/outline.ts @@ -0,0 +1,31 @@ +import { isMarkdownPath } from "./media"; + +export type OutlineItem = { + level: number; + text: string; + line: number; +}; + +export function buildOutline(relPath: string, contents: string): OutlineItem[] { + const lines = contents.split(/\r?\n/); + const items: OutlineItem[] = []; + const markdown = isMarkdownPath(relPath); + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i]; + if (markdown) { + const heading = /^(#{1,6})\s+(.+)\s*$/.exec(line); + if (heading) { + items.push({ level: heading[1].length, text: heading[2].trim(), line: i + 1 }); + } + continue; + } + const code = + /^(?:export\s+)?(?:async\s+)?(?:pub\s+)?(?:def|function|class|fn|struct|impl|interface|enum)\s+([A-Za-z0-9_]+)/.exec( + line.trim(), + ); + if (code) { + items.push({ level: 1, text: code[1], line: i + 1 }); + } + } + return items; +} diff --git a/src/lib/workspace/renamePath.ts b/src/lib/workspace/renamePath.ts new file mode 100644 index 0000000..0e0c8de --- /dev/null +++ b/src/lib/workspace/renamePath.ts @@ -0,0 +1,53 @@ +export type RenamePlan = + | { action: "noop" } + | { action: "error"; message: string } + | { action: "rename"; to: string }; + +function parentOf(rel: string): string { + const idx = rel.lastIndexOf("/"); + if (idx <= 0) { + return ""; + } + return rel.slice(0, idx); +} + +export function planRename(fromRel: string, typed: string): RenamePlan { + const name = typed.trim(); + if (!name) { + return { action: "error", message: "Name is empty" }; + } + if (name.includes("/") || name.includes("\\")) { + return { action: "error", message: "Name cannot contain a path separator" }; + } + const current = fromRel.split("/").pop() ?? fromRel; + if (name === current) { + return { action: "noop" }; + } + const parent = parentOf(fromRel); + return { action: "rename", to: parent ? `${parent}/${name}` : name }; +} + +export function planTitleRename(fromRel: string, title: string): RenamePlan { + const trimmed = title.trim(); + if (!trimmed) { + return { action: "error", message: "Name is empty" }; + } + const current = fromRel.split("/").pop() ?? fromRel; + const currentDot = current.lastIndexOf("."); + const typedDot = trimmed.lastIndexOf("."); + const nextName = + currentDot > 0 && typedDot <= 0 ? `${trimmed}${current.slice(currentDot)}` : trimmed; + return planRename(fromRel, nextName); +} + +/** The writing title edits the basename, keeping the note's Markdown format. */ +export function planMarkdownTitleRename(fromRel: string, title: string): RenamePlan { + const extension = fromRel.match(/\.(?:md|markdown|mdown)$/i)?.[0] ?? ".md"; + const name = title.trim(); + const current = fromRel.split("/").pop() ?? fromRel; + if (name === current.slice(0, -extension.length)) return { action: "noop" }; + const stem = name.toLowerCase().endsWith(extension.toLowerCase()) + ? name.slice(0, -extension.length).trim() : name; + if (!stem) return { action: "error", message: "Name is empty" }; + return planRename(fromRel, stem + extension); +} diff --git a/src/lib/workspace/treeDrop.ts b/src/lib/workspace/treeDrop.ts new file mode 100644 index 0000000..48b19e0 --- /dev/null +++ b/src/lib/workspace/treeDrop.ts @@ -0,0 +1,151 @@ +import type { TreeEntry, TreeKind } from "./types"; + +export type DropPlace = "before" | "after" | "inside"; + +export type DropTarget = { + rel: string; + place: DropPlace; +}; + +export type DropPlan = + | { action: "noop" } + | { action: "reorder"; parent: string; names: string[] } + | { + action: "move"; + from: string; + to: string; + fromParent: string; + toParent: string; + destName: string; + orderFrom: string[]; + orderTo: string[]; + }; + +export function parentRel(rel: string): string { + const idx = rel.lastIndexOf("/"); + if (idx <= 0) { + return ""; + } + return rel.slice(0, idx); +} + +export function joinRel(parent: string, name: string): string { + return parent ? `${parent}/${name}` : name; +} + +export function uniqueName(existing: Iterable, wanted: string): string { + const names = new Set(existing); + if (!names.has(wanted)) { + return wanted; + } + const dot = wanted.lastIndexOf("."); + const stem = dot > 0 ? wanted.slice(0, dot) : wanted; + const ext = dot > 0 ? wanted.slice(dot) : ""; + let n = 2; + while (names.has(`${stem} ${n}${ext}`)) { + n += 1; + } + return `${stem} ${n}${ext}`; +} + +function isInside(parent: string, child: string): boolean { + return child === parent || child.startsWith(`${parent}/`); +} + +export function dropPlaceAt(kind: TreeKind, yRatio: number): DropPlace { + if (kind === "folder") { + if (yRatio < 0.25) { + return "before"; + } + if (yRatio > 0.75) { + return "after"; + } + return "inside"; + } + return yRatio < 0.5 ? "before" : "after"; +} + +export function dropHint(name: string, place: DropPlace): string { + if (place === "inside") { + return `Into ${name}`; + } + if (place === "before") { + return `Before ${name}`; + } + return `After ${name}`; +} + +function insertAt(names: string[], targetName: string, item: string, place: DropPlace): string[] { + const next = [...names]; + let idx = next.indexOf(targetName); + if (idx < 0) { + idx = next.length; + } else if (place === "after") { + idx += 1; + } + next.splice(idx, 0, item); + return next; +} + +export function planDrop( + draggedRel: string, + target: TreeEntry, + place: DropPlace, + childrenOf: (parent: string) => string[], +): DropPlan { + if (draggedRel === target.rel_path) { + return { action: "noop" }; + } + const fromParent = parentRel(draggedRel); + const draggedName = draggedRel.split("/").pop() ?? draggedRel; + + if (place === "inside") { + if (target.kind !== "folder") { + return { action: "noop" }; + } + if (isInside(draggedRel, target.rel_path)) { + return { action: "noop" }; + } + if (fromParent === target.rel_path) { + return { action: "noop" }; + } + const destName = uniqueName(childrenOf(target.rel_path), draggedName); + return { + action: "move", + from: draggedRel, + to: joinRel(target.rel_path, destName), + fromParent, + toParent: target.rel_path, + destName, + orderFrom: childrenOf(fromParent).filter((name) => name !== draggedName), + orderTo: [...childrenOf(target.rel_path), destName], + }; + } + + if (target.kind === "folder" && isInside(draggedRel, target.rel_path)) { + return { action: "noop" }; + } + + const toParent = parentRel(target.rel_path); + if (fromParent === toParent) { + const names = childrenOf(toParent).filter((name) => name !== draggedName); + return { + action: "reorder", + parent: toParent, + names: insertAt(names, target.name, draggedName, place), + }; + } + + const destName = uniqueName(childrenOf(toParent), draggedName); + const names = childrenOf(toParent).filter((name) => name !== draggedName); + return { + action: "move", + from: draggedRel, + to: joinRel(toParent, destName), + fromParent, + toParent, + destName, + orderFrom: childrenOf(fromParent).filter((name) => name !== draggedName), + orderTo: insertAt(names, target.name, destName, place), + }; +} diff --git a/src/lib/workspace/treeSelection.ts b/src/lib/workspace/treeSelection.ts new file mode 100644 index 0000000..fc648e0 --- /dev/null +++ b/src/lib/workspace/treeSelection.ts @@ -0,0 +1,61 @@ +import type { TreeEntry } from "./types"; + +export type SelectionModifiers = { + ctrlKey?: boolean; + metaKey?: boolean; + shiftKey?: boolean; +}; + +export type TreeSelection = { + paths: Set; + anchor: string | null; +}; + +// null means the full edge; a number is the exposed width in tree indentation steps. +export type TreeSelectionEdges = { top: number | null; bottom: number | null }; + +export function treeSelectionEdges(visible: readonly string[], selected: ReadonlySet): Map { + const edges = new Map(); + for (let index = 0; index < visible.length; index++) { + const path = visible[index]; + if (!selected.has(path)) continue; + const depth = path.split("/").length; + const exposed = (neighbor: string | undefined) => neighbor !== undefined && selected.has(neighbor) + ? Math.max(0, neighbor.split("/").length - depth) + : null; + edges.set(path, { top: exposed(visible[index - 1]), bottom: exposed(visible[index + 1]) }); + } + return edges; +} + +/** Match the rendered tree order, excluding children of collapsed folders. */ +export function visibleTreePaths(childrenMap: Record, expanded: ReadonlySet): string[] { + const paths: string[] = []; + function visit(parent: string) { + for (const entry of childrenMap[parent] ?? []) { + paths.push(entry.rel_path); + if (entry.kind === "folder" && expanded.has(entry.rel_path)) visit(entry.rel_path); + } + } + visit(""); + return paths; +} + +export function selectTreePath( + current: TreeSelection, + path: string, + visible: readonly string[], + modifiers: SelectionModifiers = {}, +): TreeSelection { + const additive = modifiers.ctrlKey || modifiers.metaKey; + const anchorIndex = current.anchor === null ? -1 : visible.indexOf(current.anchor); + const targetIndex = visible.indexOf(path); + if (modifiers.shiftKey && anchorIndex !== -1 && targetIndex !== -1) { + const range = visible.slice(Math.min(anchorIndex, targetIndex), Math.max(anchorIndex, targetIndex) + 1); + return { paths: new Set(additive ? [...current.paths, ...range] : range), anchor: current.anchor }; + } + const paths = new Set(additive ? current.paths : []); + if (additive && !modifiers.shiftKey && paths.has(path)) paths.delete(path); + else paths.add(path); + return { paths, anchor: path }; +} diff --git a/src/lib/workspace/types.ts b/src/lib/workspace/types.ts new file mode 100644 index 0000000..012855c --- /dev/null +++ b/src/lib/workspace/types.ts @@ -0,0 +1,35 @@ +export type Chrome = "Writing" | "Ide"; + +export type TreeKind = "file" | "folder"; + +export type TreeEntry = { + name: string; + rel_path: string; + kind: TreeKind; +}; + +export type WorkspaceInfo = { + root: string; + name: string; + watch_mode: string; +}; + +export type WorkspaceEvent = { + root: string; + kind: string; + paths: string[]; +}; + +export type OpenBuffer = { + id: string; + relPath: string; + name: string; + contents: string; + saved: string; + chrome: Chrome; + chromeOverride: Chrome | null; + kind: "text" | "image" | "empty"; + imageUrl: string | null; + diskContents?: string | null; + diskError?: string | null; +}; diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte new file mode 100644 index 0000000..801be90 --- /dev/null +++ b/src/routes/+layout.svelte @@ -0,0 +1,7 @@ + + +{@render children()} diff --git a/src/routes/+layout.ts b/src/routes/+layout.ts new file mode 100644 index 0000000..9d24899 --- /dev/null +++ b/src/routes/+layout.ts @@ -0,0 +1,5 @@ +// Tauri doesn't have a Node.js server to do proper SSR +// so we use adapter-static with a fallback to index.html to put the site in SPA mode +// See: https://svelte.dev/docs/kit/single-page-apps +// See: https://v2.tauri.app/start/frontend/sveltekit/ for more info +export const ssr = false; diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte new file mode 100644 index 0000000..ae66b42 --- /dev/null +++ b/src/routes/+page.svelte @@ -0,0 +1,7 @@ + + +{#if terminalRoot}{:else}{/if} diff --git a/static/favicon.png b/static/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..825b9e65af7c104cfb07089bb28659393b4f2097 GIT binary patch literal 1571 zcmV+;2Hg3HP)Px)-AP12RCwC$UE6KzI1p6{F2N z1VK2vi|pOpn{~#djwYcWXTI_im_u^TJgMZ4JMOsSj!0ma>B?-(Hr@X&W@|R-$}W@Z zgj#$x=!~7LGqHW?IO8+*oE1MyDp!G=L0#^lUx?;!fXv@l^6SvTnf^ac{5OurzC#ZMYc20lI%HhX816AYVs1T3heS1*WaWH z%;x>)-J}YB5#CLzU@GBR6sXYrD>Vw(Fmt#|JP;+}<#6b63Ike{Fuo!?M{yEffez;| zp!PfsuaC)>h>-AdbnwN13g*1LowNjT5?+lFVd#9$!8Z9HA|$*6dQ8EHLu}U|obW6f z2%uGv?vr=KNq7YYa2Roj;|zooo<)lf=&2yxM@e`kM$CmCR#x>gI>I|*Ubr({5Y^rb zghxQU22N}F51}^yfDSt786oMTc!W&V;d?76)9KXX1 z+6Okem(d}YXmmOiZq$!IPk5t8nnS{%?+vDFz3BevmFNgpIod~R{>@#@5x9zJKEHLHv!gHeK~n)Ld!M8DB|Kfe%~123&Hz1Z(86nU7*G5chmyDe ziV7$pB7pJ=96hpxHv9rCR29%bLOXlKU<_13_M8x)6;P8E1Kz6G<&P?$P^%c!M5`2` zfY2zg;VK5~^>TJGQzc+33-n~gKt{{of8GzUkWmU110IgI0DLxRIM>0US|TsM=L|@F z0Bun8U!cRB7-2apz=y-7*UxOxz@Z0)@QM)9wSGki1AZ38ceG7Q72z5`i;i=J`ILzL z@iUO?SBBG-0cQuo+an4TsLy-g-x;8P4UVwk|D8{W@U1Zi z!M)+jqy@nQ$p?5tsHp-6J304Q={v-B>66$P0IDx&YT(`IcZ~bZfmn11#rXd7<5s}y zBi9eim&zQc0Dk|2>$bs0PnLmDfMP5lcXRY&cvJ=zKxI^f0%-d$tD!`LBf9^jMSYUA zI8U?CWdY@}cRq6{5~y+)#h1!*-HcGW@+gZ4B};0OnC~`xQOyH19z*TA!!BJ%9s0V3F?CAJ{hTd#*tf+ur-W9MOURF-@B77_-OshsY}6 zOXRY=5%C^*26z?l)1=$bz30!so5tfABdSYzO+H=CpV~aaUefmjvfZ3Ttu9W&W3Iu6 zROlh0MFA5h;my}8lB0tAV-Rvc2Zs_CCSJnx@d`**$idgy-iMob4dJWWw|21b4NB=LfsYp0Aeh{Ov)yztQi;eL4y5 zMi>8^SzKqk8~k?UiQK^^-5d8c%bV?$F8%X~czyiaKCI2=UH