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

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

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

pnpm check, pnpm test (341 of 341), and pnpm build pass. The full smoke
suite passes, except one template test that passed on retry.
This commit is contained in:
Knotty Wyvern
2026-10-28 10:48:44 -07:00
parent 80f5d908e0
commit 724402729e
70 changed files with 1583 additions and 1475 deletions
+502
View File
@@ -0,0 +1,502 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { tableFormulasEnabled } from "$lib/formulas";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, StateEffect, type Extension } from "@codemirror/state";
import { EditorView, drawSelection, keymap, type KeyBinding } from "@codemirror/view";
import { defaultKeymap, history, indentLess, indentWithTab, isolateHistory, redo as redoEdit, redoDepth, undo as undoEdit, undoDepth } from "@codemirror/commands";
import { foldedRanges, indentUnit, unfoldEffect } from "@codemirror/language";
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import { writerSearch } from "./writerSearch";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { savedEditor, saveEditor } from "./editorStates";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
import { noteTitle } from "./noteTitle";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import { codeMenu } from "./codeMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt, urlAt } from "./documentLinks";
import { headingFolding } from "./headingFolding";
import { languageFor } from "./languageFor";
import { languageSupport } from "./codeLanguages";
import { indentListItem, outdentListItem } from "./markdownLists";
import { insertIndent, sourceChrome, sourceEditing } from "./sourceView";
import "./headingFolding.css";
type Mode = "write" | "source";
type Props = {
buffer: OpenBuffer;
/** Write shows formatted Markdown. Source shows the text of any file. */
mode: Mode;
chrome: Chrome;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, mode, chrome, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
export function openFind(replace = false) {
if (!editor) return;
openSearchPanel(editor);
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
}
export function closeFind() { if (editor) closeSearchPanel(editor); }
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
let error = $state("");
let lastValue = "";
let lineBreak = "\n";
let refreshVersion = 0;
let menu: { open(x: number, y: number, spellingOffset?: number, linkOffset?: number): void; close(focus?: boolean): void; destroy(): void } | undefined;
const urls = new Map<string, string>();
const loading = new Map<string, Promise<void>>();
const modeConfig = new Compartment(), languageConfig = new Compartment(), title = new Compartment();
let languageExtension: Extension = [];
let languagePath = "";
// The class follows the configuration that the editor shows, not the requested mode.
let shown = $state<{ mode: Mode; chrome: Chrome; markdown: boolean } | null>(null);
const markdownDocument = $derived(isMarkdownPath(buffer.relPath));
const renameTitle = (name: string) => onRenameTitle!(buffer.id, name);
const historyKeymap: KeyBinding[] = [
{ key: "Mod-z", run: undoEdit, preventDefault: true },
{ key: "Mod-y", run: redoEdit, preventDefault: true },
{ key: "Mod-Shift-z", run: redoEdit, preventDefault: true },
];
async function loadImages(path: string, value: string) {
const previousSize = urls.size;
await Promise.all(markdownImages(value).map(async source => {
if (urls.has(source)) return;
if (loading.has(source)) return loading.get(source);
const task = (async () => {
if (isRemoteImage(source)) { urls.set(source, source); return; }
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
try { await task; } finally { loading.delete(source); }
}));
return urls.size !== previousSize;
}
// CodeMirror stores one character per line break. Write the line break of the
// file only at the buffer boundary, so pasted LF and CRLF text both make lines.
function documentSource(state: EditorState) {
return state.doc.sliceString(0, undefined, lineBreak);
}
function detectLineBreak(text: string) {
const crlf = text.split("\r\n").length - 1;
return crlf > text.split("\n").length - 1 - crlf ? "\r\n" : "\n";
}
async function insertImages(event: ClipboardEvent | DragEvent, view: EditorView) {
const data = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
const files = imageFiles(data);
if (!files.length || !onInsertImage || !markdownDocument) return;
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
try {
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
await loadImages(path, snippets.join("\n\n"));
if (editor !== view) return;
const target = view.state.field(imageDrops).get(id);
if (!target) return;
const insert = imageInsertion(view.state.doc.toString(), target.from, target.to, snippets);
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, userEvent: "input.image", annotations: isolateHistory.of("full") });
view.focus();
} catch (reason) { if (editor === view) error = String(reason); }
finally { if (editor === view) view.dispatch({ effects: clearImageDrop.of(id) }); }
}
function writeExtensions(lists: KeyBinding[]): Extension {
const current = untrack(() => buffer);
return [
headingFolding,
tableNavigation,
keymap.of([{ key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, ...lists, indentWithTab]),
EditorView.lineWrapping,
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(buffer.relPath, image.dataset.mdSrc || "", "md")) {
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Could not find this image in the workspace.");
},
validate: async source => {
if (isRemoteImage(source)) return;
for (const path of linkCandidates(buffer.relPath, source, "md")) {
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Choose an image that exists in the workspace.");
},
report: message => { error = message; },
}),
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
];
}
function modeExtensions(next: NonNullable<typeof shown>): Extension {
// Tab in a Markdown list item makes a nested item in Write and in Source.
const lists: KeyBinding[] = next.markdown ? [{ key: "Tab", run: indentListItem, shift: outdentListItem }] : [];
if (next.mode === "write") return writeExtensions(lists);
return [
sourceEditing,
sourceChrome(next.chrome),
keymap.of([...lists, { key: "Tab", run: insertIndent, shift: indentLess }]),
EditorView.contentAttributes.of({ "aria-label": $t("Editor"), spellcheck: "false" }),
];
}
function requested() {
return untrack(() => ({ mode, chrome, markdown: markdownDocument }));
}
function configuration(): Extension[] {
const current = untrack(() => buffer);
shown = requested();
return [
completionExtension(current.id, () => ({ kind: isMarkdownPath(buffer.relPath) ? "prose" : "code", language: languageFor(buffer.relPath) })),
languageConfig.of(languageExtension),
modeConfig.of(modeExtensions(shown)),
history(), drawSelection(), indentUnit.of(" "), EditorState.tabSize.of(4),
EditorView.theme({}, { dark: true }),
writerSearch,
imageDrops,
keymap.of([...searchKeymap, ...historyKeymap, ...defaultKeymap]),
EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) {
menu?.close(false);
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
}
if (!update.docChanged) return;
scroll = scroll?.map(update.changes);
lastValue = documentSource(update.state);
onChange(lastValue, current.id);
if (shown?.mode !== "write") return;
void loadImages(buffer.relPath, update.state.sliceDoc()).then(changed => {
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
});
}),
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false;
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
if (!event.ctrlKey && !event.metaKey) return false;
if (event.button !== 0) return false;
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const source = view.state.doc.toString();
const sourceLink = position === null ? undefined : markdownDocument ? documentLinkAt(source, position) : urlAt(source, position);
if (!link && !sourceLink) return false;
event.preventDefault();
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
return true;
},
paste(event, view) {
const html = event.clipboardData?.getData("text/html") || "";
if (shown?.mode === "write" && /<table[\s>]/i.test(html)) {
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
if (markdown) {
event.preventDefault(); event.stopPropagation();
const { from, to } = view.state.selection.main;
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
return true;
}
}
if (!onInsertImage || !markdownDocument || !imageFiles(event.clipboardData).length) return false;
void insertImages(event, view); return true;
},
}),
];
}
// Start Write in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
function freshState(source: string) {
const doc = EditorState.create({ doc: source }).doc;
const anchor = untrack(() => mode) === "write" ? documentBodyStart(doc.toString()) : 0;
return EditorState.create({ doc, selection: { anchor }, extensions: configuration() });
}
let scroll: ReturnType<EditorView["scrollSnapshot"]> | undefined;
$effect(() => {
const el = host;
if (!el) return;
let cancelled = false;
let releaseSelection: (() => void) | undefined;
let releaseDrop: (() => void) | undefined;
let releaseScroll: (() => void) | undefined;
const current = untrack(() => buffer);
void (async () => {
lastValue = current.contents;
const saved = savedEditor(current.id);
const restore = saved?.source === lastValue ? saved : undefined;
lineBreak = restore?.lineBreak ?? detectLineBreak(lastValue);
if (isMarkdownPath(current.relPath) && untrack(() => mode) === "write") await loadImages(current.relPath, current.contents);
languagePath = current.relPath;
languageExtension = await languageSupport(current.relPath);
if (cancelled) return;
// A restored state keeps its history. The new configuration replaces the handlers of the old editor.
const state = restore ? restore.state.update({ effects: StateEffect.reconfigure.of(configuration()) }).state : freshState(lastValue);
// Restore through CodeMirror's layout pass, once its viewport is measured.
const view = new EditorView({ state, parent: el, scrollTo: restore?.scroll });
editor = view;
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
scroll = restore?.scroll ?? view.scrollSnapshot();
// Svelte may detach the old tab before effect cleanup runs, at which point
// DOM scroll offsets read as zero. Capture while the view is still mounted.
const saveScroll = () => { if (view.dom.isConnected) scroll = view.scrollSnapshot(); };
view.scrollDOM.addEventListener("scroll", saveScroll);
releaseScroll = () => view.scrollDOM.removeEventListener("scroll", saveScroll);
if (isMarkdownPath(current.relPath)) releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.posAtCoords(point, false), path); });
releaseSelection = registerSelection(current.id, () => view.state.selection.ranges.map(range => view.state.sliceDoc(range.from, range.to)).join("\n"));
menu = isMarkdownPath(current.relPath) ? markdownMenu({
snapshot() {
const { doc, selection } = view.state;
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
undo() { undoEdit(view); },
redo() { redoEdit(view); },
canUndo() { return undoDepth(view.state) > 0; },
canRedo() { return redoDepth(view.state) > 0; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }))
: codeMenu(view, message => { error = message; });
if (!untrack(() => focusTitle) && shouldFocusOnMount()) view.focus();
})().catch(reason => { if (!cancelled) error = String(reason); });
return () => {
cancelled = true;
refreshVersion++;
menu?.destroy();
menu = undefined;
releaseDrop?.();
releaseScroll?.();
if (editor && scroll) saveEditor(current.id, { source: documentSource(editor.state), lineBreak, state: editor.state, scroll });
editor?.destroy();
releaseSelection?.();
editor = undefined;
};
});
// Write and Source are two configurations of one state, so the switch keeps the history.
$effect(() => {
const next = { mode, chrome, markdown: markdownDocument };
const view = editor;
if (!view) return;
untrack(() => {
if (shown && shown.mode === next.mode && shown.chrome === next.chrome && shown.markdown === next.markdown) return;
void (next.mode === "write" ? loadImages(buffer.relPath, view.state.doc.toString()) : Promise.resolve(false)).then(() => {
const latest = requested();
if (editor !== view || latest.mode !== next.mode || latest.chrome !== next.chrome || latest.markdown !== next.markdown) return;
shown = next;
view.dispatch({ effects: modeConfig.reconfigure(modeExtensions(next)) });
});
});
});
$effect(() => {
const path = buffer.relPath;
const view = editor;
if (!view || path === languagePath) return;
languagePath = path;
void languageSupport(path).then(extension => {
if (editor !== view || languagePath !== path) return;
languageExtension = extension;
view.dispatch({ effects: languageConfig.reconfigure(extension) });
});
});
$effect(() => {
void $tableFormulasEnabled;
editor?.dispatch({ effects: refreshImages.of() });
});
$effect(() => {
const name = markdownTitle(buffer.relPath);
const view = editor;
if (view && shown?.mode === "write") view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
});
$effect(() => {
if (!focusTitle || !editor || shown?.mode !== "write") return;
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
if (!button) return;
button.click();
onTitleFocused?.();
});
$effect(() => {
const value = buffer.contents;
const path = buffer.relPath;
const view = editor;
if (!view || value === lastValue) return;
const version = ++refreshVersion;
void (untrack(() => shown?.mode) === "write" ? loadImages(path, value) : Promise.resolve(false)).then(() => {
if (version !== refreshVersion || editor !== view || buffer.contents !== value) return;
lastValue = value;
lineBreak = detectLineBreak(value);
// Reloads start fresh history, so undo cannot revive a discarded disk version.
const anchor = Math.min(view.state.selection.main.head, value.replace(/\r\n/g, "\n").length);
view.setState(freshState(value));
view.dispatch({ selection: { anchor } });
});
});
$effect(() => {
const line = focusLine;
const view = editor;
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects });
view.focus();
});
});
</script>
<div class={(shown?.mode ?? mode) === "write" ? "live-writer" : "source-editor"} data-chrome={shown?.chrome ?? chrome}
bind:this={host} role="application" aria-label={(shown?.mode ?? mode) === "write" ? $t("Markdown writing editor") : $t("Editor")}
ondragovercapture={(event) => {
if (!onInsertImage || !markdownDocument || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.live-writer, .source-editor { position: absolute; inset: 0; }
.live-writer :global(.cm-editor), .source-editor :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
.live-writer :global(.cm-editor.cm-focused), .source-editor :global(.cm-editor.cm-focused) { outline: none; }
.live-writer :global(.cm-panels), .source-editor :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground),
.source-editor :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .source-editor :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.source-editor :global(.cm-scroller) { font: var(--rs-code-font-weight) var(--rs-code-font-size)/var(--rs-code-line-height) var(--rs-font-mono); }
.source-editor :global(.cm-content) { padding: 8px 0 24px; caret-color: var(--rs-accent); }
.source-editor[data-chrome="Writing"] :global(.cm-content) { padding: 16px 24px 48px; }
.source-editor :global(.cm-cursor) { border-left-color: var(--rs-accent); }
.source-editor :global(.cm-gutters) { border: 0; background: transparent; color: var(--rs-text-dim); }
.source-editor :global(.cm-lineNumbers .cm-gutterElement) { padding: 0 10px 0 16px; }
.source-editor :global(.cm-activeLine) { background: var(--rs-bg-active); }
.source-editor :global(.cm-activeLineGutter) { background: transparent; color: var(--rs-text); }
.source-editor :global(.cm-foldGutter .cm-gutterElement) { padding: 0 4px; cursor: pointer; }
.source-editor :global(.cm-selectionMatch) { background: var(--rs-item-selection-bg); }
.source-editor :global(.cm-matchingBracket) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-border); }
.source-editor :global(.cm-nonmatchingBracket) { color: var(--rs-error); }
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
.live-writer :global(.cm-line) { padding-inline: 0; position: relative; }
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
.live-writer :global(.writer-divider-line) { display: flex; align-items: center; }
.live-writer :global(.writer-divider) { display: inline-flex; align-items: center; flex: 1; min-width: 0; height: 1.75em; cursor: text; }
.live-writer :global(.writer-divider::after) { content: ""; width: 100%; border-top: 1px solid var(--rs-border); }
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
/* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
.live-writer :global(.writer-preview img) { max-width: 100%; }
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
.live-writer :global(.writer-table p) { margin: 0; }
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
.live-writer :global(.table-add span) { position: absolute; font: 20px/24px var(--rs-font-ui); width: 24px; height: 24px; text-align: center; pointer-events: none; }
.live-writer :global(.table-add-column span) { left: 0; top: var(--table-add-position, 50%); transform: translateY(-50%); }
.live-writer :global(.table-add-row span) { top: 0; left: var(--table-add-position, 50%); transform: translateX(-50%); }
</style>
-339
View File
@@ -1,339 +0,0 @@
<script lang="ts">
import FindPanel from "./FindPanel.svelte";
import { monacoSearch } from "./monacoSearch";
import { SearchQuery } from "@codemirror/search";
import { t } from "$lib/i18n";
import { tick, untrack } from "svelte";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { codeFont } from "./codeFont";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { codeMenu } from "./codeMenu";
import type { TableContextActions } from "./tableCellActions";
import { documentLinks, documentLinkAt } from "./documentLinks";
type Props = {
buffer: OpenBuffer;
chrome: Chrome;
onChange: (value: string, id: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
export function focus() { editor?.focus(); }
let search = $state.raw<ReturnType<typeof monacoSearch>>();
let findOpen = $state(false);
let findPanel = $state<FindPanel>();
export async function openFind(replace = false) {
if (!search || !editor) return;
const selection = editor.getSelection();
const text = selection && editor.getModel()?.getValueInRange(selection);
if (text && !text.includes("\n") && !text.includes("\r")) {
search.target.setQuery(new SearchQuery({ ...search.target.query, search: text }));
findPanel?.sync(search.target.query);
}
findOpen = true;
search.refresh();
await tick();
findPanel?.focus(replace);
}
export function closeFind() { if (findOpen) search?.target.close(); }
export function nextMatch(backward = false) { if (findOpen) search?.target.next(backward); else void openFind(); }
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
const documentPath = $derived(buffer.relPath);
async function takeImages(event: DragEvent | ClipboardEvent, data: DataTransfer | null) {
if (!isMarkdownPath(buffer.relPath) || !onInsertImage) {
return false;
}
const files = imageFiles(data);
if (files.length === 0) {
return false;
}
event.preventDefault();
event.stopPropagation();
const view = editor, model = view?.getModel();
if (!view || !model) return true;
const position = event instanceof DragEvent ? view.getTargetAtClientPoint(event.clientX, event.clientY)?.position : null;
return importImages(view, files, position);
}
async function importImages(view: import("monaco-editor").editor.IStandaloneCodeEditor, files: File[], position?: import("monaco-editor").Position | null, linkedPath?: string) {
const model = view.getModel();
if (!model) return true;
const range = position ? { startLineNumber: position.lineNumber, startColumn: position.column, endLineNumber: position.lineNumber, endColumn: position.column } : view.getSelection();
if (!range) return true;
const [marker] = model.deltaDecorations([], [{ range, options: { stickiness: 1 } }]);
try {
const snippets: string[] = linkedPath ? [workspaceFileLink(buffer.relPath, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return true;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return true;
const target = model.getDecorationRange(marker);
if (!target) return true;
const from = model.getOffsetAt(target.getStartPosition()), to = model.getOffsetAt(target.getEndPosition());
const text = imageInsertion(model.getValue(), from, to, snippets).replace(/\n/g, model.getEOL());
view.pushUndoStop();
view.executeEdits("insert-images", [{ range: target, text, forceMoveMarkers: true }], () => {
const end = model.getPositionAt(from + text.length);
view.setPosition(end);
return [view.getSelection()!];
});
view.pushUndoStop();
view.focus();
} catch (reason) { if (editor === view) loadError = String(reason); }
finally { if (!model.isDisposed()) model.deltaDecorations([marker], []); }
return true;
}
$effect(() => {
const el = host;
// Buffer snapshots change on each edit. Only a path change remounts Monaco.
const path = documentPath;
if (!el) {
return;
}
let cancelled = false;
let session: ReturnType<typeof editorSession> | undefined;
let contentListener: { dispose(): void } | undefined;
let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined;
let releaseCompletion: (() => void) | undefined;
const listeners: { dispose(): void }[] = [];
void import("./monacoEnv").then(({ monaco, currentTheme }) => {
if (cancelled || !el.isConnected) {
return;
}
session = editorSession(monaco, untrack(() => buffer));
const mode = untrack(() => chrome);
const model = session.model;
const markdown = isMarkdownPath(path);
const view = monaco.editor.create(el, {
model,
theme: currentTheme,
automaticLayout: true,
...codeFont(el),
scrollBeyondLastLine: false,
smoothScrolling: true,
cursorBlinking: "smooth",
tabSize: 2,
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: false,
...monacoChrome(mode),
});
editor = view;
search = monacoSearch(monaco, view, () => { findOpen = false; });
for (const [id, label, replace] of [["actions.find", "Find", false], ["editor.action.startFindReplaceAction", "Replace", true]] as const) {
listeners.push(view.addAction({ id, label, keybindings: [monaco.KeyMod.CtrlCmd | (replace ? monaco.KeyCode.KeyH : monaco.KeyCode.KeyF)], run: () => openFind(replace) }));
}
listeners.push(view.addAction({ id: "editor.action.nextMatchFindAction", label: "Next match", keybindings: [monaco.KeyCode.F3], run: () => nextMatch() }));
listeners.push(view.addAction({ id: "editor.action.previousMatchFindAction", label: "Previous match", keybindings: [monaco.KeyMod.Shift | monaco.KeyCode.F3], run: () => nextMatch(true) }));
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
provideLinks(candidate) {
if (candidate !== model) return { links: [] };
return { links: documentLinks(model.getValue()).map(link => {
const from = model.getPositionAt(link.from), to = model.getPositionAt(link.to);
return { range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column),
url: `runestone-link://document${linkPath}${link.kind}?${encodeURIComponent(link.target)}`, tooltip: "Open link" };
}) };
},
}));
listeners.push(monaco.editor.registerLinkOpener({ open(resource) {
const url = resource.toString(true);
if (resource.scheme === "runestone-link" && resource.path.startsWith(linkPath)) {
onOpenLink?.(resource.path.slice(linkPath.length) === "wiki" ? "wiki" : "md", decodeURIComponent(resource.query));
return true;
}
if (view.hasTextFocus() && /^(https?:|mailto:)/i.test(url) && onOpenLink) { onOpenLink("md", url); return true; }
return false;
} }));
const openSourceLink = (event: MouseEvent) => {
if (!markdown || event.button !== 0 || (!event.ctrlKey && !event.metaKey) || !onOpenLink) return;
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const link = position && documentLinkAt(model.getValue(), model.getOffsetAt(position));
if (!link) return;
event.preventDefault(); event.stopImmediatePropagation();
onOpenLink(link.kind, link.target);
};
el.addEventListener("mousedown", openSourceLink, true);
listeners.push({ dispose: () => el.removeEventListener("mousedown", openSourceLink, true) });
listeners.push(view.onDidChangeCursorPosition(event => onSelectionLine?.(event.position.lineNumber)));
if (markdown) {
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.getTargetAtClientPoint(point.x, point.y)?.position, path); });
menu = markdownMenu({
snapshot() {
const selection = view.getSelection()!, version = model.getVersionId();
return { source: model.getValue(), selection: { from: model.getOffsetAt(selection.getStartPosition()), to: model.getOffsetAt(selection.getEndPosition()) }, valid: () => editor === view && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection) };
},
apply(edit) {
const from = model.getPositionAt(edit.from), to = model.getPositionAt(edit.to);
view.pushUndoStop();
view.executeEdits("markdown-menu", [{ range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column), text: edit.insert }], () => {
const anchor = model.getPositionAt(edit.anchor), head = model.getPositionAt(edit.head);
return [new monaco.Selection(anchor.lineNumber, anchor.column, head.lineNumber, head.column)];
});
view.pushUndoStop();
},
select(from, to) {
const start = model.getPositionAt(from), end = model.getPositionAt(to);
view.setSelection(new monaco.Selection(start.lineNumber, start.column, end.lineNumber, end.column));
view.revealPositionInCenterIfOutsideViewport(end);
},
selectAll() { view.setSelection(model.getFullModelRange()); view.focus(); },
focus() { view.focus(); },
undo() { view.trigger("markdown-menu", "undo", null); },
redo() { view.trigger("markdown-menu", "redo", null); },
canUndo() { return model.canUndo(); },
canRedo() { return model.canRedo(); },
}, untrack(() => tableActions), message => { loadError = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
} else {
menu = codeMenu(view, message => { loadError = message; });
}
const openContextMenu = (event: MouseEvent) => {
event.preventDefault(); event.stopImmediatePropagation();
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const selection = view.getSelection();
if (position && (!selection || selection.isEmpty() || !selection.containsPosition(position))) view.setPosition(position);
view.focus();
menu?.open(event.clientX, event.clientY, undefined, position ? model.getOffsetAt(position) : undefined);
};
el.addEventListener("contextmenu", openContextMenu, true);
listeners.push({ dispose: () => el.removeEventListener("contextmenu", openContextMenu, true) });
listeners.push(view.onKeyDown(event => {
if (event.browserEvent.key !== "ContextMenu" && !(event.shiftKey && event.browserEvent.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
const position = view.getPosition(), rect = el.getBoundingClientRect();
const coords = position && view.getScrolledVisiblePosition(position);
if (coords) menu?.open(rect.left + coords.left, rect.top + coords.top + coords.height);
}));
listeners.push(view.onDidChangeCursorSelection(() => menu?.close(false)));
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
if (session.view) view.restoreViewState(session.view);
onSelectionLine?.(view.getPosition()?.lineNumber ?? 1);
ready += 1;
contentListener = model.onDidChangeContent(() => {
if (applying) {
return;
}
onChange(view.getValue(), documentId);
});
if (shouldFocusOnMount()) view.focus();
}).catch((error) => { if (!cancelled) loadError = String(error); });
return () => {
cancelled = true;
const view = editor;
if (view && session) session.view = view.saveViewState();
contentListener?.dispose();
releaseCompletion?.();
releaseSelection?.();
menu?.destroy();
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
search?.dispose();
search = undefined;
findOpen = false;
view?.dispose();
if (session) releaseEditorSession(session);
editor = undefined;
};
});
$effect(() => {
void ready;
const mode = chrome;
const view = editor;
if (!view) {
return;
}
view.updateOptions(monacoChrome(mode));
});
$effect(() => {
void ready;
const contents = buffer.contents;
const view = editor;
if (!view) {
return;
}
if (contents !== view.getValue()) {
applying = true;
view.setValue(contents ?? "");
applying = false;
}
});
$effect(() => {
void ready;
const line = focusLine;
const view = editor;
if (!view || line == null) {
return;
}
view.revealLineInCenter(line);
view.setPosition({ lineNumber: line, column: 1 });
view.focus();
});
</script>
<div class="source-editor">
{#if findOpen && search}<FindPanel bind:this={findPanel} target={search.target} />{/if}
<div
class="monaco-host"
role="application"
aria-label={$t("Editor")}
bind:this={host}
ondragover={(event) => {
if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}
}}
ondropcapture={(event) => {
void takeImages(event, event.dataTransfer);
}}
onpastecapture={(event) => {
void takeImages(event, event.clipboardData);
}}
></div>
</div>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.source-editor { position: absolute; inset: 0; display: flex; flex-direction: column; min-width: 0; }
.source-editor :global(.rs-find-bar) { flex-shrink: 0; border-bottom: 1px solid var(--rs-border); }
.monaco-host { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.monaco-host :global(.rs-source-search-match) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-accent); }
.monaco-host :global(.monaco-editor),
.monaco-host :global(.overflow-guard) {
height: 100%;
}
</style>
-482
View File
@@ -1,482 +0,0 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { tableFormulasEnabled } from "$lib/formulas";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
import { defaultKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
import { writerHistory, historyKeymap } from "./writerHistory";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { foldedRanges, unfoldEffect } from "@codemirror/language";
import { noteFormats } from "./noteFormats";
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import { writerSearch } from "./writerSearch";
import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
import { noteTitle } from "./noteTitle";
import { markdownTitle } from "$lib/workspace/media";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt } from "./documentLinks";
import { headingFolding } from "./headingFolding";
import "./headingFolding.css";
type Props = {
buffer: OpenBuffer;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
export function openFind(replace = false) {
if (!editor) return;
openSearchPanel(editor);
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
}
export function closeFind() { if (editor) closeSearchPanel(editor); }
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let ModelSelection: typeof import("monaco-editor").Selection;
let lastValue = "";
let publishing = false;
let historySelections: Map<number, EditorSelection> | undefined;
let freshState: ((source: string) => EditorState) | undefined;
let refreshVersion = 0;
let historyTimer: ReturnType<typeof setTimeout> | undefined;
const urls = new Map<string, string>();
const loading = new Map<string, Promise<void>>();
const title = new Compartment();
const renameTitle = (name: string) => onRenameTitle!(buffer.id, name);
async function loadImages(path: string, value: string) {
const previousSize = urls.size;
await Promise.all(markdownImages(value).map(async source => {
if (urls.has(source)) return;
if (loading.has(source)) return loading.get(source);
const task = (async () => {
if (isRemoteImage(source)) { urls.set(source, source); return; }
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
try { await task; } finally { loading.delete(source); }
}));
return urls.size !== previousSize;
}
// CodeMirror stores one character per line break. Serialize only at the model
// boundary, so pasted LF and CRLF text both create real editor lines.
function modelSource(state: EditorState) {
return state.doc.sliceString(0, undefined, model?.getEOL() ?? "\n");
}
function publish(value: string, id: string, startState: EditorState, state: EditorState) {
if (!model || value === model.getValue()) return;
historySelections?.set(model.getAlternativeVersionId(), startState.selection);
const previous = model.getValue();
let start = 0;
while (start < previous.length && start < value.length && previous[start] === value[start]) start++;
let oldEnd = previous.length, newEnd = value.length;
while (oldEnd > start && newEnd > start && previous[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
const from = model.getPositionAt(start), to = model.getPositionAt(oldEnd);
const cursorState = (state: EditorState) => state.selection.ranges.map(range => {
const anchor = state.doc.lineAt(range.anchor), head = state.doc.lineAt(range.head);
return new ModelSelection(anchor.number, range.anchor - anchor.from + 1, head.number, range.head - head.from + 1);
});
// The model emits changes synchronously. Do not echo this Writer edit back
// into CodeMirror while its update listener still runs.
publishing = true;
try {
model.pushEditOperations(cursorState(startState), [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => cursorState(state));
} finally { publishing = false; }
historySelections?.set(model.getAlternativeVersionId(), state.selection);
clearTimeout(historyTimer);
historyTimer = setTimeout(() => model?.pushStackElement(), 500);
lastValue = model.getValue();
onChange(lastValue, id);
}
async function insertImages(event: ClipboardEvent | DragEvent, view: EditorView) {
const data = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
const files = imageFiles(data);
if (!files.length || !onInsertImage) return;
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
try {
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
await loadImages(path, snippets.join("\n\n"));
if (editor !== view) return;
const target = view.state.field(imageDrops).get(id);
if (!target) return;
const insert = imageInsertion(view.state.doc.toString(), target.from, target.to, snippets);
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, userEvent: "input.image", annotations: isolateHistory.of("full") });
view.focus();
} catch (reason) { if (editor === view) error = String(reason); }
finally { if (editor === view) view.dispatch({ effects: clearImageDrop.of(id) }); }
}
$effect(() => {
const el = host;
if (!el) return;
let cancelled = false;
let session: ReturnType<typeof editorSession> | undefined;
let contentListener: { dispose(): void } | undefined;
let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined;
let releaseScroll: (() => void) | undefined;
let scroll: ReturnType<EditorView["scrollSnapshot"]> | undefined;
const current = untrack(() => buffer);
void import("./monacoEnv").then(async ({ monaco }) => {
await loadImages(current.relPath, current.contents);
if (cancelled) return;
session = editorSession(monaco, untrack(() => buffer));
model = session.model;
ModelSelection = monaco.Selection;
historySelections = session.writerSelections;
lastValue = untrack(() => buffer.contents);
if (model.getValue() !== lastValue) model.setValue(lastValue);
model.pushStackElement();
const extensions = [
completionExtension(current.id),
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
headingFolding,
writerHistory.of({
undo: () => {
clearTimeout(historyTimer);
model!.pushStackElement();
if (!model!.canUndo()) return false;
void model!.undo();
return true;
},
redo: () => {
clearTimeout(historyTimer);
if (!model!.canRedo()) return false;
void model!.redo();
return true;
},
}), drawSelection(),
EditorView.theme({}, { dark: true }),
tableNavigation,
writerSearch,
keymap.of([{ key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, indentWithTab, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(current.relPath, image.dataset.mdSrc || "", "md")) {
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Could not find this image in the workspace.");
},
validate: async source => {
if (isRemoteImage(source)) return;
for (const path of linkCandidates(current.relPath, source, "md")) {
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Choose an image that exists in the workspace.");
},
report: message => { error = message; },
}),
imageDrops,
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) {
menu?.close(false);
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
}
const isolation = update.transactions.map(transaction => transaction.annotation(isolateHistory));
const separate = update.transactions.some(transaction => {
const event = transaction.annotation(Transaction.userEvent);
return transaction.docChanged && event && !/^(input\.type|delete)($|\.)/.test(event);
});
if (separate || (update.selectionSet && !update.docChanged)) model?.pushStackElement();
if (isolation.some(value => value === "before" || value === "full")) model?.pushStackElement();
if (update.docChanged) {
scroll = scroll?.map(update.changes);
publish(modelSource(update.state), current.id, update.startState, update.state);
void loadImages(current.relPath, update.state.sliceDoc()).then(changed => {
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
});
}
if (isolation.some(value => value === "after" || value === "full")) {
clearTimeout(historyTimer);
model?.pushStackElement();
}
}),
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false;
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
if (!event.ctrlKey && !event.metaKey) return false;
if (event.button !== 0) return false;
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const sourceLink = position === null ? undefined : documentLinkAt(view.state.doc.toString(), position);
if (!link && !sourceLink) return false;
event.preventDefault();
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
return true;
},
paste(event, view) {
const html = event.clipboardData?.getData("text/html") || "";
if (/<table[\s>]/i.test(html)) {
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
if (markdown) {
event.preventDefault(); event.stopPropagation();
const { from, to } = view.state.selection.main;
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
return true;
}
}
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
void insertImages(event, view); return true;
},
}),
];
// Start in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
freshState = source => {
const doc = EditorState.create({ doc: source }).doc;
return EditorState.create({ doc, selection: { anchor: documentBodyStart(doc.toString()) }, extensions });
};
const saved = session.writer;
const state = saved?.source === lastValue
? EditorState.fromJSON(saved.state, { extensions })
: freshState(lastValue);
// Restore through CodeMirror's layout pass, once its viewport is measured.
const view = new EditorView({ state, parent: el, scrollTo: saved?.source === lastValue ? saved.scroll : undefined });
editor = view;
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
// Writer and IDE use the same model and undo stack for this document.
contentListener = model.onDidChangeContent(event => {
if (publishing) return;
const value = model!.getValue();
if (value === modelSource(view.state)) return;
lastValue = value;
const changes = event.changes.map(change => ({
from: view.state.doc.line(change.range.startLineNumber).from + change.range.startColumn - 1,
to: view.state.doc.line(change.range.endLineNumber).from + change.range.endColumn - 1,
insert: change.text,
}));
if (event.isFlush) historySelections?.clear();
const selection = event.isUndoing || event.isRedoing ? historySelections?.get(model!.getAlternativeVersionId()) : undefined;
view.dispatch({ changes, selection, scrollIntoView: !!selection, annotations: Transaction.addToHistory.of(false) });
onChange(value, current.id);
});
scroll = saved?.source === lastValue ? saved.scroll : view.scrollSnapshot();
// Svelte may detach the old tab before effect cleanup runs, at which point
// DOM scroll offsets read as zero. Capture while the view is still mounted.
const saveScroll = () => { if (view.dom.isConnected) scroll = view.scrollSnapshot(); };
view.scrollDOM.addEventListener("scroll", saveScroll);
releaseScroll = () => view.scrollDOM.removeEventListener("scroll", saveScroll);
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.posAtCoords(point, false), path); });
releaseSelection = registerSelection(current.id, () => view.state.selection.ranges.map(range => view.state.sliceDoc(range.from, range.to)).join("\n"));
menu = markdownMenu({
snapshot() {
const { doc, selection } = view.state;
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
undo() { clearTimeout(historyTimer); model?.pushStackElement(); void model?.undo(); },
redo() { clearTimeout(historyTimer); void model?.redo(); },
canUndo() { return model?.canUndo() ?? false; },
canRedo() { return model?.canRedo() ?? false; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
if (!focusTitle && shouldFocusOnMount()) view.focus();
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
cancelled = true;
refreshVersion++;
clearTimeout(historyTimer);
model?.pushStackElement();
contentListener?.dispose();
menu?.destroy();
releaseDrop?.();
releaseScroll?.();
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
editor?.destroy();
if (session) releaseEditorSession(session);
releaseSelection?.();
editor = undefined;
};
});
$effect(() => {
void $tableFormulasEnabled;
editor?.dispatch({ effects: refreshImages.of() });
});
$effect(() => {
const name = markdownTitle(buffer.relPath);
const view = editor;
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
});
$effect(() => {
if (!focusTitle || !editor) return;
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
if (!button) return;
button.click();
onTitleFocused?.();
});
$effect(() => {
const value = buffer.contents;
const path = buffer.relPath;
const view = editor;
if (!view || value === lastValue) return;
const version = ++refreshVersion;
void loadImages(path, value).then(() => {
if (version !== refreshVersion || editor !== view || buffer.contents !== value || !freshState) return;
lastValue = value;
if (model?.getValue() !== value) model?.setValue(value);
// Reloads start fresh history, so undo cannot revive a discarded disk version.
const anchor = Math.min(view.state.selection.main.head, value.replace(/\r\n/g, "\n").length);
view.setState(freshState(value));
view.dispatch({ selection: { anchor }, effects: title.reconfigure(noteTitle(markdownTitle(buffer.relPath), onRenameTitle ? renameTitle : undefined)) });
});
});
$effect(() => {
const line = focusLine;
const view = editor;
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects });
view.focus();
});
});
</script>
<div class="live-writer" bind:this={host} role="application" aria-label={$t("Markdown writing editor")}
ondragovercapture={(event) => {
if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.live-writer { position: absolute; inset: 0; }
.live-writer :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
.live-writer :global(.cm-editor.cm-focused) { outline: none; }
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
.live-writer :global(.cm-line) { padding-inline: 0; position: relative; }
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
.live-writer :global(.writer-divider-line) { display: flex; align-items: center; }
.live-writer :global(.writer-divider) { display: inline-flex; align-items: center; flex: 1; min-width: 0; height: 1.75em; cursor: text; }
.live-writer :global(.writer-divider::after) { content: ""; width: 100%; border-top: 1px solid var(--rs-border); }
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
/* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
.live-writer :global(.writer-preview img) { max-width: 100%; }
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
.live-writer :global(.writer-table p) { margin: 0; }
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
.live-writer :global(.table-add span) { position: absolute; font: 20px/24px var(--rs-font-ui); width: 24px; height: 24px; text-align: center; pointer-events: none; }
.live-writer :global(.table-add-column span) { left: 0; top: var(--table-add-position, 50%); transform: translateY(-50%); }
.live-writer :global(.table-add-row span) { top: 0; left: var(--table-add-position, 50%); transform: translateX(-50%); }
</style>
-9
View File
@@ -1,9 +0,0 @@
export function codeFont(element: HTMLElement) {
const style = getComputedStyle(element);
return {
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
fontWeight: style.getPropertyValue("--rs-code-font-weight").trim() || "300",
fontSize: Number.parseFloat(style.getPropertyValue("--rs-code-font-size")) || 13,
lineHeight: Number.parseFloat(style.getPropertyValue("--rs-code-line-height")) || 21,
};
}
+31
View File
@@ -0,0 +1,31 @@
import type { Extension } from "@codemirror/state";
import { StreamLanguage } from "@codemirror/language";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { extensionOf } from "../workspace/chrome";
import { languageFor } from "./languageFor";
import { noteFormats } from "./noteFormats";
/** The Markdown language of Write and Source, with the RuneStone note formats. */
export const noteMarkdown = () => markdown({ base: markdownLanguage, extensions: [noteFormats] });
// Each language loads when the first file of that language opens.
const loaders: Record<string, (extension: string) => Promise<Extension>> = {
markdown: async () => noteMarkdown(),
javascript: async extension => (await import("@codemirror/lang-javascript")).javascript({ jsx: extension === "jsx" }),
typescript: async extension => (await import("@codemirror/lang-javascript")).javascript({ typescript: true, jsx: extension === "tsx" }),
python: async () => (await import("@codemirror/lang-python")).python(),
json: async () => (await import("@codemirror/lang-json")).json(),
css: async () => (await import("@codemirror/lang-css")).css(),
scss: async () => (await import("@codemirror/lang-sass")).sass(),
html: async () => (await import("@codemirror/lang-html")).html(),
rust: async () => (await import("@codemirror/lang-rust")).rust(),
shell: async () => StreamLanguage.define((await import("@codemirror/legacy-modes/mode/shell")).shell),
yaml: async () => (await import("@codemirror/lang-yaml")).yaml(),
ini: async () => StreamLanguage.define((await import("@codemirror/legacy-modes/mode/toml")).toml),
xml: async () => (await import("@codemirror/lang-xml")).xml(),
};
/** The syntax support for a file. Plain text gets none. */
export async function languageSupport(relPath: string): Promise<Extension> {
return await loaders[languageFor(relPath)]?.(extensionOf(relPath)) ?? [];
}
+22 -18
View File
@@ -1,9 +1,12 @@
import { tr } from '../i18n/index.ts';
import type { editor } from "monaco-editor";
import { EditorSelection } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { redo, redoDepth, undo, undoDepth } from "@codemirror/commands";
import { selectSelectionMatches } from "@codemirror/search";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
/** Keep Monaco editing commands in the host's shared action menu. */
export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: string) => void) {
/** Keep source editing commands in the host's shared action menu. */
export function codeMenu(view: EditorView, report: (message: string) => void) {
let root: HTMLElement | undefined;
function close(focus = true) {
root?.remove(); root = undefined;
@@ -17,16 +20,14 @@ export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: s
window.addEventListener("resize", resize);
function open(x: number, y: number) {
close(false);
const model = view.getModel(), selection = view.getSelection();
if (!model || !selection) return;
const version = model.getVersionId();
const valid = () => view.getModel() === model && !model.isDisposed() && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection);
const selected = model.getValueInRange(selection);
const state = view.state, main = state.selection.main;
const valid = () => view.state.doc === state.doc && view.state.selection.eq(state.selection);
const selected = state.sliceDoc(main.from, main.to);
const word = main.empty ? state.wordAt(main.head) : main;
const replace = (text: string) => {
if (!valid()) return;
view.pushUndoStop();
view.executeEdits("code-menu", [{ range: selection, text }]);
view.pushUndoStop(); view.focus();
view.dispatch(view.state.replaceSelection(text), { userEvent: "input", scrollIntoView: true });
view.focus();
};
const clipboard = async (kind: "cut" | "copy" | "paste") => {
close();
@@ -35,19 +36,22 @@ export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: s
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
};
const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const changeAll = () => {
close();
if (!valid() || !word) return;
if (main.empty) view.dispatch({ selection: EditorSelection.single(word.from, word.to) });
selectSelectionMatches(view);
};
const items: ActionMenuItem[] = [
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !undoDepth(state), run: () => { close(); undo(view); } },
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !redoDepth(state), run: () => { close(); redo(view); } },
{ separator: true },
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+Shift+L", disabled: !word || word.empty, run: changeAll },
{ separator: true },
{ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true },
{ label: tr("Command palette"), icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
{ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); } },
];
root = actionMenu(x, y, items, close, tr("Code text actions"));
}
+13 -2
View File
@@ -27,17 +27,28 @@ export function documentLinks(source: string): DocumentLink[] {
const targetFrom = match.index + 2 + raw.length - raw.trimStart().length;
links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target });
}
links.push(...plainUrls(source, occupied));
return links.sort((a, b) => a.from - b.from);
}
function plainUrls(source: string, occupied: (from: number, to: number) => boolean = () => false) {
const links: DocumentLink[] = [];
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
const target = match[0].replace(/[.,;:!?]+$/, "").replace(/\)+$/, suffix => {
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
});
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md", target });
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md" as const, target });
}
return links.sort((a, b) => a.from - b.from);
return links;
}
export function documentLinkAt(source: string, position: number) {
return documentLinks(source).find(link => position >= link.from && position < link.to);
}
/** The plain URL at a position, for files that are not Markdown. */
export function urlAt(source: string, position: number) {
return plainUrls(source).find(link => position >= link.from && position < link.to);
}
+30
View File
@@ -0,0 +1,30 @@
import type { EditorState } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
/**
* The editor of an open document, kept while its tab stays open.
* The state holds the undo history, so Write, Source, and a tab change share it.
*/
export type SavedEditor = {
source: string;
lineBreak: string;
state: EditorState;
scroll: ReturnType<EditorView["scrollSnapshot"]>;
};
const saved = new Map<string, SavedEditor>();
let retained = new Set<string>();
export function savedEditor(id: string) {
return saved.get(id);
}
export function saveEditor(id: string, editor: SavedEditor) {
if (retained.has(id)) saved.set(id, editor);
}
/** Keep the editors of the open tabs only. */
export function retainEditorStates(ids: string[]) {
retained = new Set(ids);
for (const id of saved.keys()) if (!retained.has(id)) saved.delete(id);
}
-17
View File
@@ -23,20 +23,3 @@ export function documentMatches(source: string, query: SearchQuery) {
}
return { state, matches };
}
export function replacementText(source: string, from: number, query: SearchQuery) {
const replacement = query.literal ? query.replace : query.replace.replace(/\\([nrt\\])/g, (_, char: string) => ({ n: "\n", r: "\r", t: "\t", "\\": "\\" })[char]!);
if (!query.regexp) return replacement;
const expression = new RegExp(query.search, "gmu" + (query.caseSensitive ? "" : "i"));
expression.lastIndex = from;
const match = expression.exec(source);
return replacement.replace(/\$([$&]|\d+)/g, (token, index: string) => {
if (index === "$") return "$";
if (index === "&") return match?.[0] ?? "";
for (let length = index.length; length > 0; length--) {
const number = Number(index.slice(0, length));
if (match && number > 0 && number < match.length) return (match[number] ?? "") + index.slice(length);
}
return token;
});
}
+18
View File
@@ -13,6 +13,7 @@ import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { listLabels } from "./markdownLists";
import { activeTableFormulas } from "../formulas/index.ts";
@@ -102,6 +103,18 @@ class Checkbox extends WidgetType {
ignoreEvent() { return true; }
}
class ListLabel extends WidgetType {
constructor(readonly label: string) { super(); }
eq(other: ListLabel) { return other.label === this.label; }
toDOM() {
const span = document.createElement("span");
span.className = "writer-list-label";
span.textContent = this.label;
return span;
}
ignoreEvent() { return false; }
}
class Preview extends WidgetType {
readonly formulas = activeTableFormulas();
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
@@ -308,6 +321,11 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
return false;
}
} });
// Nested ordered markers show letters or Roman numerals. A selection over a marker shows its source.
for (const label of listLabels(state)) {
if (hidden(label.from, label.to) || state.selection.ranges.some(range => range.from < label.to && range.to > label.from)) continue;
ranges.push(Decoration.replace({ widget: new ListLabel(label.label), atomic: true }).range(label.from, label.to));
}
for (const match of source.matchAll(/\[\^([^\]\s]+)\](:)?/g)) {
const from = match.index, to = from + match[0].length;
if (hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
+259
View File
@@ -0,0 +1,259 @@
import { countColumn, EditorState, type ChangeSpec, type Line, type Text, type TransactionSpec } from "@codemirror/state";
import { ensureSyntaxTree, getIndentUnit, language, syntaxTree } from "@codemirror/language";
import type { Command } from "@codemirror/view";
type Tree = ReturnType<typeof syntaxTree>;
type Node = ReturnType<Tree["resolveInner"]>;
// A list inside a block quote keeps its quote markers at the line start.
const QUOTE = /^(?:[ \t]{0,3}>[ \t]?)*/;
const ORDERED = /^(\d{1,9})([.)])$/;
const parsed = (state: EditorState) => ensureSyntaxTree(state, state.doc.length, 200) ?? syntaxTree(state);
const quoteLength = (text: string) => QUOTE.exec(text)![0].length;
const markOf = (item: Node | null) => item?.name === "ListItem" ? item.getChild("ListMark") : null;
const isList = (node: Node | null) => node?.name === "BulletList" || node?.name === "OrderedList";
function markColumn(state: EditorState, mark: Node) {
const line = state.doc.lineAt(mark.from);
return countColumn(line.text.slice(quoteLength(line.text), mark.from - line.from), state.tabSize);
}
function contentColumn(state: EditorState, mark: Node) {
const line = state.doc.lineAt(mark.from);
const rest = line.text.slice(mark.to - line.from);
const spaces = /^ */.exec(rest)![0].length;
return markColumn(state, mark) + mark.to - mark.from + (spaces === 0 || spaces > 4 || spaces === rest.length ? 1 : spaces);
}
/** The number of leading characters that cover `columns` columns of indentation. */
function indentLength(text: string, columns: number, tabSize: number) {
let length = 0;
for (let column = 0; length < text.length && column < columns && /[ \t]/.test(text[length]); length++) {
column += text[length] === "\t" ? tabSize - column % tabSize : 1;
}
return length;
}
function itemOnLine(tree: Tree, line: Line) {
const start = line.from + /^(?:[ \t]{0,3}>[ \t]?)*[ \t]*/.exec(line.text)![0].length;
const node = tree.resolveInner(start, 1);
return node.name === "ListMark" && node.from === start ? node.parent : null;
}
/** The list item around a position. Code inside an item keeps its own indentation. */
function itemAround(tree: Tree, position: number) {
for (const side of [1, -1] as const) {
for (let node: Node | null = tree.resolveInner(position, side); node; node = node.parent) {
if (node.name === "FencedCode" || node.name === "CodeBlock") return null;
if (node.name === "ListItem") return node;
}
}
return null;
}
function itemLines(state: EditorState, item: Node) {
return { first: state.doc.lineAt(item.from).number, last: state.doc.lineAt(Math.max(item.from, item.to - 1)).number };
}
/** The outermost list items that the selection touches. A nested item moves with its parent. */
function selectedItems(state: EditorState, tree: Tree) {
const items = new Map<number, Node>();
for (const range of state.selection.ranges) {
const first = state.doc.lineAt(range.from);
let last = state.doc.lineAt(range.to);
if (!range.empty && range.to === last.from && last.number > first.number) last = state.doc.line(last.number - 1);
for (let number = first.number; number <= last.number; number++) {
const item = itemOnLine(tree, state.doc.line(number)) ?? (number === first.number ? itemAround(tree, range.from) : null);
if (item) items.set(item.from, item);
}
}
const nested = (item: Node) => {
for (let node = item.parent; node; node = node.parent) if (node.name === "ListItem" && items.has(node.from)) return true;
return false;
};
return [...items.values()].filter(item => !nested(item)).sort((a, b) => a.from - b.from);
}
/** Change a marker. Keep its last character when it stays, so a caret after the marker does not move. */
function replaceMark(state: EditorState, mark: Node, prefix: string, marker: string): ChangeSpec {
const text = state.sliceDoc(mark.from, mark.to);
const keep = marker.at(-1) === text.at(-1) ? 1 : 0;
return { from: mark.from, to: mark.to - keep, insert: prefix + marker.slice(0, marker.length - keep) };
}
/** Number each item of the ordered lists in a range from the first item of its list. */
function renumber(tree: Tree, doc: Text, from: number, to: number) {
const changes: ChangeSpec[] = [];
tree.iterate({ from, to, enter(node) {
if (node.name !== "OrderedList") return;
let next: number | undefined;
for (let item = node.node.firstChild; item; item = item.nextSibling) {
const mark = markOf(item), parts = mark && ORDERED.exec(doc.sliceString(mark.from, mark.to));
if (!mark || !parts) continue;
next ??= Number(parts[1]);
if (Number(parts[1]) !== next) changes.push({ from: mark.from, to: mark.to - 1, insert: String(next) });
next++;
}
} });
return changes;
}
function finish(state: EditorState, changes: ChangeSpec[], from: number, to: number): TransactionSpec[] {
if (!changes.length) return [];
const moved = state.changes(changes);
const doc = moved.apply(state.doc);
const parser = state.facet(language)?.parser;
const numbers = parser ? renumber(parser.parse(doc.toString()), doc, moved.mapPos(from, -1), moved.mapPos(to, 1)) : [];
return [{ changes: moved, userEvent: "input.indent", scrollIntoView: true }, { changes: numbers, sequential: true }];
}
/**
* Move the selected list items one level deeper, below the previous item.
* The moved item starts a new list as `1.`, or joins the nested list of the previous item.
* Returns null outside a list, and an empty array when no item can move.
*/
export function indentListItems(state: EditorState): TransactionSpec[] | null {
const tree = parsed(state), items = selectedItems(state, tree);
if (!items.length) return null;
const changes: ChangeSpec[] = [];
let from = state.doc.length, to = 0;
for (const item of items) {
const previous = item.prevSibling, mark = markOf(item), previousMark = markOf(previous), list = item.parent;
if (!previous || !mark || !previousMark || !list) continue;
const column = markColumn(state, mark);
const nested = isList(previous.lastChild) ? previous.lastChild : null;
const nestedMark = markOf(nested?.firstChild ?? null);
let pad = nestedMark ? markColumn(state, nestedMark) - column : 0;
if (pad <= 0) pad = Math.max(getIndentUnit(state), contentColumn(state, previousMark) - markColumn(state, previousMark));
const style = nested?.name === list.name && nestedMark ? state.sliceDoc(nestedMark.from, nestedMark.to) : state.sliceDoc(mark.from, mark.to);
changes.push(replaceMark(state, mark, " ".repeat(pad), list.name === "OrderedList" ? `1${style.at(-1)}` : style));
const lines = itemLines(state, item);
for (let number = lines.first + 1; number <= lines.last; number++) {
const line = state.doc.line(number), start = quoteLength(line.text);
if (line.text.slice(start).trim()) changes.push({ from: line.from + start, insert: " ".repeat(pad) });
}
from = Math.min(from, list.from); to = Math.max(to, list.to);
}
return finish(state, changes, from, to);
}
/**
* Move the selected nested list items one level up, after their parent item.
* The moved item takes the marker style of the outer list. Later items of its old list become its children.
* Returns null outside a list, and an empty array when no item can move.
*/
export function outdentListItems(state: EditorState): TransactionSpec[] | null {
const tree = parsed(state), items = selectedItems(state, tree);
if (!items.length) return null;
const selected = new Set(items.map(item => item.from));
const changes: ChangeSpec[] = [];
let from = state.doc.length, to = 0;
for (const item of items) {
const mark = markOf(item), list = item.parent, parent = list?.parent ?? null, parentMark = markOf(parent), outer = parent?.parent;
if (!mark || !list || !parent || !parentMark || !outer) continue;
const remove = markColumn(state, mark) - markColumn(state, parentMark);
if (remove <= 0) continue;
const lines = itemLines(state, item);
for (let number = lines.first; number <= lines.last; number++) {
const line = state.doc.line(number), start = line.from + quoteLength(line.text);
const length = indentLength(state.sliceDoc(start, number === lines.first ? mark.from : line.to), remove, state.tabSize);
if (length) changes.push({ from: start, to: start + length });
}
const text = state.sliceDoc(mark.from, mark.to), parentText = state.sliceDoc(parentMark.from, parentMark.to);
const ordered = outer.name === "OrderedList";
if (outer.name !== list.name || (ordered ? text.at(-1) !== parentText.at(-1) : text !== parentText)) {
changes.push(replaceMark(state, mark, "", ordered ? `${Number(parentText.slice(0, -1)) + 1}${parentText.at(-1)}` : parentText));
}
// The next item of the old list becomes the first child of the moved item.
const next = item.nextSibling, nextMark = markOf(next);
if (list.name === "OrderedList" && next && nextMark && !selected.has(next.from)) {
changes.push({ from: nextMark.from, to: nextMark.to - 1, insert: "1" });
}
from = Math.min(from, outer.from); to = Math.max(to, outer.to);
}
return finish(state, changes, from, to);
}
function listCommand(move: (state: EditorState) => TransactionSpec[] | null): Command {
return view => {
const specs = move(view.state);
if (!specs) return false;
if (specs.length) view.dispatch(...specs);
return true;
};
}
/** Tab in a list item makes it a nested item. */
export const indentListItem = listCommand(indentListItems);
/** Shift+Tab in a nested list item moves it one level up. */
export const outdentListItem = listCommand(outdentListItems);
function alphabetic(number: number) {
let label = "";
for (let rest = number; rest > 0; rest = Math.floor((rest - 1) / 26)) label = String.fromCharCode(97 + (rest - 1) % 26) + label;
return label;
}
function roman(number: number) {
const numerals: [number, string][] = [[1000, "m"], [900, "cm"], [500, "d"], [400, "cd"], [100, "c"], [90, "xc"], [50, "l"], [40, "xl"], [10, "x"], [9, "ix"], [5, "v"], [4, "iv"], [1, "i"]];
let label = "", rest = number;
for (const [value, numeral] of numerals) for (; rest >= value; rest -= value) label += numeral;
return label;
}
/**
* The label of an ordered list item. Level 1 uses decimal numbers, level 2 letters, and level 3 Roman numerals.
* Deeper levels repeat the sequence. Numbers that a style cannot show stay decimal, as in CSS.
*/
export function orderedLabel(level: number, number: number) {
const style = (level - 1) % 3;
if (style === 1 && number > 0) return alphabetic(number);
if (style === 2 && number > 0 && number < 4000) return roman(number);
return String(number);
}
function orderedLevel(node: Node | null) {
let level = 0;
for (; node; node = node.parent) if (node.name === "OrderedList") level++;
return level;
}
export type ListLabel = { from: number; to: number; label: string };
/**
* Labels for the markers of nested ordered lists. The Markdown source keeps its numbers.
* An item gets the start number of its list plus its position, as a Markdown renderer counts.
*/
export function listLabels(state: EditorState): ListLabel[] {
const labels: ListLabel[] = [];
syntaxTree(state).iterate({ enter(node) {
if (node.name === "OrderedList") {
const level = orderedLevel(node.node);
let start: number | undefined, index = 0;
for (let item = node.node.firstChild; item; item = item.nextSibling) {
const mark = markOf(item), parts = mark && ORDERED.exec(state.sliceDoc(mark.from, mark.to));
if (!mark || !parts) continue;
start ??= Number(parts[1]);
if (level > 1) labels.push({ from: mark.from, to: mark.to, label: orderedLabel(level, start + index) + parts[2] });
index++;
}
}
// An empty item cannot start a list inside a paragraph, so the parser reads it as text.
// Label it as the nested item that it becomes when the user types its text.
const item = node.node.parent;
if (node.name !== "Paragraph" || item?.name !== "ListItem") return;
const itemMark = markOf(item)!, level = orderedLevel(item) + 1;
if (level < 2) return;
const first = state.doc.lineAt(node.from).number, last = state.doc.lineAt(node.to).number;
for (let number = first + 1; number <= last; number++) {
const line = state.doc.line(number);
const match = /^(\s*)(\d{1,9})([.)])\s*$/.exec(line.text.slice(quoteLength(line.text)));
if (!match) continue;
const from = line.from + quoteLength(line.text) + match[1].length;
if (countColumn(line.text.slice(quoteLength(line.text), from - line.from), state.tabSize) < contentColumn(state, itemMark)) continue;
labels.push({ from, to: from + match[2].length + 1, label: orderedLabel(level, Number(match[2])) + match[3] });
}
} });
return labels;
}
-1
View File
@@ -1 +0,0 @@
declare module "monaco-editor-css";
-26
View File
@@ -1,26 +0,0 @@
import type { Chrome } from "../workspace/types";
export function monacoChrome(mode: Chrome) {
if (mode === "Writing") {
return {
wordWrap: "on" as const,
lineNumbers: "off" as const,
minimap: { enabled: false },
folding: false,
glyphMargin: false,
lineDecorationsWidth: 24,
padding: { top: 16, bottom: 48 },
renderLineHighlight: "none" as const,
};
}
return {
wordWrap: "off" as const,
lineNumbers: "on" as const,
minimap: { enabled: true, scale: 1 },
folding: true,
glyphMargin: true,
lineDecorationsWidth: 10,
padding: { top: 8, bottom: 24 },
renderLineHighlight: "line" as const,
};
}
-60
View File
@@ -1,60 +0,0 @@
import * as monaco from "monaco-editor";
import "monaco-editor-css";
import editorWorkerUrl from "monaco-editor/editor/editor.worker.js?url";
self.MonacoEnvironment = {
getWorker() {
return new Worker(editorWorkerUrl, { type: "module" });
},
};
export let currentTheme = 'runestone-default-dark';
function updateTheme() {
const style = getComputedStyle(document.documentElement);
const color = (name: string) => style.getPropertyValue(`--rs-${name}`).trim();
const syntaxColor = (role: string) => {
const value = document.documentElement.style.getPropertyValue(`--rs-syntax-${role}`).trim();
const match = /^#([0-9a-f]{3,8})$/i.exec(value);
if (!match) return undefined;
const hex = match[1];
return hex.length === 3 || hex.length === 4 ? `#${hex.slice(0, 3).split('').map(part => part + part).join('')}`
: hex.length === 6 || hex.length === 8 ? `#${hex.slice(0, 6)}` : undefined;
};
const syntaxRules = [
['keyword', 'keyword'], ['variable.parameter', 'parameter'], ['variable', 'local'],
['variable.predefined', 'global'], ['variable.property', 'instance'], ['variable.static', 'static'],
['identifier', 'local'], ['string', 'string'], ['number', 'number'], ['comment', 'comment'],
['type', 'type'], ['type.identifier', 'type'], ['entity.name.type', 'type'],
['function', 'function'], ['predefined', 'function'], ['delimiter', 'global'],
].flatMap(([token, role]) => {
const foreground = syntaxColor(role);
return foreground ? [{ token, foreground: foreground.slice(1) }] : [];
});
// Monaco permits only letters, digits, and hyphens in registered theme names.
const palette = (document.documentElement.dataset.palette || 'default').replace(/[^a-z0-9-]/gi, '-');
currentTheme = `runestone-${palette}-${document.documentElement.dataset.theme || 'dark'}`;
monaco.editor.defineTheme(currentTheme, {
base: document.documentElement.dataset.theme === 'light' ? 'vs' : 'vs-dark',
inherit: true,
rules: syntaxRules,
colors: {
...Object.fromEntries(['keyword', 'number', 'type', 'string', 'function', 'parameter'].flatMap((role, index) => {
const foreground = syntaxColor(role);
return foreground ? [[`editorBracketHighlight.foreground${index + 1}`, foreground]] : [];
})),
'editor.background': '#00000000', 'editor.foreground': color('text'),
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
'editor.inactiveSelectionBackground': color('selection'), 'editor.selectionForeground': color('selection-text'),
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': '#00000000',
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
'minimap.background': '#00000000', 'editorIndentGuide.background1': color('border'),
'editorIndentGuide.activeBackground1': color('text-dim'),
},
});
monaco.editor.setTheme(currentTheme);
}
updateTheme();
window.addEventListener('runestone-theme-changed', updateTheme);
if (import.meta.hot) import.meta.hot.dispose(() => window.removeEventListener('runestone-theme-changed', updateTheme));
export { monaco };
-71
View File
@@ -1,71 +0,0 @@
import type * as Monaco from "monaco-editor";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText, type FindTarget } from "./findTarget";
export function monacoSearch(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, close: () => void) {
const decorations = view.createDecorationsCollection();
let active = false;
let query = new SearchQuery({ search: "" });
function snapshot() {
const model = view.getModel()!;
const { state, matches } = documentMatches(model.getValue(), query);
function range(match: { from: number; to: number }) {
const from = state.doc.lineAt(match.from), to = state.doc.lineAt(match.to);
return new monaco.Range(from.number, match.from - from.from + 1, to.number, match.to - to.from + 1);
}
return { model, state, matches, range };
}
function refresh() {
active = true;
const { matches, range } = snapshot();
decorations.set(matches.map(match => ({ range: range(match), options: { inlineClassName: "rs-source-search-match" } })));
}
function next(backward = false) {
const { matches, range } = snapshot();
if (!matches.length) return;
const selection = view.getSelection();
const ranges = matches.map(range);
const current = ranges.findIndex(match => selection?.equalsRange(match));
let index: number;
if (current >= 0) index = (current + (backward ? -1 : 1) + ranges.length) % ranges.length;
else if (backward) {
index = ranges.findLastIndex(match => !selection || monaco.Position.compare(match.getEndPosition(), selection.getStartPosition()) <= 0);
if (index < 0) index = ranges.length - 1;
} else {
index = ranges.findIndex(match => !selection || monaco.Position.compare(match.getStartPosition(), selection.getEndPosition()) >= 0);
if (index < 0) index = 0;
}
view.setSelection(ranges[index]);
view.revealRangeInCenterIfOutsideViewport(ranges[index]);
}
const target: FindTarget = {
get query() { return query; }, readOnly: false,
setQuery(value) { query = value; refresh(); },
next,
selectAll() {
const { matches, range } = snapshot();
if (!matches.length) return;
view.setSelections(matches.map(match => { const value = range(match); return new monaco.Selection(value.startLineNumber, value.startColumn, value.endLineNumber, value.endColumn); }));
view.focus();
},
replace(all = false) {
const { state, matches, range } = snapshot();
const selection = view.getSelection();
const selected = all ? matches : matches.filter(match => selection?.equalsRange(range(match))).slice(0, 1);
if (!selected.length) { if (!all) next(); return; }
const edits = selected.map(match => ({ range: range(match), text: replacementText(state.doc.toString(), match.from, query) }));
const last = selected[selected.length - 1];
const inserted = edits[edits.length - 1].text;
const end = state.update({ changes: selected.map((match, index) => ({ ...match, insert: edits[index].text })) }).state;
const offset = all ? 0 : last.from + inserted.length;
const line = end.doc.lineAt(Math.min(offset, end.doc.length));
view.pushUndoStop();
view.executeEdits("document-find", edits, [new monaco.Selection(line.number, offset - line.from + 1, line.number, offset - line.from + 1)]);
view.pushUndoStop();
if (!all) next();
},
close() { active = false; decorations.clear(); close(); view.focus(); },
};
const changed = view.onDidChangeModelContent(() => { if (active) refresh(); });
return { target, refresh, dispose() { changed.dispose(); decorations.clear(); } };
}
-44
View File
@@ -1,44 +0,0 @@
import type * as Monaco from "monaco-editor";
import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
users: number;
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writerSelections: Map<number, import("@codemirror/state").EditorSelection>;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
let retained = new Set<string>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
users: 0,
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
writerSelections: new Map(),
};
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
session.users++;
return session;
}
export function retainEditorSessions(ids: string[]) {
retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id) && session.users === 0) { session.model.dispose(); sessions.delete(id); }
}
}
export function releaseEditorSession(session: Session) {
session.users = Math.max(0, session.users - 1);
if (session.users) return;
for (const [id, entry] of sessions) {
if (entry === session && !retained.has(id)) { session.model.dispose(); sessions.delete(id); break; }
}
}
+60
View File
@@ -0,0 +1,60 @@
import { countColumn, EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers, type Command } from "@codemirror/view";
import { bracketMatching, foldGutter, foldKeymap, getIndentUnit, HighlightStyle, indentOnInput, syntaxHighlighting } from "@codemirror/language";
import { closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
import { highlightSelectionMatches } from "@codemirror/search";
import { indentMore } from "@codemirror/commands";
import { tags } from "@lezer/highlight";
import { chromeLayout } from "../workspace/chrome";
import type { Chrome } from "../workspace/types";
const syntax = (role: string, fallback: string) => `var(--rs-syntax-${role}, ${fallback})`;
/** Syntax colors come from the theme tokens, so a theme change needs no editor update. */
const sourceHighlight = HighlightStyle.define([
{ tag: [tags.keyword, tags.modifier, tags.operatorKeyword, tags.controlKeyword, tags.definitionKeyword, tags.moduleKeyword, tags.tagName], color: syntax("keyword", "var(--rs-accent)") },
{ tag: tags.heading, color: syntax("keyword", "var(--rs-accent)"), fontWeight: "600" },
{ tag: [tags.string, tags.special(tags.string), tags.regexp, tags.attributeValue, tags.url, tags.monospace], color: syntax("string", "var(--rs-ok)") },
{ tag: [tags.number, tags.bool, tags.null, tags.atom, tags.unit], color: syntax("number", "var(--rs-special)") },
{ tag: tags.comment, color: syntax("comment", "var(--rs-text-dim)") },
{ tag: [tags.typeName, tags.className, tags.namespace], color: syntax("type", "var(--rs-accent-2)") },
{ tag: [tags.function(tags.variableName), tags.function(tags.propertyName), tags.macroName], color: syntax("function", "var(--rs-accent-2)") },
{ tag: [tags.propertyName, tags.attributeName], color: syntax("instance", "var(--rs-accent-2)") },
{ tag: [tags.standard(tags.variableName), tags.self, tags.special(tags.variableName)], color: syntax("global", "var(--rs-text-dim)") },
{ tag: tags.variableName, color: syntax("local", "var(--rs-text)") },
{ tag: [tags.punctuation, tags.operator, tags.meta, tags.processingInstruction], color: syntax("global", "var(--rs-text-dim)") },
{ tag: tags.emphasis, fontStyle: "italic" },
{ tag: tags.strong, fontWeight: "600" },
{ tag: tags.strikethrough, textDecoration: "line-through" },
{ tag: tags.link, color: "var(--rs-accent)", textDecoration: "underline" },
{ tag: tags.invalid, color: "var(--rs-error)" },
]);
/** Tab inserts spaces to the next indent stop at each caret. With a selection, it indents the lines. */
export const insertIndent: Command = view => {
const { state } = view;
if (state.selection.ranges.some(range => !range.empty)) return indentMore(view);
const unit = getIndentUnit(state);
view.dispatch(state.changeByRange(range => {
const line = state.doc.lineAt(range.head);
const insert = " ".repeat(unit - countColumn(line.text.slice(0, range.head - line.from), state.tabSize) % unit);
return { changes: { from: range.head, insert }, range: EditorSelection.cursor(range.head + insert.length) };
}), { scrollIntoView: true, userEvent: "input.indent" });
return true;
};
/** Code editing support for Source: syntax colors, brackets, several carets, and matches of the selection. */
export const sourceEditing: Extension = [
syntaxHighlighting(sourceHighlight), bracketMatching(), closeBrackets(), indentOnInput(), highlightSelectionMatches(),
EditorState.allowMultipleSelections.of(true),
keymap.of(closeBracketsKeymap),
];
export function sourceChrome(chrome: Chrome): Extension {
const layout = chromeLayout(chrome);
return [
layout.wrap ? EditorView.lineWrapping : [],
layout.gutters ? [lineNumbers(), foldGutter(), highlightActiveLineGutter(), keymap.of(foldKeymap)] : [],
layout.activeLine ? highlightActiveLine() : [],
];
}
+1 -2
View File
@@ -7,8 +7,7 @@ import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import Image from "@tiptap/extension-image";
import type { EditorView } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { undo, redo } from "./writerHistory";
import { isolateHistory, redo, undo } from "@codemirror/commands";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
import { tableCellMarkdown } from "./tableCellMarkdown";
import { tableSelectionControls } from "./tableSelectionControls";
+1 -2
View File
@@ -1,7 +1,6 @@
import { tr } from '../i18n/index.ts';
import type { EditorView } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { undo, redo } from "./writerHistory";
import { isolateHistory, redo, undo } from "@codemirror/commands";
import type { Editor } from "@tiptap/core";
import { useSpellingMenu } from "./spellingMenu";
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
-20
View File
@@ -1,20 +0,0 @@
import { Facet } from "@codemirror/state";
import type { Command, KeyBinding } from "@codemirror/view";
import { undo as localUndo, redo as localRedo } from "@codemirror/commands";
export const writerHistory = Facet.define<{ undo: () => boolean; redo: () => boolean }>();
export const undo: Command = view => {
const shared = view.state.facet(writerHistory)[0];
return shared ? shared.undo() : localUndo(view);
};
export const redo: Command = view => {
const shared = view.state.facet(writerHistory)[0];
return shared ? shared.redo() : localRedo(view);
};
export const historyKeymap: readonly KeyBinding[] = [
{ key: "Mod-z", run: undo, preventDefault: true },
{ key: "Mod-y", run: redo, preventDefault: true },
{ key: "Mod-Shift-z", run: redo, preventDefault: true },
];