Replace Monaco with one CodeMirror editor and nest list items with Tab

Phase 4b. DocumentEditor.svelte replaces LiveWriter.svelte and the Monaco
EditorHost.svelte. Each open document has one CodeMirror state. Write and
Source are two compartment configurations of it, so they share the undo
history. editorStates.ts keeps the state while the tab stays open. The
Monaco model, the diff bridge, its timers, and sessions.ts are gone.

- Source: syntax colors from the theme tokens, lazy language packages,
  line numbers, folding, and the current line in IDE, wrapped lines in
  Writing, several carets, and bracket matching and closing.
- Lists (card 088e778b): Tab nests a list item and Shift+Tab moves it
  up, in Write and Source. Both renumber the list. The source keeps
  "1.". Write and Read show numbers, letters, then Roman numerals.
- Indent (card 696c30ce): a fixed 4 spaces in Write and Source.
- The code menu uses CodeMirror commands. The command palette item and
  the Monaco styles, search, theme, and workers are removed.
- @codemirror/legacy-modes is pinned to 6.5.4. Version 6.5.5 uses
  parser types that do not match @codemirror/language 6.12.
- 26 smoke tests use CodeMirror instead of Monaco. New tests:
  editor/listNesting and the markdownLists unit tests.
- Docs: development, UI design, plugin host, user guide, and UI-040.

