30 lines
1.4 KiB
TypeScript
30 lines
1.4 KiB
TypeScript
import MarkdownIt from "markdown-it";
|
|
import type { Token } from "markdown-it";
|
|
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "./formulas.ts";
|
|
const escapeHtml = (text: string) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
|
|
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>`;
|
|
}
|
|
|
|
export function renderTableFormulas(tokens: Token[]) {
|
|
let rows: Token[][] | undefined;
|
|
for (const token of 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;
|
|
}
|
|
}
|
|
}
|