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:
@@ -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>
|
||||
Reference in New Issue
Block a user