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
+231
View File
@@ -0,0 +1,231 @@
import MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "../editor/tableFormulas.ts";
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
export const escapeHtml = markdown.utils.escapeHtml;
// Inline note formats also round-trip through the table cell editor.
markdown.inline.ruler.before("emphasis", "note_formats", (state, silent) => {
const marker = ["==", "%%", "$"].find(value => state.src.startsWith(value, state.pos));
if (!marker || (marker === "$" && state.src.startsWith("$$", state.pos))) return false;
let end = state.pos + marker.length;
for (; end < state.posMax; end++) {
if (state.src[end] === "\\") { end++; continue; }
if (state.src.startsWith(marker, end)) break;
}
if (end >= state.posMax || end === state.pos + marker.length) return false;
if (!silent) {
const kind = marker === "==" ? "highlight" : marker === "$" ? "math" : "comment";
const token = state.push(`note_${kind}`, "", 0);
token.content = state.src.slice(state.pos + marker.length, end);
}
state.pos = end + marker.length;
return true;
});
for (const kind of ["highlight", "math", "comment"]) {
markdown.renderer.rules[`note_${kind}`] = (tokens, index, _options, env) => {
const content = tokens[index].content;
return kind === "highlight" ? `<mark>${markdown.renderInline(content, env)}</mark>` : `<span data-cell-format="${kind}" class="md-inline-${kind}">${escapeHtml(content)}</span>`;
};
}
export function plainInlineMarkdown(source: string): string {
const literal = (text: string) => text.replace(/&/g, "&amp;").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`);
function plain(tokens: Token[]): string {
return tokens.map(token => {
if (token.type === "note_highlight") return plain(markdown.parseInline(token.content, {}));
if (token.type === "hardbreak" || token.type === "softbreak") return "<br>";
if (token.type === "image") {
const target = String(token.attrGet("src") || "");
const label = plain(token.children || []);
return token.attrGet("data-md-kind") === "wiki" ? `![[${literal(target)}\\|${label}]]` : `![${label}](<${target.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`;
}
if (token.children) return plain(token.children);
return token.nesting === 0 ? literal(token.content) : "";
}).join("");
}
return plain(markdown.parseInline(source, {}));
}
// Obsidian-style table cells use <br> for line breaks. Recognize only this
// attribute-free tag; arbitrary HTML remains escaped, including inside cells.
markdown.inline.ruler.before("html_inline", "note_line_break", (state, silent) => {
const match = /^<br\s*\/?>/i.exec(state.src.slice(state.pos));
if (!match) return false;
if (!silent) state.push("hardbreak", "br", 0);
state.pos += match[0].length;
return true;
});
const copyIcon = '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h4"/></svg>';
// Parse wiki links as inline tokens, so code spans and fenced code stay literal.
markdown.inline.ruler.before("link", "wiki_link", (state, silent) => {
const match = /^(!?)\[\[([^\]\n]+)\]\]/.exec(state.src.slice(state.pos));
if (!match) return false;
const [target, ...alias] = match[2].split("|");
const label = alias.join("|") || target;
if (!target.trim() || !markdown.validateLink(target)) return false;
if (!silent) {
if (match[1]) {
const image = state.push("image", "img", 0);
image.attrs = [["src", target.trim()], ["alt", label], ["data-md-kind", "wiki"]];
image.content = label;
const text = new MarkdownIt.Token("text", "", 0);
text.content = label;
image.children = [text];
} else {
const open = state.push("link_open", "a", 1);
open.attrs = [["href", target.trim()], ["data-kind", "wiki"], ["class", "wiki"]];
state.push("text", "", 0).content = label;
state.push("link_close", "a", -1);
}
}
state.pos += match[0].length;
return true;
});
markdown.core.ruler.after("inline", "note_blocks", state => {
for (let i = 0; i < state.tokens.length; i++) {
const token = state.tokens[i];
if (token.type !== "inline" || !token.children?.length) continue;
const first = token.children[0];
if (first.type !== "text") continue;
const item = state.tokens[i - 2];
const task = /^\[([ xX])\]\s+/.exec(first.content);
if (task && item?.type === "list_item_open") {
const checked = task[1].toLowerCase() === "x";
item.attrJoin("class", `task-list-item${checked ? " is-checked" : ""}`);
first.content = first.content.slice(task[0].length);
const checkbox = new MarkdownIt.Token("html_inline", "", 0);
checkbox.content = `<input type="checkbox" disabled aria-label="${checked ? "Completed task" : "Incomplete task"}"${checked ? " checked" : ""}> `;
token.children.unshift(checkbox);
for (let parent = i - 3; parent >= 0; parent--) {
const ancestor = state.tokens[parent];
if ((ancestor.type === "bullet_list_open" || ancestor.type === "ordered_list_open") && ancestor.level < item.level) {
ancestor.attrJoin("class", "contains-task-list");
break;
}
}
}
const callout = /^\[!(note|tip|info|warning|danger|important|success|question)\][+-]?(?:[ \t]+([^\n]*))?(?:\n|$)/i.exec(first.content);
if (callout && item?.type === "blockquote_open") {
item.attrJoin("class", "md-callout");
item.attrSet("data-callout", callout[1].toLowerCase());
const title = callout[2] || callout[1].charAt(0).toUpperCase() + callout[1].slice(1).toLowerCase();
first.content = first.content.slice(callout[0].length);
if (!first.content && token.children[1]?.type === "softbreak") token.children.splice(1, 1);
const heading = new MarkdownIt.Token("html_inline", "", 0);
heading.content = `<strong class="md-callout-title">${escapeHtml(title)}</strong>`;
token.children.unshift(heading);
}
}
});
markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => {
if (!tokens[index].attrGet("data-kind")) tokens[index].attrSet("data-kind", "md");
return renderer.renderToken(tokens, index, options);
};
markdown.renderer.rules.fence = (tokens, index) => {
const token = tokens[index];
const language = token.info.trim().split(/\s+/)[0];
const code = `<pre class="md-code" data-lang="${escapeHtml(language || "code")}"><button type="button" class="rs-fence-copy" aria-label="Copy code" title="Copy code">${copyIcon}</button><code${language ? ` class="language-${escapeHtml(language)}"` : ""}>${escapeHtml(token.content)}</code></pre>\n`;
return language.toLowerCase() === "mermaid"
? `<div class="md-mermaid"><div class="md-diagram" aria-label="Mermaid diagram"></div><details class="md-diagram-source"><summary>Diagram source</summary>${code}</details></div>\n`
: code;
};
markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
const token = tokens[index];
const original = String(token.attrGet("src") || "");
const urls = env?.urls as Map<string, string> | undefined;
const resolved = urls?.get(original) || (/^https?:\/\//i.test(original) ? original : "");
const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env);
// Only app-resolved image data or HTTP(S) URLs become image sources.
if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `<span class="missing-image" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" alt="${escapeHtml(alt)}">Image unavailable: ${escapeHtml(alt || original)}</span>`;
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" loading="lazy">`;
};
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
markdown.renderer.rules.table_close = () => '</table></div>\n';
export function tableFormulaHtml(result: FormulaResult): string {
const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`;
return `<span class="md-table-formula${result.error ? " is-error" : ""}" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${escapeHtml(result.text)}</span>`;
}
// Work from raw inline content, before Markdown formatting can interpret * or $.
// Each table gets its own reference scope, including in nested lists/callouts.
markdown.core.ruler.after("inline", "table_formulas", state => {
let rows: Token[][] | undefined;
for (const token of state.tokens) {
if (token.type === "table_open") rows = [];
else if (rows && token.type === "tr_open") rows.push([]);
else if (rows && token.type === "inline") rows.at(-1)?.push(token);
else if (rows && token.type === "table_close") {
const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content)));
rows.forEach((row, r) => row.forEach((cell, c) => {
const result = results[r][c];
if (!result) return;
const output = new MarkdownIt.Token("html_inline", "", 0);
output.content = tableFormulaHtml(result);
cell.children = [output];
}));
rows = undefined;
}
}
});
function documentParts(contents: string) {
const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(contents);
return match ? { body: contents.slice(match[0].length), properties: match[1] } : { body: contents, properties: "" };
}
export function markdownImages(contents: string): string[] {
const paths = new Set<string>();
function visit(tokens: Token[]) {
for (const token of tokens) {
if (token.type === "image") paths.add(String(token.attrGet("src") || ""));
if (token.children) visit(token.children);
}
}
visit(markdown.parse(documentParts(contents).body, {}));
return [...paths];
}
export function renderMarkdownHtml(contents: string, urls: Map<string, string>): string {
const { body, properties } = documentParts(contents);
const metadata = properties ? `<details class="md-properties"><summary>Properties</summary><pre>${escapeHtml(properties)}</pre></details>\n` : "";
return metadata + markdown.render(body, { urls });
}
export type MarkdownSection = { start: number; end: number; html: string };
// Render with the entire document's reference environment, retaining exact source
// offsets so editing one block never serializes the rest of the document.
export function renderMarkdownSections(contents: string, urls: Map<string, string>): MarkdownSection[] {
const { body, properties } = documentParts(contents);
const offset = contents.length - body.length;
const lines = [offset];
for (const match of body.matchAll(/\n/g)) lines.push(offset + match.index + 1);
const env = { urls };
const tokens = markdown.parse(body, env);
const sections: MarkdownSection[] = [];
if (offset) sections.push({ start: 0, end: offset, html: `<details class="md-properties"><summary>Properties</summary><pre>${escapeHtml(properties)}</pre></details>` });
for (let i = 0; i < tokens.length;) {
const token = tokens[i];
const start = token.map ? (lines[token.map[0]] ?? contents.length) : offset;
let end = i + 1;
if (token.nesting === 1) {
let depth = 1;
while (end < tokens.length && depth) depth += tokens[end++].nesting;
}
sections.push({ start, end: contents.length, html: markdown.renderer.render(tokens.slice(i, end), markdown.options, env) });
i = end;
}
if (!sections.length) sections.push({ start: 0, end: contents.length, html: "" });
sections[0].start = 0;
for (let i = 0; i < sections.length - 1; i++) sections[i].end = sections[i + 1].start;
return sections;
}