Phase 4f. - scripts/i18nAudit.mjs runs in pnpm check. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all four languages. - message() marks a key that a variable carries to the translation call later: table formats, formula errors, and browser status messages. - 53 new rows with French, Japanese, and Simplified Chinese text for the status and error messages of the workbench, the tree, Settings, theme import, images, the built-in browser, and code blocks. The backlinks toggle now translates too. - 13 unused rows are gone. - Errors of the plugin API stay in English. docs/development.md has the rule in "Interface text". pnpm check, pnpm test (350 of 350), and the full smoke suite pass, except two tests that failed one time under load and passed on retry and 3 of 3 times alone.
233 lines
12 KiB
TypeScript
233 lines
12 KiB
TypeScript
import { tr } from "../i18n/index.ts";
|
|
import MarkdownIt from "markdown-it";
|
|
import type { Token } from "markdown-it";
|
|
import { inlineMathEnd } from "./inlineMath.ts";
|
|
import { activeTableFormulas } from "../formulas/index.ts";
|
|
import { hasTableDelimiter } from "../editor/markdownTable.ts";
|
|
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
|
|
|
|
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
|
|
markdown.use(footnotes);
|
|
export const escapeHtml = markdown.utils.escapeHtml;
|
|
|
|
// Require a row delimiter so deleting a blank line cannot turn prose into cells.
|
|
// Markdown-it checks blockquote terminators while it reads a table body.
|
|
markdown.block.ruler.before("table", "table_prose_boundary", (state, line, _end, silent) => {
|
|
return silent && state.parentType === "table" &&
|
|
!hasTableDelimiter(state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]));
|
|
}, { alt: ["blockquote"] });
|
|
|
|
// 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) return false;
|
|
let end = state.pos + marker.length;
|
|
if (marker === "$") {
|
|
end = inlineMathEnd(state.src, state.pos, state.posMax);
|
|
if (end < 0) return false;
|
|
} else {
|
|
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, "&").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}]]` : `.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="${tr("Copy code")}" title="${tr("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="${tr("Mermaid diagram")}"></div><details class="md-diagram-source"><summary>${tr("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';
|
|
|
|
markdown.core.ruler.after("inline", "table_formulas", state => {
|
|
activeTableFormulas()?.renderTableFormulas(state.tokens);
|
|
});
|
|
|
|
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 documentBodyStart(contents: string): number {
|
|
return contents.length - documentParts(contents).body.length;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
const env: FootnoteEnvironment = {};
|
|
visit(markdown.parse(documentParts(contents).body, env));
|
|
for (const note of env.noteFootnotes?.values() ?? []) visit(note.tokens);
|
|
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` : "";
|
|
const env = { urls };
|
|
return metadata + markdown.render(body, env) + renderFootnotes(markdown, env);
|
|
}
|
|
|
|
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;
|
|
}
|