diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index 921fcc2..ccfc767 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -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.
diff --git a/docs/development.md b/docs/development.md
index 8fc62b2..e7653de 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -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`) |
diff --git a/docs/plugin-host.md b/docs/plugin-host.md
index e574f3d..9e2ecd2 100644
--- a/docs/plugin-host.md
+++ b/docs/plugin-host.md
@@ -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 `
diff --git a/src/lib/editor/EditorHost.svelte b/src/lib/editor/EditorHost.svelte
deleted file mode 100644
index 82e06ac..0000000
--- a/src/lib/editor/EditorHost.svelte
+++ /dev/null
@@ -1,339 +0,0 @@
-
-
-
-{#if findOpen && search}
{/if}
-
{
- if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) {
- event.preventDefault();
- if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
- }
- }}
- ondropcapture={(event) => {
- void takeImages(event, event.dataTransfer);
- }}
- onpastecapture={(event) => {
- void takeImages(event, event.clipboardData);
- }}
->
-
-{#if loadError}{loadError} { loadError = null; }}>{$t("Dismiss")}
{/if}
-
-
diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte
deleted file mode 100644
index 3c01b08..0000000
--- a/src/lib/editor/LiveWriter.svelte
+++ /dev/null
@@ -1,482 +0,0 @@
-
-
- {
- if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return;
- event.preventDefault();
- if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
- }}
- ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
->
-{#if error}{error} { error = ""; }}>{$t("Dismiss")}
{/if}
-
-
diff --git a/src/lib/editor/codeFont.ts b/src/lib/editor/codeFont.ts
deleted file mode 100644
index c4c9a34..0000000
--- a/src/lib/editor/codeFont.ts
+++ /dev/null
@@ -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,
- };
-}
diff --git a/src/lib/editor/codeLanguages.ts b/src/lib/editor/codeLanguages.ts
new file mode 100644
index 0000000..9432024
--- /dev/null
+++ b/src/lib/editor/codeLanguages.ts
@@ -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 Promise> = {
+ 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 {
+ return await loaders[languageFor(relPath)]?.(extensionOf(relPath)) ?? [];
+}
diff --git a/src/lib/editor/codeMenu.ts b/src/lib/editor/codeMenu.ts
index 23173c3..b431a82 100644
--- a/src/lib/editor/codeMenu.ts
+++ b/src/lib/editor/codeMenu.ts
@@ -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"));
}
diff --git a/src/lib/editor/documentLinks.ts b/src/lib/editor/documentLinks.ts
index 7b9d249..7ab8b07 100644
--- a/src/lib/editor/documentLinks.ts
+++ b/src/lib/editor/documentLinks.ts
@@ -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);
+}
diff --git a/src/lib/editor/editorStates.ts b/src/lib/editor/editorStates.ts
new file mode 100644
index 0000000..8eb7a5f
--- /dev/null
+++ b/src/lib/editor/editorStates.ts
@@ -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;
+};
+
+const saved = new Map();
+let retained = new Set();
+
+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);
+}
diff --git a/src/lib/editor/findTarget.ts b/src/lib/editor/findTarget.ts
index a36ef11..fe70635 100644
--- a/src/lib/editor/findTarget.ts
+++ b/src/lib/editor/findTarget.ts
@@ -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;
- });
-}
diff --git a/src/lib/editor/liveMarkdown.ts b/src/lib/editor/liveMarkdown.ts
index bb61dbf..1a8e3ea 100644
--- a/src/lib/editor/liveMarkdown.ts
+++ b/src/lib/editor/liveMarkdown.ts
@@ -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, 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;
diff --git a/src/lib/editor/markdownLists.ts b/src/lib/editor/markdownLists.ts
new file mode 100644
index 0000000..f287388
--- /dev/null
+++ b/src/lib/editor/markdownLists.ts
@@ -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;
+type Node = ReturnType;
+
+// 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();
+ 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;
+}
diff --git a/src/lib/editor/monaco-css.d.ts b/src/lib/editor/monaco-css.d.ts
deleted file mode 100644
index 50f3810..0000000
--- a/src/lib/editor/monaco-css.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-declare module "monaco-editor-css";
diff --git a/src/lib/editor/monacoChrome.ts b/src/lib/editor/monacoChrome.ts
deleted file mode 100644
index 5c773d3..0000000
--- a/src/lib/editor/monacoChrome.ts
+++ /dev/null
@@ -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,
- };
-}
diff --git a/src/lib/editor/monacoEnv.ts b/src/lib/editor/monacoEnv.ts
deleted file mode 100644
index fa356e0..0000000
--- a/src/lib/editor/monacoEnv.ts
+++ /dev/null
@@ -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 };
diff --git a/src/lib/editor/monacoSearch.ts b/src/lib/editor/monacoSearch.ts
deleted file mode 100644
index cb341c5..0000000
--- a/src/lib/editor/monacoSearch.ts
+++ /dev/null
@@ -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(); } };
-}
diff --git a/src/lib/editor/sessions.ts b/src/lib/editor/sessions.ts
deleted file mode 100644
index 208a680..0000000
--- a/src/lib/editor/sessions.ts
+++ /dev/null
@@ -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;
- writer?: { source: string; state: ReturnType; scroll: ReturnType };
-};
-const sessions = new Map();
-let retained = new Set();
-
-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; }
- }
-}
diff --git a/src/lib/editor/sourceView.ts b/src/lib/editor/sourceView.ts
new file mode 100644
index 0000000..4479c7b
--- /dev/null
+++ b/src/lib/editor/sourceView.ts
@@ -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() : [],
+ ];
+}
diff --git a/src/lib/editor/tableControls.ts b/src/lib/editor/tableControls.ts
index 61aa363..c2b5ef0 100644
--- a/src/lib/editor/tableControls.ts
+++ b/src/lib/editor/tableControls.ts
@@ -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";
diff --git a/src/lib/editor/tableSelectionControls.ts b/src/lib/editor/tableSelectionControls.ts
index 5d5e5ab..015a5c0 100644
--- a/src/lib/editor/tableSelectionControls.ts
+++ b/src/lib/editor/tableSelectionControls.ts
@@ -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";
diff --git a/src/lib/editor/writerHistory.ts b/src/lib/editor/writerHistory.ts
deleted file mode 100644
index 0b44240..0000000
--- a/src/lib/editor/writerHistory.ts
+++ /dev/null
@@ -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 },
-];
diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts
index 739a479..160672a 100644
--- a/src/lib/i18n/messages.ts
+++ b/src/lib/i18n/messages.ts
@@ -2519,12 +2519,6 @@ export const messageRows: [string, string, string, string][] = [
"すべての出現箇所を変更",
"更改所有匹配项"
],
- [
- "Command palette",
- "Palette de commandes",
- "コマンドパレット",
- "命令面板"
- ],
[
"Copy Markdown",
"Copier le Markdown",
diff --git a/src/lib/layout/EditorPane.svelte b/src/lib/layout/EditorPane.svelte
index 957f964..04150aa 100644
--- a/src/lib/layout/EditorPane.svelte
+++ b/src/lib/layout/EditorPane.svelte
@@ -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();
let titleFocusId = $state(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();
let readingFindPanel = $state();
$effect(() => { void buffer?.id; void reading; void previewMode; readingFind = undefined; });
@@ -86,23 +84,21 @@
if (inReading) {
const root = element?.querySelector(".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(".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}
{#key buffer.id}
- {#if !isIde && canPreview && !reading}
- selectedLine = line}
- focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
- {:else}
- selectedLine = line} />
- {/if}
+ selectedLine = line}
+ focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{/key}
{#if reading && canPreview}
diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte
index 4e02512..6eca59f 100644
--- a/src/lib/layout/Workbench.svelte
+++ b/src/lib/layout/Workbench.svelte
@@ -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] }))
diff --git a/src/lib/ui/find.css b/src/lib/ui/find.css
index 578d762..6c6e2b1 100644
--- a/src/lib/ui/find.css
+++ b/src/lib/ui/find.css
@@ -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); }
diff --git a/src/lib/workspace/chrome.ts b/src/lib/workspace/chrome.ts
index 28cdfe5..1d050f4 100644
--- a/src/lib/workspace/chrome.ts
+++ b/src/lib/workspace/chrome.ts
@@ -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 };
+}
diff --git a/tests/smoke/appearance/backgroundFrames.smoke.mjs b/tests/smoke/appearance/backgroundFrames.smoke.mjs
index 44559b9..b8f1a93 100644
--- a/tests/smoke/appearance/backgroundFrames.smoke.mjs
+++ b/tests/smoke/appearance/backgroundFrames.smoke.mjs
@@ -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();
diff --git a/tests/smoke/appearance/characterThemes.smoke.mjs b/tests/smoke/appearance/characterThemes.smoke.mjs
index bfe40ee..eedd573 100644
--- a/tests/smoke/appearance/characterThemes.smoke.mjs
+++ b/tests/smoke/appearance/characterThemes.smoke.mjs
@@ -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`) });
diff --git a/tests/smoke/appearance/density.smoke.mjs b/tests/smoke/appearance/density.smoke.mjs
index 8ee3e66..9b776b7 100644
--- a/tests/smoke/appearance/density.smoke.mjs
+++ b/tests/smoke/appearance/density.smoke.mjs
@@ -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" });
diff --git a/tests/smoke/appearance/palettes.smoke.mjs b/tests/smoke/appearance/palettes.smoke.mjs
index 3f39bee..d9e1b3a 100644
--- a/tests/smoke/appearance/palettes.smoke.mjs
+++ b/tests/smoke/appearance/palettes.smoke.mjs
@@ -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");
diff --git a/tests/smoke/editor/emptyMenu.smoke.mjs b/tests/smoke/editor/emptyMenu.smoke.mjs
index 9e0442a..baf22d5 100644
--- a/tests/smoke/editor/emptyMenu.smoke.mjs
+++ b/tests/smoke/editor/emptyMenu.smoke.mjs
@@ -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');
diff --git a/tests/smoke/editor/footnotes.smoke.mjs b/tests/smoke/editor/footnotes.smoke.mjs
index 2b29566..d2c790c 100644
--- a/tests/smoke/editor/footnotes.smoke.mjs
+++ b/tests/smoke/editor/footnotes.smoke.mjs
@@ -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);
diff --git a/tests/smoke/editor/imageNavigation.smoke.mjs b/tests/smoke/editor/imageNavigation.smoke.mjs
index c15a693..2d29f96 100644
--- a/tests/smoke/editor/imageNavigation.smoke.mjs
+++ b/tests/smoke/editor/imageNavigation.smoke.mjs
@@ -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);
diff --git a/tests/smoke/editor/images.smoke.mjs b/tests/smoke/editor/images.smoke.mjs
index 5d83f9b..1868fbf 100644
--- a/tests/smoke/editor/images.smoke.mjs
+++ b/tests/smoke/editor/images.smoke.mjs
@@ -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.
diff --git a/tests/smoke/editor/interactions.smoke.mjs b/tests/smoke/editor/interactions.smoke.mjs
index 842ebfb..5e4087f 100644
--- a/tests/smoke/editor/interactions.smoke.mjs
+++ b/tests/smoke/editor/interactions.smoke.mjs
@@ -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"));
diff --git a/tests/smoke/editor/listNesting.smoke.mjs b/tests/smoke/editor/listNesting.smoke.mjs
new file mode 100644
index 0000000..e4b2d3e
--- /dev/null
+++ b/tests/smoke/editor/listNesting.smoke.mjs
@@ -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.");
+});
diff --git a/tests/smoke/editor/markdownMenu.smoke.mjs b/tests/smoke/editor/markdownMenu.smoke.mjs
index d07e842..872335a 100644
--- a/tests/smoke/editor/markdownMenu.smoke.mjs
+++ b/tests/smoke/editor/markdownMenu.smoke.mjs
@@ -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");
diff --git a/tests/smoke/editor/markdownPaste.smoke.mjs b/tests/smoke/editor/markdownPaste.smoke.mjs
index cae9cd6..8165c6d 100644
--- a/tests/smoke/editor/markdownPaste.smoke.mjs
+++ b/tests/smoke/editor/markdownPaste.smoke.mjs
@@ -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); } });
diff --git a/tests/smoke/editor/pasteRepeat.smoke.mjs b/tests/smoke/editor/pasteRepeat.smoke.mjs
index 0201c88..b387ad9 100644
--- a/tests/smoke/editor/pasteRepeat.smoke.mjs
+++ b/tests/smoke/editor/pasteRepeat.smoke.mjs
@@ -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');
});
diff --git a/tests/smoke/editor/surfaces.smoke.mjs b/tests/smoke/editor/surfaces.smoke.mjs
index 455138f..bb2d688 100644
--- a/tests/smoke/editor/surfaces.smoke.mjs
+++ b/tests/smoke/editor/surfaces.smoke.mjs
@@ -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 });
diff --git a/tests/smoke/editor/undoHistory.smoke.mjs b/tests/smoke/editor/undoHistory.smoke.mjs
index be2ce59..d7e4ca9 100644
--- a/tests/smoke/editor/undoHistory.smoke.mjs
+++ b/tests/smoke/editor/undoHistory.smoke.mjs
@@ -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';
diff --git a/tests/smoke/find/documentFind.smoke.mjs b/tests/smoke/find/documentFind.smoke.mjs
index d311104..41fee6a 100644
--- a/tests/smoke/find/documentFind.smoke.mjs
+++ b/tests/smoke/find/documentFind.smoke.mjs
@@ -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');
diff --git a/tests/smoke/layout/outline.smoke.mjs b/tests/smoke/layout/outline.smoke.mjs
index 09ac9a8..9c5104e 100644
--- a/tests/smoke/layout/outline.smoke.mjs
+++ b/tests/smoke/layout/outline.smoke.mjs
@@ -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();
diff --git a/tests/smoke/layout/splits.smoke.mjs b/tests/smoke/layout/splits.smoke.mjs
index 5b4151d..2f654e5 100644
--- a/tests/smoke/layout/splits.smoke.mjs
+++ b/tests/smoke/layout/splits.smoke.mjs
@@ -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 });
diff --git a/tests/smoke/layout/workbench.smoke.mjs b/tests/smoke/layout/workbench.smoke.mjs
index dbd0cc1..fcad23b 100644
--- a/tests/smoke/layout/workbench.smoke.mjs
+++ b/tests/smoke/layout/workbench.smoke.mjs
@@ -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");
diff --git a/tests/smoke/links/fileDragLinks.smoke.mjs b/tests/smoke/links/fileDragLinks.smoke.mjs
index e56311b..eef0454 100644
--- a/tests/smoke/links/fileDragLinks.smoke.mjs
+++ b/tests/smoke/links/fileDragLinks.smoke.mjs
@@ -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(""));
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");
diff --git a/tests/smoke/links/linkMenus.smoke.mjs b/tests/smoke/links/linkMenus.smoke.mjs
index af95da8..6c1608a 100644
--- a/tests/smoke/links/linkMenus.smoke.mjs
+++ b/tests/smoke/links/linkMenus.smoke.mjs
@@ -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();
diff --git a/tests/smoke/links/sectionLinks.smoke.mjs b/tests/smoke/links/sectionLinks.smoke.mjs
index eff33b7..b51190f 100644
--- a/tests/smoke/links/sectionLinks.smoke.mjs
+++ b/tests/smoke/links/sectionLinks.smoke.mjs
@@ -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` });
diff --git a/tests/smoke/settings/displayLanguage.smoke.mjs b/tests/smoke/settings/displayLanguage.smoke.mjs
index 63a86aa..389cf35 100644
--- a/tests/smoke/settings/displayLanguage.smoke.mjs
+++ b/tests/smoke/settings/displayLanguage.smoke.mjs
@@ -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();
diff --git a/tests/smoke/settings/general.smoke.mjs b/tests/smoke/settings/general.smoke.mjs
index aaa8d17..afac8a0 100644
--- a/tests/smoke/settings/general.smoke.mjs
+++ b/tests/smoke/settings/general.smoke.mjs
@@ -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");
diff --git a/tests/smoke/tables/drag.smoke.mjs b/tests/smoke/tables/drag.smoke.mjs
index 3894571..8e2aa30 100644
--- a/tests/smoke/tables/drag.smoke.mjs
+++ b/tests/smoke/tables/drag.smoke.mjs
@@ -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();
diff --git a/tests/smoke/tables/formulas.smoke.mjs b/tests/smoke/tables/formulas.smoke.mjs
index 65d1d17..0197434 100644
--- a/tests/smoke/tables/formulas.smoke.mjs
+++ b/tests/smoke/tables/formulas.smoke.mjs
@@ -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);
diff --git a/tests/smoke/tabs/menus.smoke.mjs b/tests/smoke/tabs/menus.smoke.mjs
index 32d8fea..653281e 100644
--- a/tests/smoke/tabs/menus.smoke.mjs
+++ b/tests/smoke/tabs/menus.smoke.mjs
@@ -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();
diff --git a/tests/smoke/tabs/scroll.smoke.mjs b/tests/smoke/tabs/scroll.smoke.mjs
index 43302aa..df3d0df 100644
--- a/tests/smoke/tabs/scroll.smoke.mjs
+++ b/tests/smoke/tabs/scroll.smoke.mjs
@@ -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');
});
diff --git a/tests/smoke/tree/newFiles.smoke.mjs b/tests/smoke/tree/newFiles.smoke.mjs
index 2508d46..bfc7b61 100644
--- a/tests/smoke/tree/newFiles.smoke.mjs
+++ b/tests/smoke/tree/newFiles.smoke.mjs
@@ -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();
diff --git a/tests/smoke/workspace/openAndCreate.smoke.mjs b/tests/smoke/workspace/openAndCreate.smoke.mjs
index c76feb2..27d0285 100644
--- a/tests/smoke/workspace/openAndCreate.smoke.mjs
+++ b/tests/smoke/workspace/openAndCreate.smoke.mjs
@@ -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");
diff --git a/tests/unit/editor/documentFind.spec.ts b/tests/unit/editor/documentFind.spec.ts
index effd56d..dd4f2fb 100644
--- a/tests/unit/editor/documentFind.spec.ts
+++ b/tests/unit/editor/documentFind.spec.ts
@@ -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, []);
diff --git a/tests/unit/editor/markdownLists.spec.ts b/tests/unit/editor/markdownLists.spec.ts
new file mode 100644
index 0000000..1648310
--- /dev/null
+++ b/tests/unit/editor/markdownLists.spec.ts
@@ -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."]);
+});
diff --git a/tests/unit/workspace/chrome.spec.ts b/tests/unit/workspace/chrome.spec.ts
index 2a44a06..e5b18c9 100644
--- a/tests/unit/workspace/chrome.spec.ts
+++ b/tests/unit/workspace/chrome.spec.ts
@@ -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", () => {
diff --git a/vite.config.js b/vite.config.js
index 8604d37..fab0c1b 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -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"),
},