Initial RuneStone project

This commit is contained in:
Knotty Wyvern
2026-09-26 01:25:42 -07:00
commit bdc15e952d
190 changed files with 25986 additions and 0 deletions
+240
View File
@@ -0,0 +1,240 @@
<script lang="ts">
import { 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 { editorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { markdownMenu } from "./markdownMenu";
import type { TableContextActions } from "./tableCellActions";
type Props = {
buffer: OpenBuffer;
chrome: Chrome;
onChange: (value: string, id: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
tableActions?: TableContextActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
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 ? [workspaceImageLink(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;
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;
const listeners: { dispose(): void }[] = [];
void import("./monacoEnv").then(({ monaco }) => {
if (cancelled || !el.isConnected) {
return;
}
session = editorSession(monaco, untrack(() => buffer));
const mode = untrack(() => chrome);
const model = session.model;
const markdown = isMarkdownPath(untrack(() => buffer.relPath));
const view = monaco.editor.create(el, {
model,
theme: "runestone-dark",
automaticLayout: true,
fontFamily: "Cascadia Code, JetBrains Mono, Consolas, ui-monospace, monospace",
scrollBeyondLastLine: false,
smoothScrolling: true,
cursorBlinking: "smooth",
tabSize: 2,
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: !markdown,
...monacoChrome(mode),
});
editor = view;
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();
},
selectAll() { view.setSelection(model.getFullModelRange()); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { loadError = message; });
listeners.push(view.onContextMenu(event => {
event.event.preventDefault(); event.event.stopPropagation();
menu?.open(event.event.posx, event.event.posy);
}));
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);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
if (session.view) view.restoreViewState(session.view);
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();
releaseSelection?.();
menu?.destroy();
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
view?.dispose();
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="monaco-host"
role="application"
aria-label="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>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>Dismiss</button></p>{/if}
<style>
.monaco-host {
position: absolute;
inset: 0;
overflow: hidden;
}
.monaco-host :global(.monaco-editor),
.monaco-host :global(.overflow-guard) {
height: 100%;
}
</style>
+356
View File
@@ -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>
+283
View File
@@ -0,0 +1,283 @@
<script lang="ts">
import { untrack } from "svelte";
import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownBlocks } from "$lib/workspace/markdownBlocks";
import { findMarkdownImages, isRemoteImage, resolveImageRel } from "$lib/workspace/media";
import { renderMarkdownHtml } from "$lib/workspace/noteHtml";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { writerContextItems } from "./writerMenu";
type Props = {
buffer: OpenBuffer;
onChange: (value: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
};
type OpenMenu = { x: number; y: number; items: MenuItem[] } | null;
let { buffer, onChange, onInsertImage, onOpenLink }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("@tiptap/core").Editor | undefined;
let ready = $state(0);
let applying = false;
let skipUpdate = true;
let menu = $state<OpenMenu>(null);
function imageFiles(data: DataTransfer | null): File[] {
if (!data) {
return [];
}
return [...data.files].filter((file) => file.type.startsWith("image/"));
}
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
for (const block of markdownBlocks(contents)) {
if (block.type !== "text") {
continue;
}
for (const image of findMarkdownImages(block.line)) {
if (urls.has(image.src)) {
continue;
}
if (isRemoteImage(image.src)) {
urls.set(image.src, image.src.trim());
continue;
}
const primary = resolveImageRel(noteRel, image.src);
const base = image.src.replaceAll("\\", "/").split("/").pop() ?? image.src;
try {
urls.set(image.src, await workspaceReadDataUrl(primary));
} catch {
try {
urls.set(image.src, await workspaceReadDataUrl(base));
} catch {
urls.set(image.src, "");
}
}
}
}
return urls;
}
$effect(() => {
const el = host;
if (!el) {
return;
}
let cancelled = false;
void Promise.all([
import("@tiptap/core"),
import("@tiptap/starter-kit"),
import("@tiptap/extension-image"),
import("@tiptap/extension-link"),
import("@tiptap/extension-table"),
import("@tiptap/extension-superscript"),
import("@tiptap/extension-subscript"),
import("@tiptap/extension-task-list"),
import("@tiptap/extension-task-item"),
import("@tiptap/extension-highlight"),
import("./headingMarks"),
import("./writerMarks"),
]).then(async ([core, starter, imageMod, linkMod, tableMod, supMod, subMod, taskListMod, taskItemMod, highlightMod, marks, extra]) => {
if (cancelled || !el.isConnected) {
return;
}
const path = untrack(() => buffer.relPath);
const value = untrack(() => buffer.contents ?? "");
const urls = await loadUrls(path, value);
if (cancelled) {
return;
}
applying = true;
const html = renderMarkdownHtml(value, urls) || "<p></p>";
const Image = imageMod.default.extend({
addAttributes() {
return {
...this.parent?.(),
"data-md-src": { default: null },
"data-md-kind": { default: "md" },
};
},
});
const Link = linkMod.default.extend({
addAttributes() {
return {
...this.parent?.(),
"data-kind": { default: "md" },
class: { default: null },
};
},
});
const view = new core.Editor({
element: el,
extensions: [
starter.default.configure({ heading: { levels: [1, 2, 3, 4, 5, 6] } }),
Image.configure({ inline: false, allowBase64: true }),
Link.configure({ openOnClick: false, autolink: false }),
tableMod.TableKit.configure({ table: { resizable: false } }),
supMod.default,
subMod.default,
taskListMod.default,
taskItemMod.default.configure({ nested: false }),
highlightMod.default.configure({ multicolor: false }),
extra.MathMark,
extra.CommentMark,
marks.HeadingMarks,
],
content: html,
editorProps: {
attributes: { class: "reading writer-doc" },
handleDOMEvents: {
contextmenu: (pmView, event) => {
event.preventDefault();
if (!editor) {
return true;
}
const hit = pmView.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) {
const { from, to } = editor.state.selection;
if (from === to || hit.pos < from || hit.pos > to) {
editor.chain().setTextSelection(hit.pos).run();
}
}
menu = {
x: event.clientX,
y: event.clientY,
items: writerContextItems(editor),
};
return true;
},
},
handleClick: (_view, _pos, event) => {
const node = event.target instanceof Element ? event.target.closest("a") : null;
if (!node) {
return false;
}
const href = node.getAttribute("href") ?? "";
const kind = node.getAttribute("data-kind");
if (kind === "wiki") {
event.preventDefault();
onOpenLink?.("wiki", href);
return true;
}
if (kind === "md" && !/^https?:\/\//i.test(href)) {
event.preventDefault();
onOpenLink?.("md", href);
return true;
}
return false;
},
},
onCreate: () => {
applying = false;
queueMicrotask(() => {
skipUpdate = false;
});
},
onUpdate: ({ editor: current }) => {
if (applying || skipUpdate) {
return;
}
onChange(htmlToMarkdown(current.getHTML()));
},
});
editor = view;
ready += 1;
view.commands.focus("end");
});
return () => {
cancelled = true;
editor?.destroy();
editor = undefined;
};
});
$effect(() => {
void ready;
const contents = buffer.contents;
const view = editor;
if (!view) {
return;
}
if (view.isFocused) {
return;
}
const current = htmlToMarkdown(view.getHTML());
if (contents === current) {
return;
}
applying = true;
void loadUrls(buffer.relPath, contents).then((urls) => {
if (editor !== view) {
return;
}
view.commands.setContent(renderMarkdownHtml(contents, urls) || "<p></p>");
applying = false;
});
});
</script>
<div
class="writer-host"
role="application"
aria-label="Writer"
bind:this={host}
ondragover={(event) => {
if (imageFiles(event.dataTransfer).length > 0) {
event.preventDefault();
}
}}
ondrop={(event) => {
const files = imageFiles(event.dataTransfer);
if (files.length === 0 || !onInsertImage) {
return;
}
event.preventDefault();
void (async () => {
for (const file of files) {
const snippet = await onInsertImage(file);
const rel = snippet ? /\(([^)]+)\)/.exec(snippet)?.[1] : null;
if (!rel || !editor) {
continue;
}
try {
const src = await workspaceReadDataUrl(rel);
editor.commands.insertContent(
`<img src="${src}" alt="${file.name}" data-md-src="${rel}" data-md-kind="md" />`,
);
} catch {
editor.commands.insertContent(snippet);
}
}
})();
}}
></div>
{#if menu}
<ContextMenu
x={menu.x}
y={menu.y}
items={menu.items}
onClose={() => (menu = null)}
/>
{/if}
<style>
.writer-host {
position: absolute;
inset: 0;
overflow: hidden;
}
.writer-host :global(.tiptap),
.writer-host :global(.ProseMirror) {
height: 100%;
overflow: auto;
}
</style>
+90
View File
@@ -0,0 +1,90 @@
import { Extension } from "@tiptap/core";
import type { Node as PmNode } from "@tiptap/pm/model";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
export function headingMarkText(level: number): string {
const n = Math.min(6, Math.max(1, Math.floor(level)));
return "#".repeat(n);
}
export function fenceOpenText(lang: string): string {
const name = lang.trim();
return name ? `\`\`\`${name}` : "```";
}
export function findInlineCodeRange(doc: PmNode, pos: number): { from: number; to: number } | null {
const $pos = doc.resolve(pos);
const type = doc.type.schema.marks.code;
if (!type || !$pos.parent.inlineContent) {
return null;
}
const parentStart = $pos.start();
let runFrom = -1;
let runTo = -1;
let hit: { from: number; to: number } | null = null;
$pos.parent.forEach((child, offset) => {
const from = parentStart + offset;
const to = from + child.nodeSize;
if (type.isInSet(child.marks)) {
if (runFrom === -1) {
runFrom = from;
}
runTo = to;
return;
}
if (runFrom !== -1 && pos >= runFrom && pos <= runTo) {
hit = { from: runFrom, to: runTo };
}
runFrom = -1;
runTo = -1;
});
if (hit) {
return hit;
}
if (runFrom !== -1 && pos >= runFrom && pos <= runTo) {
return { from: runFrom, to: runTo };
}
return null;
}
export const HeadingMarks = Extension.create({
name: "headingMarks",
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey("headingMarks"),
props: {
decorations(state) {
const { $from } = state.selection;
if ($from.parent.type.name === "codeBlock") {
const lang = String($from.parent.attrs.language ?? "");
return DecorationSet.create(state.doc, [
Decoration.node($from.before(), $from.after(), {
class: "is-editing",
"data-fence-open": fenceOpenText(lang),
}),
]);
}
if ($from.parent.type.name === "heading") {
const level = Number($from.parent.attrs.level ?? 1);
return DecorationSet.create(state.doc, [
Decoration.node($from.before(), $from.after(), {
class: "is-editing",
"data-heading-marks": headingMarkText(level),
}),
]);
}
const range = findInlineCodeRange(state.doc, $from.pos);
if (!range) {
return DecorationSet.empty;
}
return DecorationSet.create(state.doc, [
Decoration.inline(range.from, range.to, { class: "is-editing-ticks" }),
]);
},
},
}),
];
},
});
+170
View File
@@ -0,0 +1,170 @@
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
export type ImageActions = {
edit?: () => void;
done?: () => void;
editing?: boolean;
select?: () => void;
remove?: () => void;
markdown?: () => string;
swap?: (image: HTMLImageElement) => Promise<void>;
open?: (image: HTMLImageElement) => void;
reveal?: (image: HTMLImageElement) => Promise<void>;
report?: (message: string) => void;
};
async function copyImage(image: HTMLImageElement) {
const png = (async () => {
await image.decode();
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
const context = canvas.getContext("2d");
if (!context) throw new Error("Image clipboard is unavailable.");
context.drawImage(image, 0, 0);
return await new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png"));
})();
await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]);
}
function button(label: string, icon: ActionIcon, action: () => void) {
const control = document.createElement("button");
control.type = "button";
control.className = "image-action";
control.setAttribute("aria-label", label);
control.dataset.tooltip = label;
control.append(actionIcon(icon));
control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); });
return control;
}
function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
const dialog = document.createElement("dialog");
dialog.className = "image-lightbox";
dialog.setAttribute("aria-label", "Image zoom");
const header = document.createElement("div");
header.className = "image-lightbox-toolbar";
const name = document.createElement("span");
name.className = "image-lightbox-name";
name.textContent = original.dataset.mdSrc || original.alt || "Image";
const viewport = document.createElement("div");
viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement;
image.removeAttribute("loading");
image.draggable = false;
let scale = 0;
const status = document.createElement("span");
status.className = "image-lightbox-scale";
status.setAttribute("aria-live", "polite");
function resize(next: number) {
scale = next;
image.style.width = scale ? `${image.naturalWidth * scale}px` : "";
viewport.classList.toggle("is-zoomed", scale > 0);
status.textContent = scale ? `${Math.round(scale * 100)}%` : "Fit";
zoomOut.disabled = scale === 0;
zoomIn.disabled = scale >= 4;
}
const zoomOut = button("Zoom out", "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2));
const zoomIn = button("Zoom in", "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1));
const fit = button("Fit image", "select", () => resize(0));
const close = button("Close image", "close", () => dialog.close());
header.append(name, zoomOut, status, zoomIn, fit, close);
viewport.append(image);
dialog.append(header, viewport);
dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); });
// Escape and focus trapping are provided by the native modal dialog.
dialog.addEventListener("close", () => { dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
image.addEventListener("load", () => resize(scale));
document.body.append(dialog);
dialog.showModal();
resize(0);
close.focus();
return () => { if (dialog.isConnected) dialog.close(); };
}
export function imageControls(root: HTMLElement, actions: ImageActions = {}, measure?: () => void): () => void {
const cleanup: (() => void)[] = [];
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
if (image.closest(".md-image-frame")) continue;
const frame = document.createElement("span");
frame.className = "md-image-frame";
frame.contentEditable = "false";
frame.tabIndex = 0;
frame.setAttribute("role", "group");
frame.setAttribute("aria-label", `Image: ${image.alt || image.dataset.mdSrc || "image"}`);
image.replaceWith(frame);
frame.append(image);
image.draggable = false;
const toolbar = document.createElement("span");
toolbar.className = "md-image-actions";
let closeZoom: (() => void) | undefined;
const zoom = button("Zoom in", "zoom-in", () => { closeZoom = zoomImage(image, zoom); });
cleanup.push(() => closeZoom?.());
toolbar.append(zoom);
if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit));
frame.append(toolbar);
let menu: HTMLElement | undefined;
let openingMenu = false;
function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); }
async function run(action: () => void | Promise<void>) {
closeMenu(false);
try { await action(); } catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (actions.report) actions.report(message);
else { frame.dataset.error = message; frame.setAttribute("aria-description", message); }
}
}
function select() {
actions.select?.();
frame.classList.add("is-selected");
frame.focus({ preventScroll: true });
}
function openMenu(x: number, y: number) {
closeMenu(false); select();
const items: ActionMenuItem[] = [
{ label: "Copy image", icon: "copy", run: () => void run(() => copyImage(image)) },
...(actions.markdown ? [{ label: "Copy Markdown", icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []),
...(actions.swap ? [{ label: "Swap image…", icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []),
...(actions.remove ? [{ label: "Remove image", icon: "trash" as const, run: () => void run(actions.remove!) }] : []),
{ separator: true },
{ label: "Zoom in", icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } },
...(actions.edit ? [{ label: "Edit image source", icon: "code" as const, run: () => void run(actions.edit!) }] : []),
...(actions.open ? [{ label: "Open in new tab", icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []),
{ label: "Copy path", icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) },
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: "Show in Explorer", icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
];
openingMenu = true;
try { menu = actionMenu(x, y, items, closeMenu, "Image actions"); }
finally { openingMenu = false; }
}
frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } });
frame.addEventListener("contextmenu", event => { event.preventDefault(); event.stopPropagation(); openMenu(event.clientX, event.clientY); });
frame.addEventListener("keydown", event => {
if (event.target !== frame) return;
if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
event.preventDefault(); event.stopPropagation(); const rect = frame.getBoundingClientRect(); openMenu(rect.left + 16, rect.top + 16);
} else if ((event.key === "Delete" || event.key === "Backspace") && actions.remove) {
event.preventDefault(); event.stopPropagation(); actions.remove();
} else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c") {
event.preventDefault(); event.stopPropagation(); void run(() => copyImage(image));
} else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); }
});
const outside = (event: Event) => {
if (openingMenu) return;
if (event.target instanceof Node && !frame.contains(event.target) && !menu?.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); }
};
const dismiss = () => closeMenu(false);
const scroll = (event: Event) => { if (menu && event.target instanceof Node && !menu.contains(event.target)) closeMenu(false); };
document.addEventListener("mousedown", outside, true);
document.addEventListener("focusin", outside, true);
window.addEventListener("resize", dismiss);
document.addEventListener("scroll", scroll, true);
cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); window.removeEventListener("resize", dismiss); document.removeEventListener("scroll", scroll, true); });
if (measure) {
image.addEventListener("load", measure);
image.addEventListener("error", measure);
cleanup.push(() => { image.removeEventListener("load", measure); image.removeEventListener("error", measure); });
}
}
return () => cleanup.forEach(dispose => dispose());
}
+18
View File
@@ -0,0 +1,18 @@
import { StateEffect, StateField } from "@codemirror/state";
export const trackImageDrop = StateEffect.define<{ id: symbol; from: number; to: number }>();
export const clearImageDrop = StateEffect.define<symbol>();
export const imageDrops = StateField.define<Map<symbol, { from: number; to: number }>>({
create: () => new Map(),
update(value, transaction) {
const next = new Map([...value].map(([id, range]) => [id, {
from: transaction.changes.mapPos(range.from, 1),
to: transaction.changes.mapPos(range.to, 1),
}]));
for (const effect of transaction.effects) {
if (effect.is(trackImageDrop)) next.set(effect.value.id, effect.value);
if (effect.is(clearImageDrop)) next.delete(effect.value);
}
return next;
},
});
+76
View File
@@ -0,0 +1,76 @@
import { EditorView, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { imageControls, type ImageActions } from "./imageControls";
import { editImageSource } from "./imageSource";
import { requestText } from "../workspace/dialogs.svelte";
import { isRemoteImage } from "../workspace/media";
import { actionIcon } from "../ui/actionIcons";
export type ImageContext = {
open?: (image: HTMLImageElement) => void;
reveal?: (image: HTMLImageElement) => Promise<void>;
validate?: (source: string) => Promise<void>;
report?: (message: string) => void;
};
const cleanups = new WeakMap<HTMLElement, () => void>();
export class ImagePreview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
toDOM(view: EditorView) {
const dom = document.createElement(this.block ? "div" : "span");
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
dom.innerHTML = this.html;
const range = () => {
const position = view.posAtDOM(dom);
const from = this.editing ? position - this.source.length : position;
return { from, to: from + this.source.length };
};
const replace = (insert: string) => {
if (!dom.isConnected) return;
const target = range();
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, effects: editImageSource.of(null), annotations: isolateHistory.of("full"), userEvent: "input.image" });
view.focus();
};
const actions: ImageActions = {
editing: this.editing,
select: () => { const { from, to } = range(); view.dispatch({ selection: { anchor: from, head: to } }); },
edit: () => {
const target = range();
view.dispatch({ effects: [editImageSource.of(target), EditorView.scrollIntoView(target.from, { y: "nearest" })], selection: { anchor: target.from, head: target.to } });
view.focus();
},
done: () => { view.dispatch({ effects: editImageSource.of(null) }); view.focus(); },
remove: () => replace(""),
markdown: () => this.source,
open: this.context.open,
reveal: this.context.reveal,
report: this.context.report,
swap: async image => {
const before = view.state.doc;
const path = (await requestText("Image path relative to this note, or https URL", image.dataset.mdSrc || ""))?.trim();
if (!path || !dom.isConnected || view.state.doc !== before) return;
if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error("Choose a workspace image path or an http/https URL.");
await this.context.validate?.(path);
if (!dom.isConnected || view.state.doc !== before) return;
const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char));
const alt = image.alt.replace(/[\\\[\]]/g, "\\$&");
replace(`![${alt}](<${target}>)`);
},
};
cleanups.set(dom, imageControls(dom, actions, () => { if (dom.isConnected) view.requestMeasure(); }));
// A missing attachment must still offer a way to repair its hidden source.
if (!dom.querySelector("img")) {
const edit = document.createElement("button");
edit.type = "button"; edit.className = "image-action";
const label = this.editing ? "Hide image source" : "Edit image source";
edit.setAttribute("aria-label", label); edit.dataset.tooltip = label;
edit.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
dom.append(edit);
}
return dom;
}
destroy(dom: HTMLElement) { cleanups.get(dom)?.(); }
ignoreEvent() { return true; }
}
+22
View File
@@ -0,0 +1,22 @@
import { StateEffect, StateField } from "@codemirror/state";
import { markdownLanguage } from "@codemirror/lang-markdown";
export type ImageRange = { from: number; to: number };
export function imageSourceRanges(source: string): ImageRange[] {
const ranges: ImageRange[] = [];
// Image controls must also work beyond CodeMirror's partially parsed viewport.
markdownLanguage.parser.parse(source).iterate({ enter(node) {
if (node.name === "Image") { ranges.push({ from: node.from, to: node.to }); return false; }
} });
return ranges;
}
export const editImageSource = StateEffect.define<ImageRange | null>();
export const imageSource = StateField.define<ImageRange | null>({
create: () => null,
update(value, transaction) {
if (value) value = { from: transaction.changes.mapPos(value.from, -1), to: transaction.changes.mapPos(value.to, 1) };
for (const effect of transaction.effects) if (effect.is(editImageSource)) value = effect.value;
if (value && transaction.selection && !transaction.selection.ranges.some(range => range.from <= value.to && range.to >= value.from)) return null;
return value;
},
});
+39
View File
@@ -0,0 +1,39 @@
const LANGUAGES: Record<string, string> = {
md: "markdown",
markdown: "markdown",
mdown: "markdown",
txt: "plaintext",
py: "python",
js: "javascript",
mjs: "javascript",
cjs: "javascript",
ts: "typescript",
tsx: "typescript",
jsx: "javascript",
json: "json",
css: "css",
scss: "scss",
html: "html",
htm: "html",
rs: "rust",
sh: "shell",
bash: "shell",
yml: "yaml",
yaml: "yaml",
toml: "ini",
xml: "xml",
svg: "xml",
};
function fileExt(relPath: string): string {
const base = relPath.split("/").pop() ?? relPath;
const dot = base.lastIndexOf(".");
if (dot <= 0) {
return "";
}
return base.slice(dot + 1).toLowerCase();
}
export function languageFor(relPath: string): string {
return LANGUAGES[fileExt(relPath)] ?? "plaintext";
}
+173
View File
@@ -0,0 +1,173 @@
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
import { tableControls, tableEditors } from "./tableControls";
import { parseMarkdownTable } from "./markdownTable";
import type { TableContextActions } from "./tableCellActions";
import { imageControls } from "./imageControls";
import { ImagePreview, type ImageContext } from "./imagePreview";
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
class Checkbox extends WidgetType {
constructor(readonly checked: boolean) { super(); }
eq(other: Checkbox) { return this.checked === other.checked; }
toDOM(view: EditorView) {
const box = document.createElement("input");
box.type = "checkbox";
box.checked = this.checked;
box.className = "writer-checkbox";
box.setAttribute("aria-label", this.checked ? "Mark task incomplete" : "Mark task complete");
box.addEventListener("mousedown", event => event.preventDefault());
box.addEventListener("click", event => {
event.stopPropagation();
const line = view.state.doc.lineAt(view.posAtDOM(box));
const match = /^(\s*[-+*]\s+\[)([ xX])(\])/.exec(line.text);
if (!match) return;
const from = line.from + match[1].length;
view.dispatch({ changes: { from, to: from + 1, insert: this.checked ? " " : "x" }, userEvent: "input" });
});
return box;
}
ignoreEvent() { return true; }
}
class Preview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false) { super(); }
eq(other: Preview) { return other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
updateDOM(dom: HTMLElement) { return tableEditors.get(dom)?.source === this.source; }
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
toDOM(view: EditorView) {
const dom = document.createElement("div");
dom.className = "reading writer-preview";
dom.innerHTML = this.html;
tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
if (event.target instanceof Element && event.target.closest("summary, .md-image-frame")) return;
if (event.ctrlKey || event.metaKey) return;
event.preventDefault();
view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true });
view.focus();
});
requestAnimationFrame(() => {
if (dom.isConnected) {
void renderDiagrams(dom, () => !dom.isConnected).then(() => view.requestMeasure());
view.requestMeasure();
}
});
return dom;
}
ignoreEvent() { return true; }
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
function build(state: EditorState): DecorationSet {
const ranges: Range<Decoration>[] = [];
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
const selected = (from: number, to: number) => active.some(range => range.from <= to && range.to >= from);
const hiddenBlocks: { from: number; to: number }[] = [];
const source = state.doc.toString();
const editing = state.field(imageSource);
const imageNodes = imageSourceRanges(source);
for (const section of renderMarkdownSections(source, urls)) {
if (!/(?:<pre|<table|<img|md-properties|md-callout|missing-image)/.test(section.html)) continue;
// The first rendered section includes leading blank lines. Keep those
// editable when the user exits above a table at the start of a note.
if (/<table>/.test(section.html)) section.start += /^(?:[ \t]*\r?\n)+/.exec(source.slice(section.start, section.end))?.[0].length ?? 0;
const end = section.end - (source.slice(section.start, section.end).match(/\n+$/)?.[0].length || 0);
const isTable = /<table>/.test(section.html) && parseMarkdownTable(source.slice(section.start, end));
if (end <= section.start) continue;
const imageHtml = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g) || [];
const nodes = imageNodes.filter(node => node.from >= section.start && node.to <= end);
if (!isTable && imageHtml.length && imageHtml.length === nodes.length && (!/md-callout/.test(section.html) || selected(section.start, end))) {
nodes.forEach((node, index) => {
const revealed = editing?.from === node.from;
const block = state.doc.lineAt(node.from).from === node.from && state.doc.lineAt(node.to).to === node.to;
const widget = new ImagePreview(imageHtml[index], source.slice(node.from, node.to), images, revealed, revealed || block);
if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to));
else {
hiddenBlocks.push(node);
ranges.push(Decoration.replace({ widget, block }).range(node.from, node.to));
}
});
continue;
}
if (!isTable && selected(section.start, end)) {
// Keep images below the editable source, without duplicating surrounding prose.
const images = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g)?.join("");
if (images) ranges.push(Decoration.widget({ widget: new Preview(images, source.slice(section.start, end), actions, true), block: true, side: 1 }).range(end));
continue;
}
hiddenBlocks.push({ from: section.start, to: end });
ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions), block: true }).range(section.start, end));
}
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({}).range(from, to)); };
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
const codeRanges: { from: number; to: number }[] = [];
syntaxTree(state).iterate({ enter(node) {
if (hidden(node.from, node.to)) return false;
if (node.name === "FencedCode" || node.name === "CodeBlock") {
codeRanges.push({ from: node.from, to: node.to });
mark(node.from, node.to, "writer-code-source");
return false;
}
const line = state.doc.lineAt(node.from);
if (/^ATXHeading[1-6]$/.test(node.name)) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
}
if (selected(node.from, node.to)) return;
if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1));
if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong");
if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis");
if (node.name === "Strikethrough") mark(node.from, node.to, "writer-strike");
if (node.name === "InlineCode") mark(node.from, node.to, "writer-inline-code");
if (node.name === "NoteHighlight") mark(node.from, node.to, "writer-highlight");
if (node.name === "NoteMath") mark(node.from, node.to, "writer-math");
if (node.name === "NoteComment") mark(node.from, node.to, "writer-comment");
if (["EmphasisMark", "StrikethroughMark", "CodeMark", "NoteFormatMark"].includes(node.name)) replace(node.from, node.to);
if (node.name === "Link") {
// Wiki links are handled separately, because CommonMark sees their inner
// brackets as an incomplete reference link.
if (source[node.from - 1] === "[" && source[node.to] === "]") return false;
const text = source.slice(node.from, node.to);
const match = /^\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)$/.exec(text);
if (!match) return;
replace(node.from, node.from + 1);
replace(node.from + 1 + match[1].length, node.to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", title: "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
return false;
}
if (node.name === "TaskMarker") {
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
if (!match) return;
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x") }).range(line.from + match[1].length, line.from + match[0].length));
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
}
} });
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
const from = match.index, to = from + match[0].length;
if (selected(from, to) || hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
const separator = match[1].indexOf("|");
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
replace(from, labelStart);
replace(to - 2, to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0] } }).range(labelStart, to - 2));
}
return Decoration.set(ranges, true);
}
return [imageSource, StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state) : value;
},
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field))],
})];
}
+93
View File
@@ -0,0 +1,93 @@
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
export type TextSelection = { from: number; to: number };
export type MarkdownEdit = TextSelection & { insert: string; anchor: number; head: number };
export type InlineFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear";
export type ParagraphStyle = "bullet" | "number" | "task" | "body" | "quote" | 1 | 2 | 3 | 4 | 5 | 6;
export type InsertBlock = "footnote" | "table" | "callout" | "rule" | "code" | "math";
export function replacement(selection: TextSelection, insert: string, start = 0, end = insert.length): MarkdownEdit {
return { ...selection, insert, anchor: selection.from + start, head: selection.from + end };
}
export function formatText(source: string, selection: TextSelection, format: InlineFormat): MarkdownEdit {
let { from, to } = selection;
const selected = source.slice(from, to);
if (format === "clear") {
let marker: string | undefined;
do {
marker = ["**", "__", "~~", "==", "%%", "*", "_", "$", "`"].find(value => source.slice(0, from).endsWith(value) && source.slice(to).startsWith(value));
if (marker) { from -= marker.length; to += marker.length; }
} while (marker);
// The inline serializer uses <br> in tables; retain real newlines in prose.
return replacement({ from, to }, plainInlineMarkdown(source.slice(from, to)).replace(/<br>/g, source.includes("\r\n") ? "\r\n" : "\n"));
}
let marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format];
// Ignore boundary whitespace so emphasis stays valid Markdown.
if (selected.trim()) { from += selected.length - selected.trimStart().length; to -= selected.length - selected.trimEnd().length; }
const text = source.slice(from, to);
if (format === "code") {
const wrapped = /^(`+)([\s\S]+)\1$/.exec(text);
if (wrapped && !wrapped[2].startsWith("`") && !wrapped[2].endsWith("`")) return replacement({ from, to }, wrapped[2].replace(/^ (.*) $/s, "$1"));
const before = /(`+) ?$/.exec(source.slice(0, from)), after = /^ ?(`+)/.exec(source.slice(to));
if (before && after && before[1] === after[1]) return replacement({ from: from - before[0].length, to: to + after[0].length }, text);
}
const isWrapped = text.startsWith(marker) && text.endsWith(marker) && text.length >= marker.length * 2
&& !(format === "italic" && text.startsWith("**") && !text.startsWith("***"));
if (isWrapped) return replacement({ from, to }, text.slice(marker.length, -marker.length));
const before = source.slice(0, from), after = source.slice(to);
const surrounds = before.endsWith(marker) && after.startsWith(marker)
&& !(format === "italic" && before.endsWith("**") && !before.endsWith("***"));
if (surrounds) return replacement({ from: from - marker.length, to: to + marker.length }, text);
if (format === "code") marker = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1);
const padding = format === "code" && /^`|`$/.test(text) ? " " : "";
return replacement({ from, to }, marker + padding + text + padding + marker, marker.length + padding.length, marker.length + padding.length + text.length);
}
export function paragraphText(source: string, selection: TextSelection, style: ParagraphStyle): MarkdownEdit {
const from = selection.from === 0 ? 0 : source.lastIndexOf("\n", selection.from - 1) + 1;
// A selection ending at the start of the next line must not format that line.
const last = selection.to > selection.from && source[selection.to - 1] === "\n" ? selection.to - 1 : selection.to;
const newline = source.indexOf("\n", last);
const to = newline < 0 ? source.length : newline > 0 && source[newline - 1] === "\r" ? newline - 1 : newline;
const eol = source.includes("\r\n") ? "\r\n" : "\n";
let number = 0;
const insert = source.slice(from, to).split(/\r?\n/).map(line => {
if (!line.trim() && from !== to) { number = 0; return line; }
const indent = /^[\t ]*/.exec(line)![0];
const body = line.slice(indent.length).replace(/^(?:#{1,6}\s+|>\s?|(?:[-+*]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)/, "");
const prefix = typeof style === "number" ? "#".repeat(style) + " " : { bullet: "- ", number: `${++number}. `, task: "- [ ] ", quote: "> ", body: "" }[style];
return indent + prefix + body;
}).join(eol);
return replacement({ from, to }, insert, selection.from === selection.to ? insert.length : 0);
}
export function insertBlock(source: string, selection: TextSelection, kind: InsertBlock): MarkdownEdit {
const eol = source.includes("\r\n") ? "\r\n" : "\n";
const text = source.slice(selection.from, selection.to);
if (kind === "footnote") {
let id = 1;
while (source.includes(`[^${id}]`)) id++;
const reference = `[^${id}]`, definition = (text || "Footnote text").replace(/\r?\n/g, eol + " ");
const tail = source.slice(selection.to);
const beforeDefinition = reference + tail;
const gap = beforeDefinition.endsWith(eol + eol) ? "" : beforeDefinition.endsWith(eol) ? eol : eol + eol;
const insert = beforeDefinition + gap + reference + ": " + definition + eol;
const start = beforeDefinition.length + gap.length + reference.length + 2;
return replacement({ from: selection.from, to: source.length }, insert, start, start + definition.length);
}
const fence = "`".repeat(Math.max(2, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1);
const content = text || (kind === "code" ? "Code" : kind === "math" ? "equation" : "Callout text");
let block = kind === "table" ? "| Column 1 | Column 2 |\n| --- | --- |\n| | |"
: kind === "rule" ? "---" : kind === "code" ? `${fence}\n${content}\n${fence}`
: kind === "math" ? `$$\n${content}\n$$` : `> [!note]\n> ${content.replace(/\r?\n/g, "\n> ")}`;
block = block.replace(/\r?\n/g, eol);
// Structural inserts should not delete selected prose.
const at = kind === "table" || kind === "rule" ? { from: selection.to, to: selection.to } : selection;
const before = source.slice(0, at.from), after = source.slice(at.to);
const leading = !before || before.endsWith(eol + eol) ? "" : before.endsWith(eol) ? eol : eol + eol;
const trailing = after.startsWith(eol + eol) ? "" : after.startsWith(eol) ? eol : eol + eol;
const start = kind === "table" ? block.indexOf("Column 1") : kind === "rule" ? block.length : block.indexOf(eol) + eol.length + (kind === "callout" ? 2 : 0);
const length = kind === "table" ? 8 : kind === "rule" ? 0 : content.length;
return replacement(at, leading + block + trailing, leading.length + start, leading.length + start + length);
}
+122
View File
@@ -0,0 +1,122 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { requestText } from "../workspace/dialogs.svelte";
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
import { cellFormats, type TableContextActions } from "./tableCellActions";
import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands";
export type MarkdownMenuEditor = {
snapshot: () => { source: string; selection: TextSelection; valid: () => boolean };
apply: (edit: MarkdownEdit) => void;
selectAll: () => void;
focus: () => void;
};
// A shared controller keeps menus, async selection guards, and clipboard behavior
// identical in the writing editor and the source editor.
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) {
let root: HTMLElement | undefined, destroyed = false;
function close(focus = true) {
root?.remove(); root = undefined;
if (focus && !destroyed) editor.focus();
}
const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); };
const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
close(false);
const snapshot = editor.snapshot(), { source, selection } = snapshot;
const text = source.slice(selection.from, selection.to);
const valid = () => !destroyed && snapshot.valid();
function apply(edit: MarkdownEdit) {
if (!valid()) return;
close(); editor.apply(edit); editor.focus();
}
async function request(run: () => Promise<void>) {
close(false);
try { await run(); } catch (error) { if (!destroyed) report(error instanceof Error ? error.message : String(error)); }
finally { if (valid()) editor.focus(); }
}
function link(external: boolean) {
void request(async () => {
const target = (await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text))?.trim();
if (!target || !valid()) return;
if (external) {
try {
const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error();
} catch { report("Enter a valid http, https, or mailto link."); return; }
const label = (text || target).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " ");
apply(replacement(selection, `[${label}](${target.replace(/[()<>]/g, char => encodeURIComponent(char).replace("(", "%28").replace(")", "%29"))})`));
} else {
if (/[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
const label = text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim();
apply(replacement(selection, `[[${target}${label && label !== target ? "|" + label : ""}]]`));
}
});
}
function clipboard(kind: "cut" | "copy" | "paste" | "plain") {
void request(async () => {
try {
if (kind === "cut" || kind === "copy") {
await navigator.clipboard.writeText(text);
if (kind === "cut") apply(replacement(selection, ""));
} else {
let value = "";
if (kind === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
if (rich) value = htmlToMarkdown(await (await rich.getType("text/html")).text());
} catch { /* Fall back to the text clipboard on older WebViews. */ }
}
if (!value) value = await navigator.clipboard.readText();
if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n")));
}
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) });
const items: ActionMenuItem[] = [
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const target = await actions.onExtract?.(text, text, valid);
if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`));
}) },
{ label: "Format", icon: "format", children: cellFormats.flatMap(([label, kind]) => [
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
{ label, icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
]) },
{ label: "Paragraph", icon: "paragraph", children: [
paragraph("Bullet list", "bullet", "bullet"), paragraph("Numbered list", "number", "number"), paragraph("Task list", "task", "task"),
{ separator: true },
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(`Heading ${level}`, level, "heading")),
paragraph("Body", "body", "paragraph"), { separator: true }, paragraph("Quote", "quote", "quote"),
] },
{ label: "Insert", icon: "insert", children: [
insert("Footnote", "footnote", "footnote"), insert("Table", "table", "table"), insert("Callout", "callout", "quote"), insert("Horizontal rule", "rule", "rule"),
{ separator: true }, insert("Code block", "code", "code"), insert("Math block", "math", "math"),
] },
{ separator: true },
{ label: "Cut", icon: "cut", disabled: !text, run: () => clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: !text, run: () => clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
];
root = actionMenu(x, y, items, close, "Markdown text actions");
}
return { open, close, destroy() {
destroyed = true; close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
} };
}
+74
View File
@@ -0,0 +1,74 @@
export type TableCell = { text: string; from: number; to: number };
export type TableRow = { from: number; to: number; indent: string; cells: TableCell[] };
export type MarkdownTable = { rows: TableRow[]; columns: number; eol: string; end: number };
function row(text: string, from: number): TableRow {
const pipes: number[] = [];
for (let index = 0; index < text.length; index++) {
if (text[index] !== "|") continue;
let slashes = 0;
for (let before = index - 1; before >= 0 && text[before] === "\\"; before--) slashes++;
if (slashes % 2 === 0) pipes.push(index);
}
const start = text.search(/\S/);
const end = text.trimEnd().length;
const left = pipes[0] === start ? pipes.shift()! + 1 : 0;
const right = pipes.at(-1) === end - 1 ? pipes.pop()! : text.length;
const boundaries = [left - 1, ...pipes, right];
const cells = boundaries.slice(0, -1).map((boundary, index) => {
const rawFrom = boundary + 1, rawTo = boundaries[index + 1];
const raw = text.slice(rawFrom, rawTo);
const leading = raw.length - raw.trimStart().length;
const cellFrom = from + rawFrom + leading;
return { text: raw.trim(), from: cellFrom, to: Math.max(cellFrom, from + rawTo - (raw.length - raw.trimEnd().length)) };
});
return { from, to: from + text.length, indent: /^\s*/.exec(text)![0], cells };
}
export function parseMarkdownTable(source: string): MarkdownTable | null {
const rows: TableRow[] = [];
let offset = 0;
const eol = source.includes("\r\n") ? "\r\n" : "\n";
for (const line of source.split(eol)) {
if (!line.trim()) break;
rows.push(row(line, offset));
offset += line.length + eol.length;
}
if (rows.length < 2 || !source.slice(rows[0].from, rows[0].to).includes("|")) return null;
const columns = rows[0].cells.length;
if (rows[1].cells.length !== columns || !rows[1].cells.every(cell => /^:?-+:?$/.test(cell.text))) return null;
return { rows, columns, eol, end: rows.at(-1)!.to };
}
export function appendTableColumn(source: string): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const body = table.rows.map((row, index) => {
const cells = row.cells.map(cell => cell.text);
while (cells.length < table.columns) cells.push("");
cells.splice(table.columns, 0, index === 1 ? "---" : "");
return `${row.indent}| ${cells.join(" | ")} |`;
}).join(table.eol);
return body + source.slice(table.end);
}
export function appendTableRow(source: string): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const row = `${table.rows[0].indent}| ${Array.from({ length: table.columns }, () => "").join(" | ")} |`;
return source.slice(0, table.end) + table.eol + row + source.slice(table.end);
}
// Change only the selected cell: padding, alignment, and every other row stay intact.
export function replaceTableCell(source: string, rowIndex: number, column: number, text: string): string {
const table = parseMarkdownTable(source);
if (!table || rowIndex === 1 || column < 0 || column >= table.columns || /[\r\n]/.test(text)) return source;
const row = table.rows[rowIndex];
if (!row) return source;
const cell = row.cells[column];
if (cell) return source.slice(0, cell.from) + text + source.slice(cell.to);
const cells = row.cells.map(cell => cell.text);
while (cells.length <= column) cells.push("");
cells[column] = text;
return source.slice(0, row.from) + `${row.indent}| ${cells.join(" | ")} |` + source.slice(row.to);
}
+1
View File
@@ -0,0 +1 @@
declare module "monaco-editor-css";
+30
View File
@@ -0,0 +1,30 @@
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 },
fontSize: 16,
lineHeight: 26,
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 },
fontSize: 14,
lineHeight: 22,
folding: true,
glyphMargin: true,
lineDecorationsWidth: 10,
padding: { top: 8, bottom: 24 },
renderLineHighlight: "line" as const,
};
}
+32
View File
@@ -0,0 +1,32 @@
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" });
},
};
monaco.editor.defineTheme("runestone-dark", {
base: "vs-dark",
inherit: true,
rules: [],
colors: {
"editor.background": "#141414",
"editor.foreground": "#e6e6e6",
"editor.lineHighlightBackground": "#ffffff0d",
"editor.selectionBackground": "#264f78",
"editorCursor.foreground": "#82aaff",
"editorLineNumber.foreground": "#5a5a5a",
"editorLineNumber.activeForeground": "#c8c8c8",
"editorGutter.background": "#141414",
"editorWidget.background": "#1c1c1c",
"editorWidget.border": "#2e2e2e",
"minimap.background": "#1c1c1c",
"editorIndentGuide.background1": "#2e2e2e",
"editorIndentGuide.activeBackground1": "#3e3e3e",
},
});
export { monaco };
+99
View File
@@ -0,0 +1,99 @@
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
type RenameTitle = (title: string) => Promise<void>;
class NoteTitle extends WidgetType {
constructor(readonly title: string, readonly rename?: RenameTitle) { super(); }
eq(other: NoteTitle) { return this.title === other.title && this.rename === other.rename; }
toDOM(view: EditorView) {
// Contain heading margins so CodeMirror measures the full block height.
const block = document.createElement("div");
block.style.display = "flow-root";
const heading = document.createElement("h1");
heading.className = "document-title";
heading.textContent = this.title;
block.append(heading);
if (!this.rename) return block;
const button = document.createElement("button");
button.type = "button";
button.className = "note-title-button";
button.setAttribute("aria-label", "Rename note");
button.append(document.createTextNode(this.title), actionIcon("rename"));
const help = document.createElement("span");
help.className = "note-title-help";
help.textContent = "Rename note";
help.setAttribute("role", "tooltip");
button.append(help);
heading.replaceChildren(button);
const input = document.createElement("input");
input.className = "note-title-input";
input.setAttribute("aria-label", "Note filename");
input.autocomplete = "off";
input.spellcheck = false;
input.hidden = true;
heading.append(input);
const message = document.createElement("p");
message.className = "note-title-error";
message.setAttribute("role", "alert");
message.hidden = true;
block.append(message);
let editing = false, pending = false;
const finish = () => {
editing = false;
input.hidden = true;
button.hidden = false;
message.hidden = true;
input.removeAttribute("aria-invalid");
view.requestMeasure();
};
const commit = async (focusEditor: boolean) => {
if (!editing || pending) return;
pending = true;
input.readOnly = true;
input.setAttribute("aria-busy", "true");
try {
await this.rename!(input.value);
finish();
if (focusEditor && view.dom.isConnected && (document.activeElement === input || document.activeElement === document.body)) view.focus();
} catch (reason) {
if (!block.isConnected) return;
input.setAttribute("aria-invalid", "true");
message.textContent = reason instanceof Error ? reason.message : String(reason);
message.hidden = false;
view.requestMeasure();
} finally {
pending = false;
input.readOnly = false;
input.removeAttribute("aria-busy");
}
};
button.onclick = () => {
editing = true;
input.value = this.title;
button.hidden = true;
input.hidden = false;
input.focus();
input.select();
view.requestMeasure();
};
input.onblur = () => { void commit(false); };
input.onkeydown = event => {
event.stopPropagation();
if (event.isComposing) return;
if (event.key === "Enter") { event.preventDefault(); void commit(true); }
if (event.key === "Escape" && !pending) { event.preventDefault(); finish(); button.focus(); }
};
return block;
}
ignoreEvent() { return true; }
}
// Filename editing stays outside the Markdown and its undo history.
export function noteTitle(title: string, rename?: RenameTitle) {
return EditorView.decorations.of(Decoration.set([
Decoration.widget({ widget: new NoteTitle(title, rename), block: true, side: -1 }).range(0),
]));
}
+10
View File
@@ -0,0 +1,10 @@
// Readers retain editor selection when toolbar buttons take focus.
let current: { id: string; read: () => string } | undefined;
export function registerSelection(id: string, read: () => string): () => void {
const owner = { id, read };
current = owner;
return () => { if (current === owner) current = undefined; };
}
export function selectedEditorText(id?: string): string {
return current && current.id === id ? current.read() : "";
}
+30
View File
@@ -0,0 +1,30 @@
import type * as Monaco from "monaco-editor";
import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
};
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
return session;
}
export function retainEditorSessions(ids: string[]) {
const retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id)) { session.model.dispose(); sessions.delete(id); }
}
}
+98
View File
@@ -0,0 +1,98 @@
import type { Editor, JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown";
import type { ActionMenuItem } from "../ui/actionMenu";
export type TableContextActions = {
onSearch?: (text: string) => void;
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
};
export const cellFormats = [
["Bold", "bold"], ["Italic", "italic"], ["Strikethrough", "strike"], ["Highlight", "highlight"],
["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"],
] as const;
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void): ActionMenuItem[] {
const selection = editor.state.selection, doc = editor.state.doc;
const text = doc.textBetween(selection.from, selection.to, "\n");
const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection);
function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); }
async function request(command: () => Promise<void>) {
pending(true); close();
try { await command(); } catch (error) { report(error instanceof Error ? error.message : String(error)); }
finally { pending(false); if (!editor.isDestroyed) editor.view.focus(); }
}
function link(external: boolean) {
void request(async () => {
const target = await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text);
if (!target || !valid()) return;
if (external) {
try {
const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL");
} catch { report("Enter a valid http, https, or mailto link."); return; }
}
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
run(() => {
const attrs = { href: target, "data-kind": external ? "md" : "wiki" };
if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] });
else editor.commands.setMark("link", attrs);
});
});
}
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
await request(async () => {
try {
if (action === "copy" || action === "cut") {
await navigator.clipboard.writeText(text);
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
} else {
let html = "", value = "";
if (action === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
if (rich) html = await (await rich.getType("text/html")).text();
const plain = data.find(item => item.types.includes("text/plain"));
if (plain) value = await (await plain.getType("text/plain")).text();
} catch { /* Text clipboard is also supported on older WebViews. */ }
}
if (!html && !value) value = await navigator.clipboard.readText();
if (!html && !value) return;
run(() => {
if (html) editor.commands.insertContent(html);
else {
const nodes: JSONContent[] = [];
value.replace(/\r\n?/g, "\n").split("\n").forEach((line, i) => { if (i) nodes.push({ type: "hardBreak" }); if (line) nodes.push({ type: "text", text: line, marks: [] }); });
editor.commands.insertContent(nodes);
}
});
}
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
return [
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null;
const markdown = extractedCellMarkdown(selected || []);
const target = await actions.onExtract?.(markdown, text, valid);
if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); });
}) },
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, disabled: selection.empty, run: () => run(() => {
if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind);
}) })) },
{ label: "Paragraph", icon: "paragraph", disabled: true, title: "Markdown table cells contain inline text" },
{ label: "Insert", icon: "insert", disabled: true, title: "Use the Row and Column menus to change the table" },
{ separator: true },
{ label: "Cut", icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => void clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
];
}
+63
View File
@@ -0,0 +1,63 @@
import type { JSONContent } from "@tiptap/core";
import { isTableFormula } from "./tableFormulas.ts";
// Extract inline content into a note without confusing literal <br> in code
// with actual cell hard breaks.
export function extractedCellMarkdown(nodes: JSONContent[]): string {
return nodes.map(node => {
if (node.type === "hardBreak") return "\n";
if (node.type === "paragraph") return extractedCellMarkdown(node.content || []);
return tableCellMarkdown(node);
}).join("");
}
function literal(text: string): string {
return text.replace(/&/g, "&amp;").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`).replace(/\r?\n/g, "<br>");
}
function wrap(text: string, marker: string): string {
const [, before, body, after] = /^(\s*)([\s\S]*?)(\s*)$/.exec(text)!;
return body ? `${before}${marker}${body}${marker}${after}` : text;
}
// A cell is inline Markdown. Paragraphs from pasted text become safe table breaks.
export function tableCellMarkdown(node: JSONContent): string {
// Keep plain formula input as readable source. Formatted/code/escaped text
// still follows ordinary Markdown serialization and remains literal.
if (node.type === "doc" && node.content?.length === 1 && node.content[0].type === "paragraph") {
const children = node.content[0].content || [];
const text = children.map(child => child.text || "").join("");
if (children.every(child => child.type === "text" && !child.marks?.length) && (isTableFormula(text) || /^\s*\\=(?!=)/.test(text))) return text.replace(/\|/g, "\\|");
}
if (node.type === "hardBreak") return "<br>";
if (node.type === "image") {
const source = String(node.attrs?.["data-md-src"] || node.attrs?.src || "");
const alt = String(node.attrs?.alt || "");
return node.attrs?.["data-md-kind"] === "wiki"
? `![[${literal(source)}${alt && alt !== source ? `\\|${literal(alt)}` : ""}]]`
: `![${literal(alt)}](<${source.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`;
}
let text = node.text === undefined
? (node.content || []).map(tableCellMarkdown).join(node.type === "doc" ? "<br>" : "")
: literal(node.text);
for (const mark of node.marks || []) {
if (mark.type === "code") {
const raw = node.text || "";
const fence = "`".repeat(Math.max(0, ...[...raw.matchAll(/`+/g)].map(match => match[0].length)) + 1);
const padding = /^`|`$|^ .* $/.test(raw) ? " " : "";
text = `${fence}${padding}${raw.replace(/\|/g, "\\|")}${padding}${fence}`;
}
if (mark.type === "bold") text = wrap(text, "**");
if (mark.type === "italic") text = wrap(text, "*");
if (mark.type === "strike") text = wrap(text, "~~");
if (mark.type === "highlight") text = wrap(text, "==");
if (mark.type === "math" || mark.type === "comment") text = wrap((node.text || "").replace(/\|/g, "\\|"), mark.type === "math" ? "$" : "%%");
if (mark.type === "link") {
const href = String(mark.attrs?.href || "");
text = mark.attrs?.["data-kind"] === "wiki"
? `[[${literal(href)}\\|${text}]]`
: `[${text}](<${href.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>${mark.attrs?.title ? ` "${String(mark.attrs.title).replace(/"/g, "&quot;")}"` : ""})`;
}
}
return text;
}
+386
View File
@@ -0,0 +1,386 @@
import { Editor, Mark } from "@tiptap/core";
import Highlight from "@tiptap/extension-highlight";
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, undo, redo } from "@codemirror/commands";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
import { tableCellMarkdown } from "./tableCellMarkdown";
import { tableSelectionControls } from "./tableSelectionControls";
import { tableDragControls } from "./tableDragControls";
import type { TableContextActions } from "./tableCellActions";
import { actionIcon } from "../ui/actionIcons";
import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./tableFormulas";
import { tableFormulaHtml } from "../workspace/noteHtml";
const cellFormats = ["math", "comment"].map(name => Mark.create({
name,
parseHTML: () => [{ tag: `span[data-cell-format="${name}"]` }],
renderHTML: () => ["span", { "data-cell-format": name, class: `md-inline-${name}` }, 0],
}));
const CellLink = Link.extend({
addAttributes() { return { ...this.parent?.(), "data-kind": { default: "md" } }; },
});
const CellImage = Image.extend({
addAttributes() { return { ...this.parent?.(), "data-md-src": { default: null }, "data-md-kind": { default: "md" } }; },
parseHTML() { return [...(this.parent?.() || []), { tag: "span.missing-image[data-md-src]" }]; },
renderHTML({ HTMLAttributes }) {
return HTMLAttributes.src
? ["img", HTMLAttributes]
: ["span", { ...HTMLAttributes, class: "missing-image" }, `Image unavailable: ${HTMLAttributes.alt || HTMLAttributes["data-md-src"] || ""}`];
},
});
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
const table = scroll?.querySelector("table");
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
const wrapper = document.createElement("div");
wrapper.className = "writer-table";
scroll.before(wrapper);
wrapper.append(scroll);
let editor: Editor | undefined;
let active: HTMLTableCellElement | undefined;
let firstEdit = true;
let selectionControls: ReturnType<typeof tableSelectionControls> | undefined;
let dragControls: ReturnType<typeof tableDragControls> | undefined;
const controller = { source: initialSource, enter, destroy: () => { dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
tableEditors.set(root, controller);
function enter(forward: boolean, x?: number) {
const row = table!.rows[forward ? 0 : table!.rows.length - 1];
const cells = [...row.cells];
let cell = cells[forward ? 0 : cells.length - 1];
if (x !== undefined) {
const distance = (candidate: HTMLTableCellElement) => {
const rect = candidate.getBoundingClientRect();
return Math.max(rect.left - x, x - rect.right, 0);
};
cell = cells.reduce((nearest, candidate) => distance(candidate) < distance(nearest) ? candidate : nearest);
}
activate(cell);
const current = editor!;
let position = forward ? 1 : current.state.doc.content.size - 1;
if (x !== undefined) {
const edge = current.view.coordsAtPos(position);
position = current.view.posAtCoords({ left: x, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
}
current.commands.setTextSelection(position);
current.view.focus();
cell.scrollIntoView({ block: "nearest", inline: "nearest" });
}
function refreshFormulas() {
const parsed = parseMarkdownTable(controller.source);
if (!parsed) return;
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
const results = evaluateTableFormulas(grid);
for (const row of table!.rows) for (const cell of row.cells) {
const result = results[row.rowIndex]?.[cell.cellIndex];
const address = cellAddress(row.rowIndex, cell.cellIndex);
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
if (result && cell !== active) cell.innerHTML = tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
formulaHint.textContent = result?.error ? formulaErrors[result.error] : "";
formulaHint.hidden = !formulaHint.textContent;
}
}
}
function change(insert: string, structural = false) {
const source = controller.source;
const from = view.posAtDOM(root);
if (view.state.doc.sliceString(from, from + source.length) !== source || insert === source) return;
// Keep the same DOM/editor on typing, including composition and text selection.
if (!structural) controller.source = insert;
let start = 0, oldEnd = source.length, newEnd = insert.length;
while (start < oldEnd && start < newEnd && source[start] === insert[start]) start++;
while (oldEnd > start && newEnd > start && source[oldEnd - 1] === insert[newEnd - 1]) { oldEnd--; newEnd--; }
view.dispatch({
changes: { from: from + start, to: from + oldEnd, insert: insert.slice(start, newEnd) },
userEvent: structural ? "input" : editor?.view.composing ? "input.type.compose" : "input.type.table",
annotations: structural ? isolateHistory.of("full") : firstEdit ? isolateHistory.of("before") : [],
});
firstEdit = false;
if (!structural) refreshFormulas();
view.requestMeasure();
}
function finish() {
if (!editor || !active) return;
const cell = active;
const html = editor.getHTML();
editor.destroy(); editor = undefined; active = undefined;
cell.innerHTML = html;
cell.classList.remove("is-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaHint.hidden = true;
view.requestMeasure();
if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") });
}
function leave(after: boolean) {
const from = view.posAtDOM(root), to = from + controller.source.length;
finish();
let anchor = after ? Math.min(view.state.doc.length, to + 1) : Math.max(0, from - 1);
if (after && to + 1 >= view.state.doc.length) {
view.dispatch({ changes: { from: view.state.doc.length, insert: to === view.state.doc.length ? "\n\n" : "\n" }, userEvent: "input" });
anchor = to + 2;
} else if (after && view.state.doc.sliceString(to, to + 2) === "\n\n") {
// Leave the separator blank so typing below cannot become another row.
anchor = to + 2;
} else if (!after && from === 0) {
view.dispatch({ changes: { from: 0, insert: "\n\n" }, userEvent: "input" });
anchor = 0;
}
view.dispatch({ selection: { anchor }, scrollIntoView: true });
view.focus();
}
function activate(cell: HTMLTableCellElement) {
if (active === cell) return;
finish();
active = cell;
firstEdit = true;
const row = (cell.parentElement as HTMLTableRowElement).rowIndex;
const column = cell.cellIndex;
const sourceRow = row === 0 ? 0 : row + 1;
const originalCell = parseMarkdownTable(controller.source)?.rows[sourceRow]?.cells[column];
// The nested editor owns browser focus, but the outer editor also needs to
// leave its previous active line so its Markdown markers render again.
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
const formula = originalCell && (isTableFormula(originalCell.text) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
const html = cell.innerHTML;
formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`;
cell.innerHTML = "";
cell.classList.add("is-editing");
editor = new Editor({
element: cell,
extensions: [
StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }),
CellLink.configure({ openOnClick: false, autolink: false }),
CellImage.configure({ inline: true, allowBase64: true }),
Highlight, ...cellFormats,
],
content: formula ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: formula }] }] } : html,
enableInputRules: false,
enablePasteRules: false,
editorProps: {
attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" },
handleKeyDown(_editorView, event) {
if (event.isComposing) return false;
if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
// The nested editor owns cursor movement, including word movement
// and selections. Never let an arrow reach the prose editor.
event.stopPropagation();
// Native cursor movement can precede ProseMirror's selectionchange
// observer (especially during key repeat). Test the visible caret.
const native = document.getSelection();
if (native?.anchorNode && native.focusNode && _editorView.dom.contains(native.anchorNode) && _editorView.dom.contains(native.focusNode)) {
const anchor = _editorView.posAtDOM(native.anchorNode, native.anchorOffset);
const head = _editorView.posAtDOM(native.focusNode, native.focusOffset);
if (anchor !== _editorView.state.selection.anchor || head !== _editorView.state.selection.head) editor!.commands.setTextSelection({ from: anchor, to: head });
}
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || !_editorView.state.selection.empty) return false;
const direction = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down";
const horizontal = direction === "left" || direction === "right";
const backwards = direction === "left" || direction === "up";
const { $head } = _editorView.state.selection;
// Pasted rich text can have several paragraphs within one cell.
if ($head.depth && (backwards ? $head.before(1) > 0 : $head.after(1) < _editorView.state.doc.content.size)) return false;
if (!_editorView.endOfTextblock(direction)) return false;
event.preventDefault();
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
const next = horizontal
? cells[cells.indexOf(cell) + (backwards ? -1 : 1)]
: table!.rows[row + (backwards ? -1 : 1)]?.cells[column];
// Once there are no more cells in this direction, return to prose.
if (!next) { leave(!backwards); return true; }
const caret = _editorView.coordsAtPos(_editorView.state.selection.head);
activate(next);
const current = editor!;
let position = backwards ? current.state.doc.content.size - 1 : 1;
if (!horizontal) {
// Enter the closest position on the first/last visual line, even
// when either cell wraps or contains a hard break.
const edge = current.view.coordsAtPos(position);
position = current.view.posAtCoords({ left: caret.left, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
}
current.commands.setTextSelection(position);
current.view.focus();
next.scrollIntoView({ block: "nearest", inline: "nearest" });
return true;
}
// Keep formatting shortcuts local; the workbench also binds Ctrl+B.
if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation();
if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) {
event.preventDefault(); event.stopPropagation();
const position = event.key === "Home" ? 1 : editor!.state.doc.content.size - 1;
editor?.commands.setTextSelection(event.shiftKey ? { from: editor.state.selection.anchor, to: position } : position);
return true;
}
if ((event.ctrlKey || event.metaKey) && ["z", "y"].includes(event.key.toLowerCase())) {
event.preventDefault(); event.stopPropagation();
const from = view.posAtDOM(root);
(event.key.toLowerCase() === "y" || event.shiftKey ? redo : undo)(view);
requestAnimationFrame(() => {
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
(updated?.querySelector("table")?.rows[row]?.cells[column])?.focus();
});
return true;
}
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
if (event.key === "Enter") {
event.preventDefault();
if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); }
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
return true;
}
if (event.key === "Tab") {
event.preventDefault();
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)];
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
else if (event.shiftKey) leave(false);
else add("row", true);
return true;
}
return false;
},
},
onUpdate({ editor: current }) {
const text = tableCellMarkdown(current.getJSON());
const source = controller.source;
// Track the full edited range, including typed spaces. Re-parsing the
// trimmed cell on each key would gradually turn those spaces into padding.
const insert = contentFrom === undefined || contentTo === undefined
? replaceTableCell(source, sourceRow, column, text)
: source.slice(0, contentFrom) + text + source.slice(contentTo);
contentFrom ??= parseMarkdownTable(insert)?.rows[sourceRow]?.cells[column]?.from;
if (contentFrom !== undefined) contentTo = contentFrom + text.length;
change(insert);
},
onBlur() {
// A toolbar click, another cell, or the prose editor can now take focus.
queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); });
},
});
editor.commands.setTextSelection(editor.state.doc.content.size - 1); editor.view.focus();
refreshFormulas();
view.requestMeasure();
}
function add(kind: "row" | "column", focusNew = false) {
const from = view.posAtDOM(root);
finish();
const current = controller.source;
change(kind === "column" ? appendTableColumn(current) : appendTableRow(current), true);
view.focus();
requestAnimationFrame(() => {
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
if (!updated) return;
if (focusNew) updated.querySelector<HTMLTableCellElement>("tbody tr:last-child td")?.focus();
if (kind === "column") {
const viewport = updated.querySelector<HTMLElement>(".md-table-scroll")!;
viewport.scrollLeft = viewport.scrollWidth;
} else updated.querySelector(".table-add-row")?.scrollIntoView({ block: "nearest", inline: "nearest" });
view.requestMeasure();
});
}
const help = document.createElement("div");
help.className = "table-edit-help";
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
const footer = document.createElement("div");
footer.className = "table-footer";
const formulaTools = document.createElement("div");
formulaTools.className = "table-formula-tools";
const formulaHelp = document.createElement("details");
formulaHelp.className = "table-formula-help";
const summary = document.createElement("summary");
summary.append(actionIcon("math"), document.createTextNode("Formulas"));
summary.title = "How to calculate with table cells";
// Committing a wrapped formula can shrink its row. Keep the click target in
// place until mouseup, then finish editing and give keyboard focus to help.
summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } });
summary.addEventListener("click", () => { finish(); summary.focus(); });
const instructions = document.createElement("div");
instructions.className = "table-formula-instructions";
const intro = document.createElement("p");
intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2.";
const examples = document.createElement("dl");
for (const [formula, description] of [
["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."],
["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."],
["=SUM(B2:B10)", "Add the values in a range."],
["=(B2+C2)/2", "Add two values and divide by two."],
["=ROUND(B2/3,2)", "Round to two decimal places."],
]) {
const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd");
code.textContent = formula; term.append(code); descriptionElement.textContent = description;
examples.append(term, descriptionElement);
}
const functions = document.createElement("p");
functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.";
const references = document.createElement("p");
references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting.";
instructions.append(intro, examples, functions, references);
formulaHelp.append(summary, instructions);
formulaHelp.addEventListener("toggle", () => view.requestMeasure());
const formulaStatus = document.createElement("span");
formulaStatus.className = "table-formula-status";
formulaStatus.textContent = "Type = in a cell to calculate";
const formulaHint = document.createElement("div");
formulaHint.className = "table-formula-hint";
formulaHint.hidden = true;
formulaTools.append(formulaHelp, formulaStatus);
footer.append(help, formulaTools, formulaHint);
wrapper.after(footer);
for (const kind of ["column", "row"] as const) {
const button = document.createElement("button");
const label = kind === "column" ? "Add column to the right" : "Add row below";
button.type = "button";
button.className = `table-add table-add-${kind}`;
button.title = label;
button.setAttribute("aria-label", label);
const plus = document.createElement("span");
plus.append(actionIcon("plus"));
plus.setAttribute("aria-hidden", "true");
button.append(plus);
button.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); });
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); add(kind); });
button.addEventListener("pointermove", event => {
const rect = button.getBoundingClientRect();
button.style.setProperty("--table-add-position", `${kind === "column" ? Math.max(12, Math.min(rect.height - 12, event.clientY - rect.top)) : Math.max(12, Math.min(rect.width - 12, event.clientX - rect.left))}px`);
});
wrapper.append(button);
}
for (const row of table.rows) for (const cell of row.cells) {
cell.tabIndex = 0;
cell.setAttribute("aria-label", `${cellAddress(row.rowIndex, cell.cellIndex)} · Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
cell.addEventListener("focus", () => activate(cell));
}
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions);
dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change);
table.addEventListener("mousedown", event => {
if (event.button !== 0) return;
if (event.ctrlKey || event.metaKey || !(event.target instanceof Element)) return;
const cell = event.target.closest<HTMLTableCellElement>("td, th");
if (!cell) return;
event.stopPropagation();
if (active !== cell) {
event.preventDefault(); activate(cell);
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
}
});
refreshFormulas();
}
+226
View File
@@ -0,0 +1,226 @@
import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure";
import type { CellRange } from "./tableSelection";
const controls = new WeakMap<HTMLTableElement, (axis: TableAxis, index: number, keyboard: boolean) => void>();
export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, scroll: HTMLElement, view: EditorView, source: () => string, select: (range: CellRange) => void, change: (text: string, structural: boolean) => void) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
const handles: { axis: TableAxis; index: number; button: HTMLButtonElement }[] = [];
const layer = document.createElement("div");
layer.className = "table-drag-layer";
wrapper.append(layer);
const indicator = document.createElement("div");
indicator.className = "table-drop-indicator";
indicator.hidden = true;
layer.append(indicator);
let preview: HTMLElement | undefined, previewLabel: HTMLElement | undefined;
let drag: { axis: TableAxis; index: number; pointer: number; x: number; y: number; startX: number; startY: number; active: boolean; to?: number; before: string } | undefined;
let frame = 0, layoutFrame = 0;
function selectAxis(axis: TableAxis, index: number) {
select(axis === "row"
? { anchor: { row: index, column: 0 }, head: { row: index, column: table.rows[0].cells.length - 1 } }
: { anchor: { row: 0, column: index }, head: { row: table.rows.length - 1, column: index } });
}
function focusAxis(axis: TableAxis, index: number, keyboard = true) {
selectAxis(axis, index);
const button = handles.find(handle => handle.axis === axis && handle.index === index)?.button;
button?.toggleAttribute("data-pointer-focus", !keyboard);
button?.focus({ preventScroll: true });
}
controls.set(table, focusAxis);
function commit(axis: TableAxis, index: number, to: number, keyboard = true) {
const before = source(), after = moveTableAxis(before, axis, index, to);
if (before === after) return;
const from = view.posAtDOM(root), left = scroll.scrollLeft;
change(after, true);
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
const next = updated?.querySelector("table");
const viewport = updated?.querySelector<HTMLElement>(".md-table-scroll");
if (viewport) viewport.scrollLeft = left;
if (next) controls.get(next)?.(axis, to, keyboard);
}
function layout() {
layoutFrame = 0;
const origin = wrapper.getBoundingClientRect(), viewport = scroll.getBoundingClientRect();
for (const { axis, index, button } of handles) {
const rect = (axis === "row" ? table.rows[index] : table.rows[0].cells[index]).getBoundingClientRect();
const left = Math.max(viewport.left, rect.left), right = Math.min(viewport.right, rect.right);
button.hidden = axis === "column" && right <= left;
Object.assign(button.style, axis === "row"
? { left: `${viewport.left - origin.left - 26}px`, top: `${rect.top - origin.top}px`, width: "26px", height: `${rect.height}px` }
: { left: `${left - origin.left}px`, top: `${viewport.top - origin.top - 26}px`, width: `${Math.max(0, right - left)}px`, height: "26px" });
button.style.setProperty("--table-tooltip-left", `${axis === "row" ? 26 : viewport.left - left}px`);
button.style.setProperty("--table-tooltip-width", `${Math.min(260, viewport.width)}px`);
}
}
function scheduleLayout() { if (!layoutFrame) layoutFrame = requestAnimationFrame(layout); }
function createPreview() {
if (!drag) return;
preview = document.createElement("div");
preview.className = `reading table-drag-preview table-drag-preview-${drag.axis}`;
preview.setAttribute("aria-hidden", "true");
preview.inert = true;
previewLabel = document.createElement("div");
previewLabel.className = "table-drag-preview-label";
preview.append(previewLabel);
const content = document.createElement("div");
content.className = "table-drag-preview-content";
const copy = document.createElement("table");
const rows = drag.axis === "row" ? [table.rows[drag.index]] : [...table.rows];
const width = drag.axis === "row" ? table.getBoundingClientRect().width : table.rows[0].cells[drag.index].getBoundingClientRect().width;
preview.style.width = `${Math.min(width, drag.axis === "row" ? 560 : 280, window.innerWidth - 24)}px`;
copy.style.font = getComputedStyle(table).font;
for (const row of rows) {
const clonedRow = document.createElement("tr");
const cells = drag.axis === "row" ? [...row.cells] : [row.cells[drag.index]];
for (const cell of cells) {
const clonedCell = cell.cloneNode(true) as HTMLTableCellElement;
// A visual snapshot must not duplicate focusable controls, document IDs,
// or selection styling from the real cells.
for (const element of [clonedCell, ...clonedCell.querySelectorAll("*")]) {
for (const attribute of ["id", "tabindex", "contenteditable", "aria-selected", "aria-label", "data-selection-edges", "title"]) element.removeAttribute(attribute);
element.classList.remove("is-cell-selected", "is-editing");
}
clonedCell.style.width = `${cell.getBoundingClientRect().width / width * 100}%`;
clonedRow.append(clonedCell);
}
copy.append(clonedRow);
}
content.append(copy); preview.append(content); document.body.append(preview);
updatePreview();
}
function updatePreview() {
if (!preview || !previewLabel || !drag) return;
const valid = drag.to !== undefined;
preview.classList.toggle("is-invalid-drop", !valid);
previewLabel.textContent = `${drag.axis === "row" ? "Row" : "Column"} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : " · Release to cancel"}`;
const rect = preview.getBoundingClientRect();
const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8));
const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8));
preview.style.transform = `translate3d(${x}px, ${y}px, 0)`;
}
function updateTarget() {
if (!drag?.active) return;
const { axis, x, y, index } = drag;
const viewport = scroll.getBoundingClientRect(), origin = wrapper.getBoundingClientRect();
drag.to = undefined;
indicator.hidden = true;
if (x < viewport.left - 32 || x > viewport.right + 32 || y < viewport.top - 32 || y > viewport.bottom + 32) return;
const items = axis === "row" ? [...table.rows].slice(1) : [...table.rows[0].cells];
if (!items.length) return;
const coordinate = axis === "row" ? y : x;
let boundary = items.findIndex(item => {
const rect = item.getBoundingClientRect();
return coordinate < (axis === "row" ? (rect.top + rect.bottom) / 2 : (rect.left + rect.right) / 2);
});
if (boundary < 0) boundary = items.length;
const insertion = boundary + (axis === "row" ? 1 : 0);
drag.to = insertion > index ? insertion - 1 : insertion;
if (drag.to === index) return;
const edge = (items[boundary] || items[items.length - 1]).getBoundingClientRect();
const position = axis === "row" ? (boundary === items.length ? edge.bottom : edge.top) : (boundary === items.length ? edge.right : edge.left);
if (axis === "column" && (position < viewport.left || position > viewport.right)) return;
indicator.hidden = false;
Object.assign(indicator.style, axis === "row"
? { left: `${viewport.left - origin.left}px`, top: `${position - origin.top - 2}px`, width: `${viewport.width}px`, height: "4px" }
: { left: `${position - origin.left - 2}px`, top: `${viewport.top - origin.top}px`, width: "4px", height: `${table.getBoundingClientRect().height}px` });
}
function tick() {
if (!drag?.active) return;
const viewport = scroll.getBoundingClientRect(), editor = view.scrollDOM.getBoundingClientRect();
const speed = (coordinate: number, start: number, end: number) => coordinate < start + 36 ? -Math.min(18, (start + 36 - coordinate) / 3) : coordinate > end - 36 ? Math.min(18, (coordinate - end + 36) / 3) : 0;
if (drag.x >= viewport.left - 32 && drag.x <= viewport.right + 32) {
if (drag.axis === "column") scroll.scrollLeft += speed(drag.x, viewport.left, viewport.right);
// Stop at the table's ends so an edge drag cannot scroll its own drop
// target out from under the pointer after the last row becomes visible.
const vertical = speed(drag.y, editor.top, editor.bottom);
view.scrollDOM.scrollTop += vertical > 0
? Math.min(vertical, Math.max(0, viewport.bottom - editor.bottom + 36))
: Math.max(vertical, Math.min(0, viewport.top - editor.top - 36));
}
layout(); updateTarget(); updatePreview();
frame = requestAnimationFrame(tick);
}
function cancel() {
const previous = drag;
drag = undefined;
cancelAnimationFrame(frame);
indicator.hidden = true;
preview?.remove(); preview = undefined; previewLabel = undefined;
wrapper.classList.remove("is-table-dragging");
if (previous) {
const button = handles.find(handle => handle.axis === previous.axis && handle.index === previous.index)?.button;
if (button?.hasPointerCapture(previous.pointer)) button.releasePointerCapture(previous.pointer);
}
}
for (const axis of ["column", "row"] as const) {
const length = axis === "row" ? table.rows.length : table.rows[0].cells.length;
for (let index = axis === "row" ? 1 : 0; index < length; index++) {
const button = document.createElement("button");
button.type = "button";
button.className = `table-drag-handle table-drag-${axis}`;
button.dataset.index = String(index);
const label = `Move ${axis} ${index + 1}`;
const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`;
button.setAttribute("aria-label", label);
button.title = tooltip;
button.dataset.tooltip = tooltip;
button.append(actionIcon("grip"));
layer.append(button);
handles.push({ axis, index, button });
button.addEventListener("pointerdown", event => {
if (event.button !== 0 || drag) return;
event.preventDefault(); event.stopPropagation();
focusAxis(axis, index, false);
drag = { axis, index, pointer: event.pointerId, x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY, active: false, before: source() };
button.setPointerCapture(event.pointerId);
}, options);
button.addEventListener("lostpointercapture", () => { if (drag) cancel(); }, options);
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); }, options);
button.addEventListener("blur", () => button.removeAttribute("data-pointer-focus"), options);
button.addEventListener("keydown", event => {
button.removeAttribute("data-pointer-focus");
const previous = axis === "row" ? "ArrowUp" : "ArrowLeft", next = axis === "row" ? "ArrowDown" : "ArrowRight";
if (![previous, next, " ", "Enter"].includes(event.key)) return;
event.preventDefault(); event.stopPropagation();
if (drag) return;
if (event.key === previous || event.key === next) commit(axis, index, index + (event.key === previous ? -1 : 1));
else focusAxis(axis, index);
}, options);
}
}
document.addEventListener("pointermove", event => {
if (!drag || event.pointerId !== drag.pointer) return;
drag.x = event.clientX; drag.y = event.clientY;
if (!drag.active && Math.hypot(drag.x - drag.startX, drag.y - drag.startY) >= 5) {
drag.active = true; wrapper.classList.add("is-table-dragging"); createPreview(); tick();
}
if (drag.active) { event.preventDefault(); updateTarget(); updatePreview(); }
}, { ...options, passive: false });
document.addEventListener("pointerup", event => {
if (!drag || event.pointerId !== drag.pointer) return;
drag.x = event.clientX; drag.y = event.clientY; updateTarget();
const completed = drag;
cancel();
if (completed.active && completed.to !== undefined && source() === completed.before) commit(completed.axis, completed.index, completed.to, false);
}, options);
document.addEventListener("pointercancel", cancel, options);
document.addEventListener("keydown", event => {
if (drag && event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); cancel(); }
}, { ...options, capture: true });
window.addEventListener("blur", cancel, options);
scroll.addEventListener("scroll", scheduleLayout, options);
const observer = new ResizeObserver(scheduleLayout);
observer.observe(table); observer.observe(scroll);
scheduleLayout();
return { destroy() { cancel(); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
}
+151
View File
@@ -0,0 +1,151 @@
// Formulas are plain Markdown cell text. No JavaScript evaluation or external data.
export const formulaErrors = {
"#ERROR!": "Invalid formula syntax or function arguments",
"#REF!": "Cell reference is outside this table",
"#VALUE!": "Expected a number",
"#NAME?": "Unknown function or cell name",
"#DIV/0!": "Cannot divide by zero or average an empty range",
"#CYCLE!": "Circular cell reference",
"#NUM!": "Result is not a finite number",
"#LIMIT!": "Formula is too complex",
} as const;
type ErrorCode = keyof typeof formulaErrors;
export type FormulaResult = { formula: string; text: string; value?: number; error?: ErrorCode };
class FormulaError extends Error {
code: ErrorCode;
constructor(code: ErrorCode) { super(formulaErrors[code]); this.code = code; }
}
function fail(code: ErrorCode): never { throw new FormulaError(code); }
export const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
export function cellAddress(row: number, column: number): string {
let letters = "";
for (let n = column + 1; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + (n - 1) % 26) + letters;
return letters + (row + 1);
}
type Scalar = number | string | null;
type Value = Scalar | Scalar[];
const number = (value: Value): number => typeof value === "number" ? value : value === null ? 0 : fail("#VALUE!");
const finite = (value: number) => Number.isFinite(value) ? value : fail("#NUM!");
const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
// Header is row 1; the Markdown separator is not a spreadsheet row.
export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[][] {
const cache = new Map<string, Scalar | FormulaError>();
const visiting = new Set<string>();
let budget = 50000;
const spend = () => { if (--budget < 0) fail("#LIMIT!"); };
function reference(address: string): [number, number] {
const match = /^\$?([A-Z]+)\$?([1-9]\d*)$/i.exec(address) || fail("#REF!");
let column = 0;
for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
const row = Number(match[2]);
if (row > grid.length || column > (grid[0]?.length || 0)) fail("#REF!");
return [row - 1, column - 1];
}
function cell(row: number, column: number): Scalar {
spend();
const key = `${row}:${column}`;
if (visiting.has(key)) fail("#CYCLE!");
if (visiting.size >= 128) fail("#LIMIT!");
const cached = cache.get(key);
if (cached instanceof FormulaError) throw cached;
if (cache.has(key)) return cached!;
const source = (grid[row]?.[column] || "").trim();
if (!isTableFormula(source)) return source === "" ? null : numeric.test(source) ? finite(Number(source)) : source;
visiting.add(key);
try {
const value = parse(source.slice(1));
cache.set(key, value);
return value;
} catch (error) {
const problem = error instanceof FormulaError ? error : new FormulaError("#LIMIT!");
cache.set(key, problem);
throw problem;
} finally { visiting.delete(key); }
}
function parse(source: string): number {
if (source.length > 2048) fail("#LIMIT!");
const tokens: string[] = [];
const pattern = /\s*(\$?[A-Za-z]+\$?\d+|[A-Za-z_]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+\-*/^%(),:])/y;
let offset = 0;
while (offset < source.trimEnd().length) {
pattern.lastIndex = offset;
const match = pattern.exec(source) || fail("#ERROR!");
tokens.push(match[1]); offset = pattern.lastIndex;
}
let position = 0, depth = 0;
const peek = () => tokens[position];
const take = () => { spend(); return tokens[position++]; };
const expect = (token: string) => { if (take() !== token) fail("#ERROR!"); };
function expression(min = 0): Value {
if (++depth > 64) fail("#LIMIT!");
let left: Value;
const token = take();
if (token === "+" || token === "-") left = number(expression(3)) * (token === "-" ? -1 : 1);
else if (token === "(") { left = expression(); expect(")"); }
else if (token && numeric.test(token)) left = finite(Number(token));
else if (token && /^\$?[a-z]+\$?\d+$/i.test(token)) {
const [row, column] = reference(token);
if (peek() === ":") {
take(); const [endRow, endColumn] = reference(take() || "");
const values: Scalar[] = [];
for (let r = Math.min(row, endRow); r <= Math.max(row, endRow); r++) {
for (let c = Math.min(column, endColumn); c <= Math.max(column, endColumn); c++) values.push(cell(r, c));
}
left = values;
} else left = cell(row, column);
} else if (token && /^[a-z_]+$/i.test(token)) {
if (peek() !== "(") fail("#NAME?");
take(); const args: Value[] = [];
if (peek() !== ")") {
do { args.push(expression()); if (peek() !== ",") break; take(); } while (true);
}
expect(")");
left = call(token.toUpperCase(), args);
} else fail("#ERROR!");
while (true) {
const op = peek();
if (op === "%") { take(); left = number(left) / 100; continue; }
const precedence = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 3 : -1;
if (precedence < min) break;
take();
const right = number(expression(precedence + (op === "^" ? 0 : 1))), a = number(left);
left = finite(op === "+" ? a + right : op === "-" ? a - right : op === "*" ? a * right : op === "/" ? (right === 0 ? fail("#DIV/0!") : a / right) : a ** right);
}
depth--;
return left;
}
const result = finite(number(expression()));
if (position !== tokens.length) fail("#ERROR!");
return result;
}
function call(name: string, args: Value[]): number {
if (name === "ABS") return args.length === 1 ? Math.abs(number(args[0])) : fail("#ERROR!");
if (name === "ROUND") {
if (args.length < 1 || args.length > 2) fail("#ERROR!");
const value = number(args[0]), digits = args.length === 2 ? number(args[1]) : 0;
if (!Number.isInteger(digits) || Math.abs(digits) > 100) fail("#NUM!");
const factor = 10 ** digits, scaled = Math.abs(value) * factor;
return finite(Math.sign(value) * Math.round(scaled + Number.EPSILON * scaled) / factor);
}
if (!["SUM", "AVERAGE", "MIN", "MAX", "COUNT"].includes(name)) fail("#NAME?");
const values = args.flat().filter((value): value is number => typeof value === "number");
if (name === "COUNT") return values.length;
if (name === "MIN" || name === "MAX") return values.length ? values.reduce((a, b) => name === "MIN" ? Math.min(a, b) : Math.max(a, b)) : 0;
const sum = finite(values.reduce((a, b) => a + b, 0));
return name === "AVERAGE" ? (values.length ? sum / values.length : fail("#DIV/0!")) : sum;
}
return grid.map((row, r) => row.map((source, c) => {
if (!isTableFormula(source)) return null;
const formula = source.trim();
try {
const value = number(cell(r, c));
return { formula, value, text: String(Number(value.toPrecision(12))) };
} catch (error) {
const code = error instanceof FormulaError ? error.code : "#LIMIT!";
return { formula, text: code, error: code };
}
}));
}
+32
View File
@@ -0,0 +1,32 @@
import { Prec } from "@codemirror/state";
import { keymap } from "@codemirror/view";
import { tableEditors } from "./tableControls";
// Tables are atomic in the prose editor. Intercept a movement that would cross
// one before CodeMirror skips the widget, and hand focus to its cell editor.
export const tableNavigation = Prec.high(keymap.of(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].map(key => ({
key,
run(view) {
const selection = view.state.selection.main;
if (!view.hasFocus || !selection.empty || view.state.selection.ranges.length !== 1) return false;
const forward = key === "ArrowRight" || key === "ArrowDown";
const vertical = key === "ArrowUp" || key === "ArrowDown";
const next = vertical ? view.moveVertically(selection, forward) : view.moveByChar(selection, forward);
const previews = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")];
if (!forward) previews.reverse();
for (const root of previews) {
const table = tableEditors.get(root);
if (!table) continue;
const from = view.posAtDOM(root), to = from + table.source.length;
const crosses = forward
? selection.head <= from && next.head >= from
: selection.head >= to && next.head <= to;
if (!crosses) continue;
const goal = selection.goalColumn ?? next.goalColumn;
const x = goal === undefined ? view.coordsAtPos(selection.head)?.left : view.contentDOM.getBoundingClientRect().left + goal;
table.enter(forward, vertical ? x : undefined);
return true;
}
return false;
},
}))));
+119
View File
@@ -0,0 +1,119 @@
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable.ts";
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
export type CellPoint = { row: number; column: number };
export type CellRange = { anchor: CellPoint; head: CellPoint };
export type CellFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear";
export function bounds(range: CellRange) {
return { top: Math.min(range.anchor.row, range.head.row), bottom: Math.max(range.anchor.row, range.head.row), left: Math.min(range.anchor.column, range.head.column), right: Math.max(range.anchor.column, range.head.column) };
}
const sourceRow = (row: number) => row === 0 ? 0 : row + 1;
export function mapTableCells(source: string, range: CellRange, transform: (text: string) => string): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const { top, bottom, left, right } = bounds(range);
for (let r = Math.max(0, top); r <= Math.min(bottom, table.rows.length - 2); r++) {
for (let c = Math.max(0, left); c <= Math.min(right, table.columns - 1); c++) {
source = replaceTableCell(source, sourceRow(r), c, transform(table.rows[sourceRow(r)].cells[c]?.text || ""));
}
}
return source;
}
export function formatTableCells(source: string, range: CellRange, format: CellFormat): string {
if (format === "clear") return mapTableCells(source, range, plainInlineMarkdown);
const marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format];
const wrapped = (text: string) => format === "code" ? /^(`+)(?!`)([\s\S]*[^`])\1(?!`)$/.test(text)
: text.startsWith(marker) && text.endsWith(marker) && text.length > marker.length * 2 && !(format === "italic" && text.startsWith("**") && !text.startsWith("***"));
let allWrapped = true;
mapTableCells(source, range, text => { if (text.trim() && !wrapped(text)) allWrapped = false; return text; });
return mapTableCells(source, range, text => {
if (!text.trim()) return text;
if (wrapped(text)) return allWrapped ? (format === "code" ? plainInlineMarkdown(text) : text.slice(marker.length, -marker.length)) : text;
if (format === "code") {
const fence = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(m => m[0].length)) + 1);
return `${fence} ${text} ${fence}`;
}
return marker + text + marker;
});
}
export function alignTableCells(source: string, range: CellRange, alignment: "left" | "center" | "right"): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const { left, right } = bounds(range);
const marker = { left: ":---", center: ":---:", right: "---:" }[alignment];
for (let c = Math.min(right, table.columns - 1); c >= Math.max(0, left); c--) {
const cell = table.rows[1].cells[c];
source = source.slice(0, cell.from) + marker + source.slice(cell.to);
}
return source;
}
export function copyTableCells(source: string, range: CellRange): string {
const table = parseMarkdownTable(source);
if (!table) return "";
const { top, bottom, left, right } = bounds(range);
const quote = (value: string) => /[\t\r\n"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
return Array.from({ length: bottom - top + 1 }, (_, r) => Array.from({ length: right - left + 1 }, (_, c) => quote(table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "")).join("\t")).join("\n");
}
// Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table.
export function clipboardCells(text: string): string[][] {
const table = parseMarkdownTable(text);
if (table) return table.rows.filter((_, i) => i !== 1).map(row => row.cells.map(cell => cell.text));
const rows: string[][] = [[]];
let cell = "", quoted = false;
text = text.replace(/\r\n?/g, "\n").replace(/\n$/, "");
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char === '"' && (quoted || !cell)) {
if (quoted && text[i + 1] === '"') { cell += '"'; i++; }
else quoted = !quoted;
} else if (!quoted && (char === "\t" || char === "\n")) {
rows.at(-1)!.push(cell); cell = "";
if (char === "\n") rows.push([]);
} else cell += char;
}
rows.at(-1)!.push(cell);
return rows.map(row => row.map(value => value.replace(/\n/g, "<br>").replace(/(\\*)\|/g, (match, slashes: string) => slashes.length % 2 ? match : `${slashes}\\|`)));
}
export function pasteTableCells(source: string, range: CellRange, text: string): string {
if (!parseMarkdownTable(source)) return source;
const cells = clipboardCells(text), { top, bottom, left, right } = bounds(range);
if (cells.length === 1 && cells[0].length === 1) return mapTableCells(source, range, () => cells[0][0]);
const gridWidth = Math.max(...cells.map(row => row.length));
const height = Math.max(bottom - top + 1, cells.length), width = Math.max(right - left + 1, gridWidth);
while (parseMarkdownTable(source)!.columns < left + width) source = appendTableColumn(source);
while (parseMarkdownTable(source)!.rows.length - 1 < top + height) source = appendTableRow(source);
for (let r = 0; r < height; r++) for (let c = 0; c < width; c++) {
source = replaceTableCell(source, sourceRow(top + r), left + c, cells[r % cells.length][c % gridWidth] ?? "");
}
return source;
}
// Whole rows/columns are removed structurally; a partial rectangle shifts cells left.
export function deleteTableCells(source: string, range: CellRange): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const { top, bottom, left, right } = bounds(range);
const allRows = top === 0 && bottom >= table.rows.length - 2;
const allColumns = left === 0 && right >= table.columns - 1;
if (allRows && allColumns) return source.slice(table.end);
const rows = table.rows.flatMap((row, i) => {
const r = i === 0 ? 0 : i - 1;
if (allColumns && i !== 1 && r >= top && r <= bottom) return [];
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || "");
if (allRows || (i !== 1 && r >= top && r <= bottom)) {
cells.splice(left, right - left + 1);
if (!allRows) while (cells.length < table.columns) cells.push("");
}
return [{ ...row, cells }];
});
// Deleting the header promotes the first remaining body row.
if (allColumns && top === 0) [rows[0], rows[1]] = [rows[1], rows[0]];
return rows.map(row => `${row.indent}| ${row.cells.join(" | ")} |`).join(table.eol) + source.slice(table.end);
}
+225
View File
@@ -0,0 +1,225 @@
import type { EditorView } from "@codemirror/view";
import { undo, redo, isolateHistory } from "@codemirror/commands";
import type { Editor } from "@tiptap/core";
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
const selections = new WeakMap<Element, (range: CellRange) => void>();
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void }, actions: TableContextActions) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
let range: CellRange | undefined, down: CellPoint | undefined, dragging = false;
let menu: HTMLElement | undefined;
let pending = false;
wrapper.tabIndex = -1;
wrapper.contentEditable = "false";
const point = (cell: HTMLTableCellElement): CellPoint => ({ row: (cell.parentElement as HTMLTableRowElement).rowIndex, column: cell.cellIndex });
function cellAt(target: EventTarget | null) {
const cell = target instanceof Element ? target.closest<HTMLTableCellElement>("td, th") : null;
return cell?.closest("table") === table ? cell : null;
}
function closeMenu() { menu?.remove(); menu = undefined; }
function clear() {
range = undefined; closeMenu();
wrapper.classList.remove("has-cell-selection");
for (const cell of table.querySelectorAll("th, td")) { cell.classList.remove("is-cell-selected"); cell.removeAttribute("aria-selected"); cell.removeAttribute("data-selection-edges"); }
}
function select(next: CellRange) {
finish();
const clamp = (p: CellPoint) => ({ row: Math.max(0, Math.min(table.rows.length - 1, p.row)), column: Math.max(0, Math.min(table.rows[0].cells.length - 1, p.column)) });
range = { anchor: clamp(next.anchor), head: clamp(next.head) };
const { top, bottom, left, right } = bounds(range);
wrapper.classList.add("has-cell-selection");
for (const row of table.rows) for (const cell of row.cells) {
const selected = row.rowIndex >= top && row.rowIndex <= bottom && cell.cellIndex >= left && cell.cellIndex <= right;
cell.classList.toggle("is-cell-selected", selected);
cell.setAttribute("aria-selected", String(selected));
if (selected) cell.setAttribute("data-selection-edges", [
row.rowIndex === top && "top", row.rowIndex === bottom && "bottom",
cell.cellIndex === left && "left", cell.cellIndex === right && "right",
].filter(Boolean).join(" "));
else cell.removeAttribute("data-selection-edges");
}
document.getSelection()?.removeAllRanges();
wrapper.focus({ preventScroll: true });
}
selections.set(table, select);
function apply(transform: (text: string, selected: CellRange) => string, restore?: CellRange) {
if (!range) return;
const selected = range, from = view.posAtDOM(root);
closeMenu(); finish();
change(transform(source(), selected), true);
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
const nextTable = updated?.querySelector("table");
if (nextTable) selections.get(nextTable)?.(restore || selected);
else view.focus();
}
const clearCells = () => apply((text, selected) => mapTableCells(text, selected, () => ""));
const format = (kind: CellFormat) => apply((text, selected) => formatTableCells(text, selected, kind));
async function clipboard(action: "copy" | "cut" | "paste") {
if (!range) return;
const before = source(), selected = range;
closeMenu(); wrapper.focus({ preventScroll: true });
try {
if (action === "paste") {
const text = await navigator.clipboard.readText();
if (root.isConnected && source() === before && range === selected) apply((value, target) => pasteTableCells(value, target, text));
} else {
await navigator.clipboard.writeText(copyTableCells(before, selected));
if (action === "cut" && root.isConnected && source() === before && range === selected) clearCells();
}
} catch {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
}
}
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
if (!at) return;
closeMenu();
const cellRange = { anchor: at, head: at };
const returnFocus = () => { closeMenu(); if (textEditor && !textEditor.isDestroyed) textEditor.view.focus(); else wrapper.focus(); };
function structural(axis: TableAxis, operation: TableOperation) {
range ??= cellRange;
const index = axis === "row" ? at!.row : at!.column;
const next = { ...at! };
if (operation === "previous") next[axis]--;
if (operation === "next" || operation === "after" || operation === "duplicate") next[axis]++;
apply(text => changeTableStructure(text, axis, index, operation), { anchor: next, head: next });
}
const row = at.row, column = at.column, lastRow = table.rows.length - 1, lastColumn = table.rows[0].cells.length - 1;
const sep: ActionMenuItem = { separator: true };
const align = (alignment: "left" | "center" | "right") => {
range ??= cellRange;
apply((text, selected) => alignTableCells(text, selected, alignment));
};
const alignmentItems: ActionMenuItem[] = [
{ label: "Align left", icon: "left", run: () => align("left") },
{ label: "Align centre", icon: "center", run: () => align("center") },
{ label: "Align right", icon: "right", run: () => align("right") },
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
const report = (message: string) => {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
};
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
}, value => { pending = value; }, report) : [
...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })),
sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },
...alignmentItems,
sep, { label: "Clear cells", icon: "clear", run: clearCells },
{ label: "Delete cells", icon: "trash", run: () => apply(deleteTableCells), title: "Remove selected rows/columns; otherwise shift cells left" },
];
items.push(sep,
{ label: "Row", icon: "row", children: [
{ label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") },
{ label: "Add row below", icon: "row-after", run: () => structural("row", "after") }, sep,
{ label: "Move row up", icon: "up", disabled: row <= 1, run: () => structural("row", "previous") },
{ label: "Move row down", icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep,
{ label: "Duplicate row", icon: "copy", run: () => structural("row", "duplicate") },
{ label: "Delete row", icon: "trash", run: () => structural("row", "delete") },
] },
{ label: "Column", icon: "column", children: [
{ label: "Add column to the left", icon: "column-before", run: () => structural("column", "before") },
{ label: "Add column to the right", icon: "column-after", run: () => structural("column", "after") }, sep,
{ label: "Move column left", icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") },
{ label: "Move column right", icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep,
...alignmentItems, sep,
{ label: "Duplicate column", icon: "copy", run: () => structural("column", "duplicate") },
{ label: "Delete column", icon: "trash", run: () => structural("column", "delete") },
] }, sep,
{ label: "Sort by column (A to Z)", icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } },
{ label: "Sort by column (Z to A)", icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } },
);
menu = actionMenu(x, y, items, returnFocus);
}
table.addEventListener("mousedown", event => {
const cell = cellAt(event.target);
if (cell && event.button === 2) { event.preventDefault(); return; }
if (!cell || event.button !== 0 || event.ctrlKey || event.metaKey) return;
closeMenu(); down = point(cell); dragging = false;
if (event.shiftKey) {
event.preventDefault(); event.stopImmediatePropagation();
const active = table.querySelector<HTMLTableCellElement>(".is-editing");
select({ anchor: range?.anchor || (active ? point(active) : down), head: down }); dragging = true;
} else clear();
}, { ...options, capture: true });
document.addEventListener("mousemove", event => {
if (!down || !(event.buttons & 1)) return;
const cell = cellAt(document.elementFromPoint(event.clientX, event.clientY));
if (!cell) return;
const head = point(cell);
if (dragging || head.row !== down.row || head.column !== down.column) {
event.preventDefault(); dragging = true;
select({ anchor: range?.anchor || down, head });
}
}, options);
document.addEventListener("mouseup", () => { down = undefined; }, options);
table.addEventListener("dragstart", event => event.preventDefault(), options);
table.addEventListener("focus", event => { if (range && cellAt(event.target)) clear(); }, { ...options, capture: true });
table.addEventListener("click", event => { if (dragging) { event.preventDefault(); event.stopPropagation(); dragging = false; } }, { ...options, capture: true });
table.addEventListener("contextmenu", event => {
const cell = cellAt(event.target); if (!cell) return;
event.preventDefault(); event.stopPropagation();
if (cell.classList.contains("is-cell-selected")) showMenu(event.clientX, event.clientY, point(cell));
else {
clear(); rich.activate(cell);
const current = rich.get();
// A context click can arrive before the browser's selectionchange event.
// Read the visible word selection before moving focus into the menu.
const native = document.getSelection();
if (current && native && !native.isCollapsed && native.anchorNode && native.focusNode && current.view.dom.contains(native.anchorNode) && current.view.dom.contains(native.focusNode)) {
current.commands.setTextSelection({ from: current.view.posAtDOM(native.anchorNode, native.anchorOffset), to: current.view.posAtDOM(native.focusNode, native.focusOffset) });
}
if (current?.state.selection.empty) {
const hit = current.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) current.commands.setTextSelection(hit.pos);
}
showMenu(event.clientX, event.clientY, point(cell), current);
}
}, options);
document.addEventListener("mousedown", event => { if (!wrapper.contains(event.target as Node) && !menu?.contains(event.target as Node)) { clear(); if (!pending) finish(); } }, options);
document.addEventListener("scroll", event => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }, { ...options, capture: true });
window.addEventListener("resize", closeMenu, options);
wrapper.addEventListener("keydown", event => {
if (!range) return;
const mod = event.ctrlKey || event.metaKey, key = event.key.toLowerCase();
const handled = ["Escape", "Delete", "Backspace", "Enter", "ContextMenu", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) || (event.shiftKey && event.key === "F10") || (mod && ["b", "i", "z", "y", "a"].includes(key));
if (!handled) return;
event.preventDefault(); event.stopPropagation();
if (mod && ["z", "y"].includes(key)) { closeMenu(); (key === "y" || event.shiftKey ? redo : undo)(view); view.focus(); }
else if (mod && key === "a") select({ anchor: { row: 0, column: 0 }, head: { row: table.rows.length - 1, column: table.rows[0].cells.length - 1 } });
else if (mod && ["b", "i"].includes(key)) format(key === "b" ? "bold" : "italic");
else if (event.key === "Escape") { clear(); view.focus(); }
else if (event.key === "Delete" || event.key === "Backspace") clearCells();
else if (event.key === "Enter") { const target = table.rows[range.head.row].cells[range.head.column]; clear(); target.focus(); }
else if (event.key === "ContextMenu" || event.key === "F10") { const rect = table.rows[range.head.row].cells[range.head.column].getBoundingClientRect(); showMenu(rect.left, rect.bottom); }
else {
const head = { ...range.head };
if (event.key === "ArrowLeft") head.column--; if (event.key === "ArrowRight") head.column++;
if (event.key === "ArrowUp") head.row--; if (event.key === "ArrowDown") head.row++;
select({ anchor: event.shiftKey ? range.anchor : head, head });
table.rows[range!.head.row].cells[range!.head.column].scrollIntoView({ block: "nearest", inline: "nearest" });
}
}, options);
for (const action of ["copy", "cut", "paste"] as const) wrapper.addEventListener(action, event => {
if (!range || !event.clipboardData) return;
if (action === "paste" && !event.clipboardData.types.includes("text/plain")) return;
event.preventDefault(); event.stopPropagation();
if (action === "paste") apply((text, selected) => pasteTableCells(text, selected, event.clipboardData!.getData("text/plain")));
else { event.clipboardData.setData("text/plain", copyTableCells(source(), range)); if (action === "cut") clearCells(); }
}, { ...options, capture: true });
// Spreadsheet data pasted while editing one cell becomes a grid operation.
wrapper.addEventListener("paste", event => {
if (range) return;
const text = event.clipboardData?.getData("text/plain") || "";
const cell = cellAt(event.target);
if (!cell || !text.includes("\t")) return;
event.preventDefault(); event.stopPropagation(); select({ anchor: point(cell), head: point(cell) });
apply((value, selected) => pasteTableCells(value, selected, text));
}, { ...options, capture: true });
return { select, keepEditing: () => !!menu || pending, destroy: () => { lifecycle.abort(); closeMenu(); selections.delete(table); } };
}
+69
View File
@@ -0,0 +1,69 @@
import { parseMarkdownTable } from "./markdownTable.ts";
import { deleteTableCells } from "./tableSelection.ts";
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
export type TableAxis = "row" | "column";
export type TableOperation = "before" | "after" | "previous" | "next" | "duplicate" | "delete";
// Indices refer to rendered rows (header = 0), or columns. `to` is the
// final position, after removing the source item.
export function moveTableAxis(source: string, axis: TableAxis, from: number, to: number): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const size = axis === "row" ? table.rows.length - 1 : table.columns;
const first = axis === "row" ? 1 : 0;
if (![from, to].every(index => Number.isInteger(index) && index >= first && index < size) || from === to) return source;
function move<T>(items: T[], start: number, end: number) {
items.splice(end, 0, items.splice(start, 1)[0]);
return items;
}
const rows = axis === "row"
? move(table.rows.map(row => source.slice(row.from, row.to)), from + 1, to + 1)
: table.rows.map(row => {
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, i) => row.cells[i]?.text || "");
return `${row.indent}| ${move(cells, from, to).join(" | ")} |`;
});
return rows.join(table.eol) + source.slice(table.end);
}
export function changeTableStructure(source: string, axis: TableAxis, index: number, operation: TableOperation): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const size = axis === "row" ? table.rows.length - 1 : table.columns;
if (index < 0 || index >= size) return source;
if (operation === "delete") return deleteTableCells(source, axis === "row"
? { anchor: { row: index, column: 0 }, head: { row: index, column: table.columns - 1 } }
: { anchor: { row: 0, column: index }, head: { row: table.rows.length - 2, column: index } });
const moving = operation === "previous" || operation === "next";
const other = index + (operation === "previous" ? -1 : 1);
// The Markdown header stays a header; row movement and sorting affect the body.
if (moving && (other < (axis === "row" ? 1 : 0) || other >= size || (axis === "row" && index === 0))) return source;
if (axis === "row") {
if (index === 0 && operation === "before") return source;
const rows = table.rows.map(row => source.slice(row.from, row.to));
const at = index === 0 ? 0 : index + 1;
if (moving) [rows[at], rows[other + 1]] = [rows[other + 1], rows[at]];
else {
const value = operation === "duplicate" ? rows[at] : `${table.rows[0].indent}| ${Array(table.columns).fill("").join(" | ")} |`;
rows.splice(index === 0 ? 2 : at + (operation === "before" ? 0 : 1), 0, value);
}
return rows.join(table.eol) + source.slice(table.end);
}
const rows = table.rows.map((row, r) => {
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || "");
if (moving) [cells[index], cells[other]] = [cells[other], cells[index]];
else cells.splice(index + (operation === "before" ? 0 : 1), 0, operation === "duplicate" ? cells[index] : r === 1 ? "---" : "");
return `${row.indent}| ${cells.join(" | ")} |`;
});
return rows.join(table.eol) + source.slice(table.end);
}
export function sortTableColumn(source: string, column: number, descending = false): string {
const table = parseMarkdownTable(source);
if (!table || column < 0 || column >= table.columns) return source;
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
const key = (text: string) => plainInlineMarkdown(text).replace(/<br>/g, " ").replace(/\\([\\`*_[\]~<>!|=$%])/g, "$1").trim();
const rows = table.rows.slice(2).map(row => ({ row, key: key(row.cells[column]?.text || "") }));
rows.sort((a, b) => !a.key ? (b.key ? 1 : 0) : !b.key ? -1 : collator.compare(a.key, b.key) * (descending ? -1 : 1));
return [...table.rows.slice(0, 2), ...rows.map(item => item.row)].map(row => source.slice(row.from, row.to)).join(table.eol) + source.slice(table.end);
}
+26
View File
@@ -0,0 +1,26 @@
import { isImagePath } from "../workspace/media";
type Point = { x: number; y: number };
const targets = new Map<HTMLElement, (path: string, point: Point) => void>();
let highlighted: HTMLElement | undefined;
export function registerImageDropTarget(element: HTMLElement, drop: (path: string, point: Point) => void) {
targets.set(element, drop);
return () => { targets.delete(element); element.classList.remove("image-drop-target"); };
}
function targetAt(path: string, point: Point) {
if (!isImagePath(path)) return;
const hit = document.elementFromPoint(point.x, point.y);
return [...targets].find(([element]) => element.isConnected && hit && element.contains(hit));
}
export function highlightImageDrop(path?: string, point?: Point): boolean {
highlighted?.classList.remove("image-drop-target");
highlighted = path && point ? targetAt(path, point)?.[0] : undefined;
highlighted?.classList.add("image-drop-target");
return !!highlighted;
}
export function dropWorkspaceImage(path: string, point: Point): boolean {
const target = targetAt(path, point);
highlightImageDrop();
target?.[1](path, point);
return !!target;
}
+21
View File
@@ -0,0 +1,21 @@
import { Mark } from "@tiptap/core";
export const MathMark = Mark.create({
name: "math",
parseHTML() {
return [{ tag: "span[data-math]" }];
},
renderHTML() {
return ["span", { "data-math": "1", class: "md-math" }, 0];
},
});
export const CommentMark = Mark.create({
name: "comment",
parseHTML() {
return [{ tag: "span[data-comment]" }];
},
renderHTML() {
return ["span", { "data-comment": "1", class: "md-comment" }, 0];
},
});
+143
View File
@@ -0,0 +1,143 @@
import type { Editor } from "@tiptap/core";
import type { MenuItem } from "../layout/menuTypes";
function selectedText(editor: Editor): string {
const { from, to } = editor.state.selection;
return editor.state.doc.textBetween(from, to, "\n");
}
async function writeClipboard(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
}
export async function cutSelection(editor: Editor): Promise<void> {
const text = selectedText(editor);
if (text && !(await writeClipboard(text))) {
return;
}
editor.chain().focus().deleteSelection().run();
}
export async function copySelection(editor: Editor): Promise<void> {
const text = selectedText(editor);
if (text) {
await writeClipboard(text);
}
}
export async function pasteClipboard(editor: Editor): Promise<void> {
let text = "";
try {
text = await navigator.clipboard.readText();
} catch {
return;
}
if (!text) {
return;
}
editor.chain().focus().run();
editor.view.dispatch(editor.state.tr.insertText(text));
}
export function writerContextItems(editor: Editor): MenuItem[] {
const inTable = editor.isActive("table");
return [
{ kind: "action", label: "Cut", run: () => void cutSelection(editor) },
{ kind: "action", label: "Copy", run: () => void copySelection(editor) },
{ kind: "action", label: "Paste", run: () => void pasteClipboard(editor) },
{ kind: "sep" },
{
kind: "group",
label: "Style",
items: [
{ kind: "action", label: "Heading 1", run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() },
{ kind: "action", label: "Heading 2", run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() },
{ kind: "action", label: "Heading 3", run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() },
{ kind: "action", label: "Heading 4", run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() },
{ kind: "action", label: "Heading 5", run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() },
{ kind: "action", label: "Heading 6", run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() },
{ kind: "action", label: "Body", run: () => editor.chain().focus().setParagraph().run() },
{ kind: "action", label: "Quote", run: () => editor.chain().focus().toggleBlockquote().run() },
{ kind: "sep" },
{ kind: "action", label: "Bullet list", run: () => editor.chain().focus().toggleBulletList().run() },
{ kind: "action", label: "Numbered list", run: () => editor.chain().focus().toggleOrderedList().run() },
{ kind: "action", label: "Task list", run: () => editor.chain().focus().toggleTaskList().run() },
],
},
{
kind: "group",
label: "Format",
items: [
{ kind: "action", label: "Bold", run: () => editor.chain().focus().toggleBold().run() },
{ kind: "action", label: "Italic", run: () => editor.chain().focus().toggleItalic().run() },
{ kind: "action", label: "Strikethrough", run: () => editor.chain().focus().toggleStrike().run() },
{ kind: "action", label: "Highlight", run: () => editor.chain().focus().toggleHighlight().run() },
{ kind: "action", label: "Code", run: () => editor.chain().focus().toggleCode().run() },
{ kind: "action", label: "Math", run: () => editor.chain().focus().toggleMark("math").run() },
{ kind: "action", label: "Comment", run: () => editor.chain().focus().toggleMark("comment").run() },
{ kind: "sep" },
{ kind: "action", label: "Clear formatting", run: () => editor.chain().focus().unsetAllMarks().run() },
],
},
{
kind: "group",
label: "Table",
items: [
{
kind: "action",
label: "Insert table",
run: () => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
},
{ kind: "sep" },
{
kind: "action",
label: "Add row above",
disabled: !inTable,
run: () => editor.chain().focus().addRowBefore().run(),
},
{
kind: "action",
label: "Add row below",
disabled: !inTable,
run: () => editor.chain().focus().addRowAfter().run(),
},
{
kind: "action",
label: "Delete row",
disabled: !inTable,
run: () => editor.chain().focus().deleteRow().run(),
},
{ kind: "sep" },
{
kind: "action",
label: "Add column left",
disabled: !inTable,
run: () => editor.chain().focus().addColumnBefore().run(),
},
{
kind: "action",
label: "Add column right",
disabled: !inTable,
run: () => editor.chain().focus().addColumnAfter().run(),
},
{
kind: "action",
label: "Delete column",
disabled: !inTable,
run: () => editor.chain().focus().deleteColumn().run(),
},
{
kind: "action",
label: "Delete table",
disabled: !inTable,
run: () => editor.chain().focus().deleteTable().run(),
},
],
},
];
}