// 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, aggregateShort } 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: each measure with its own small // aggregate select (Average first), distinct counts under text columns, // nothing under identifiers. A first text column carries the Σ mark. const measure = (c) => c.type === "number" && !c.identifier; const numeric = model.columns.some(measure); const markFirst = model.columns.length > 1 && model.columns[0].type !== "number"; const tools = doc.createElement("div"); tools.className = "md-table-tools"; let foot = null; const fns = model.columns.map(() => "mean"); const aggCell = (c, i, all) => { const wrap = doc.createElement("span"); wrap.className = "dt-sum"; const label = doc.createElement("label"); label.className = "dt-sum-fn"; const select = doc.createElement("select"); select.setAttribute("aria-label", "Summary of " + (c.name || "column " + (i + 1))); AGGREGATES.forEach(([k, text]) => { const o = doc.createElement("option"); o.value = k; o.textContent = text; select.appendChild(o); }); select.value = fns[i]; select.addEventListener("change", () => { fns[i] = select.value; renderFoot(); }); const short = doc.createElement("span"); short.className = "dt-sum-fn-label"; short.setAttribute("aria-hidden", "true"); short.textContent = aggregateShort(fns[i]); label.append(select, short); label.insertAdjacentHTML("beforeend", ''); const value = doc.createElement("b"); value.className = "dt-sum-value"; value.textContent = summarize(c, all, fns[i]).text; wrap.append(label, value); return wrap; }; 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"); if (i === 0 && markFirst) { td.className = "md-summary-label"; td.innerHTML = 'Summary'; } else if (measure(c)) { td.className = "is-num"; td.appendChild(aggCell(c, i, all)); } else if (c.type !== "number") { td.className = "is-muted"; td.textContent = summarize(c, all).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'; sigma.addEventListener("click", () => { const on = !foot; sigma.setAttribute("aria-pressed", on ? "true" : "false"); sigma.classList.toggle("is-on", 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); } 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); }, };