pnpm check, pnpm test (341 of 341), and pnpm build pass. The full smoke
suite passes, except one template test that passed on retry.
This commit is contained in:
Knotty Wyvern
2026-10-28 10:48:44 -07:00
parent 80f5d908e0
commit 724402729e
70 changed files with 1583 additions and 1475 deletions
+20
View File
@@ -753,3 +753,23 @@ Native shell, background image, and desktop acceptance remain open.
- Evidence: The browser check also covers mixed tabs, pinned tabs, plugin tabs, and Cancel with unsaved edits.
- Evidence files: .audit/secondary-last-tab-cancel.png and .audit/compact-tabs-{width}-{theme}.png.
- Limits: Desktop calls use browser mocks. Native window closure and active terminal confirmation still need desktop acceptance.
### UI-040 — Nested lists and one editor for Write and Source
- Type: Rule change
- Date: 2026-10-28
- Status: Implemented for user review
- Decision source: Cards 088e778b and 696c30ce, and the approved Phase 4 plan of 2026-10-28.
- Previous rule: Tab in a list item added indentation and kept the number. Write indented by 2 spaces, and the IDE view by 2 spaces in Monaco.
- New rule: Tab in a list item makes a nested item, and Shift+Tab moves it one level up. Both renumber the list.
- New rule: Nested ordered lists show decimal numbers at level 1, letters at level 2, and Roman numerals at level 3 in Write and Read. The Markdown source keeps the numbers, for example `1.`.
- New rule: The indent is a fixed 4 spaces in Write and Source, with no setting.
- New rule: Write and Source are two configurations of one CodeMirror state. They share the undo history.
- Reason: Lists behave as in common word processors. One editor removes the Monaco model bridge and its timers.
- Scope: Markdown documents in Write and Source, and all source files.
- Shared implementation: DocumentEditor.svelte, markdownLists.ts, liveMarkdown.ts, sourceView.ts, codeLanguages.ts, editorStates.ts, and the `.reading ol ol` styles in app.css.
- Exceptions: An empty nested item cannot start a list inside a paragraph in CommonMark. Write labels it, and Read shows it as text until the item has text.
- Evidence: editor/listNesting.smoke.mjs covers Tab, Shift+Tab, labels, Read letters, the shared history, and the 4-space indent in both themes at 1440 and 600 pixels.
- Evidence files: output/smoke/editor/listNesting/.
- Replaces / replaced by: None.
- Limits: Source has no minimap, no command palette, and no bracket pair colors. Browser checks use desktop service mocks. Native desktop acceptance remains open.
+2 -2
View File
@@ -50,7 +50,7 @@ Rust errors appear in the terminal that runs `pnpm tauri dev`.
## Architecture
RuneStone is a Tauri 2 app. A Rust host gives native services to a Svelte 5 and TypeScript interface.
CodeMirror drives the Writer view, and Monaco drives the source editor.
CodeMirror drives the editor. Each open document has one editor state, and Write and Source are two configurations of it.
Windows is the primary platform. macOS and Linux builds are experimental.
### Desktop host: `src-tauri/src/`
@@ -81,7 +81,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
| Folder | Responsibility |
| --- | --- |
| `layout/` | The app shell (`Workbench.svelte`), the file tree, tabs, panes, Settings, and dialogs |
| `editor/` | The Writer view (`LiveWriter.svelte`), the source editor (`EditorHost.svelte`), tables, links, images, and editor menus |
| `editor/` | The document editor (`DocumentEditor.svelte`) with its Write and Source configurations, Markdown lists, tables, links, images, and editor menus |
| `formulas/` | Table formulas: the parser and evaluator (`engine.ts`), the rendered results, the formula help, and the `tableFormulas` setting (`index.ts`) |
| `workspace/` | Tauri wrappers, document buffers, the note index and backlinks, paths, templates, and tab transfer (`tabTransfer.ts`) |
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
+4 -4
View File
@@ -155,17 +155,17 @@ The policy stops a script that comes in through rendered content, for example a
| --- | --- | --- |
| `default-src` | `'self'` | All other types come only from the app. |
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: the PDF Viewer decodes JPEG 2000 and JBIG2 images and color profiles with WebAssembly in its worker. It does not permit `eval`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of Monaco, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, the Vite dev server, and plugins (Terminal, CSV Viewer, PDF Viewer, Background Slideshow). |
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
| `font-src` | `'self' data:` | The Monaco icon font, and fonts that the PDF Viewer embeds. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: fonts that the PDF Viewer embeds. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the Background Slideshow worker reads its image from a Blob URL. |
| `worker-src` | `'self' blob:` | `'self'`: Monaco workers. `blob:`: the PDF Viewer and Background Slideshow workers. |
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves. The app starts no worker now. `blob:`: the PDF Viewer and Background Slideshow workers. |
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
| `base-uri` | `'self'` | |
| `form-action` | `'none'` | No form sends data to an address. |
| `frame-ancestors` | `'none'` | |
No source permits `'unsafe-eval'`. The app, Monaco, Mermaid, and the current plugins do not use `eval` or `new Function`.
No source permits `'unsafe-eval'`. The app, CodeMirror, Mermaid, and the current plugins do not use `eval` or `new Function`.
`style-src` needs `'unsafe-inline'`, because style attributes and generated `<style>` elements have no nonce.
Tauri sends the policy as a header with each HTML page of the installed app. It adds the SHA-256 hash of the inline start script of SvelteKit to `script-src`.
+1 -2
View File
@@ -81,7 +81,6 @@ These rules apply to navigation rows, file and folder trees, lists, grids, and t
- Find adjacency from the visible order, including sorting and expanded tree branches. At an indentation change, keep the exposed edges and omit the parts that selected rows share.
- Ordinary table grid lines can stay inside a region. They must not become highlighted selection borders.
- A menu choice and a file selection have different purposes. File selections use the selection fill and outer outline. Hover uses the shared active background on both.
- The IDE command palette uses the shared selection fill, outline, and corner radius.
## Menus and pickers
@@ -190,7 +189,7 @@ Decisions: [UI-009](design-decisions.md#ui-009--character-theme-appearances), [U
- The app image fills the work area below the titlebar, including new tabs and document views. It stays fixed while content scrolls.
- Sidebars use `--rs-image-sidebar-bg` (82% tint). Editor surfaces use `--rs-image-editor-bg` (90% tint). Without an image, both are opaque.
- Writer, Reading, split, and IDE views share the editor surface. Monaco layers stay transparent above it.
- Writer, Reading, split, and IDE views share the editor surface. CodeMirror layers stay transparent above it.
- Code blocks in Writer and Reading use `--rs-code-block-bg`.
- New-tab buttons use `--rs-image-control-bg` and `--rs-image-control-hover-bg`. Their tint keeps labels readable while the image stays visible. The new-tab screen shows only its action buttons, with icons, labels, and shortcuts.
- Headers and dialogs keep their own surfaces.
+4
View File
@@ -79,6 +79,9 @@ Each document pane has two controls:
Hover over a control, or focus it with the keyboard, to see its name.
Writer keeps your Markdown source, frontmatter, and Windows line endings. Read shows frontmatter in a collapsed **Properties** section.
Select a checkbox to complete a task. Copy code blocks without their Markdown fences with the **Copy code** button.
In a list item, press Tab to make a nested item. Press Shift+Tab to move it one level up. RuneStone renumbers the list.
Nested ordered lists show letters, then Roman numerals. The Markdown source keeps the numbers, for example `1.`.
Tab in other text indents by 4 spaces.
To rename a note, select its title in Writer and type a new name. Press Enter or leave the field to save the name. Press Escape to cancel.
The file keeps its folder, extension, contents, and edit history.
@@ -209,6 +212,7 @@ This table lists the Windows and Linux keys.
| Save | Ctrl+S |
| Find in document / Search workspace | Ctrl+F / Ctrl+Shift+F |
| Switch Writer and IDE | Ctrl+E |
| Nest a list item / Move it up | Tab / Shift+Tab |
| Show or hide the sidebar | Ctrl+B |
| Rename | F2 |
| Delete to the trash / Delete permanently | Delete / Shift+Delete |
+13 -2
View File
@@ -25,12 +25,24 @@
},
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-html": "^6.4.12",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/lang-rust": "^6.0.2",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.12.4",
"@codemirror/legacy-modes": "^6.5.4",
"@codemirror/search": "^6.7.2",
"@codemirror/state": "^6.7.5",
"@codemirror/view": "^6.43.12",
"@lezer/highlight": "^1.2.3",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-dialog": "^2.7.3",
"@tauri-apps/plugin-opener": "^2",
@@ -41,8 +53,7 @@
"@tiptap/pm": "^3.31.3",
"@tiptap/starter-kit": "^3.31.3",
"markdown-it": "^15.0.2",
"mermaid": "^12.0.0",
"monaco-editor": "^0.56.0"
"mermaid": "^12.0.0"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.10",
+160 -25
View File
@@ -8,15 +8,48 @@ importers:
.:
dependencies:
'@codemirror/autocomplete':
specifier: ^6.20.3
version: 6.20.3
'@codemirror/commands':
specifier: ^6.11.1
version: 6.11.1
'@codemirror/lang-css':
specifier: ^6.3.1
version: 6.3.1
'@codemirror/lang-html':
specifier: ^6.4.12
version: 6.4.12
'@codemirror/lang-javascript':
specifier: ^6.2.5
version: 6.2.5
'@codemirror/lang-json':
specifier: ^6.0.2
version: 6.0.2
'@codemirror/lang-markdown':
specifier: ^6.5.2
version: 6.5.2
'@codemirror/lang-python':
specifier: ^6.2.1
version: 6.2.1
'@codemirror/lang-rust':
specifier: ^6.0.2
version: 6.0.2
'@codemirror/lang-sass':
specifier: ^6.0.2
version: 6.0.2
'@codemirror/lang-xml':
specifier: ^6.1.0
version: 6.1.0
'@codemirror/lang-yaml':
specifier: ^6.1.3
version: 6.1.3
'@codemirror/language':
specifier: ^6.12.4
version: 6.12.4
'@codemirror/legacy-modes':
specifier: ^6.5.4
version: 6.5.4
'@codemirror/search':
specifier: ^6.7.2
version: 6.7.2
@@ -26,6 +59,9 @@ importers:
'@codemirror/view':
specifier: ^6.43.12
version: 6.43.12
'@lezer/highlight':
specifier: ^1.2.3
version: 1.2.3
'@tauri-apps/api':
specifier: ^2
version: 2.11.1
@@ -59,9 +95,6 @@ importers:
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
@@ -132,12 +165,33 @@ packages:
'@codemirror/[email protected]':
resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-EZaGjCUegtiU7kSMvOfEZpaCReowEf3yNidYu7+vfuGTm9ow4mthAparY5hisJqOHmJowVH3Upu+eJlUji6qqA==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-l/bdzIABvnTo1nzdY6U+kPAC51czYQcOErfzQ9zSm9D8GmNPD0WTW8st/CJwBTPLO8jlrbyvlSEcN20dc4iL0Q==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-3z0blhicHLfwi2UgkZYRPioSgVTo9PV5GP5ducFH6FaHy0IAJRg+ixj5gTR1gnT/glAIC8xv4w2VL1LoZfs+Jg==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-AZ8DJBuXGVHybpBQhmZtgew5//4hv3tdkXnr3vDmOUMJRuB6vn/uuwtmTOTlqEaQFg3hQSVeA90NmvIQyUV6FQ==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-/cZr6qZyl08iYNLGsJ862CXXNI51LryRFRE40ejgoIjXZz0C1rGkD3/Ek5jM/8w1ceRjqtt4qx/KLMh4zBTgew==}
'@codemirror/[email protected]':
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
@@ -187,12 +241,30 @@ packages:
'@lezer/[email protected]':
resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==}
'@lezer/[email protected]':
resolution: {integrity: sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==}
'@lezer/[email protected]':
resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==}
'@lezer/[email protected]':
resolution: {integrity: sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==}
'@lezer/[email protected]':
resolution: {integrity: sha512-MhQIURHRytsNzP/YXnqpYKW6la6voAH3kyplTOOiCdjyFY6cWWGFVmYVdHIPrElqSDf4iCDktQCockB9FxuhzQ==}
'@lezer/[email protected]':
resolution: {integrity: sha512-XxErOjZzQ7yJt1agUT4fu9qQvESZ3acgoxpPaPTPOiUx+duCjaVAtZGFIgphkHxlN05djdVAIOy/wItShMEjqQ==}
'@lezer/[email protected]':
resolution: {integrity: sha512-3mMGdCTUZ/84ArHOuXWQr37pnf7f+Nw9ycPUeKX+wu19b7pSMcZGLbaXwvD2APMBDOGxPmpK/O6S1v1EvLoqgQ==}
'@lezer/[email protected]':
resolution: {integrity: sha512-CdDwirL0OEaStFue/66ZmFSeppuL6Dwjlk8qk153mSQwiSH/Dlri4GNymrNWnUmPl2Um7QfV1FO9KFUyX3Twww==}
'@lezer/[email protected]':
resolution: {integrity: sha512-2lrrHqxalACEbxIbsjhqGpSW8kWpUKuY6RHgnSAFZa6qK62wvnPxA8hGOwOoDbwHcOFs5M4o27mjGu+P7TvBmw==}
'@marijn/[email protected]':
resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==}
@@ -902,9 +974,6 @@ packages:
[email protected]:
resolution: {integrity: sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==}
[email protected]:
resolution: {integrity: sha512-yb1cEmaOum7wFvOCSQxyfgVlv5D47Rc30iZWoMpbDIWTnJ6grDDQyu2KFJzB2k7u0pMuJcQ1zphH//fFnw2tjQ==}
[email protected]:
resolution: {integrity: sha512-f/ZeWvW/BCXbhGEf1Ujp29EASo/lk1FDnETgNKwJrsVvGZhUWCZyg3xLJjAsxfOmt8KjswHmI5EwCQcPMpOYhQ==}
@@ -1076,11 +1145,6 @@ packages:
resolution: {integrity: sha512-q4IGxMv56jCqT4OCRCADBoDP3LO4MhmTXjFbphHPXs4g3j9Xg5RDnxqN8IF/3vIWEU+VCnUq+7JUg/cfy2E6Qw==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==}
engines: {node: '>= 18'}
hasBin: true
[email protected]:
resolution: {integrity: sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==}
engines: {node: '>= 20'}
@@ -1093,9 +1157,6 @@ packages:
resolution: {integrity: sha512-/wQXC9iBxoGV8p3erbvaXs9h77VyLDBH6GdayVjj3hEcSQhFU4N1WUhUppotCEqlIxI2pRMwjwBSwTB1MfZBgQ==}
engines: {node: '>=22.12.0'}
[email protected]:
resolution: {integrity: sha512-sXboRm3BeBeLm938eaiyLMe0OxzfXIlZvbv4ir/jVgQy1zDhWjgmny0WoN45fuDKhCCQsYMbBJrv/A6jd8aCUg==}
[email protected]:
resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
engines: {node: '>=4'}
@@ -1407,6 +1468,11 @@ snapshots:
'@lezer/common': 1.5.2
'@lezer/javascript': 1.5.4
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.12.4
'@lezer/json': 1.0.3
'@codemirror/[email protected]':
dependencies:
'@codemirror/autocomplete': 6.20.3
@@ -1417,6 +1483,46 @@ snapshots:
'@lezer/common': 1.5.2
'@lezer/markdown': 1.7.2
'@codemirror/[email protected]':
dependencies:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.12.4
'@codemirror/state': 6.7.5
'@lezer/common': 1.5.2
'@lezer/python': 1.1.19
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.12.4
'@lezer/rust': 1.0.3
'@codemirror/[email protected]':
dependencies:
'@codemirror/lang-css': 6.3.1
'@codemirror/language': 6.12.4
'@codemirror/state': 6.7.5
'@lezer/common': 1.5.2
'@lezer/sass': 1.1.0
'@codemirror/[email protected]':
dependencies:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.12.4
'@codemirror/state': 6.7.5
'@codemirror/view': 6.43.12
'@lezer/common': 1.5.2
'@lezer/xml': 1.0.6
'@codemirror/[email protected]':
dependencies:
'@codemirror/autocomplete': 6.20.3
'@codemirror/language': 6.12.4
'@codemirror/state': 6.7.5
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/yaml': 1.0.4
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.7.5
@@ -1426,6 +1532,10 @@ snapshots:
'@lezer/lr': 1.4.10
style-mod: 4.1.4
'@codemirror/[email protected]':
dependencies:
'@codemirror/language': 6.12.4
'@codemirror/[email protected]':
dependencies:
'@codemirror/state': 6.7.5
@@ -1500,6 +1610,12 @@ snapshots:
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
@@ -1509,6 +1625,36 @@ snapshots:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@lezer/[email protected]':
dependencies:
'@lezer/common': 1.5.2
'@lezer/highlight': 1.2.3
'@lezer/lr': 1.4.10
'@marijn/[email protected]': {}
'@mermaid-js/[email protected]':
@@ -2188,10 +2334,6 @@ snapshots:
optionalDependencies:
'@types/trusted-types': 2.0.7
[email protected]:
optionalDependencies:
'@types/trusted-types': 2.0.7
[email protected]: {}
[email protected]: {}
@@ -2317,8 +2459,6 @@ snapshots:
punycode.js: 2.3.1
uc.micro: 3.0.0
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -2349,11 +2489,6 @@ snapshots:
ts-dedent: 2.3.0
uuid: 14.0.2
[email protected]:
dependencies:
dompurify: 3.4.8
marked: 14.0.0
[email protected]: {}
[email protected]: {}
+6 -21
View File
@@ -157,6 +157,12 @@ button:disabled {
.reading li::marker { color: var(--rs-text-dim); }
.reading li > p { margin-bottom: 0.6em; }
.reading li > ul, .reading li > ol { margin: 0.35em 0 0.5em; }
/* Nested ordered lists use letters, then Roman numerals. Write labels its markers the same way. */
.reading ol ol { list-style-type: lower-alpha; }
.reading ol ol ol { list-style-type: lower-roman; }
.reading ol ol ol ol { list-style-type: decimal; }
.reading ol ol ol ol ol { list-style-type: lower-alpha; }
.reading ol ol ol ol ol ol { list-style-type: lower-roman; }
.reading .task-list-item { list-style: none; position: relative; }
.reading .task-list-item > input,
.reading .task-list-item > p > input {
@@ -210,27 +216,6 @@ button:disabled {
}
.reading pre.md-code { padding-top: 44px; }
/* Monaco's command picker uses the host selection and control dimensions. */
.quick-input-widget .quick-input-list .monaco-list-row {
border-radius: var(--rs-item-selection-radius);
}
.quick-input-widget .quick-input-list .monaco-list-row:is(:hover, .focused, .selected) {
background: var(--rs-item-selection-bg) !important;
color: var(--rs-text) !important;
}
.quick-input-widget .quick-input-list .monaco-list-row.focused {
outline: var(--rs-item-selection-width) solid var(--rs-item-selection-border) !important;
outline-offset: calc(-1 * var(--rs-item-selection-width));
}
.quick-input-widget .monaco-inputbox {
border-radius: var(--rs-control-radius) !important;
border-color: var(--rs-border) !important;
}
.quick-input-widget .monaco-inputbox:is(.synthetic-focus, :focus-within) {
outline: var(--rs-item-selection-width) solid var(--rs-item-selection-border) !important;
outline-offset: calc(-1 * var(--rs-item-selection-width));
}
.quick-input-widget .monaco-inputbox input:focus { outline: none !important; }
.reading pre code {
background: transparent;
padding: 0;
+6 -4
View File
@@ -2,7 +2,7 @@ import { Prec, StateEffect, StateField } from "@codemirror/state";
import { Decoration, EditorView, keymap, ViewPlugin, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { completionHub } from "./hub";
import type { CompletionHandle } from "./contracts";
import type { CompletionHandle, CompletionSnapshot } from "./contracts";
class Ghost extends WidgetType {
constructor(readonly text: string) { super(); }
eq(other: Ghost) { return other.text === this.text; }
@@ -20,7 +20,9 @@ const ghosts = StateField.define({
provide: field => EditorView.decorations.from(field),
});
const handles = new WeakMap<EditorView, CompletionHandle>();
export function completionExtension(documentId: string) {
type CompletionContext = Pick<CompletionSnapshot, "kind" | "language">;
/** Ghost text completion for an editor. The context gives the kind and the language of the current file. */
export function completionExtension(documentId: string, context: () => CompletionContext = () => ({ kind: "prose", language: "markdown" })) {
return [ghosts, EditorView.baseTheme({ ".rs-completion-ghost": { opacity: "0.65", fontStyle: "italic", pointerEvents: "none" } }),
ViewPlugin.fromClass(class {
handle: CompletionHandle;
@@ -29,10 +31,10 @@ export function completionExtension(documentId: string) {
revision = 0;
constructor(readonly view: EditorView) {
this.handle = completionHub.registerSurface({
id: `writer:${documentId}:${crypto.randomUUID()}`,
id: `editor:${documentId}:${crypto.randomUUID()}`,
snapshot: () => ({ documentId, revision: this.revision, text: view.state.doc.toString(), caret: view.state.selection.main.head,
selectionEnd: view.state.selection.ranges.length > 1 ? -1 : view.state.selection.main.anchor,
focused: view.hasFocus, composing: view.composing, readOnly: view.state.readOnly, kind: "prose", language: "markdown" }),
focused: view.hasFocus, composing: view.composing, readOnly: view.state.readOnly, ...context() }),
preview: text => {
const sequence = ++this.sequence, caret = view.state.selection.main.head;
queueMicrotask(() => { if (!this.disposed && this.sequence === sequence) view.dispatch({ effects: preview.of(text ? { text, caret } : null) }); });
-51
View File
@@ -1,51 +0,0 @@
import type * as Monaco from "monaco-editor";
import { completionHub } from "./hub";
export function connectMonacoCompletion(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, documentId: string, prose: boolean) {
const model = view.getModel()!;
let composing = false;
const decoration = view.createDecorationsCollection();
if (!document.getElementById("rs-completion-style")) {
const style = document.createElement("style"); style.id = "rs-completion-style";
style.textContent = ".rs-completion-ghost{opacity:.65;font-style:italic;pointer-events:none}";
document.head.append(style);
}
const handle = completionHub.registerSurface({
id: `source:${documentId}:${crypto.randomUUID()}`,
snapshot: () => {
const selection = view.getSelection(), position = view.getPosition();
return { documentId, revision: model.getVersionId(), text: model.getValue(), caret: position ? model.getOffsetAt(position) : 0,
selectionEnd: (view.getSelections()?.length === 1 && selection?.isEmpty()) && position ? model.getOffsetAt(position) : -1,
focused: view.hasTextFocus(), composing, readOnly: view.getOption(monaco.editor.EditorOption.readOnly), kind: prose ? "prose" : "code", language: model.getLanguageId() };
},
preview: text => {
const p = view.getPosition();
decoration.set(text && p ? [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), options: {
after: { content: text.replace(/\r?\n/g, " ↵ "), inlineClassName: "rs-completion-ghost", cursorStops: monaco.editor.InjectedTextCursorStops.None },
showIfCollapsed: true,
} }] : []);
},
insert: (text, expected) => {
if (model.getVersionId() !== expected.revision || !view.getSelection()?.isEmpty()) return false;
const p = model.getPositionAt(expected.caret);
view.pushUndoStop();
const done = view.executeEdits("autocomplete", [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), text }]);
view.setPosition(model.getPositionAt(expected.caret + text.length)); view.pushUndoStop(); return done;
},
});
const listeners = [model.onDidChangeContent(() => handle.changed()), view.onDidChangeCursorSelection(() => handle.changed()),
view.onDidFocusEditorText(() => handle.changed()), view.onDidBlurEditorText(() => handle.dismiss()),
view.onDidCompositionStart(() => { composing = true; handle.dismiss(); }), view.onDidCompositionEnd(() => { composing = false; handle.changed(); }),
view.onKeyDown(event => {
if (composing) return;
const key = event.browserEvent.key;
if (key === "Tab" && !event.shiftKey && !event.ctrlKey && !event.altKey) {
if (view.getDomNode()?.querySelector(".suggest-widget.visible")) { handle.dismiss(); return; }
if (handle.accept()) { event.preventDefault(); event.stopPropagation(); }
} else if (key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && key === " ") { event.preventDefault(); event.stopPropagation(); handle.request(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && key === "ArrowRight" && handle.accept(true)) { event.preventDefault(); event.stopPropagation(); }
}),
];
return () => { handle.dispose(); decoration.clear(); listeners.forEach(item => item.dispose()); };
}
+6 -8
View File
@@ -2,15 +2,13 @@ import { EditorState } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import { history, historyKeymap, defaultKeymap } from '@codemirror/commands';
import { completionExtension } from './codemirror';
import { connectMonacoCompletion } from './monaco';
import { completionHub } from './hub';
import { ExternalSession } from '../plugins/externalSession';
import { monaco } from '../editor/monacoEnv';
const writer = new EditorView({ parent: document.querySelector('#writer')!, state: EditorState.create({ doc: 'The ', selection: { anchor: 4 }, extensions: [history(), keymap.of([...historyKeymap, ...defaultKeymap]), completionExtension('fixture')] }) });
const model = monaco.editor.createModel('The ', 'markdown');
const source = monaco.editor.create(document.querySelector('#source') as HTMLElement, { model, theme: 'vs-dark', automaticLayout: true });
const stopSource = connectMonacoCompletion(monaco, source, 'fixture-source', true);
source.setPosition({ lineNumber: 1, column: 5 });
const editor = (parent: string, documentId: string) => new EditorView({ parent: document.querySelector(parent)!, state: EditorState.create({ doc: 'The ', selection: { anchor: 4 }, extensions: [history(), keymap.of([...historyKeymap, ...defaultKeymap]), completionExtension(documentId)] }) });
const writer = editor('#writer', 'fixture');
const source = editor('#source', 'fixture-source');
// Plugin browser tests read the source text through `model`.
const model = { getValue: () => source.state.doc.toString() };
let stopProvider = completionHub.registerProvider({ id: 'fixture', delayMs: 100, complete: async () => 'quiet harbor.' });
Object.assign(window, { completionTest: { writer, source, model, completionHub, stopProvider,
async plugin(code: string) {
@@ -29,5 +27,5 @@ Object.assign(window, { completionTest: { writer, source, model, completionHub,
await session.mount('settings', document.querySelector('#plugin') as HTMLElement);
return session;
},
destroy() { stopProvider(); stopSource(); writer.destroy(); source.dispose(); model.dispose(); },
destroy() { stopProvider(); writer.destroy(); source.destroy(); },
} });
+502
View File
@@ -0,0 +1,502 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { tableFormulasEnabled } from "$lib/formulas";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, StateEffect, type Extension } from "@codemirror/state";
import { EditorView, drawSelection, keymap, type KeyBinding } from "@codemirror/view";
import { defaultKeymap, history, indentLess, indentWithTab, isolateHistory, redo as redoEdit, redoDepth, undo as undoEdit, undoDepth } from "@codemirror/commands";
import { foldedRanges, indentUnit, unfoldEffect } from "@codemirror/language";
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import { writerSearch } from "./writerSearch";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { savedEditor, saveEditor } from "./editorStates";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
import { noteTitle } from "./noteTitle";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import { codeMenu } from "./codeMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt, urlAt } from "./documentLinks";
import { headingFolding } from "./headingFolding";
import { languageFor } from "./languageFor";
import { languageSupport } from "./codeLanguages";
import { indentListItem, outdentListItem } from "./markdownLists";
import { insertIndent, sourceChrome, sourceEditing } from "./sourceView";
import "./headingFolding.css";
type Mode = "write" | "source";
type Props = {
buffer: OpenBuffer;
/** Write shows formatted Markdown. Source shows the text of any file. */
mode: Mode;
chrome: Chrome;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, mode, chrome, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
export function openFind(replace = false) {
if (!editor) return;
openSearchPanel(editor);
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
}
export function closeFind() { if (editor) closeSearchPanel(editor); }
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
let error = $state("");
let lastValue = "";
let lineBreak = "\n";
let refreshVersion = 0;
let menu: { open(x: number, y: number, spellingOffset?: number, linkOffset?: number): void; close(focus?: boolean): void; destroy(): void } | undefined;
const urls = new Map<string, string>();
const loading = new Map<string, Promise<void>>();
const modeConfig = new Compartment(), languageConfig = new Compartment(), title = new Compartment();
let languageExtension: Extension = [];
let languagePath = "";
// The class follows the configuration that the editor shows, not the requested mode.
let shown = $state<{ mode: Mode; chrome: Chrome; markdown: boolean } | null>(null);
const markdownDocument = $derived(isMarkdownPath(buffer.relPath));
const renameTitle = (name: string) => onRenameTitle!(buffer.id, name);
const historyKeymap: KeyBinding[] = [
{ key: "Mod-z", run: undoEdit, preventDefault: true },
{ key: "Mod-y", run: redoEdit, preventDefault: true },
{ key: "Mod-Shift-z", run: redoEdit, preventDefault: true },
];
async function loadImages(path: string, value: string) {
const previousSize = urls.size;
await Promise.all(markdownImages(value).map(async source => {
if (urls.has(source)) return;
if (loading.has(source)) return loading.get(source);
const task = (async () => {
if (isRemoteImage(source)) { urls.set(source, source); return; }
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
try { await task; } finally { loading.delete(source); }
}));
return urls.size !== previousSize;
}
// CodeMirror stores one character per line break. Write the line break of the
// file only at the buffer boundary, so pasted LF and CRLF text both make lines.
function documentSource(state: EditorState) {
return state.doc.sliceString(0, undefined, lineBreak);
}
function detectLineBreak(text: string) {
const crlf = text.split("\r\n").length - 1;
return crlf > text.split("\n").length - 1 - crlf ? "\r\n" : "\n";
}
async function insertImages(event: ClipboardEvent | DragEvent, view: EditorView) {
const data = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
const files = imageFiles(data);
if (!files.length || !onInsertImage || !markdownDocument) return;
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
try {
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
await loadImages(path, snippets.join("\n\n"));
if (editor !== view) return;
const target = view.state.field(imageDrops).get(id);
if (!target) return;
const insert = imageInsertion(view.state.doc.toString(), target.from, target.to, snippets);
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, userEvent: "input.image", annotations: isolateHistory.of("full") });
view.focus();
} catch (reason) { if (editor === view) error = String(reason); }
finally { if (editor === view) view.dispatch({ effects: clearImageDrop.of(id) }); }
}
function writeExtensions(lists: KeyBinding[]): Extension {
const current = untrack(() => buffer);
return [
headingFolding,
tableNavigation,
keymap.of([{ key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, ...lists, indentWithTab]),
EditorView.lineWrapping,
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(buffer.relPath, image.dataset.mdSrc || "", "md")) {
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Could not find this image in the workspace.");
},
validate: async source => {
if (isRemoteImage(source)) return;
for (const path of linkCandidates(buffer.relPath, source, "md")) {
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Choose an image that exists in the workspace.");
},
report: message => { error = message; },
}),
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
];
}
function modeExtensions(next: NonNullable<typeof shown>): Extension {
// Tab in a Markdown list item makes a nested item in Write and in Source.
const lists: KeyBinding[] = next.markdown ? [{ key: "Tab", run: indentListItem, shift: outdentListItem }] : [];
if (next.mode === "write") return writeExtensions(lists);
return [
sourceEditing,
sourceChrome(next.chrome),
keymap.of([...lists, { key: "Tab", run: insertIndent, shift: indentLess }]),
EditorView.contentAttributes.of({ "aria-label": $t("Editor"), spellcheck: "false" }),
];
}
function requested() {
return untrack(() => ({ mode, chrome, markdown: markdownDocument }));
}
function configuration(): Extension[] {
const current = untrack(() => buffer);
shown = requested();
return [
completionExtension(current.id, () => ({ kind: isMarkdownPath(buffer.relPath) ? "prose" : "code", language: languageFor(buffer.relPath) })),
languageConfig.of(languageExtension),
modeConfig.of(modeExtensions(shown)),
history(), drawSelection(), indentUnit.of(" "), EditorState.tabSize.of(4),
EditorView.theme({}, { dark: true }),
writerSearch,
imageDrops,
keymap.of([...searchKeymap, ...historyKeymap, ...defaultKeymap]),
EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) {
menu?.close(false);
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
}
if (!update.docChanged) return;
scroll = scroll?.map(update.changes);
lastValue = documentSource(update.state);
onChange(lastValue, current.id);
if (shown?.mode !== "write") return;
void loadImages(buffer.relPath, update.state.sliceDoc()).then(changed => {
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
});
}),
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false;
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
if (!event.ctrlKey && !event.metaKey) return false;
if (event.button !== 0) return false;
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const source = view.state.doc.toString();
const sourceLink = position === null ? undefined : markdownDocument ? documentLinkAt(source, position) : urlAt(source, position);
if (!link && !sourceLink) return false;
event.preventDefault();
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
return true;
},
paste(event, view) {
const html = event.clipboardData?.getData("text/html") || "";
if (shown?.mode === "write" && /<table[\s>]/i.test(html)) {
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
if (markdown) {
event.preventDefault(); event.stopPropagation();
const { from, to } = view.state.selection.main;
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
return true;
}
}
if (!onInsertImage || !markdownDocument || !imageFiles(event.clipboardData).length) return false;
void insertImages(event, view); return true;
},
}),
];
}
// Start Write in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
function freshState(source: string) {
const doc = EditorState.create({ doc: source }).doc;
const anchor = untrack(() => mode) === "write" ? documentBodyStart(doc.toString()) : 0;
return EditorState.create({ doc, selection: { anchor }, extensions: configuration() });
}
let scroll: ReturnType<EditorView["scrollSnapshot"]> | undefined;
$effect(() => {
const el = host;
if (!el) return;
let cancelled = false;
let releaseSelection: (() => void) | undefined;
let releaseDrop: (() => void) | undefined;
let releaseScroll: (() => void) | undefined;
const current = untrack(() => buffer);
void (async () => {
lastValue = current.contents;
const saved = savedEditor(current.id);
const restore = saved?.source === lastValue ? saved : undefined;
lineBreak = restore?.lineBreak ?? detectLineBreak(lastValue);
if (isMarkdownPath(current.relPath) && untrack(() => mode) === "write") await loadImages(current.relPath, current.contents);
languagePath = current.relPath;
languageExtension = await languageSupport(current.relPath);
if (cancelled) return;
// A restored state keeps its history. The new configuration replaces the handlers of the old editor.
const state = restore ? restore.state.update({ effects: StateEffect.reconfigure.of(configuration()) }).state : freshState(lastValue);
// Restore through CodeMirror's layout pass, once its viewport is measured.
const view = new EditorView({ state, parent: el, scrollTo: restore?.scroll });
editor = view;
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
scroll = restore?.scroll ?? view.scrollSnapshot();
// Svelte may detach the old tab before effect cleanup runs, at which point
// DOM scroll offsets read as zero. Capture while the view is still mounted.
const saveScroll = () => { if (view.dom.isConnected) scroll = view.scrollSnapshot(); };
view.scrollDOM.addEventListener("scroll", saveScroll);
releaseScroll = () => view.scrollDOM.removeEventListener("scroll", saveScroll);
if (isMarkdownPath(current.relPath)) releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.posAtCoords(point, false), path); });
releaseSelection = registerSelection(current.id, () => view.state.selection.ranges.map(range => view.state.sliceDoc(range.from, range.to)).join("\n"));
menu = isMarkdownPath(current.relPath) ? markdownMenu({
snapshot() {
const { doc, selection } = view.state;
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
undo() { undoEdit(view); },
redo() { redoEdit(view); },
canUndo() { return undoDepth(view.state) > 0; },
canRedo() { return redoDepth(view.state) > 0; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }))
: codeMenu(view, message => { error = message; });
if (!untrack(() => focusTitle) && shouldFocusOnMount()) view.focus();
})().catch(reason => { if (!cancelled) error = String(reason); });
return () => {
cancelled = true;
refreshVersion++;
menu?.destroy();
menu = undefined;
releaseDrop?.();
releaseScroll?.();
if (editor && scroll) saveEditor(current.id, { source: documentSource(editor.state), lineBreak, state: editor.state, scroll });
editor?.destroy();
releaseSelection?.();
editor = undefined;
};
});
// Write and Source are two configurations of one state, so the switch keeps the history.
$effect(() => {
const next = { mode, chrome, markdown: markdownDocument };
const view = editor;
if (!view) return;
untrack(() => {
if (shown && shown.mode === next.mode && shown.chrome === next.chrome && shown.markdown === next.markdown) return;
void (next.mode === "write" ? loadImages(buffer.relPath, view.state.doc.toString()) : Promise.resolve(false)).then(() => {
const latest = requested();
if (editor !== view || latest.mode !== next.mode || latest.chrome !== next.chrome || latest.markdown !== next.markdown) return;
shown = next;
view.dispatch({ effects: modeConfig.reconfigure(modeExtensions(next)) });
});
});
});
$effect(() => {
const path = buffer.relPath;
const view = editor;
if (!view || path === languagePath) return;
languagePath = path;
void languageSupport(path).then(extension => {
if (editor !== view || languagePath !== path) return;
languageExtension = extension;
view.dispatch({ effects: languageConfig.reconfigure(extension) });
});
});
$effect(() => {
void $tableFormulasEnabled;
editor?.dispatch({ effects: refreshImages.of() });
});
$effect(() => {
const name = markdownTitle(buffer.relPath);
const view = editor;
if (view && shown?.mode === "write") view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
});
$effect(() => {
if (!focusTitle || !editor || shown?.mode !== "write") return;
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
if (!button) return;
button.click();
onTitleFocused?.();
});
$effect(() => {
const value = buffer.contents;
const path = buffer.relPath;
const view = editor;
if (!view || value === lastValue) return;
const version = ++refreshVersion;
void (untrack(() => shown?.mode) === "write" ? loadImages(path, value) : Promise.resolve(false)).then(() => {
if (version !== refreshVersion || editor !== view || buffer.contents !== value) return;
lastValue = value;
lineBreak = detectLineBreak(value);
// Reloads start fresh history, so undo cannot revive a discarded disk version.
const anchor = Math.min(view.state.selection.main.head, value.replace(/\r\n/g, "\n").length);
view.setState(freshState(value));
view.dispatch({ selection: { anchor } });
});
});
$effect(() => {
const line = focusLine;
const view = editor;
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects });
view.focus();
});
});
</script>
<div class={(shown?.mode ?? mode) === "write" ? "live-writer" : "source-editor"} data-chrome={shown?.chrome ?? chrome}
bind:this={host} role="application" aria-label={(shown?.mode ?? mode) === "write" ? $t("Markdown writing editor") : $t("Editor")}
ondragovercapture={(event) => {
if (!onInsertImage || !markdownDocument || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.live-writer, .source-editor { position: absolute; inset: 0; }
.live-writer :global(.cm-editor), .source-editor :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
.live-writer :global(.cm-editor.cm-focused), .source-editor :global(.cm-editor.cm-focused) { outline: none; }
.live-writer :global(.cm-panels), .source-editor :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground),
.source-editor :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .source-editor :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.source-editor :global(.cm-scroller) { font: var(--rs-code-font-weight) var(--rs-code-font-size)/var(--rs-code-line-height) var(--rs-font-mono); }
.source-editor :global(.cm-content) { padding: 8px 0 24px; caret-color: var(--rs-accent); }
.source-editor[data-chrome="Writing"] :global(.cm-content) { padding: 16px 24px 48px; }
.source-editor :global(.cm-cursor) { border-left-color: var(--rs-accent); }
.source-editor :global(.cm-gutters) { border: 0; background: transparent; color: var(--rs-text-dim); }
.source-editor :global(.cm-lineNumbers .cm-gutterElement) { padding: 0 10px 0 16px; }
.source-editor :global(.cm-activeLine) { background: var(--rs-bg-active); }
.source-editor :global(.cm-activeLineGutter) { background: transparent; color: var(--rs-text); }
.source-editor :global(.cm-foldGutter .cm-gutterElement) { padding: 0 4px; cursor: pointer; }
.source-editor :global(.cm-selectionMatch) { background: var(--rs-item-selection-bg); }
.source-editor :global(.cm-matchingBracket) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-border); }
.source-editor :global(.cm-nonmatchingBracket) { color: var(--rs-error); }
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
.live-writer :global(.cm-line) { padding-inline: 0; position: relative; }
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
.live-writer :global(.writer-divider-line) { display: flex; align-items: center; }
.live-writer :global(.writer-divider) { display: inline-flex; align-items: center; flex: 1; min-width: 0; height: 1.75em; cursor: text; }
.live-writer :global(.writer-divider::after) { content: ""; width: 100%; border-top: 1px solid var(--rs-border); }
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
/* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
.live-writer :global(.writer-preview img) { max-width: 100%; }
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
.live-writer :global(.writer-table p) { margin: 0; }
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
.live-writer :global(.table-add span) { position: absolute; font: 20px/24px var(--rs-font-ui); width: 24px; height: 24px; text-align: center; pointer-events: none; }
.live-writer :global(.table-add-column span) { left: 0; top: var(--table-add-position, 50%); transform: translateY(-50%); }
.live-writer :global(.table-add-row span) { top: 0; left: var(--table-add-position, 50%); transform: translateX(-50%); }
</style>
-339
View File
@@ -1,339 +0,0 @@
<script lang="ts">
import FindPanel from "./FindPanel.svelte";
import { monacoSearch } from "./monacoSearch";
import { SearchQuery } from "@codemirror/search";
import { t } from "$lib/i18n";
import { tick, untrack } from "svelte";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { codeFont } from "./codeFont";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { codeMenu } from "./codeMenu";
import type { TableContextActions } from "./tableCellActions";
import { documentLinks, documentLinkAt } from "./documentLinks";
type Props = {
buffer: OpenBuffer;
chrome: Chrome;
onChange: (value: string, id: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
export function focus() { editor?.focus(); }
let search = $state.raw<ReturnType<typeof monacoSearch>>();
let findOpen = $state(false);
let findPanel = $state<FindPanel>();
export async function openFind(replace = false) {
if (!search || !editor) return;
const selection = editor.getSelection();
const text = selection && editor.getModel()?.getValueInRange(selection);
if (text && !text.includes("\n") && !text.includes("\r")) {
search.target.setQuery(new SearchQuery({ ...search.target.query, search: text }));
findPanel?.sync(search.target.query);
}
findOpen = true;
search.refresh();
await tick();
findPanel?.focus(replace);
}
export function closeFind() { if (findOpen) search?.target.close(); }
export function nextMatch(backward = false) { if (findOpen) search?.target.next(backward); else void openFind(); }
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
const documentPath = $derived(buffer.relPath);
async function takeImages(event: DragEvent | ClipboardEvent, data: DataTransfer | null) {
if (!isMarkdownPath(buffer.relPath) || !onInsertImage) {
return false;
}
const files = imageFiles(data);
if (files.length === 0) {
return false;
}
event.preventDefault();
event.stopPropagation();
const view = editor, model = view?.getModel();
if (!view || !model) return true;
const position = event instanceof DragEvent ? view.getTargetAtClientPoint(event.clientX, event.clientY)?.position : null;
return importImages(view, files, position);
}
async function importImages(view: import("monaco-editor").editor.IStandaloneCodeEditor, files: File[], position?: import("monaco-editor").Position | null, linkedPath?: string) {
const model = view.getModel();
if (!model) return true;
const range = position ? { startLineNumber: position.lineNumber, startColumn: position.column, endLineNumber: position.lineNumber, endColumn: position.column } : view.getSelection();
if (!range) return true;
const [marker] = model.deltaDecorations([], [{ range, options: { stickiness: 1 } }]);
try {
const snippets: string[] = linkedPath ? [workspaceFileLink(buffer.relPath, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return true;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return true;
const target = model.getDecorationRange(marker);
if (!target) return true;
const from = model.getOffsetAt(target.getStartPosition()), to = model.getOffsetAt(target.getEndPosition());
const text = imageInsertion(model.getValue(), from, to, snippets).replace(/\n/g, model.getEOL());
view.pushUndoStop();
view.executeEdits("insert-images", [{ range: target, text, forceMoveMarkers: true }], () => {
const end = model.getPositionAt(from + text.length);
view.setPosition(end);
return [view.getSelection()!];
});
view.pushUndoStop();
view.focus();
} catch (reason) { if (editor === view) loadError = String(reason); }
finally { if (!model.isDisposed()) model.deltaDecorations([marker], []); }
return true;
}
$effect(() => {
const el = host;
// Buffer snapshots change on each edit. Only a path change remounts Monaco.
const path = documentPath;
if (!el) {
return;
}
let cancelled = false;
let session: ReturnType<typeof editorSession> | undefined;
let contentListener: { dispose(): void } | undefined;
let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined;
let releaseCompletion: (() => void) | undefined;
const listeners: { dispose(): void }[] = [];
void import("./monacoEnv").then(({ monaco, currentTheme }) => {
if (cancelled || !el.isConnected) {
return;
}
session = editorSession(monaco, untrack(() => buffer));
const mode = untrack(() => chrome);
const model = session.model;
const markdown = isMarkdownPath(path);
const view = monaco.editor.create(el, {
model,
theme: currentTheme,
automaticLayout: true,
...codeFont(el),
scrollBeyondLastLine: false,
smoothScrolling: true,
cursorBlinking: "smooth",
tabSize: 2,
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: false,
...monacoChrome(mode),
});
editor = view;
search = monacoSearch(monaco, view, () => { findOpen = false; });
for (const [id, label, replace] of [["actions.find", "Find", false], ["editor.action.startFindReplaceAction", "Replace", true]] as const) {
listeners.push(view.addAction({ id, label, keybindings: [monaco.KeyMod.CtrlCmd | (replace ? monaco.KeyCode.KeyH : monaco.KeyCode.KeyF)], run: () => openFind(replace) }));
}
listeners.push(view.addAction({ id: "editor.action.nextMatchFindAction", label: "Next match", keybindings: [monaco.KeyCode.F3], run: () => nextMatch() }));
listeners.push(view.addAction({ id: "editor.action.previousMatchFindAction", label: "Previous match", keybindings: [monaco.KeyMod.Shift | monaco.KeyCode.F3], run: () => nextMatch(true) }));
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
provideLinks(candidate) {
if (candidate !== model) return { links: [] };
return { links: documentLinks(model.getValue()).map(link => {
const from = model.getPositionAt(link.from), to = model.getPositionAt(link.to);
return { range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column),
url: `runestone-link://document${linkPath}${link.kind}?${encodeURIComponent(link.target)}`, tooltip: "Open link" };
}) };
},
}));
listeners.push(monaco.editor.registerLinkOpener({ open(resource) {
const url = resource.toString(true);
if (resource.scheme === "runestone-link" && resource.path.startsWith(linkPath)) {
onOpenLink?.(resource.path.slice(linkPath.length) === "wiki" ? "wiki" : "md", decodeURIComponent(resource.query));
return true;
}
if (view.hasTextFocus() && /^(https?:|mailto:)/i.test(url) && onOpenLink) { onOpenLink("md", url); return true; }
return false;
} }));
const openSourceLink = (event: MouseEvent) => {
if (!markdown || event.button !== 0 || (!event.ctrlKey && !event.metaKey) || !onOpenLink) return;
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const link = position && documentLinkAt(model.getValue(), model.getOffsetAt(position));
if (!link) return;
event.preventDefault(); event.stopImmediatePropagation();
onOpenLink(link.kind, link.target);
};
el.addEventListener("mousedown", openSourceLink, true);
listeners.push({ dispose: () => el.removeEventListener("mousedown", openSourceLink, true) });
listeners.push(view.onDidChangeCursorPosition(event => onSelectionLine?.(event.position.lineNumber)));
if (markdown) {
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.getTargetAtClientPoint(point.x, point.y)?.position, path); });
menu = markdownMenu({
snapshot() {
const selection = view.getSelection()!, version = model.getVersionId();
return { source: model.getValue(), selection: { from: model.getOffsetAt(selection.getStartPosition()), to: model.getOffsetAt(selection.getEndPosition()) }, valid: () => editor === view && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection) };
},
apply(edit) {
const from = model.getPositionAt(edit.from), to = model.getPositionAt(edit.to);
view.pushUndoStop();
view.executeEdits("markdown-menu", [{ range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column), text: edit.insert }], () => {
const anchor = model.getPositionAt(edit.anchor), head = model.getPositionAt(edit.head);
return [new monaco.Selection(anchor.lineNumber, anchor.column, head.lineNumber, head.column)];
});
view.pushUndoStop();
},
select(from, to) {
const start = model.getPositionAt(from), end = model.getPositionAt(to);
view.setSelection(new monaco.Selection(start.lineNumber, start.column, end.lineNumber, end.column));
view.revealPositionInCenterIfOutsideViewport(end);
},
selectAll() { view.setSelection(model.getFullModelRange()); view.focus(); },
focus() { view.focus(); },
undo() { view.trigger("markdown-menu", "undo", null); },
redo() { view.trigger("markdown-menu", "redo", null); },
canUndo() { return model.canUndo(); },
canRedo() { return model.canRedo(); },
}, untrack(() => tableActions), message => { loadError = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
} else {
menu = codeMenu(view, message => { loadError = message; });
}
const openContextMenu = (event: MouseEvent) => {
event.preventDefault(); event.stopImmediatePropagation();
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const selection = view.getSelection();
if (position && (!selection || selection.isEmpty() || !selection.containsPosition(position))) view.setPosition(position);
view.focus();
menu?.open(event.clientX, event.clientY, undefined, position ? model.getOffsetAt(position) : undefined);
};
el.addEventListener("contextmenu", openContextMenu, true);
listeners.push({ dispose: () => el.removeEventListener("contextmenu", openContextMenu, true) });
listeners.push(view.onKeyDown(event => {
if (event.browserEvent.key !== "ContextMenu" && !(event.shiftKey && event.browserEvent.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
const position = view.getPosition(), rect = el.getBoundingClientRect();
const coords = position && view.getScrolledVisiblePosition(position);
if (coords) menu?.open(rect.left + coords.left, rect.top + coords.top + coords.height);
}));
listeners.push(view.onDidChangeCursorSelection(() => menu?.close(false)));
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
if (session.view) view.restoreViewState(session.view);
onSelectionLine?.(view.getPosition()?.lineNumber ?? 1);
ready += 1;
contentListener = model.onDidChangeContent(() => {
if (applying) {
return;
}
onChange(view.getValue(), documentId);
});
if (shouldFocusOnMount()) view.focus();
}).catch((error) => { if (!cancelled) loadError = String(error); });
return () => {
cancelled = true;
const view = editor;
if (view && session) session.view = view.saveViewState();
contentListener?.dispose();
releaseCompletion?.();
releaseSelection?.();
menu?.destroy();
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
search?.dispose();
search = undefined;
findOpen = false;
view?.dispose();
if (session) releaseEditorSession(session);
editor = undefined;
};
});
$effect(() => {
void ready;
const mode = chrome;
const view = editor;
if (!view) {
return;
}
view.updateOptions(monacoChrome(mode));
});
$effect(() => {
void ready;
const contents = buffer.contents;
const view = editor;
if (!view) {
return;
}
if (contents !== view.getValue()) {
applying = true;
view.setValue(contents ?? "");
applying = false;
}
});
$effect(() => {
void ready;
const line = focusLine;
const view = editor;
if (!view || line == null) {
return;
}
view.revealLineInCenter(line);
view.setPosition({ lineNumber: line, column: 1 });
view.focus();
});
</script>
<div class="source-editor">
{#if findOpen && search}<FindPanel bind:this={findPanel} target={search.target} />{/if}
<div
class="monaco-host"
role="application"
aria-label={$t("Editor")}
bind:this={host}
ondragover={(event) => {
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);
}}
></div>
</div>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.source-editor { position: absolute; inset: 0; display: flex; flex-direction: column; min-width: 0; }
.source-editor :global(.rs-find-bar) { flex-shrink: 0; border-bottom: 1px solid var(--rs-border); }
.monaco-host { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.monaco-host :global(.rs-source-search-match) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-accent); }
.monaco-host :global(.monaco-editor),
.monaco-host :global(.overflow-guard) {
height: 100%;
}
</style>
-482
View File
@@ -1,482 +0,0 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { tableFormulasEnabled } from "$lib/formulas";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
import { defaultKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
import { writerHistory, historyKeymap } from "./writerHistory";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { foldedRanges, unfoldEffect } from "@codemirror/language";
import { noteFormats } from "./noteFormats";
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import { writerSearch } from "./writerSearch";
import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
import { noteTitle } from "./noteTitle";
import { markdownTitle } from "$lib/workspace/media";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt } from "./documentLinks";
import { headingFolding } from "./headingFolding";
import "./headingFolding.css";
type Props = {
buffer: OpenBuffer;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
export function openFind(replace = false) {
if (!editor) return;
openSearchPanel(editor);
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
}
export function closeFind() { if (editor) closeSearchPanel(editor); }
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let ModelSelection: typeof import("monaco-editor").Selection;
let lastValue = "";
let publishing = false;
let historySelections: Map<number, EditorSelection> | undefined;
let freshState: ((source: string) => EditorState) | undefined;
let refreshVersion = 0;
let historyTimer: ReturnType<typeof setTimeout> | undefined;
const urls = new Map<string, string>();
const loading = new Map<string, Promise<void>>();
const title = new Compartment();
const renameTitle = (name: string) => onRenameTitle!(buffer.id, name);
async function loadImages(path: string, value: string) {
const previousSize = urls.size;
await Promise.all(markdownImages(value).map(async source => {
if (urls.has(source)) return;
if (loading.has(source)) return loading.get(source);
const task = (async () => {
if (isRemoteImage(source)) { urls.set(source, source); return; }
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
try { await task; } finally { loading.delete(source); }
}));
return urls.size !== previousSize;
}
// CodeMirror stores one character per line break. Serialize only at the model
// boundary, so pasted LF and CRLF text both create real editor lines.
function modelSource(state: EditorState) {
return state.doc.sliceString(0, undefined, model?.getEOL() ?? "\n");
}
function publish(value: string, id: string, startState: EditorState, state: EditorState) {
if (!model || value === model.getValue()) return;
historySelections?.set(model.getAlternativeVersionId(), startState.selection);
const previous = model.getValue();
let start = 0;
while (start < previous.length && start < value.length && previous[start] === value[start]) start++;
let oldEnd = previous.length, newEnd = value.length;
while (oldEnd > start && newEnd > start && previous[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
const from = model.getPositionAt(start), to = model.getPositionAt(oldEnd);
const cursorState = (state: EditorState) => state.selection.ranges.map(range => {
const anchor = state.doc.lineAt(range.anchor), head = state.doc.lineAt(range.head);
return new ModelSelection(anchor.number, range.anchor - anchor.from + 1, head.number, range.head - head.from + 1);
});
// The model emits changes synchronously. Do not echo this Writer edit back
// into CodeMirror while its update listener still runs.
publishing = true;
try {
model.pushEditOperations(cursorState(startState), [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => cursorState(state));
} finally { publishing = false; }
historySelections?.set(model.getAlternativeVersionId(), state.selection);
clearTimeout(historyTimer);
historyTimer = setTimeout(() => model?.pushStackElement(), 500);
lastValue = model.getValue();
onChange(lastValue, id);
}
async function insertImages(event: ClipboardEvent | DragEvent, view: EditorView) {
const data = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
const files = imageFiles(data);
if (!files.length || !onInsertImage) return;
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
try {
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
await loadImages(path, snippets.join("\n\n"));
if (editor !== view) return;
const target = view.state.field(imageDrops).get(id);
if (!target) return;
const insert = imageInsertion(view.state.doc.toString(), target.from, target.to, snippets);
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, userEvent: "input.image", annotations: isolateHistory.of("full") });
view.focus();
} catch (reason) { if (editor === view) error = String(reason); }
finally { if (editor === view) view.dispatch({ effects: clearImageDrop.of(id) }); }
}
$effect(() => {
const el = host;
if (!el) return;
let cancelled = false;
let session: ReturnType<typeof editorSession> | undefined;
let contentListener: { dispose(): void } | undefined;
let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined;
let releaseScroll: (() => void) | undefined;
let scroll: ReturnType<EditorView["scrollSnapshot"]> | undefined;
const current = untrack(() => buffer);
void import("./monacoEnv").then(async ({ monaco }) => {
await loadImages(current.relPath, current.contents);
if (cancelled) return;
session = editorSession(monaco, untrack(() => buffer));
model = session.model;
ModelSelection = monaco.Selection;
historySelections = session.writerSelections;
lastValue = untrack(() => buffer.contents);
if (model.getValue() !== lastValue) model.setValue(lastValue);
model.pushStackElement();
const extensions = [
completionExtension(current.id),
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
headingFolding,
writerHistory.of({
undo: () => {
clearTimeout(historyTimer);
model!.pushStackElement();
if (!model!.canUndo()) return false;
void model!.undo();
return true;
},
redo: () => {
clearTimeout(historyTimer);
if (!model!.canRedo()) return false;
void model!.redo();
return true;
},
}), drawSelection(),
EditorView.theme({}, { dark: true }),
tableNavigation,
writerSearch,
keymap.of([{ key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, indentWithTab, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(current.relPath, image.dataset.mdSrc || "", "md")) {
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Could not find this image in the workspace.");
},
validate: async source => {
if (isRemoteImage(source)) return;
for (const path of linkCandidates(current.relPath, source, "md")) {
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Choose an image that exists in the workspace.");
},
report: message => { error = message; },
}),
imageDrops,
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) {
menu?.close(false);
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
}
const isolation = update.transactions.map(transaction => transaction.annotation(isolateHistory));
const separate = update.transactions.some(transaction => {
const event = transaction.annotation(Transaction.userEvent);
return transaction.docChanged && event && !/^(input\.type|delete)($|\.)/.test(event);
});
if (separate || (update.selectionSet && !update.docChanged)) model?.pushStackElement();
if (isolation.some(value => value === "before" || value === "full")) model?.pushStackElement();
if (update.docChanged) {
scroll = scroll?.map(update.changes);
publish(modelSource(update.state), current.id, update.startState, update.state);
void loadImages(current.relPath, update.state.sliceDoc()).then(changed => {
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
});
}
if (isolation.some(value => value === "after" || value === "full")) {
clearTimeout(historyTimer);
model?.pushStackElement();
}
}),
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false;
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
if (!event.ctrlKey && !event.metaKey) return false;
if (event.button !== 0) return false;
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const sourceLink = position === null ? undefined : documentLinkAt(view.state.doc.toString(), position);
if (!link && !sourceLink) return false;
event.preventDefault();
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
return true;
},
paste(event, view) {
const html = event.clipboardData?.getData("text/html") || "";
if (/<table[\s>]/i.test(html)) {
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
if (markdown) {
event.preventDefault(); event.stopPropagation();
const { from, to } = view.state.selection.main;
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
return true;
}
}
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
void insertImages(event, view); return true;
},
}),
];
// Start in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
freshState = source => {
const doc = EditorState.create({ doc: source }).doc;
return EditorState.create({ doc, selection: { anchor: documentBodyStart(doc.toString()) }, extensions });
};
const saved = session.writer;
const state = saved?.source === lastValue
? EditorState.fromJSON(saved.state, { extensions })
: freshState(lastValue);
// Restore through CodeMirror's layout pass, once its viewport is measured.
const view = new EditorView({ state, parent: el, scrollTo: saved?.source === lastValue ? saved.scroll : undefined });
editor = view;
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
// Writer and IDE use the same model and undo stack for this document.
contentListener = model.onDidChangeContent(event => {
if (publishing) return;
const value = model!.getValue();
if (value === modelSource(view.state)) return;
lastValue = value;
const changes = event.changes.map(change => ({
from: view.state.doc.line(change.range.startLineNumber).from + change.range.startColumn - 1,
to: view.state.doc.line(change.range.endLineNumber).from + change.range.endColumn - 1,
insert: change.text,
}));
if (event.isFlush) historySelections?.clear();
const selection = event.isUndoing || event.isRedoing ? historySelections?.get(model!.getAlternativeVersionId()) : undefined;
view.dispatch({ changes, selection, scrollIntoView: !!selection, annotations: Transaction.addToHistory.of(false) });
onChange(value, current.id);
});
scroll = saved?.source === lastValue ? saved.scroll : view.scrollSnapshot();
// Svelte may detach the old tab before effect cleanup runs, at which point
// DOM scroll offsets read as zero. Capture while the view is still mounted.
const saveScroll = () => { if (view.dom.isConnected) scroll = view.scrollSnapshot(); };
view.scrollDOM.addEventListener("scroll", saveScroll);
releaseScroll = () => view.scrollDOM.removeEventListener("scroll", saveScroll);
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.posAtCoords(point, false), path); });
releaseSelection = registerSelection(current.id, () => view.state.selection.ranges.map(range => view.state.sliceDoc(range.from, range.to)).join("\n"));
menu = markdownMenu({
snapshot() {
const { doc, selection } = view.state;
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
undo() { clearTimeout(historyTimer); model?.pushStackElement(); void model?.undo(); },
redo() { clearTimeout(historyTimer); void model?.redo(); },
canUndo() { return model?.canUndo() ?? false; },
canRedo() { return model?.canRedo() ?? false; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
if (!focusTitle && shouldFocusOnMount()) view.focus();
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
cancelled = true;
refreshVersion++;
clearTimeout(historyTimer);
model?.pushStackElement();
contentListener?.dispose();
menu?.destroy();
releaseDrop?.();
releaseScroll?.();
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
editor?.destroy();
if (session) releaseEditorSession(session);
releaseSelection?.();
editor = undefined;
};
});
$effect(() => {
void $tableFormulasEnabled;
editor?.dispatch({ effects: refreshImages.of() });
});
$effect(() => {
const name = markdownTitle(buffer.relPath);
const view = editor;
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
});
$effect(() => {
if (!focusTitle || !editor) return;
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
if (!button) return;
button.click();
onTitleFocused?.();
});
$effect(() => {
const value = buffer.contents;
const path = buffer.relPath;
const view = editor;
if (!view || value === lastValue) return;
const version = ++refreshVersion;
void loadImages(path, value).then(() => {
if (version !== refreshVersion || editor !== view || buffer.contents !== value || !freshState) return;
lastValue = value;
if (model?.getValue() !== value) model?.setValue(value);
// Reloads start fresh history, so undo cannot revive a discarded disk version.
const anchor = Math.min(view.state.selection.main.head, value.replace(/\r\n/g, "\n").length);
view.setState(freshState(value));
view.dispatch({ selection: { anchor }, effects: title.reconfigure(noteTitle(markdownTitle(buffer.relPath), onRenameTitle ? renameTitle : undefined)) });
});
});
$effect(() => {
const line = focusLine;
const view = editor;
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects });
view.focus();
});
});
</script>
<div class="live-writer" bind:this={host} role="application" aria-label={$t("Markdown writing editor")}
ondragovercapture={(event) => {
if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.live-writer { position: absolute; inset: 0; }
.live-writer :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
.live-writer :global(.cm-editor.cm-focused) { outline: none; }
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
.live-writer :global(.cm-line) { padding-inline: 0; position: relative; }
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
.live-writer :global(.writer-divider-line) { display: flex; align-items: center; }
.live-writer :global(.writer-divider) { display: inline-flex; align-items: center; flex: 1; min-width: 0; height: 1.75em; cursor: text; }
.live-writer :global(.writer-divider::after) { content: ""; width: 100%; border-top: 1px solid var(--rs-border); }
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
/* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
.live-writer :global(.writer-preview img) { max-width: 100%; }
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
.live-writer :global(.writer-table p) { margin: 0; }
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
.live-writer :global(.table-add span) { position: absolute; font: 20px/24px var(--rs-font-ui); width: 24px; height: 24px; text-align: center; pointer-events: none; }
.live-writer :global(.table-add-column span) { left: 0; top: var(--table-add-position, 50%); transform: translateY(-50%); }
.live-writer :global(.table-add-row span) { top: 0; left: var(--table-add-position, 50%); transform: translateX(-50%); }
</style>
-9
View File
@@ -1,9 +0,0 @@
export function codeFont(element: HTMLElement) {
const style = getComputedStyle(element);
return {
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
fontWeight: style.getPropertyValue("--rs-code-font-weight").trim() || "300",
fontSize: Number.parseFloat(style.getPropertyValue("--rs-code-font-size")) || 13,
lineHeight: Number.parseFloat(style.getPropertyValue("--rs-code-line-height")) || 21,
};
}
+31
View File
@@ -0,0 +1,31 @@
import type { Extension } from "@codemirror/state";
import { StreamLanguage } from "@codemirror/language";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { extensionOf } from "../workspace/chrome";
import { languageFor } from "./languageFor";
import { noteFormats } from "./noteFormats";
/** The Markdown language of Write and Source, with the RuneStone note formats. */
export const noteMarkdown = () => markdown({ base: markdownLanguage, extensions: [noteFormats] });
// Each language loads when the first file of that language opens.
const loaders: Record<string, (extension: string) => Promise<Extension>> = {
markdown: async () => noteMarkdown(),
javascript: async extension => (await import("@codemirror/lang-javascript")).javascript({ jsx: extension === "jsx" }),
typescript: async extension => (await import("@codemirror/lang-javascript")).javascript({ typescript: true, jsx: extension === "tsx" }),
python: async () => (await import("@codemirror/lang-python")).python(),
json: async () => (await import("@codemirror/lang-json")).json(),
css: async () => (await import("@codemirror/lang-css")).css(),
scss: async () => (await import("@codemirror/lang-sass")).sass(),
html: async () => (await import("@codemirror/lang-html")).html(),
rust: async () => (await import("@codemirror/lang-rust")).rust(),
shell: async () => StreamLanguage.define((await import("@codemirror/legacy-modes/mode/shell")).shell),
yaml: async () => (await import("@codemirror/lang-yaml")).yaml(),
ini: async () => StreamLanguage.define((await import("@codemirror/legacy-modes/mode/toml")).toml),
xml: async () => (await import("@codemirror/lang-xml")).xml(),
};
/** The syntax support for a file. Plain text gets none. */
export async function languageSupport(relPath: string): Promise<Extension> {
return await loaders[languageFor(relPath)]?.(extensionOf(relPath)) ?? [];
}
+22 -18
View File
@@ -1,9 +1,12 @@
import { tr } from '../i18n/index.ts';
import type { editor } from "monaco-editor";
import { EditorSelection } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
import { selectSelectionMatches } from "@codemirror/search";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
/** Keep Monaco editing commands in the host's shared action menu. */
export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: string) => void) {
/** Keep source editing commands in the host's shared action menu. */
export function codeMenu(view: EditorView, report: (message: string) => void) {
let root: HTMLElement | undefined;
function close(focus = true) {
root?.remove(); root = undefined;
@@ -17,16 +20,14 @@ export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: s
window.addEventListener("resize", resize);
function open(x: number, y: number) {
close(false);
const model = view.getModel(), selection = view.getSelection();
if (!model || !selection) return;
const version = model.getVersionId();
const valid = () => view.getModel() === model && !model.isDisposed() && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection);
const selected = model.getValueInRange(selection);
const state = view.state, main = state.selection.main;
const valid = () => view.state.doc === state.doc && view.state.selection.eq(state.selection);
const selected = state.sliceDoc(main.from, main.to);
const word = main.empty ? state.wordAt(main.head) : main;
const replace = (text: string) => {
if (!valid()) return;
view.pushUndoStop();
view.executeEdits("code-menu", [{ range: selection, text }]);
view.pushUndoStop(); view.focus();
view.dispatch(view.state.replaceSelection(text), { userEvent: "input", scrollIntoView: true });
view.focus();
};
const clipboard = async (kind: "cut" | "copy" | "paste") => {
close();
@@ -35,19 +36,22 @@ export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: s
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
};
const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const changeAll = () => {
close();
if (!valid() || !word) return;
if (main.empty) view.dispatch({ selection: EditorSelection.single(word.from, word.to) });
selectSelectionMatches(view);
};
const items: ActionMenuItem[] = [
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !undoDepth(state), run: () => { close(); undo(view); } },
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !redoDepth(state), run: () => { close(); redo(view); } },
{ separator: true },
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+Shift+L", disabled: !word || word.empty, run: changeAll },
{ separator: true },
{ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true },
{ label: tr("Command palette"), icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
{ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); } },
];
root = actionMenu(x, y, items, close, tr("Code text actions"));
}
+13 -2
View File
@@ -27,17 +27,28 @@ export function documentLinks(source: string): DocumentLink[] {
const targetFrom = match.index + 2 + raw.length - raw.trimStart().length;
links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target });
}
links.push(...plainUrls(source, occupied));
return links.sort((a, b) => a.from - b.from);
}
function plainUrls(source: string, occupied: (from: number, to: number) => boolean = () => false) {
const links: DocumentLink[] = [];
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
const target = match[0].replace(/[.,;:!?]+$/, "").replace(/\)+$/, suffix => {
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
});
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md", target });
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md" as const, target });
}
return links.sort((a, b) => a.from - b.from);
return links;
}
export function documentLinkAt(source: string, position: number) {
return documentLinks(source).find(link => position >= link.from && position < link.to);
}
/** The plain URL at a position, for files that are not Markdown. */
export function urlAt(source: string, position: number) {
return plainUrls(source).find(link => position >= link.from && position < link.to);
}
+30
View File
@@ -0,0 +1,30 @@
import type { EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
/**
* The editor of an open document, kept while its tab stays open.
* The state holds the undo history, so Write, Source, and a tab change share it.
*/
export type SavedEditor = {
source: string;
lineBreak: string;
state: EditorState;
scroll: ReturnType<EditorView["scrollSnapshot"]>;
};
const saved = new Map<string, SavedEditor>();
let retained = new Set<string>();
export function savedEditor(id: string) {
return saved.get(id);
}
export function saveEditor(id: string, editor: SavedEditor) {
if (retained.has(id)) saved.set(id, editor);
}
/** Keep the editors of the open tabs only. */
export function retainEditorStates(ids: string[]) {
retained = new Set(ids);
for (const id of saved.keys()) if (!retained.has(id)) saved.delete(id);
}
-17
View File
@@ -23,20 +23,3 @@ export function documentMatches(source: string, query: SearchQuery) {
}
return { state, matches };
}
export function replacementText(source: string, from: number, query: SearchQuery) {
const replacement = query.literal ? query.replace : query.replace.replace(/\\([nrt\\])/g, (_, char: string) => ({ n: "\n", r: "\r", t: "\t", "\\": "\\" })[char]!);
if (!query.regexp) return replacement;
const expression = new RegExp(query.search, "gmu" + (query.caseSensitive ? "" : "i"));
expression.lastIndex = from;
const match = expression.exec(source);
return replacement.replace(/\$([$&]|\d+)/g, (token, index: string) => {
if (index === "$") return "$";
if (index === "&") return match?.[0] ?? "";
for (let length = index.length; length > 0; length--) {
const number = Number(index.slice(0, length));
if (match && number > 0 && number < match.length) return (match[number] ?? "") + index.slice(length);
}
return token;
});
}
+18
View File
@@ -13,6 +13,7 @@ import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { listLabels } from "./markdownLists";
import { activeTableFormulas } from "../formulas/index.ts";
@@ -102,6 +103,18 @@ class Checkbox extends WidgetType {
ignoreEvent() { return true; }
}
class ListLabel extends WidgetType {
constructor(readonly label: string) { super(); }
eq(other: ListLabel) { return other.label === this.label; }
toDOM() {
const span = document.createElement("span");
span.className = "writer-list-label";
span.textContent = this.label;
return span;
}
ignoreEvent() { return false; }
}
class Preview extends WidgetType {
readonly formulas = activeTableFormulas();
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
@@ -308,6 +321,11 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
return false;
}
} });
// Nested ordered markers show letters or Roman numerals. A selection over a marker shows its source.
for (const label of listLabels(state)) {
if (hidden(label.from, label.to) || state.selection.ranges.some(range => range.from < label.to && range.to > label.from)) continue;
ranges.push(Decoration.replace({ widget: new ListLabel(label.label), atomic: true }).range(label.from, label.to));
}
for (const match of source.matchAll(/\[\^([^\]\s]+)\](:)?/g)) {
const from = match.index, to = from + match[0].length;
if (hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
+259
View File
@@ -0,0 +1,259 @@
import { countColumn, EditorState, type ChangeSpec, type Line, type Text, type TransactionSpec } from "@codemirror/state";
import { ensureSyntaxTree, getIndentUnit, language, syntaxTree } from "@codemirror/language";
import type { Command } from "@codemirror/view";
type Tree = ReturnType<typeof syntaxTree>;
type Node = ReturnType<Tree["resolveInner"]>;
// A list inside a block quote keeps its quote markers at the line start.
const QUOTE = /^(?:[ \t]{0,3}>[ \t]?)*/;
const ORDERED = /^(\d{1,9})([.)])$/;
const parsed = (state: EditorState) => ensureSyntaxTree(state, state.doc.length, 200) ?? syntaxTree(state);
const quoteLength = (text: string) => QUOTE.exec(text)![0].length;
const markOf = (item: Node | null) => item?.name === "ListItem" ? item.getChild("ListMark") : null;
const isList = (node: Node | null) => node?.name === "BulletList" || node?.name === "OrderedList";
function markColumn(state: EditorState, mark: Node) {
const line = state.doc.lineAt(mark.from);
return countColumn(line.text.slice(quoteLength(line.text), mark.from - line.from), state.tabSize);
}
function contentColumn(state: EditorState, mark: Node) {
const line = state.doc.lineAt(mark.from);
const rest = line.text.slice(mark.to - line.from);
const spaces = /^ */.exec(rest)![0].length;
return markColumn(state, mark) + mark.to - mark.from + (spaces === 0 || spaces > 4 || spaces === rest.length ? 1 : spaces);
}
/** The number of leading characters that cover `columns` columns of indentation. */
function indentLength(text: string, columns: number, tabSize: number) {
let length = 0;
for (let column = 0; length < text.length && column < columns && /[ \t]/.test(text[length]); length++) {
column += text[length] === "\t" ? tabSize - column % tabSize : 1;
}
return length;
}
function itemOnLine(tree: Tree, line: Line) {
const start = line.from + /^(?:[ \t]{0,3}>[ \t]?)*[ \t]*/.exec(line.text)![0].length;
const node = tree.resolveInner(start, 1);
return node.name === "ListMark" && node.from === start ? node.parent : null;
}
/** The list item around a position. Code inside an item keeps its own indentation. */
function itemAround(tree: Tree, position: number) {
for (const side of [1, -1] as const) {
for (let node: Node | null = tree.resolveInner(position, side); node; node = node.parent) {
if (node.name === "FencedCode" || node.name === "CodeBlock") return null;
if (node.name === "ListItem") return node;
}
}
return null;
}
function itemLines(state: EditorState, item: Node) {
return { first: state.doc.lineAt(item.from).number, last: state.doc.lineAt(Math.max(item.from, item.to - 1)).number };
}
/** The outermost list items that the selection touches. A nested item moves with its parent. */
function selectedItems(state: EditorState, tree: Tree) {
const items = new Map<number, Node>();
for (const range of state.selection.ranges) {
const first = state.doc.lineAt(range.from);
let last = state.doc.lineAt(range.to);
if (!range.empty && range.to === last.from && last.number > first.number) last = state.doc.line(last.number - 1);
for (let number = first.number; number <= last.number; number++) {
const item = itemOnLine(tree, state.doc.line(number)) ?? (number === first.number ? itemAround(tree, range.from) : null);
if (item) items.set(item.from, item);
}
}
const nested = (item: Node) => {
for (let node = item.parent; node; node = node.parent) if (node.name === "ListItem" && items.has(node.from)) return true;
return false;
};
return [...items.values()].filter(item => !nested(item)).sort((a, b) => a.from - b.from);
}
/** Change a marker. Keep its last character when it stays, so a caret after the marker does not move. */
function replaceMark(state: EditorState, mark: Node, prefix: string, marker: string): ChangeSpec {
const text = state.sliceDoc(mark.from, mark.to);
const keep = marker.at(-1) === text.at(-1) ? 1 : 0;
return { from: mark.from, to: mark.to - keep, insert: prefix + marker.slice(0, marker.length - keep) };
}
/** Number each item of the ordered lists in a range from the first item of its list. */
function renumber(tree: Tree, doc: Text, from: number, to: number) {
const changes: ChangeSpec[] = [];
tree.iterate({ from, to, enter(node) {
if (node.name !== "OrderedList") return;
let next: number | undefined;
for (let item = node.node.firstChild; item; item = item.nextSibling) {
const mark = markOf(item), parts = mark && ORDERED.exec(doc.sliceString(mark.from, mark.to));
if (!mark || !parts) continue;
next ??= Number(parts[1]);
if (Number(parts[1]) !== next) changes.push({ from: mark.from, to: mark.to - 1, insert: String(next) });
next++;
}
} });
return changes;
}
function finish(state: EditorState, changes: ChangeSpec[], from: number, to: number): TransactionSpec[] {
if (!changes.length) return [];
const moved = state.changes(changes);
const doc = moved.apply(state.doc);
const parser = state.facet(language)?.parser;
const numbers = parser ? renumber(parser.parse(doc.toString()), doc, moved.mapPos(from, -1), moved.mapPos(to, 1)) : [];
return [{ changes: moved, userEvent: "input.indent", scrollIntoView: true }, { changes: numbers, sequential: true }];
}
/**
* Move the selected list items one level deeper, below the previous item.
* The moved item starts a new list as `1.`, or joins the nested list of the previous item.
* Returns null outside a list, and an empty array when no item can move.
*/
export function indentListItems(state: EditorState): TransactionSpec[] | null {
const tree = parsed(state), items = selectedItems(state, tree);
if (!items.length) return null;
const changes: ChangeSpec[] = [];
let from = state.doc.length, to = 0;
for (const item of items) {
const previous = item.prevSibling, mark = markOf(item), previousMark = markOf(previous), list = item.parent;
if (!previous || !mark || !previousMark || !list) continue;
const column = markColumn(state, mark);
const nested = isList(previous.lastChild) ? previous.lastChild : null;
const nestedMark = markOf(nested?.firstChild ?? null);
let pad = nestedMark ? markColumn(state, nestedMark) - column : 0;
if (pad <= 0) pad = Math.max(getIndentUnit(state), contentColumn(state, previousMark) - markColumn(state, previousMark));
const style = nested?.name === list.name && nestedMark ? state.sliceDoc(nestedMark.from, nestedMark.to) : state.sliceDoc(mark.from, mark.to);
changes.push(replaceMark(state, mark, " ".repeat(pad), list.name === "OrderedList" ? `1${style.at(-1)}` : style));
const lines = itemLines(state, item);
for (let number = lines.first + 1; number <= lines.last; number++) {
const line = state.doc.line(number), start = quoteLength(line.text);
if (line.text.slice(start).trim()) changes.push({ from: line.from + start, insert: " ".repeat(pad) });
}
from = Math.min(from, list.from); to = Math.max(to, list.to);
}
return finish(state, changes, from, to);
}
/**
* Move the selected nested list items one level up, after their parent item.
* The moved item takes the marker style of the outer list. Later items of its old list become its children.
* Returns null outside a list, and an empty array when no item can move.
*/
export function outdentListItems(state: EditorState): TransactionSpec[] | null {
const tree = parsed(state), items = selectedItems(state, tree);
if (!items.length) return null;
const selected = new Set(items.map(item => item.from));
const changes: ChangeSpec[] = [];
let from = state.doc.length, to = 0;
for (const item of items) {
const mark = markOf(item), list = item.parent, parent = list?.parent ?? null, parentMark = markOf(parent), outer = parent?.parent;
if (!mark || !list || !parent || !parentMark || !outer) continue;
const remove = markColumn(state, mark) - markColumn(state, parentMark);
if (remove <= 0) continue;
const lines = itemLines(state, item);
for (let number = lines.first; number <= lines.last; number++) {
const line = state.doc.line(number), start = line.from + quoteLength(line.text);
const length = indentLength(state.sliceDoc(start, number === lines.first ? mark.from : line.to), remove, state.tabSize);
if (length) changes.push({ from: start, to: start + length });
}
const text = state.sliceDoc(mark.from, mark.to), parentText = state.sliceDoc(parentMark.from, parentMark.to);
const ordered = outer.name === "OrderedList";
if (outer.name !== list.name || (ordered ? text.at(-1) !== parentText.at(-1) : text !== parentText)) {
changes.push(replaceMark(state, mark, "", ordered ? `${Number(parentText.slice(0, -1)) + 1}${parentText.at(-1)}` : parentText));
}
// The next item of the old list becomes the first child of the moved item.
const next = item.nextSibling, nextMark = markOf(next);
if (list.name === "OrderedList" && next && nextMark && !selected.has(next.from)) {
changes.push({ from: nextMark.from, to: nextMark.to - 1, insert: "1" });
}
from = Math.min(from, outer.from); to = Math.max(to, outer.to);
}
return finish(state, changes, from, to);
}
function listCommand(move: (state: EditorState) => TransactionSpec[] | null): Command {
return view => {
const specs = move(view.state);
if (!specs) return false;
if (specs.length) view.dispatch(...specs);
return true;
};
}
/** Tab in a list item makes it a nested item. */
export const indentListItem = listCommand(indentListItems);
/** Shift+Tab in a nested list item moves it one level up. */
export const outdentListItem = listCommand(outdentListItems);
function alphabetic(number: number) {
let label = "";
for (let rest = number; rest > 0; rest = Math.floor((rest - 1) / 26)) label = String.fromCharCode(97 + (rest - 1) % 26) + label;
return label;
}
function roman(number: number) {
const numerals: [number, string][] = [[1000, "m"], [900, "cm"], [500, "d"], [400, "cd"], [100, "c"], [90, "xc"], [50, "l"], [40, "xl"], [10, "x"], [9, "ix"], [5, "v"], [4, "iv"], [1, "i"]];
let label = "", rest = number;
for (const [value, numeral] of numerals) for (; rest >= value; rest -= value) label += numeral;
return label;
}
/**
* The label of an ordered list item. Level 1 uses decimal numbers, level 2 letters, and level 3 Roman numerals.
* Deeper levels repeat the sequence. Numbers that a style cannot show stay decimal, as in CSS.
*/
export function orderedLabel(level: number, number: number) {
const style = (level - 1) % 3;
if (style === 1 && number > 0) return alphabetic(number);
if (style === 2 && number > 0 && number < 4000) return roman(number);
return String(number);
}
function orderedLevel(node: Node | null) {
let level = 0;
for (; node; node = node.parent) if (node.name === "OrderedList") level++;
return level;
}
export type ListLabel = { from: number; to: number; label: string };
/**
* Labels for the markers of nested ordered lists. The Markdown source keeps its numbers.
* An item gets the start number of its list plus its position, as a Markdown renderer counts.
*/
export function listLabels(state: EditorState): ListLabel[] {
const labels: ListLabel[] = [];
syntaxTree(state).iterate({ enter(node) {
if (node.name === "OrderedList") {
const level = orderedLevel(node.node);
let start: number | undefined, index = 0;
for (let item = node.node.firstChild; item; item = item.nextSibling) {
const mark = markOf(item), parts = mark && ORDERED.exec(state.sliceDoc(mark.from, mark.to));
if (!mark || !parts) continue;
start ??= Number(parts[1]);
if (level > 1) labels.push({ from: mark.from, to: mark.to, label: orderedLabel(level, start + index) + parts[2] });
index++;
}
}
// An empty item cannot start a list inside a paragraph, so the parser reads it as text.
// Label it as the nested item that it becomes when the user types its text.
const item = node.node.parent;
if (node.name !== "Paragraph" || item?.name !== "ListItem") return;
const itemMark = markOf(item)!, level = orderedLevel(item) + 1;
if (level < 2) return;
const first = state.doc.lineAt(node.from).number, last = state.doc.lineAt(node.to).number;
for (let number = first + 1; number <= last; number++) {
const line = state.doc.line(number);
const match = /^(\s*)(\d{1,9})([.)])\s*$/.exec(line.text.slice(quoteLength(line.text)));
if (!match) continue;
const from = line.from + quoteLength(line.text) + match[1].length;
if (countColumn(line.text.slice(quoteLength(line.text), from - line.from), state.tabSize) < contentColumn(state, itemMark)) continue;
labels.push({ from, to: from + match[2].length + 1, label: orderedLabel(level, Number(match[2])) + match[3] });
}
} });
return labels;
}
-1
View File
@@ -1 +0,0 @@
declare module "monaco-editor-css";
-26
View File
@@ -1,26 +0,0 @@
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 },
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 },
folding: true,
glyphMargin: true,
lineDecorationsWidth: 10,
padding: { top: 8, bottom: 24 },
renderLineHighlight: "line" as const,
};
}
-60
View File
@@ -1,60 +0,0 @@
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" });
},
};
export let currentTheme = 'runestone-default-dark';
function updateTheme() {
const style = getComputedStyle(document.documentElement);
const color = (name: string) => style.getPropertyValue(`--rs-${name}`).trim();
const syntaxColor = (role: string) => {
const value = document.documentElement.style.getPropertyValue(`--rs-syntax-${role}`).trim();
const match = /^#([0-9a-f]{3,8})$/i.exec(value);
if (!match) return undefined;
const hex = match[1];
return hex.length === 3 || hex.length === 4 ? `#${hex.slice(0, 3).split('').map(part => part + part).join('')}`
: hex.length === 6 || hex.length === 8 ? `#${hex.slice(0, 6)}` : undefined;
};
const syntaxRules = [
['keyword', 'keyword'], ['variable.parameter', 'parameter'], ['variable', 'local'],
['variable.predefined', 'global'], ['variable.property', 'instance'], ['variable.static', 'static'],
['identifier', 'local'], ['string', 'string'], ['number', 'number'], ['comment', 'comment'],
['type', 'type'], ['type.identifier', 'type'], ['entity.name.type', 'type'],
['function', 'function'], ['predefined', 'function'], ['delimiter', 'global'],
].flatMap(([token, role]) => {
const foreground = syntaxColor(role);
return foreground ? [{ token, foreground: foreground.slice(1) }] : [];
});
// Monaco permits only letters, digits, and hyphens in registered theme names.
const palette = (document.documentElement.dataset.palette || 'default').replace(/[^a-z0-9-]/gi, '-');
currentTheme = `runestone-${palette}-${document.documentElement.dataset.theme || 'dark'}`;
monaco.editor.defineTheme(currentTheme, {
base: document.documentElement.dataset.theme === 'light' ? 'vs' : 'vs-dark',
inherit: true,
rules: syntaxRules,
colors: {
...Object.fromEntries(['keyword', 'number', 'type', 'string', 'function', 'parameter'].flatMap((role, index) => {
const foreground = syntaxColor(role);
return foreground ? [[`editorBracketHighlight.foreground${index + 1}`, foreground]] : [];
})),
'editor.background': '#00000000', 'editor.foreground': color('text'),
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
'editor.inactiveSelectionBackground': color('selection'), 'editor.selectionForeground': color('selection-text'),
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': '#00000000',
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
'minimap.background': '#00000000', 'editorIndentGuide.background1': color('border'),
'editorIndentGuide.activeBackground1': color('text-dim'),
},
});
monaco.editor.setTheme(currentTheme);
}
updateTheme();
window.addEventListener('runestone-theme-changed', updateTheme);
if (import.meta.hot) import.meta.hot.dispose(() => window.removeEventListener('runestone-theme-changed', updateTheme));
export { monaco };
-71
View File
@@ -1,71 +0,0 @@
import type * as Monaco from "monaco-editor";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText, type FindTarget } from "./findTarget";
export function monacoSearch(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, close: () => void) {
const decorations = view.createDecorationsCollection();
let active = false;
let query = new SearchQuery({ search: "" });
function snapshot() {
const model = view.getModel()!;
const { state, matches } = documentMatches(model.getValue(), query);
function range(match: { from: number; to: number }) {
const from = state.doc.lineAt(match.from), to = state.doc.lineAt(match.to);
return new monaco.Range(from.number, match.from - from.from + 1, to.number, match.to - to.from + 1);
}
return { model, state, matches, range };
}
function refresh() {
active = true;
const { matches, range } = snapshot();
decorations.set(matches.map(match => ({ range: range(match), options: { inlineClassName: "rs-source-search-match" } })));
}
function next(backward = false) {
const { matches, range } = snapshot();
if (!matches.length) return;
const selection = view.getSelection();
const ranges = matches.map(range);
const current = ranges.findIndex(match => selection?.equalsRange(match));
let index: number;
if (current >= 0) index = (current + (backward ? -1 : 1) + ranges.length) % ranges.length;
else if (backward) {
index = ranges.findLastIndex(match => !selection || monaco.Position.compare(match.getEndPosition(), selection.getStartPosition()) <= 0);
if (index < 0) index = ranges.length - 1;
} else {
index = ranges.findIndex(match => !selection || monaco.Position.compare(match.getStartPosition(), selection.getEndPosition()) >= 0);
if (index < 0) index = 0;
}
view.setSelection(ranges[index]);
view.revealRangeInCenterIfOutsideViewport(ranges[index]);
}
const target: FindTarget = {
get query() { return query; }, readOnly: false,
setQuery(value) { query = value; refresh(); },
next,
selectAll() {
const { matches, range } = snapshot();
if (!matches.length) return;
view.setSelections(matches.map(match => { const value = range(match); return new monaco.Selection(value.startLineNumber, value.startColumn, value.endLineNumber, value.endColumn); }));
view.focus();
},
replace(all = false) {
const { state, matches, range } = snapshot();
const selection = view.getSelection();
const selected = all ? matches : matches.filter(match => selection?.equalsRange(range(match))).slice(0, 1);
if (!selected.length) { if (!all) next(); return; }
const edits = selected.map(match => ({ range: range(match), text: replacementText(state.doc.toString(), match.from, query) }));
const last = selected[selected.length - 1];
const inserted = edits[edits.length - 1].text;
const end = state.update({ changes: selected.map((match, index) => ({ ...match, insert: edits[index].text })) }).state;
const offset = all ? 0 : last.from + inserted.length;
const line = end.doc.lineAt(Math.min(offset, end.doc.length));
view.pushUndoStop();
view.executeEdits("document-find", edits, [new monaco.Selection(line.number, offset - line.from + 1, line.number, offset - line.from + 1)]);
view.pushUndoStop();
if (!all) next();
},
close() { active = false; decorations.clear(); close(); view.focus(); },
};
const changed = view.onDidChangeModelContent(() => { if (active) refresh(); });
return { target, refresh, dispose() { changed.dispose(); decorations.clear(); } };
}
-44
View File
@@ -1,44 +0,0 @@
import type * as Monaco from "monaco-editor";
import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
users: number;
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writerSelections: Map<number, import("@codemirror/state").EditorSelection>;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
let retained = new Set<string>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
users: 0,
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
writerSelections: new Map(),
};
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
session.users++;
return session;
}
export function retainEditorSessions(ids: string[]) {
retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id) && session.users === 0) { session.model.dispose(); sessions.delete(id); }
}
}
export function releaseEditorSession(session: Session) {
session.users = Math.max(0, session.users - 1);
if (session.users) return;
for (const [id, entry] of sessions) {
if (entry === session && !retained.has(id)) { session.model.dispose(); sessions.delete(id); break; }
}
}
+60
View File
@@ -0,0 +1,60 @@
import { countColumn, EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers, type Command } from "@codemirror/view";
import { bracketMatching, foldGutter, foldKeymap, getIndentUnit, HighlightStyle, indentOnInput, syntaxHighlighting } from "@codemirror/language";
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
import { highlightSelectionMatches } from "@codemirror/search";
import { indentMore } from "@codemirror/commands";
import { tags } from "@lezer/highlight";
import { chromeLayout } from "../workspace/chrome";
import type { Chrome } from "../workspace/types";
const syntax = (role: string, fallback: string) => `var(--rs-syntax-${role}, ${fallback})`;
/** Syntax colors come from the theme tokens, so a theme change needs no editor update. */
const sourceHighlight = HighlightStyle.define([
{ tag: [tags.keyword, tags.modifier, tags.operatorKeyword, tags.controlKeyword, tags.definitionKeyword, tags.moduleKeyword, tags.tagName], color: syntax("keyword", "var(--rs-accent)") },
{ tag: tags.heading, color: syntax("keyword", "var(--rs-accent)"), fontWeight: "600" },
{ tag: [tags.string, tags.special(tags.string), tags.regexp, tags.attributeValue, tags.url, tags.monospace], color: syntax("string", "var(--rs-ok)") },
{ tag: [tags.number, tags.bool, tags.null, tags.atom, tags.unit], color: syntax("number", "var(--rs-special)") },
{ tag: tags.comment, color: syntax("comment", "var(--rs-text-dim)") },
{ tag: [tags.typeName, tags.className, tags.namespace], color: syntax("type", "var(--rs-accent-2)") },
{ tag: [tags.function(tags.variableName), tags.function(tags.propertyName), tags.macroName], color: syntax("function", "var(--rs-accent-2)") },
{ tag: [tags.propertyName, tags.attributeName], color: syntax("instance", "var(--rs-accent-2)") },
{ tag: [tags.standard(tags.variableName), tags.self, tags.special(tags.variableName)], color: syntax("global", "var(--rs-text-dim)") },
{ tag: tags.variableName, color: syntax("local", "var(--rs-text)") },
{ tag: [tags.punctuation, tags.operator, tags.meta, tags.processingInstruction], color: syntax("global", "var(--rs-text-dim)") },
{ tag: tags.emphasis, fontStyle: "italic" },
{ tag: tags.strong, fontWeight: "600" },
{ tag: tags.strikethrough, textDecoration: "line-through" },
{ tag: tags.link, color: "var(--rs-accent)", textDecoration: "underline" },
{ tag: tags.invalid, color: "var(--rs-error)" },
]);
/** Tab inserts spaces to the next indent stop at each caret. With a selection, it indents the lines. */
export const insertIndent: Command = view => {
const { state } = view;
if (state.selection.ranges.some(range => !range.empty)) return indentMore(view);
const unit = getIndentUnit(state);
view.dispatch(state.changeByRange(range => {
const line = state.doc.lineAt(range.head);
const insert = " ".repeat(unit - countColumn(line.text.slice(0, range.head - line.from), state.tabSize) % unit);
return { changes: { from: range.head, insert }, range: EditorSelection.cursor(range.head + insert.length) };
}), { scrollIntoView: true, userEvent: "input.indent" });
return true;
};
/** Code editing support for Source: syntax colors, brackets, several carets, and matches of the selection. */
export const sourceEditing: Extension = [
syntaxHighlighting(sourceHighlight), bracketMatching(), closeBrackets(), indentOnInput(), highlightSelectionMatches(),
EditorState.allowMultipleSelections.of(true),
keymap.of(closeBracketsKeymap),
];
export function sourceChrome(chrome: Chrome): Extension {
const layout = chromeLayout(chrome);
return [
layout.wrap ? EditorView.lineWrapping : [],
layout.gutters ? [lineNumbers(), foldGutter(), highlightActiveLineGutter(), keymap.of(foldKeymap)] : [],
layout.activeLine ? highlightActiveLine() : [],
];
}
+1 -2
View File
@@ -7,8 +7,7 @@ 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 } from "@codemirror/commands";
import { undo, redo } from "./writerHistory";
import { isolateHistory, redo, undo } from "@codemirror/commands";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
import { tableCellMarkdown } from "./tableCellMarkdown";
import { tableSelectionControls } from "./tableSelectionControls";
+1 -2
View File
@@ -1,7 +1,6 @@
import { tr } from '../i18n/index.ts';
import type { EditorView } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { undo, redo } from "./writerHistory";
import { isolateHistory, redo, undo } from "@codemirror/commands";
import type { Editor } from "@tiptap/core";
import { useSpellingMenu } from "./spellingMenu";
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
-20
View File
@@ -1,20 +0,0 @@
import { Facet } from "@codemirror/state";
import type { Command, KeyBinding } from "@codemirror/view";
import { undo as localUndo, redo as localRedo } from "@codemirror/commands";
export const writerHistory = Facet.define<{ undo: () => boolean; redo: () => boolean }>();
export const undo: Command = view => {
const shared = view.state.facet(writerHistory)[0];
return shared ? shared.undo() : localUndo(view);
};
export const redo: Command = view => {
const shared = view.state.facet(writerHistory)[0];
return shared ? shared.redo() : localRedo(view);
};
export const historyKeymap: readonly KeyBinding[] = [
{ key: "Mod-z", run: undo, preventDefault: true },
{ key: "Mod-y", run: redo, preventDefault: true },
{ key: "Mod-Shift-z", run: redo, preventDefault: true },
];
-6
View File
@@ -2519,12 +2519,6 @@ export const messageRows: [string, string, string, string][] = [
"すべての出現箇所を変更",
"更改所有匹配项"
],
[
"Command palette",
"Palette de commandes",
"コマンドパレット",
"命令面板"
],
[
"Copy Markdown",
"Copier le Markdown",
+9 -16
View File
@@ -5,8 +5,7 @@
import FindPanel from "$lib/editor/FindPanel.svelte";
import { readingSearch } from "$lib/editor/readingSearch";
import type { FindTarget } from "$lib/editor/findTarget";
import EditorHost from "$lib/editor/EditorHost.svelte";
import LiveWriter from "$lib/editor/LiveWriter.svelte";
import DocumentEditor from "$lib/editor/DocumentEditor.svelte";
import { tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import ImageViewer from "./ImageViewer.svelte";
@@ -70,8 +69,7 @@
let modeControls = $state<HTMLDivElement>();
let titleFocusId = $state<string | null>(null);
let element: HTMLDivElement | undefined = $state();
let writerEditor: LiveWriter | undefined = $state();
let sourceEditor: EditorHost | undefined = $state();
let documentEditor: DocumentEditor | undefined = $state();
let readingFind = $state.raw<FindTarget>();
let readingFindPanel = $state<FindPanel>();
$effect(() => { void buffer?.id; void reading; void previewMode; readingFind = undefined; });
@@ -86,23 +84,21 @@
if (inReading) {
const root = element?.querySelector<HTMLElement>(".reading");
if (!root) return;
sourceEditor?.closeFind();
writerEditor?.closeFind();
documentEditor?.closeFind();
readingFind ??= readingSearch(root, () => { readingFind = undefined; });
await tick();
if (advance) readingFind.next(event.shiftKey);
else readingFindPanel?.focus();
} else {
readingFind = undefined;
if (writerEditor) { if (advance) writerEditor.nextMatch(event.shiftKey); else writerEditor.openFind(key === "h"); }
else if (sourceEditor) { if (advance) sourceEditor.nextMatch(event.shiftKey); else await sourceEditor.openFind(key === "h"); }
if (advance) documentEditor?.nextMatch(event.shiftKey);
else documentEditor?.openFind(key === "h");
}
}
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
export function focusEditor() {
if (reading) element?.querySelector<HTMLElement>(".reading")?.focus({ preventScroll: true });
else if (writerEditor) writerEditor.focus();
else sourceEditor?.focus();
else documentEditor?.focus();
}
export function focusTitle(id: string) {
titleFocusId = id;
@@ -216,12 +212,9 @@
{:else}
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
{#key buffer.id}
{#if !isIde && canPreview && !reading}
<LiveWriter bind:this={writerEditor} {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{:else}
<EditorHost bind:this={sourceEditor} {buffer} {chrome} {onChange} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line} />
{/if}
<DocumentEditor bind:this={documentEditor} {buffer} mode={!isIde && canPreview && !reading ? "write" : "source"} {chrome}
{onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{/key}
</div>
{#if reading && canPreview}
+3 -3
View File
@@ -11,7 +11,7 @@
import type { MenuLink } from "$lib/editor/linkMenu";
import { loadMarks, saveMarks } from "$lib/workspace/marks";
import { moveMarks } from "$lib/workspace/treeMoveHistory";
import { retainEditorSessions } from "$lib/editor/sessions";
import { retainEditorStates } from "$lib/editor/editorStates";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
@@ -229,8 +229,8 @@
});
return next;
}
$effect(() => retainEditorSessions(tabs.map(tab => tab.id)));
onDestroy(() => retainEditorSessions([]));
$effect(() => retainEditorStates(tabs.map(tab => tab.id)));
onDestroy(() => retainEditorStates([]));
const documentViews = $derived.by(() => {
const bounds = paneBounds(documentPanes.layout);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
+3 -3
View File
@@ -54,6 +54,6 @@
.rs-find-options label { display: inline-flex; align-items: center; gap: 5px; min-height: 24px; cursor: pointer; }
.rs-find-options input { margin: 0; accent-color: var(--rs-accent); }
.rs-find-error { color: var(--rs-error); }
.live-writer .cm-panels.cm-panels-top { border-bottom: 1px solid var(--rs-border); }
.live-writer .cm-searchMatch { background: var(--rs-item-selection-bg); }
.live-writer .cm-searchMatch-selected { background: var(--rs-selection); outline: 1px solid var(--rs-accent); }
:is(.live-writer, .source-editor) .cm-panels.cm-panels-top { border-bottom: 1px solid var(--rs-border); }
:is(.live-writer, .source-editor) .cm-searchMatch { background: var(--rs-item-selection-bg); }
:is(.live-writer, .source-editor) .cm-searchMatch-selected { background: var(--rs-selection); outline: 1px solid var(--rs-accent); }
+6
View File
@@ -25,3 +25,9 @@ export function detectChrome(relPath: string): Chrome {
}
return "Ide";
}
/** Writing wraps lines and hides the code gutters. IDE shows line numbers, folding, and the current line. */
export function chromeLayout(chrome: Chrome) {
const ide = chrome === "Ide";
return { wrap: !ide, gutters: ide, activeLine: ide };
}
@@ -102,13 +102,13 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
assert.deepEqual(await background.boundingBox(), beforeScroll);
await page.screenshot({ path: `${output}/${theme}-reader.png` });
await page.getByRole('button', { name: 'Split', exact: true }).click();
await page.locator('.monaco-editor').waitFor();
assert.equal(await style(page.locator('.monaco-editor-background').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.locator('.source-editor .cm-content').waitFor();
assert.equal(await style(page.locator('.source-editor .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` });
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'IDE', exact: true }).click();
await page.locator('.monaco-editor').waitFor();
await page.locator('.source-editor .cm-content').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` });
await page.setViewportSize({ width: 680, height: 720 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
@@ -37,11 +37,10 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await openFile(main, 'Theme.md');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await openFile(ide, 'Theme.py');
await ide.locator('.monaco-editor textarea').waitFor();
const editorIds = () => ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
await ide.locator('.source-editor .cm-content').waitFor();
// Mark each mounted editor once. A new editor has no mark, so it gets a new identifier.
const editorIds = () => ide.evaluate(() => [...document.querySelectorAll('.source-editor .cm-editor')]
.map(node => node.dataset.smokeId ||= String(window.__editorSerial = (window.__editorSerial || 0) + 1)));
const initialEditors = await editorIds();
const openSettings = async () => {
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
@@ -108,7 +107,7 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await settings.waitForFunction(() => window.exportedTheme);
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), template);
await ide.waitForFunction(expected => {
const spans = [...document.querySelectorAll('.view-line span')].filter(node => !node.children.length);
const spans = [...document.querySelectorAll('.source-editor .cm-line span')].filter(node => !node.children.length);
return Object.entries(expected).every(([text, color]) => {
const node = spans.find(node => node.textContent.replaceAll('\u00a0', ' ').includes(text));
const probe = document.createElement('i');
@@ -116,7 +115,7 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
const target = getComputedStyle(probe).color; probe.remove();
return node && getComputedStyle(node).color === target;
});
}, { return: colors['syntax-keyword'], RuneStone: colors['syntax-string'], 42: colors['syntax-number'], print: colors['syntax-keyword'], '# Character colors': colors['syntax-comment'] });
}, { return: colors['syntax-keyword'], RuneStone: colors['syntax-string'], 42: colors['syntax-number'], print: colors['syntax-function'], '# Character colors': colors['syntax-comment'] });
assert.deepEqual(await editorIds(), initialEditors, 'Theme changes preserve the editor');
if (theme === 'harvest-moon') {
const normalized = await settings.evaluate(async () => {
@@ -147,17 +146,17 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
assert.equal(await main.evaluate(() => window.getSelection().toString()), 'A calm surface with readable text.');
await main.screenshot({ path: path.join(output, `${theme}-${mode}-writer-selection.png`) });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
editor.setSelection(new monaco.Selection(1, 1, 3, 21)); editor.focus();
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
view.dispatch({ selection: { anchor: 0, head: view.state.doc.line(3).from + 20 } }); view.focus();
});
await ide.locator('.selected-text').first().waitFor();
assert.equal(await ide.locator('.selected-text').first().evaluate(node => getComputedStyle(node).backgroundColor),
await ide.locator('.source-editor .cm-selectionBackground').first().waitFor();
assert.equal(await ide.locator('.source-editor .cm-selectionBackground').first().evaluate(node => getComputedStyle(node).backgroundColor),
warmFill, 'IDE selection uses the same warm fill');
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide-selection.png`) });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setPosition({ lineNumber: 1, column: 1 });
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')).dispatch({ selection: { anchor: 0 } });
});
}
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide.png`) });
+1 -1
View File
@@ -75,7 +75,7 @@ await runSmoke("appearance/density", async ({ page }) => {
await documentView().press("Home");
}
await editorLayout().press("Home");
await page.locator(".monaco-editor").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
await page.locator(".line-history").waitFor();
await page.evaluate(() => window.removeGit());
await page.locator(".line-history").waitFor({ state: "hidden" });
+16 -19
View File
@@ -1,4 +1,4 @@
// Built-in palettes: modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.
// Built-in palettes: modes, light-only Sakura, migration, persistence, typography, cross-window sync, source editor updates, and narrow settings.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -28,24 +28,21 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".monaco-editor textarea").waitFor();
await main.waitForFunction(async file => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
}, `theme-${index}.py`);
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
await main.locator(".source-editor .cm-content").waitFor();
await main.waitForFunction(file => document.querySelector(".editor .breadcrumb")?.textContent.endsWith(file)
&& document.querySelector(".source-editor .cm-content")?.dataset.language === "python", `theme-${index}.py`);
await main.locator(".source-editor .cm-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
async function editorIds() {
return main.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
// Mark each mounted editor once. A new editor has no mark, so it gets a new identifier.
return main.evaluate(() => [...document.querySelectorAll(".source-editor .cm-editor")]
.map(node => node.dataset.smokeId ||= String(window.__editorSerial = (window.__editorSerial || 0) + 1)));
}
// Wait until "RuneStone", "print", and "42" have three distinct syntax colors.
// Wait until "RuneStone", "def", and "42" have three distinct syntax colors.
async function waitForSyntax() {
await main.waitForFunction(() => {
const spans = [...document.querySelectorAll(".view-line span")];
const colors = ["RuneStone", "print", "42"].map(text => {
const spans = [...document.querySelectorAll(".source-editor .cm-line span")];
const colors = ["RuneStone", "def", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return span ? getComputedStyle(span).color : null;
});
@@ -79,7 +76,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
const surfaces = [...document.querySelectorAll(".source-editor .cm-editor")];
const workarea = document.querySelector(".editor > .body");
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === "rgba(0, 0, 0, 0)")
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
@@ -94,16 +91,16 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
const before = await editorIds();
await choose(settings, theme, mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
assert.deepEqual(await editorIds(), before, "Existing source editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
assert.notDeepEqual(await editorIds(), before, "A new file creates a new source editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme, mode });
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}.png`) });
await main.screenshot({ path: path.join(output, `appearance-editor-${theme}-${mode}.png`) });
if (theme === "sakura") {
const keywordColor = await main.locator(".view-line span").evaluateAll(spans => {
const keywordColor = await main.locator(".source-editor .cm-line span").evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === "def");
return keyword ? getComputedStyle(keyword).color : null;
});
@@ -120,7 +117,7 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim()), "#d97757");
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new source editors`);
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
+3 -3
View File
@@ -97,13 +97,13 @@ await runSmoke("editor/emptyMenu", async ({ page }) => {
}
await page.getByRole('group',{name:'Editor layout'}).hover();
await page.getByRole('button',{name:'IDE',exact:true}).click();
await page.locator('.monaco-editor').waitFor();
await page.locator('.monaco-editor textarea').focus();
await page.locator('.source-editor .cm-content').waitFor();
await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Shift+F10');
await menu().waitFor();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
await page.locator('.monaco-editor textarea').focus();
await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await page.keyboard.press('Shift+F10');
+2 -2
View File
@@ -108,10 +108,10 @@ await runSmoke("editor/footnotes", async ({ page }) => {
const pane = button.closest('.reading').parentElement.getBoundingClientRect();
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), false);
assert.equal(await page.locator(".md-page").getByText("Child content.", { exact: true }).isVisible(), false);
await page.screenshot({ path: `${output}/reader-${theme}-narrow.png` });
await page.keyboard.press("Space");
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), true);
assert.equal(await page.locator(".md-page").getByText("Child content.", { exact: true }).isVisible(), true);
await page.getByRole("button", { name: "Collapse Last section", exact: true }).click();
await page.locator(".md-footnote-ref a").first().click();
assert.equal(await page.locator(".md-footnotes").isVisible(), true);
+2 -2
View File
@@ -146,8 +146,8 @@ await runSmoke("editor/imageNavigation", async ({ page }) => {
// The layout switcher names its buttons by mode (src/lib/layout/EditorPane.svelte:200-208, src/lib/ui/ModeSwitcher.svelte:96).
await page.getByRole("group", { name: "Editor layout", exact: true }).hover();
await page.getByRole("button", { name: "IDE", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
await dragFromTree(".monaco-editor .view-lines");
await page.locator(".source-editor .cm-content").waitFor();
await dragFromTree(".source-editor .cm-content");
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);
+10 -10
View File
@@ -149,24 +149,24 @@ await runSmoke("editor/images", async ({ page }) => {
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Read", exact: true }).focus();
await page.keyboard.press("Home");
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").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 { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
});
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);
const sourceBefore = await source();
await drop(2, ".source-editor .cm-content");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 5);
await page.keyboard.press("Control+z");
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), sourceBefore);
assert.equal(await source(), 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());
const beforeFailure = await source();
await page.evaluate(() => { window.__TEST__.failWrite = true; });
await drop(1, ".monaco-editor .view-lines");
await drop(1, ".source-editor .cm-content");
await page.getByText("Image write failed", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), beforeFailure);
assert.equal(await source(), beforeFailure);
await page.evaluate(() => { window.__TEST__.failWrite = false; });
// File drops over a rendered widget are handled by the editor's capture listener.
+8 -9
View File
@@ -77,20 +77,19 @@ await runSmoke("editor/interactions", async ({ page }) => {
await page.locator('.writer-link[data-href="https://example.com"]').click({ modifiers: ["Control"] });
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
const linkPoint = await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
const position = view.getModel().getPositionAt(view.getValue().indexOf("[Local]") + 3);
view.revealPositionInCenter(position);
view.setPosition(position); view.focus();
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
const position = view.state.doc.toString().indexOf("[Local]") + 3;
view.dispatch({ selection: { anchor: position }, scrollIntoView: true }); view.focus();
return position;
});
await page.waitForTimeout(300);
const point = await page.evaluate(async position => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected), rect = view.getDomNode().getBoundingClientRect(), coords = view.getScrolledVisiblePosition(position);
return { x: rect.left + coords.left + 2, y: rect.top + coords.top + coords.height / 2 };
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const coords = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content")).coordsAtPos(position);
return { x: coords.left + 2, y: (coords.top + coords.bottom) / 2 };
}, linkPoint);
await page.keyboard.down("Control"); await page.mouse.click(point.x, point.y); await page.keyboard.up("Control");
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.includes("other.md"));
+118
View File
@@ -0,0 +1,118 @@
// List nesting: Tab and Shift+Tab in Write, nested labels in Write and Read, one undo history in Write and Source, and the 4-space indent in Source.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/listNesting", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/readme.md": "# Requirements\n\n1. Topic\n2. \n3. A\n",
"src/hello.py": "print('hello')\n",
},
}),
spelling_menu_install: () => null,
}),
});
const output = await outputDir("editor/listNesting");
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
async function open(name, editor) {
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.getByRole("textbox", { name: editor, exact: true }).waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
const doc = () => page.evaluate(() => window.__CM__.state.doc.toString());
const caretAt = (text, offset = text.length) => page.evaluate(([text, offset]) => {
window.__CM__.dispatch({ selection: { anchor: window.__CM__.state.doc.toString().indexOf(text) + offset } });
window.__CM__.focus();
}, [text, offset]);
const labels = () => page.locator(".live-writer .writer-list-label").allTextContents();
await open("readme.md", "Writing editor");
await caretAt("2. ");
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. \n2. A\n", "Tab nests the empty item and renumbers the next item");
assert.deepEqual(await labels(), ["a."], "The nested item shows a letter before it has text");
await page.keyboard.type("Sub item");
await page.keyboard.press("Enter");
await page.keyboard.type("Second");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n");
assert.deepEqual(await labels(), ["a.", "b."]);
for (const width of [1440, 600]) {
if (width === 600) {
await page.getByRole("button", { name: "Files", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
}
await page.setViewportSize({ width, height: 800 });
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => (await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode }), mode);
await page.locator(".live-writer .cm-content").screenshot({ path: `${output}/writer-${mode}-${width}.png` });
}
}
await page.setViewportSize({ width: 1440, height: 900 });
await page.locator(".live-writer .cm-content").focus();
await page.keyboard.press("Shift+Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n2. Second\n3. A\n", "Shift+Tab moves the item up and renumbers the outer list");
assert.deepEqual(await labels(), ["a."]);
await page.keyboard.press("Control+z");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "One undo step restores the nesting and the numbers");
await caretAt("1. Topic");
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "The first item stays in place");
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
await page.locator(".md-page ol ol").waitFor();
assert.equal(await page.locator(".md-page ol ol").evaluate(list => getComputedStyle(list).listStyleType), "lower-alpha");
assert.equal(await page.locator(".md-page > .reading > ol, .md-page ol").first().evaluate(list => getComputedStyle(list).listStyleType), "decimal");
await page.locator(".md-page").screenshot({ path: `${output}/reader.png` });
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
// Write and Source share the undo history of the document.
await caretAt("2. A");
await page.keyboard.type(" more");
await page.keyboard.press("Control+e");
await page.locator('.source-editor[data-chrome="Ide"] .cm-gutters').waitFor();
assert.equal(await page.locator(".source-editor .cm-content").getAttribute("data-language"), "markdown");
await page.locator(".source-editor .cm-content").focus();
await page.keyboard.press("Control+z");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "Source undoes the last edit from Write");
await page.keyboard.press("Control+Shift+KeyZ");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A more\n");
await caretAt("2. A more");
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n 3. A more\n", "Tab nests list items in Source too");
await page.keyboard.press("Control+e");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
assert.deepEqual(await labels(), ["a.", "b.", "c."]);
// Source indents code to the next 4-column stop.
await open("hello.py", "Editor");
await caretAt("print", 0);
await page.keyboard.press("Tab");
assert.equal(await doc(), " print('hello')\n");
await caretAt("print", 2);
await page.keyboard.press("Tab");
assert.equal(await doc(), " pr int('hello')\n", "Tab inside a line fills to the next stop");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+z");
assert.equal(await doc(), "print('hello')\n");
await page.locator(".source-editor").screenshot({ path: `${output}/source-ide.png` });
// The history of a document stays while its tab stays open.
await open("readme.md", "Writing editor");
await page.locator(".live-writer .cm-content").focus();
await page.keyboard.press("Control+z");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A more\n", "Undo after a tab change reverts the Tab from Source");
console.log("PASS: Tab and Shift+Tab nesting, renumbering, Write labels, Read letters, shared undo in Write and Source and across tabs, Source list Tab, and 4-space code indent.");
});
+7 -7
View File
@@ -32,21 +32,21 @@ await runSmoke("editor/markdownMenu", async ({ page }) => {
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
}
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);
await page.evaluate(async () => { window.__EditorView = (await import("/node_modules/@codemirror/view/dist/index.js")).EditorView; });
await page.waitForFunction(expected => [...document.querySelectorAll(".cm-content")].some(node => window.__EditorView.findFromDOM(node)?.state.doc.toString() === expected), text);
}
await page.goto(smokeUrl);
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();
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
view.dispatch({ selection: { anchor: 0, head: 5 } }); view.focus();
}, source);
const menu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
await page.keyboard.press("Shift+F10");
+3 -1
View File
@@ -34,7 +34,9 @@ await runSmoke("editor/markdownPaste", async ({ page }) => {
clipboardData.setData("text/plain", source);
view.contentDOM.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData }));
view.dispatch({ selection: { anchor: 0 } });
const { forceParsing, syntaxTree } = await import("/node_modules/.vite/deps/@codemirror_language.js");
// Import the module URL that the app loaded, so the language state is the same instance.
const languageUrl = performance.getEntriesByType("resource").map(entry => entry.name).find(name => new URL(name).pathname === "/node_modules/.vite/deps/@codemirror_language.js");
const { forceParsing, syntaxTree } = await import(languageUrl);
forceParsing(view, view.state.doc.length, 5000);
const nodes = [];
syntaxTree(view.state).iterate({ enter(node) { if (node.name === "StrongEmphasis") nodes.push(node.from); } });
+7 -7
View File
@@ -65,7 +65,7 @@ await runSmoke("editor/pasteRepeat", async ({ page }) => {
assert.equal(await page.evaluate(() => window.__TEST__.files.get('notes/pasted.md').replace(/\r\n?/g, '\n')), formatted);
if (iteration === 5) {
await page.keyboard.press('Control+e');
await page.locator('.monaco-editor textarea').waitFor();
await page.locator('.source-editor .cm-content').waitFor();
await page.keyboard.press('Control+e');
await expectWriter(formatted);
}
@@ -86,13 +86,13 @@ await runSmoke("editor/pasteRepeat", async ({ page }) => {
await expectWriter(formatted);
assert.equal(await page.evaluate(() => window.__WRITER__.state.doc.lines), formatted.split('\n').length);
await page.keyboard.press('Control+s');
const synchronized = await page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const model = monaco.editor.getModels().find(model => model.uri.path.endsWith('/pasted.md'));
const source = window.__WRITER__.state.doc.sliceString(0, undefined, model.getEOL());
return source === model.getValue() && source === window.__TEST__.files.get('notes/pasted.md');
// The saved file keeps one line break. The Writer text with that line break is the saved source.
const synchronized = await page.evaluate(() => {
const saved = window.__TEST__.files.get('notes/pasted.md');
const lineBreak = saved.includes('\r\n') ? '\r\n' : '\n';
return window.__WRITER__.state.doc.sliceString(0, undefined, lineBreak) === saved;
});
assert.equal(synchronized, true, 'Writer, model, and saved source agree');
assert.equal(synchronized, true, 'Writer and saved source agree');
}
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, IDE reopen, and LF/CRLF/CR clipboard replacement');
});
+18 -33
View File
@@ -1,4 +1,4 @@
// Editor menu surfaces: Writer, spelling, IDE, and code menus share the file menu styles; code tint and the command palette match in both themes.
// Editor menu surfaces: Writer, spelling, IDE, and code menus share the file menu styles; and the code tint match in both themes.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -93,59 +93,44 @@ await runSmoke("editor/surfaces", async ({ page }) => {
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'IDE', exact: true }).click();
await page.locator('.monaco-editor').waitFor();
await page.locator('.monaco-host').click({ button: 'right', position: { x: 500, y: 400 } });
await page.locator('.source-editor .cm-content').waitFor();
await page.locator('.source-editor').click({ button: 'right', position: { x: 500, y: 400 } });
assert.deepEqual(await styles(writer), reference, 'Markdown IDE retains the same menu');
await dismiss();
await page.locator('[data-tree-rel="sample.txt"]').click();
await page.locator('.monaco-host').click({ button: 'right', position: { x: 500, y: 400 } });
await page.locator('.source-editor').click({ button: 'right', position: { x: 500, y: 400 } });
const code = menu('Code text actions');
assert.deepEqual(await styles(code), reference, 'Code IDE uses the host menu');
assert.equal(await page.locator('.monaco-menu').count(), 0);
// The host menu is the only menu. The editor adds no menu of its own.
assert.equal(await page.getByRole('menu').count(), 1);
assert.equal(await code.getByRole('menuitem', { name: 'Command palette F1', exact: true }).count(), 0);
await page.screenshot({ path: `${output}/ide-menu-${theme}.png` });
await page.getByRole('menuitem', { name: 'Command palette F1', exact: true }).click();
const palette = page.locator('.quick-input-widget');
await palette.waitFor({ state: 'visible' });
const paletteMetrics = () => palette.evaluate(node => {
const row = node.querySelector('.monaco-list-row.focused');
const field = node.querySelector('.monaco-inputbox');
const a = getComputedStyle(row), b = getComputedStyle(field);
const probe = document.createElement('div');
probe.style.background = 'var(--rs-item-selection-bg)'; probe.style.color = 'var(--rs-item-selection-border)';
node.append(probe); const expected = getComputedStyle(probe);
const result = { fill: a.backgroundColor, expectedFill: expected.backgroundColor, outline: a.outlineColor, expectedOutline: expected.color, radius: a.borderRadius, inputRadius: b.borderRadius, inputOutline: b.outlineColor, inputOutlineWidth: b.outlineWidth };
probe.remove(); return result;
});
let p = await paletteMetrics();
assert.equal(p.fill, p.expectedFill);
assert.equal(p.outline, p.expectedOutline);
assert.equal(p.radius, '5px'); assert.equal(p.inputRadius, '5px');
assert.equal(p.inputOutline, p.expectedOutline); assert.equal(p.inputOutlineWidth, '2px');
await page.keyboard.press('ArrowDown');
p = await paletteMetrics(); assert.equal(p.fill, p.expectedFill);
await page.screenshot({ path: `${output}/palette-${theme}.png` });
await page.keyboard.press('Escape');
await dismiss();
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await page.locator('.monaco-host').click({ button: 'right', position: { x: 100, y: 300 } });
await page.locator('.source-editor').click({ button: 'right', position: { x: 100, y: 300 } });
await code.waitFor();
const bounds = await code.boundingBox();
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 560);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem', { name: 'Command palette F1', exact: true }).evaluate(n => n === document.activeElement), true);
assert.equal(await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).evaluate(n => n === document.activeElement), true);
await page.screenshot({ path: `${output}/ide-narrow-${theme}.png` });
await page.keyboard.press('Enter');
await palette.waitFor({ state: 'visible' });
await page.screenshot({ path: `${output}/palette-narrow-${theme}.png` });
await page.keyboard.press('Escape');
await code.waitFor({ state: 'detached' });
// The keyboard choice runs the action: the selection covers the whole file.
assert.equal(await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
return view.state.selection.main.from === 0 && view.state.selection.main.to === view.state.doc.length;
}), true);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.locator('[data-tree-rel="a.md"]').click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'Writer', exact: true }).click();
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/IDE parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'palette selection/focus', 'narrow keyboard menu/palette'], nativeDesktop: 'not tested' });
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/IDE parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'narrow keyboard menu'], nativeDesktop: 'not tested' });
}
console.log(JSON.stringify(report, null, 2));
}, { timeout: 15000 });
+9 -12
View File
@@ -68,22 +68,21 @@ await runSmoke("editor/undoHistory", async ({ page }) => {
assert.equal(await page.evaluate(() => window.__WRITER__.state.selection.main.head), (original + ' first edit').length);
console.log('PASS: Writer undo and redo survive window focus refresh and restore the caret');
await page.keyboard.press('Control+e');
await page.locator('.monaco-editor textarea').waitFor();
await page.locator('.source-editor .cm-content').waitFor();
await page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
editor.setPosition({ lineNumber: editor.getModel().getLineCount(), column: editor.getModel().getLineMaxColumn(editor.getModel().getLineCount()) });
editor.focus();
window.__IDE__ = editor;
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
view.dispatch({ selection: { anchor: view.state.doc.length } });
view.focus();
window.__IDE__ = view;
});
await page.keyboard.type(' second edit');
assert.equal(await page.evaluate(() => window.__IDE__.getDomNode()?.isConnected), true, 'Typing keeps the same IDE editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.getValue()), original + ' first edit second edit');
assert.equal(await page.evaluate(() => window.__IDE__.dom.isConnected), true, 'Typing keeps the same IDE editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.state.doc.toString()), original + ' first edit second edit');
await page.keyboard.press('Control+e');
await expectWriter(original + ' first edit second edit');
await page.locator('.cm-content').click();
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit second');
// One burst of typing is one undo step, in Source as in Write.
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
@@ -91,8 +90,6 @@ await runSmoke("editor/undoHistory", async ({ page }) => {
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second edit');
console.log('PASS: Writer undo includes edits from IDE mode');
const tableSource = '# Table\n\n| A | B |\n| --- | --- |\n| One | Two |\n\nTail.\n';
+15 -14
View File
@@ -36,17 +36,17 @@ await runSmoke("find/documentFind", async ({ page }) => {
}
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.find-widget.visible').count(), 0, 'No Monaco floating find widget');
assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel');
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
const pane = await page.locator('.editor.pane-active').boundingBox();
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
}
async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.monaco-editor'));
await page.waitForFunction(() => !!document.querySelector('.source-editor .cm-content'));
return page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
window.__MONACO__ = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected && view.getDomNode().getBoundingClientRect().width > 0);
window.__MONACO__.focus();
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__SOURCE__ = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
window.__SOURCE__.focus();
});
}
await page.goto(smokeUrl);
@@ -84,21 +84,22 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.keyboard.press('Escape');
await mode('Editor layout', 'IDE');
await sourceEditor();
await page.evaluate(() => { window.__MONACO__.getModel().setValue('Alpha alpha alphabet\r\nAlpha second\r\nAlpha third'); window.__MONACO__.setPosition({ lineNumber: 1, column: 1 }); });
await page.evaluate(() => { const view = window.__SOURCE__; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: 'Alpha alpha alphabet\r\nAlpha second\r\nAlpha third' }, selection: { anchor: 0 } }); });
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.keyboard.press('Enter');
const first = await page.evaluate(() => window.__MONACO__.getSelection().toString());
const selection = () => page.evaluate(() => JSON.stringify(window.__SOURCE__.state.selection.main));
const first = await selection();
await page.keyboard.press('Enter');
assert.notEqual(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
assert.notEqual(await selection(), first);
await page.keyboard.press('Shift+Enter');
assert.equal(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
assert.equal(await selection(), first);
await page.getByRole('checkbox', { name: 'Match case' }).check();
await page.getByRole('checkbox', { name: 'Whole word' }).check();
await replace.fill('Gamma');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__MONACO__.getValue().replace(/\r\n/g, '\n')), 'Gamma alpha alphabet\nGamma second\nGamma third');
assert.equal(await page.evaluate(() => window.__SOURCE__.state.doc.toString()), 'Gamma alpha alphabet\nGamma second\nGamma third');
await page.getByRole('checkbox', { name: 'Regex' }).check();
await find.fill('[');
assert.equal(await find.getAttribute('aria-invalid'), 'true');
@@ -107,15 +108,15 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.getByRole('checkbox', { name: 'Whole word' }).uncheck();
await replace.fill('$1!');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.match(await page.evaluate(() => window.__MONACO__.getValue()), /^Gamma! alpha/);
assert.match(await page.evaluate(() => window.__SOURCE__.state.doc.toString()), /^Gamma! alpha/);
await page.getByRole('checkbox', { name: 'Regex' }).uncheck();
await find.fill('Gamma');
await page.getByRole('button', { name: 'Select all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__MONACO__.getSelections().length), 3);
assert.equal(await page.evaluate(() => window.__SOURCE__.state.selection.ranges.length), 3);
await page.screenshot({ path: `${output}/source-${theme}.png` });
await find.focus(); await page.keyboard.press('Escape');
assert.equal(await find.count(), 0);
assert.equal(await page.evaluate(() => window.__MONACO__.hasTextFocus()), true);
assert.equal(await page.evaluate(() => window.__SOURCE__.hasFocus), true);
await page.keyboard.press('Control+h');
assert.equal(await replace.evaluate(node => node === document.activeElement), true);
await find.fill('Gamma');
@@ -128,7 +129,7 @@ await runSmoke("find/documentFind", async ({ page }) => {
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
await find.focus(); await page.keyboard.press('Escape');
await page.evaluate(sample => window.__MONACO__.getModel().setValue(sample), sample);
await page.evaluate(sample => { const view = window.__SOURCE__; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: sample } }); }, sample);
await mode('Document view', 'Read');
await page.locator('.reading').focus();
await page.keyboard.press('Control+f');
+1 -1
View File
@@ -40,7 +40,7 @@ await runSmoke("layout/outline", async ({ browser }) => {
await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
+12 -6
View File
@@ -67,11 +67,11 @@ await runSmoke("layout/splits", async ({ page }) => {
assert.equal(await page.evaluate(()=>window.__TEST__.writes.includes('a.md')),false,'Save uses the focused right pane');
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.__TEST__.writes.includes('a.md'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'IDE',exact:true}).click(); await pane('notes/b.md').locator('.monaco-editor').waitFor();
await pane('notes/b.md').getByRole('button',{name:'IDE',exact:true}).click(); await pane('notes/b.md').locator('.source-editor .cm-content').waitFor();
assert.equal(await pane('a.md').locator('.cm-content').count(),1,'Changing the right mode keeps the left editor');
await openRight('a.md','Right note');
assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getEditors().some(editor=>editor.getModel()?.uri.path.endsWith('/b.md') && editor.hasTextFocus());}); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>!!document.activeElement?.matches('[data-document-path="notes/b.md"] .source-editor .cm-content')); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('IDE edit.'));
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
await pane('notes/b.md').getByRole('button',{name:'Writer',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
@@ -85,7 +85,8 @@ await runSmoke("layout/splits", async ({ page }) => {
for(const path of ['a.md','notes/b.md']) await pane(path).locator('.cm-content').evaluate(async node=> {
const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const v=EditorView.findFromDOM(node); const source=v.state.doc.toString(); const from=source.indexOf(source.includes('Alpha') ? 'Origin' : 'Second'); v.dispatch({selection:{anchor:from,head:from+6}});
});
const selections=await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const resource=performance.getEntriesByType('resource').find(entry=>new URL(entry.name).pathname==='/src/lib/editor/selection.ts'); const {selectedEditorText}=await import(resource.name); return monaco.editor.getModels().map(model=>selectedEditorText(model.uri.path.split('/')[1])).filter(Boolean).sort(); });
// Read the selection of each pane editor. Each editor keeps its own selection.
const selections=(await Promise.all(['a.md','notes/b.md'].map(path=>pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const {state}=EditorView.findFromDOM(node); return state.sliceDoc(state.selection.main.from,state.selection.main.to); })))).filter(Boolean).sort();
assert.deepEqual(selections,['Origin','Second'],'Each pane retains its own selection');
await openRight('a.md','Right note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='notes/b.md');
@@ -99,7 +100,7 @@ await runSmoke("layout/splits", async ({ page }) => {
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),1); assert.equal(await pane('a.md').count(),1);
assert.match(await text('a.md'),/Left unsaved/);
assert.equal(await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); return monaco.editor.getModels().length; }),2,'Closing a split preserves both tab models');
assert.equal(await page.getByRole('tab').count(),2,'Closing a split preserves both tabs');
await page.getByRole('tab',{name:/b.md/}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/Right still unsaved/,'The closed split retains its unsaved buffer');
await page.getByRole('tab',{name:/a.md/}).click(); await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
@@ -139,6 +140,11 @@ await runSmoke("layout/splits", async ({ page }) => {
await page.keyboard.press('Control+w'); await pane('notes/b.md').waitFor({state:'detached'});
await focus('a.md'); await append('a.md','\nOther tab closed.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('a.md').includes('Other tab closed.'));
assert.equal(await page.evaluate(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getModels().some(model=>model.uri.path.endsWith('/b.md'));}),false,'Closing the tab releases only its model');
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and model release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs and models','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
// A closed tab releases its editor state. The reopened note has no undo history.
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
const reopened=await text('notes/b.md');
assert.match(reopened,/Close guard\./);
await focus('notes/b.md'); await page.keyboard.press('Control+z');
assert.equal(await text('notes/b.md'),reopened,'Closing the tab releases only its editor state');
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and editor state release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
}, { timeout: 15000 });
+16 -14
View File
@@ -59,20 +59,20 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await mode("Editor layout", "IDE");
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").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();
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
return EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString();
});
}
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);
await page.evaluate(async () => { window.__EditorView = (await import("/node_modules/@codemirror/view/dist/index.js")).EditorView; });
await page.waitForFunction(expected => window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString() === expected, text);
}
async function focusEditor() {
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
await page.locator(".source-editor .cm-content").click({position:{x:120,y:12}});
}
await page.goto(smokeUrl);
@@ -88,7 +88,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.getByRole("tab", { name: /welcome\.md/ }).click();
await focusEditor();
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() !== expected), original + "Added in source.");
await page.waitForFunction(expected => window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString() !== expected, original + "Added in source.");
await page.keyboard.press("Control+y");
await waitForText(original + "Added in source.");
await page.keyboard.press("Control+s");
@@ -96,7 +96,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await mode("Document view", "Split");
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".monaco-host").isVisible());
assert.ok(await page.locator(".source-editor").isVisible());
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Agent update\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
@@ -132,7 +132,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
// A new note starts in its filename field, which keeps its own keys (src/lib/editor/LiveWriter.svelte:381, src/lib/editor/noteTitle.ts:80).
// A new note starts in its filename field, which keeps its own keys (src/lib/editor/DocumentEditor.svelte:386-392, src/lib/editor/noteTitle.ts:80).
await page.getByRole("textbox", { name: "Note filename", exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "core-rebuild.png") });
await page.keyboard.press("Escape");
@@ -156,7 +156,7 @@ await runSmoke("layout/workbench", async ({ page }) => {
await read.click();
assert.equal(await read.getAttribute("aria-pressed"), "true");
await page.locator(".reading h1:not(.document-title)").waitFor();
assert.equal(await page.locator(".monaco-host").isVisible(), false);
assert.equal(await page.locator(".source-editor").isVisible(), false);
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
assert.equal(await page.locator(".reading ol > li").count(), 3);
assert.equal(await page.locator(".reading ol ul > li").count(), 2);
@@ -178,8 +178,8 @@ await runSmoke("layout/workbench", async ({ page }) => {
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await mode("Document view", "Split");
await page.waitForFunction(() => {
const host = document.querySelector(".monaco-host");
const rendered = host?.querySelector(".monaco-editor");
const host = document.querySelector(".source-editor");
const rendered = host?.querySelector(".cm-editor");
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
});
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
@@ -191,7 +191,8 @@ await runSmoke("layout/workbench", async ({ page }) => {
await page.screenshot({ path: path.join(output, "reader-split-wide.png") });
await mode("Document view", "Edit");
assert.equal(await contents(), showcase);
// The editor stores one line break character. The saved file keeps its own line breaks.
assert.equal(await contents(), showcase.replace(/\r\n/g, "\n"));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await documentView.hover();
await read.focus();
@@ -235,7 +236,8 @@ await runSmoke("layout/workbench", async ({ page }) => {
await waitForText(writingSource);
await mode("Editor layout", "Writer");
await writer.waitFor();
await paragraph.click();
// Write keeps the caret of the IDE undo, so the paragraph can show its source.
await page.locator(".live-writer .cm-line").filter({ hasText: /A (\*\*)?formatted(\*\*)? paragraph\./ }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
+10 -10
View File
@@ -30,7 +30,7 @@ await runSmoke("links/fileDragLinks", async ({ page }) => {
await page.mouse.up();
}
const writerSource = () => page.evaluate(() => window.dragWriter.state.doc.toString());
const ideSource = () => page.evaluate(() => window.dragMonaco.getValue());
const ideSource = () => page.evaluate(() => window.dragSource.state.doc.toString());
await page.goto(smokeUrl);
await row("notes").click();
@@ -60,21 +60,21 @@ await runSmoke("links/fileDragLinks", async ({ page }) => {
console.log("PASS: Writer drags insert escaped document links and image embeds, and undo restores the source");
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
window.dragMonaco = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.dragSource = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
});
const originalIde = await ideSource();
await drag("files/report [Q1] (#1).pdf", ".monaco-editor .view-lines");
await page.waitForFunction(() => window.dragMonaco.getValue().includes(".pdf)"));
await drag("files/report [Q1] (#1).pdf", ".source-editor .cm-content");
await page.waitForFunction(() => window.dragSource.state.doc.toString().includes(".pdf)"));
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
await page.evaluate(() => window.dragMonaco.focus());
assert.equal(await page.evaluate(() => window.dragMonaco.hasTextFocus()), true);
await page.evaluate(() => window.dragSource.focus());
assert.equal(await page.evaluate(() => window.dragSource.hasFocus), true);
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.dragMonaco.getValue() === expected, originalIde, { timeout: 3000 });
await page.waitForFunction(expected => window.dragSource.state.doc.toString() === expected, originalIde, { timeout: 3000 });
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
await drag("images/diagram (#1).svg", ".monaco-editor .view-lines");
await drag("images/diagram (#1).svg", ".source-editor .cm-content");
assert.ok((await ideSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
console.log("PASS: IDE drags insert escaped document links and image embeds, undo restores the source, and no file moves");
+3 -3
View File
@@ -108,10 +108,10 @@ await runSmoke("links/linkMenus", async ({ page }) => {
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button',{name:'Edit',exact:true}).click();
await page.getByRole('group', { name:'Editor layout',exact:true }).hover(); await page.getByRole('button',{name:'IDE',exact:true}).click();
await page.locator('.monaco-editor').waitFor();
await page.evaluate(async () => { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const editor=monaco.editor.getEditors()[0]; const model=editor.getModel(); const pos=model.getPositionAt(model.getValue().indexOf('Web label')+2); editor.setPosition(pos); editor.focus(); });
await page.locator('.source-editor .cm-content').waitFor();
await page.evaluate(async () => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')); view.dispatch({selection:{anchor:view.state.doc.toString().indexOf('Web label')+2}}); view.focus(); });
await page.keyboard.press('Shift+F10'); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const editor=monaco.editor.getEditors()[0]; return editor.getModel().getValueInRange(editor.getSelection()); }), 'https://example.com/path');
assert.equal(await page.evaluate(async () => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const {state}=EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')); return state.sliceDoc(state.selection.main.from,state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/ide-edit-url-${theme}.png` });
await page.getByRole('group', { name:'Editor layout',exact:true }).hover(); await page.getByRole('button',{name:'Writer',exact:true}).click();
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
+2 -2
View File
@@ -112,13 +112,13 @@ await runSmoke("links/sectionLinks", async ({ page }) => {
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await choose('Document view', 'edit');
await choose('Editor layout', 'Ide');
await page.locator('.monaco-editor').waitFor();
await page.locator('.source-editor .cm-content').waitFor();
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'edit');
await page.waitForFunction(() => {
const node = document.querySelector('.monaco-editor .view-lines');
const node = document.querySelector('.source-editor .cm-content');
return node?.textContent.includes('Linux');
});
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
@@ -66,8 +66,8 @@ await runSmoke('settings/displayLanguage', async ({ browser }) => {
}), `${language}: Delete selected table cell keyboard action`);
await settings.screenshot({ path: path.join(output, `${language}-general.png`) });
await main.locator('[data-tree-rel="theme-0.py"]').click();
await main.locator('.monaco-editor textarea').waitFor();
await main.locator('.view-lines').first().click({ button: 'right' });
await main.locator('.source-editor .cm-content').waitFor();
await main.locator('.source-editor .cm-content').click({ button: 'right' });
await main.locator('.rs-menu').waitFor();
const copyLabels = { fr: 'Copier', ja: 'コピー', 'zh-CN': '复制', en: 'Copy' };
await main.locator('.rs-menu .action-label').filter({ hasText: new RegExp('^' + copyLabels[language] + '$') }).waitFor();
+6 -5
View File
@@ -43,8 +43,9 @@ await runSmoke("settings/general", async ({ browser }) => {
}
async function edit(value) {
await page.evaluate(async text => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setValue(text);
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } });
}, value);
}
const writes = () => page.evaluate(() => window.__TEST__.state.writes.length);
@@ -77,7 +78,7 @@ await runSmoke("settings/general", async ({ browser }) => {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000));
await showSettings();
await changeSeconds(3);
@@ -99,11 +100,11 @@ await runSmoke("settings/general", async ({ browser }) => {
assert.equal(await writes(), before + 1);
await page.keyboard.press("Control+s");
await page.waitForFunction(count => window.__TEST__.state.writes.length === count, before + 2);
await page.locator(".monaco-editor textarea").focus();
await page.locator(".source-editor .cm-content").focus();
await showSettings(true);
await settings.waitFor();
await closeSettings();
await page.locator(".monaco-editor textarea").focus();
await page.locator(".source-editor .cm-content").focus();
await page.keyboard.press("F1");
await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor();
await page.keyboard.press("Escape");
+1 -1
View File
@@ -21,7 +21,7 @@ await runSmoke("tables/drag", async ({ page }) => {
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
}
const table = page.locator('.live-writer table');
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
+1 -1
View File
@@ -22,7 +22,7 @@ await runSmoke("tables/formulas", async ({ page }) => {
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
await page.keyboard.press('Control+e');
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
}
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
+1 -1
View File
@@ -63,7 +63,7 @@ await runSmoke("tabs/menus", async ({ page }) => {
await page.locator(".cm-editor").waitFor();
await show("d.md");
await item("Source mode").click();
await page.locator(".monaco-editor").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
await show("d.md");
await item("Writing mode").click();
await page.locator(".cm-editor").waitFor();
+6 -13
View File
@@ -17,18 +17,11 @@ await runSmoke("tabs/scroll", async ({ page }) => {
}
async function roundTrip(selector, label) {
const scroller = page.locator(selector);
const position = async (top) => label === 'IDE'
? page.evaluate(async top => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
if (top !== undefined) editor.setScrollTop(top, 1);
return editor.getScrollTop();
}, top)
: scroller.evaluate((el, top) => {
if (top !== undefined) el.scrollTop = top;
return el.scrollTop;
}, top);
// The Writing layout restores a line-anchored CodeMirror scrollSnapshot (src/lib/editor/LiveWriter.svelte:330-333).
const position = async (top) => scroller.evaluate((el, top) => {
if (top !== undefined) el.scrollTop = top;
return el.scrollTop;
}, top);
// The Writing layout restores a line-anchored CodeMirror scrollSnapshot (src/lib/editor/DocumentEditor.svelte:304-305).
// Re-estimated heights of the lines above can move scrollTop, so compare the top visible line and its offset.
const visibleTop = () => label === 'Writing'
? scroller.evaluate(async el => {
@@ -86,5 +79,5 @@ await runSmoke("tabs/scroll", async ({ page }) => {
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
await mode('Editor layout', 'IDE');
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
await roundTrip('.monaco-scrollable-element', 'IDE');
await roundTrip('.source-editor .cm-scroller', 'IDE');
});
+6 -9
View File
@@ -44,9 +44,9 @@ await runSmoke("tree/newFiles", async ({ page }) => {
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
return view && { language: view.contentDOM.dataset.language, value: view.state.doc.toString(), fontSize: parseFloat(getComputedStyle(view.contentDOM).fontSize) };
});
}
@@ -67,17 +67,14 @@ await runSmoke("tree/newFiles", async ({ page }) => {
await row("notes/hello_world.py").waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/hello_world.py.md")), false);
await row("hello.txt").dblclick();
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
await page.waitForFunction(() => !!document.querySelector(".source-editor .cm-line"));
await row("hello.txt").click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
assert.equal(await row("hello.txt").locator("input.rename").inputValue(), "hello.txt");
await row("hello.txt").locator("input.rename").fill("hello.py");
await page.keyboard.press("Enter");
await row("hello.py").waitFor();
await page.waitForFunction(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.getLanguageId() === "python");
});
await page.waitForFunction(() => document.querySelector(".source-editor .cm-content")?.getAttribute("data-language") === "python");
const code = await modelDetails();
assert.equal(code.value, "print('hello')\n");
assert.equal(code.fontSize, 13);
@@ -102,7 +99,7 @@ await runSmoke("tree/newFiles", async ({ page }) => {
return !event.defaultPrevented;
});
// Writer combines spelling suggestions with the Markdown actions (docs/design-decisions.md UI-027;
// src/lib/editor/LiveWriter.svelte:255-262 prevents the native menu and passes the spelling offset).
// the contextmenu handler of src/lib/editor/DocumentEditor.svelte prevents the native menu and passes the spelling offset).
assert.equal(nativeAllowed, false, "Plain text opens the shared Markdown menu instead of the native one");
const textMenu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
await textMenu.getByRole("menuitem", { name: "Misspelled", exact: true }).waitFor();
@@ -47,10 +47,11 @@ await runSmoke("workspace/openAndCreate", async ({ page }) => {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
await page.locator(".monaco-editor textarea").waitFor();
await page.locator(".source-editor .cm-content").waitFor();
await page.evaluate(async () => {
window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco;
window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected).setValue("My pending edit");
window.__EditorView = (await import("/node_modules/@codemirror/view/dist/index.js")).EditorView;
const view = window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "My pending edit" } });
});
const trigger = page.getByRole("button", { name: "Open folder", exact: true });
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
@@ -97,7 +98,7 @@ await runSmoke("workspace/openAndCreate", async ({ page }) => {
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes", "D:\\Other", "D:\\Projects\\Fresh notes"]);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|message").length), 0);
assert.equal(await page.evaluate(() => window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected)?.getValue()), "My pending edit");
assert.equal(await page.evaluate(() => window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString()), "My pending edit");
assert(await page.getByRole("tab", { name: /note\.txt/ }).isVisible());
await trigger.click();
await page.keyboard.press("End");
+1 -7
View File
@@ -1,7 +1,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText } from "../../../src/lib/editor/findTarget.ts";
import { documentMatches } from "../../../src/lib/editor/findTarget.ts";
test("document search uses Writer word matching and normalized CRLF positions", () => {
const query = new SearchQuery({ search: "Alpha", wholeWord: true, caseSensitive: true });
@@ -11,12 +11,6 @@ test("document search uses Writer word matching and normalized CRLF positions",
assert.equal(state.doc.lineAt(matches[1].from).from, 15);
});
test("replacement keeps regex context, capture groups, dollars, and line breaks", () => {
const query = new SearchQuery({ search: "(?<=G)(amma)", regexp: true, replace: "$1-$12-$&-$$\\n" });
assert.equal(replacementText("Gamma", 1, query), "amma-amma2-amma-$\n");
assert.equal(replacementText("Alpha", 0, new SearchQuery({ search: "Alpha", replace: "$1\\t" })), "$1\t");
});
test("empty and invalid queries do not produce matches", () => {
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "" })).matches, []);
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "[", regexp: true })).matches, []);
+90
View File
@@ -0,0 +1,90 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { indentUnit } from "@codemirror/language";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { noteFormats } from "../../../src/lib/editor/noteFormats.ts";
import { indentListItems, listLabels, orderedLabel, outdentListItems } from "../../../src/lib/editor/markdownLists.ts";
const extensions = [markdown({ base: markdownLanguage, extensions: [noteFormats] }), indentUnit.of(" ")];
/** A document with `|` at the caret, or two `|` around a selection. */
function editor(marked: string) {
const anchor = marked.indexOf("|"), head = marked.indexOf("|", anchor + 1);
const doc = marked.replaceAll("|", "");
return EditorState.create({ doc, selection: { anchor, head: head < 0 ? anchor : head - 1 }, extensions });
}
function run(move: typeof indentListItems, marked: string) {
const state = editor(marked), specs = move(state);
if (!specs) return null;
const next = state.update(...specs).state;
const { from, to } = next.selection.main;
const doc = next.doc.toString();
return from === to ? doc.slice(0, from) + "|" + doc.slice(from) : doc.slice(0, from) + "|" + doc.slice(from, to) + "|" + doc.slice(to);
}
test("tab makes a nested list and renumbers the items after it", () => {
assert.equal(run(indentListItems, "1. Topic\n2. B|\n3. A"), "1. Topic\n 1. B|\n2. A");
});
test("tab on an empty item keeps the caret after its marker", () => {
assert.equal(run(indentListItems, "1. Topic\n2.|\n3. A"), "1. Topic\n 1.|\n2. A");
assert.equal(run(indentListItems, "1. Topic\n2. |\n3. A"), "1. Topic\n 1. |\n2. A");
});
test("tab adds the item to the nested list of the previous item", () => {
assert.equal(run(indentListItems, "1. A\n 1. x\n2. B|\n3. C"), "1. A\n 1. x\n 2. B|\n2. C");
});
test("tab moves the children of an item with it", () => {
assert.equal(run(indentListItems, "1. A\n2. B|\n 1. b\n3. C"), "1. A\n 1. B|\n 1. b\n2. C");
});
test("tab nests each selected item under the first unselected item", () => {
assert.equal(run(indentListItems, "1. A\n|2. B\n3. C|\n4. D"), "1. A\n| 1. B\n 2. C|\n2. D");
});
test("tab nests bullet items and keeps their marker", () => {
assert.equal(run(indentListItems, "- a\n- b|"), "- a\n - b|");
assert.equal(run(indentListItems, "- [ ] a\n- [x] b|"), "- [ ] a\n - [x] b|");
});
test("tab keeps the first item in place and ignores text outside lists", () => {
assert.deepEqual(indentListItems(editor("1. A|\n2. B")), []);
assert.equal(indentListItems(editor("Plain| text")), null);
assert.equal(indentListItems(editor("1. A\n\n ```\n co|de\n ```")), null);
});
test("shift+tab moves a nested item up and makes the later items its children", () => {
assert.equal(run(outdentListItems, "1. A\n 1. x\n 2. y|\n 3. z\n2. B"), "1. A\n 1. x\n2. y|\n 1. z\n3. B");
});
test("shift+tab gives the item the marker style of the outer list", () => {
assert.equal(run(outdentListItems, "1. A\n - x|\n2. B"), "1. A\n2. x|\n3. B");
assert.equal(run(outdentListItems, "- A\n 1. x|\n- B"), "- A\n- x|\n- B");
});
test("shift+tab keeps a top-level item in place", () => {
assert.deepEqual(outdentListItems(editor("1. A|\n2. B")), []);
assert.equal(outdentListItems(editor("Plain| text")), null);
});
test("ordered labels use numbers, letters, and Roman numerals by level", () => {
assert.equal(orderedLabel(1, 3), "3");
assert.equal(orderedLabel(2, 1), "a");
assert.equal(orderedLabel(2, 27), "aa");
assert.equal(orderedLabel(3, 4), "iv");
assert.equal(orderedLabel(4, 2), "2");
assert.equal(orderedLabel(2, 0), "0");
});
test("nested ordered markers get labels and the first level keeps its source", () => {
const state = editor("1. A\n 1. x\n 1. y\n 1. z\n2. B|");
assert.deepEqual(listLabels(state).map(label => [state.sliceDoc(label.from, label.to), label.label]), [["1.", "a."], ["1.", "b."], ["1.", "i."]]);
});
test("an empty nested marker gets its label before the item has text", () => {
const state = editor("1. Topic\n 1.\n2. A|");
assert.deepEqual(listLabels(state).map(label => label.label), ["a."]);
});
+5 -10
View File
@@ -1,7 +1,6 @@
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";
import { chromeLayout, detectChrome, extensionOf, treeFileParts } from "../../../src/lib/workspace/chrome.ts";
test("markdown files open in writing chrome", () => {
assert.equal(detectChrome("notes/inbox.md"), "Writing");
@@ -14,16 +13,12 @@ test("scripts open in ide chrome", () => {
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("writing chrome wraps and hides the code gutters", () => {
assert.deepEqual(chromeLayout("Writing"), { wrap: true, gutters: false, activeLine: 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("ide chrome shows the code gutters and does not wrap", () => {
assert.deepEqual(chromeLayout("Ide"), { wrap: false, gutters: true, activeLine: true });
});
test("extensionOf reads the last suffix", () => {
-9
View File
@@ -9,7 +9,6 @@ const packageVersion = JSON.parse(readFileSync(new URL("./package.json", import.
const appVersion = process.env.RUNESTONE_VERSION || packageVersion;
const host = process.env.TAURI_DEV_HOST;
const monacoCss = `${process.cwd().replaceAll("\\", "/")}/node_modules/monaco-editor/min/vs/editor/editor.main.css`;
/**
* CSP mode for the smoke tests (`RUNESTONE_CSP=1`, or `pnpm smoke --csp`).
@@ -83,14 +82,6 @@ export default defineConfig(() => ({
define: {
__RUNESTONE_VERSION__: JSON.stringify(appVersion),
},
resolve: {
alias: {
"monaco-editor-css": monacoCss,
},
},
optimizeDeps: {
include: ["monaco-editor"],
},
worker: {
format: /** @type {"es"} */ ("es"),
},