// Tables inside rendered Markdown and notebook outputs (pandas DataFrames) get
// a light version of the table viewer: click a header to sort, an optional Σ
// summary row, and "Open as table" for the full analysis view. Redaction slots
// stay in place (rows are moved, never re-rendered); sorting and the exported
// data use the anonymized text (XXXX-n).
import { analyzeTable, sortIndices, summarize, AGGREGATES } from "./table-analysis.js";
// "Open as table" opens the full viewer; data-table.js registers it (kept out of
// this module so the extraction can be tested without the compiled template).
let openTable = null;
export const setTableOpener = (fn) => { openTable = fn; };
const SKIP = ".dt, .csv-table, pre, .diff-file-table, .md-table-off";
// A cell's text with its redaction chips or slots read back as XXXX-n.
export function cellText(cell) {
const copy = cell.cloneNode(true);
copy.querySelectorAll("mark.redact-chip[data-term]").forEach((m) => m.replaceWith(m.dataset.term));
copy.querySelectorAll(".redact-slot").forEach((m) => m.replaceWith("XXXX-" + (m.textContent || "").trim()));
copy.querySelectorAll(".md-sort").forEach((m) => m.remove());
return copy.textContent.replace(/\s+/g, " ").trim();
}
const spans = (row) => [...row.cells].some((c) => c.colSpan > 1 || c.rowSpan > 1);
// { header: [text], trs: [body
], headerCells: [
] } or null for tables
// this light mode can't handle (merged cells, fewer than two data rows).
export function tableData(table) {
if (!table?.rows?.length || table.closest(SKIP) || table.parentElement?.closest?.("table")) return null;
let headRows = table.tHead ? [...table.tHead.rows] : [];
let trs = [...table.tBodies].flatMap((b) => [...b.rows]);
if (!headRows.length) {
const first = table.rows[0];
if (!first || ![...first.cells].every((c) => c.tagName === "TH")) return null;
headRows = [first];
trs = trs.filter((r) => r !== first);
}
if (trs.length < 2 || trs.some(spans)) return null;
// pandas writes the column names and the index name on two header rows.
if (headRows.some(spans) && headRows.length > 1) return null;
const width = Math.max(...trs.map((r) => r.cells.length), ...headRows.map((r) => r.cells.length));
if (headRows.some((r) => r.cells.length !== width && spans(r))) return null;
const header = Array.from({ length: width }, (_, i) => headRows.map((r) => (r.cells[i] ? cellText(r.cells[i]) : "")).filter(Boolean).join(" ") || (i === 0 ? "" : "Column " + (i + 1)));
const rows = [header, ...trs.map((r) => Array.from({ length: width }, (_, i) => (r.cells[i] ? cellText(r.cells[i]) : "")))];
return { rows, trs, headerCells: [...headRows[headRows.length - 1].cells] };
}
const SORT_ICON = '';
function titleFor(table) {
const root = table.closest(".markdown-body, notebook, markdown") || table.ownerDocument.body;
let title = "";
for (const h of root.querySelectorAll("h1, h2, h3, h4")) {
if (h.compareDocumentPosition(table) & 4) title = h.textContent.replace(/\s+/g, " ").trim(); else break;
}
return title ? "Table · " + title : "Table";
}
function enhance(table) {
if (table.dataset.dtEnhanced) return;
const data = tableData(table);
if (!data) return;
table.dataset.dtEnhanced = "1";
const doc = table.ownerDocument;
const model = analyzeTable(data.rows);
const original = data.trs.slice();
const parentOf = new Map(original.map((tr) => [tr, tr.parentNode]));
let sort = null;
const wrap = doc.createElement("div");
wrap.className = "md-table";
table.parentNode.insertBefore(wrap, table);
wrap.appendChild(table);
const apply = () => {
const order = sort ? sortIndices(model, original.map((_, i) => i), sort.index, sort.dir) : original.map((_, i) => i);
order.forEach((i) => parentOf.get(original[i]).appendChild(original[i]));
data.headerCells.forEach((th, i) => {
const dir = sort && sort.index === i ? sort.dir : null;
th.setAttribute("aria-sort", dir === "asc" ? "ascending" : dir === "desc" ? "descending" : "none");
th.querySelector(".dt-sort-icon")?.setAttribute("class", "dt-sort-icon" + (dir ? " is-" + dir : ""));
});
};
data.headerCells.forEach((th, i) => {
if (i >= model.columns.length) return;
th.classList.add("md-sortable");
const button = doc.createElement("button");
button.type = "button";
button.className = "md-sort";
button.setAttribute("aria-label", "Sort by " + (model.columns[i].name || "column " + (i + 1)));
button.innerHTML = SORT_ICON;
th.appendChild(button);
th.addEventListener("click", (event) => {
if (event.target.closest("a")) return;
const dir = sort && sort.index === i ? sort.dir : null;
sort = dir === "asc" ? { index: i, dir: "desc" } : dir === "desc" ? null : { index: i, dir: "asc" };
apply();
});
});
apply();
// Σ: a footer row like the table viewer's: one aggregate for every measure,
// chosen with a single select in the first column (or beside Σ when the
// first column holds a value). Text and identifier columns stay empty.
const measure = (c) => c.type === "number" && !c.identifier;
const numeric = model.columns.some(measure);
const labelInFirst = model.columns.length > 1 && !measure(model.columns[0]);
const tools = doc.createElement("div");
tools.className = "md-table-tools";
let foot = null, fn = "mean";
const select = doc.createElement("select");
select.className = "md-table-agg";
select.setAttribute("aria-label", "Summary row");
AGGREGATES.forEach(([k, text]) => { const o = doc.createElement("option"); o.value = k; o.textContent = text; select.appendChild(o); });
select.addEventListener("change", () => { fn = select.value; renderFoot(); });
const renderFoot = () => {
if (!foot) return;
const all = original.map((_, i) => i);
const tr = foot.rows[0];
tr.textContent = "";
model.columns.forEach((c, i) => {
const td = doc.createElement("td");
const align = data.headerCells[i]?.getAttribute("align") || data.headerCells[i]?.style.textAlign;
if (align) td.style.textAlign = align;
if (i === 0 && labelInFirst) { td.className = "md-summary-label"; td.appendChild(select); }
else if (measure(c)) { td.className = "is-num"; td.textContent = summarize(c, all, fn).text; }
tr.appendChild(td);
});
};
if (numeric) {
const sigma = doc.createElement("button");
sigma.type = "button";
sigma.className = "md-table-btn md-sigma";
sigma.setAttribute("aria-pressed", "false");
sigma.title = "Show a summary row";
sigma.innerHTML = 'ΣSummary';
if (!labelInFirst) select.hidden = true;
sigma.addEventListener("click", () => {
const on = !foot;
sigma.setAttribute("aria-pressed", on ? "true" : "false");
sigma.classList.toggle("is-on", on);
if (!labelInFirst) select.hidden = !on;
if (on) {
foot = doc.createElement("tfoot");
foot.className = "md-summary";
foot.appendChild(doc.createElement("tr"));
table.appendChild(foot);
renderFoot();
} else { foot.remove(); foot = null; }
});
tools.appendChild(sigma);
if (!labelInFirst) tools.appendChild(select);
}
const open = doc.createElement("button");
open.type = "button";
open.className = "md-table-btn md-open";
open.innerHTML = 'Open as table';
open.addEventListener("click", () => openTable?.(data.rows, titleFor(table)));
tools.appendChild(open);
wrap.appendChild(tools);
}
export function enhanceTables(root) {
if (!root?.querySelectorAll) return;
root.querySelectorAll("table:not([data-dt-enhanced])").forEach((table) => {
try { enhance(table); } catch { table.dataset.dtEnhanced = "error"; }
});
}
// v-data-tables on v-html Markdown: enhance after each render (idempotent).
export const dataTablesDirective = {
mounted(el) { enhanceTables(el); },
updated(el) { enhanceTables(el); },
};