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
+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))],
})];
}