Initial RuneStone project
This commit is contained in:
@@ -0,0 +1,356 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||
import { defaultKeymap, history, historyField, historyKeymap, isolateHistory } from "@codemirror/commands";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { searchKeymap } from "@codemirror/search";
|
||||
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 } from "$lib/workspace/noteHtml";
|
||||
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
|
||||
import { registerImageDropTarget } from "./workspaceImageDrop";
|
||||
import { editorSession } 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 { tableNavigation } from "./tableNavigation";
|
||||
|
||||
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;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
};
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
let error = $state("");
|
||||
let model: import("monaco-editor").editor.ITextModel | undefined;
|
||||
let lastValue = "";
|
||||
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;
|
||||
}
|
||||
|
||||
function publish(value: string, id: string) {
|
||||
if (!model || value === model.getValue()) return;
|
||||
const before = model.getValue();
|
||||
let start = 0;
|
||||
while (start < before.length && start < value.length && before[start] === value[start]) start++;
|
||||
let oldEnd = before.length, newEnd = value.length;
|
||||
while (oldEnd > start && newEnd > start && before[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
|
||||
const from = model.getPositionAt(start), to = model.getPositionAt(oldEnd);
|
||||
model.pushEditOperations(null, [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => null);
|
||||
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 ? [workspaceImageLink(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 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;
|
||||
lastValue = untrack(() => buffer.contents);
|
||||
if (model.getValue() !== lastValue) model.setValue(lastValue);
|
||||
model.pushStackElement();
|
||||
const extensions = [
|
||||
EditorState.lineSeparator.of(model.getEOL()),
|
||||
markdown({ base: markdownLanguage, extensions: [{
|
||||
defineNodes: ["NoteHighlight", "NoteMath", "NoteComment", "NoteFormatMark"],
|
||||
parseInline: [{ name: "NoteFormats", before: "Emphasis", parse(context, next, position) {
|
||||
const marker = next === 61 ? "==" : next === 37 ? "%%" : next === 36 ? "$" : "";
|
||||
if (!marker || context.slice(position, position + marker.length) !== marker) return -1;
|
||||
if (marker === "$" && (context.char(position + 1) === 36 || context.char(position - 1) === 36)) return -1;
|
||||
let end = position + marker.length;
|
||||
for (; end < context.end; end++) {
|
||||
if (context.char(end) === 92) { end++; continue; }
|
||||
if (context.slice(end, end + marker.length) === marker) break;
|
||||
}
|
||||
if (end >= context.end || end === position + marker.length) return -1;
|
||||
const kind = marker === "==" ? "NoteHighlight" : marker === "$" ? "NoteMath" : "NoteComment";
|
||||
const children = marker === "==" ? context.parser.parseInline(context.slice(position + marker.length, end), position + marker.length) : [];
|
||||
return context.addElement(context.elt(kind, position, end + marker.length, [
|
||||
context.elt("NoteFormatMark", position, position + marker.length), ...children,
|
||||
context.elt("NoteFormatMark", end, end + marker.length),
|
||||
]));
|
||||
} }],
|
||||
}] }),
|
||||
// Rich cell serialization can change delimiters away from the caret.
|
||||
// Keep a burst of typing together even when those source edits aren't adjacent.
|
||||
history({ joinToEvent: (transaction, adjacent) => adjacent || transaction.isUserEvent("input.type.table") }), drawSelection(),
|
||||
EditorView.theme({}, { dark: true }),
|
||||
tableNavigation,
|
||||
keymap.of([{ key: "Escape", run: view => {
|
||||
if (!view.state.field(imageSource)) return false;
|
||||
view.dispatch({ effects: editImageSource.of(null) }); return true;
|
||||
} }, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
|
||||
liveMarkdown(urls, untrack(() => tableActions), {
|
||||
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": "Writing editor", "aria-multiline": "true", spellcheck: "true" }),
|
||||
EditorView.updateListener.of(update => {
|
||||
if (update.docChanged || update.selectionSet) menu?.close(false);
|
||||
if (update.docChanged) {
|
||||
scroll = scroll?.map(update.changes);
|
||||
publish(update.state.sliceDoc(), current.id);
|
||||
void loadImages(current.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 });
|
||||
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);
|
||||
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);
|
||||
return true;
|
||||
},
|
||||
click(event) {
|
||||
if (!event.ctrlKey && !event.metaKey) return false;
|
||||
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
|
||||
if (!link) return false;
|
||||
event.preventDefault();
|
||||
onOpenLink?.(link.getAttribute("data-kind") === "wiki" ? "wiki" : "md", link.getAttribute("data-href") || link.getAttribute("href") || "");
|
||||
return true;
|
||||
},
|
||||
paste(event, view) {
|
||||
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
|
||||
void insertImages(event, view); return true;
|
||||
},
|
||||
}),
|
||||
];
|
||||
freshState = source => EditorState.create({ doc: source, extensions });
|
||||
const saved = session.writer;
|
||||
const state = saved?.source === lastValue
|
||||
? EditorState.fromJSON(saved.state, { extensions }, { history: historyField })
|
||||
: 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;
|
||||
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") }); },
|
||||
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
|
||||
focus() { view.focus(); },
|
||||
}, untrack(() => tableActions), message => { error = message; });
|
||||
if (shouldFocusOnMount()) view.focus();
|
||||
}).catch(reason => { if (!cancelled) error = String(reason); });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
refreshVersion++;
|
||||
clearTimeout(historyTimer);
|
||||
model?.pushStackElement();
|
||||
menu?.destroy();
|
||||
releaseDrop?.();
|
||||
releaseScroll?.();
|
||||
if (session && editor && scroll) session.writer = { source: editor.state.sliceDoc(), state: editor.state.toJSON({ history: historyField }), scroll };
|
||||
editor?.destroy();
|
||||
releaseSelection?.();
|
||||
editor = undefined;
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const name = markdownTitle(buffer.relPath);
|
||||
const view = editor;
|
||||
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
|
||||
});
|
||||
|
||||
$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;
|
||||
view.dispatch({ selection: { anchor }, effects: EditorView.scrollIntoView(anchor, { y: "center" }) });
|
||||
view.focus();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="live-writer" bind:this={host} role="application" aria-label="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 = ""; }}>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-prose-size)/1.75 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: 0; }
|
||||
.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-selectionBackground), .live-writer :global(.cm-focused .cm-selectionBackground) { background: var(--rs-bg-active); }
|
||||
.live-writer :global(.writer-heading) { color: var(--rs-text-strong); font-weight: 650; line-height: 1.4; }
|
||||
.live-writer :global(.writer-h1) { font-size: 2.1em; }
|
||||
.live-writer :global(.writer-h2) { font-size: 1.5em; }
|
||||
.live-writer :global(.writer-h3) { font-size: 1.2em; }
|
||||
.live-writer :global(.writer-strong) { font-weight: 650; 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-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-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-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; }
|
||||
.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; margin: 1.4em 0 0; padding: 26px; }
|
||||
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 4px; }
|
||||
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
|
||||
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1.75em; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.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