mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
- The table's scroll box is now its rounded frame (border, 8px radius, clipping): the sticky header and the summary row are clipped to the same corners top and bottom, and the box ends at the summary row, so no row shows below it. In gists the frame keeps its border. - The summary row is back to its earlier content: Σ in the row-number column, a small "Avg ▾" select before each numeric value, "N distinct" under text columns, in muted labels with semibold right-aligned values. The single row-wide select is gone. - Identifier columns (seed, run...) stay empty, with "Treat as number" in the column menu. - Markdown and notebook tables use the same cells: Σ in a first text column, "Avg ▾" per numeric column, distinct counts muted. - "Show more" sits under the frame instead of inside the scroll box. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
189 lines
8.8 KiB
JavaScript
189 lines
8.8 KiB
JavaScript
// 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 <tr>], headerCells: [<th>] } 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 = '<svg class="dt-sort-icon" viewBox="0 0 10 14" aria-hidden="true"><path class="up" d="M5 1.5 8.5 5.5h-7z"/><path class="down" d="M5 12.5 1.5 8.5h7z"/></svg>';
|
|
|
|
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", '<svg class="ui-icon dt-sum-caret" aria-hidden="true"><use href="#ui-icon-chevron-down"></use></svg>');
|
|
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 = '<span aria-hidden="true">Σ</span><span class="sr-only">Summary</span>'; }
|
|
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 = '<span aria-hidden="true">Σ</span><span class="md-table-btn-text">Summary</span>';
|
|
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 = '<svg class="ui-icon" aria-hidden="true"><use href="#ui-icon-chart"></use></svg><span>Open as table</span>';
|
|
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); },
|
|
};
|