mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
The CSV/TSV viewer (explorer, gists, the author's preview) becomes an analysis view that runs on the anonymized text already in the page: click-to-sort headers (numbers, dates, natural text; stable, empty cells last), a search box and per-column range or value filters, a summary row (Average by default; Sum, Median, Min, Max, Count, Std dev) over the filtered rows, group by with an aggregate, column stats with a histogram, copy as CSV or Markdown and download of the current view, and a Chart view (bar, line, scatter) drawn in inline SVG. The view lives in the URL fragment (#table:group=model, #table-2:... for a gist file) so a link can carry it; links without it open as before. Markdown and notebook tables (pandas DataFrames) get sortable headers, an optional summary row and "Open as table" for the full view. Redaction slots keep rendering; sorting uses the XXXX-n text. The 1 MB limit holds: rows render 200 at a time as one escaped HTML string while aggregates, filters and charts use every row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
180 lines
8.0 KiB
JavaScript
180 lines
8.0 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 } 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 with one aggregate for every numeric column (Average first).
|
|
const numeric = model.columns.some((c) => c.type === "number");
|
|
const tools = doc.createElement("div");
|
|
tools.className = "md-table-tools";
|
|
let foot = null, fn = "mean", select = null;
|
|
const renderFoot = () => {
|
|
if (!foot) return;
|
|
const all = original.map((_, i) => i);
|
|
const tr = foot.rows[0];
|
|
tr.textContent = "";
|
|
let labelled = false;
|
|
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 (c.type === "number") {
|
|
td.className = "is-num";
|
|
td.textContent = summarize(c, all, fn).text;
|
|
} else if (!labelled && i === 0) {
|
|
td.className = "md-summary-label";
|
|
td.textContent = AGGREGATES.find(([k]) => k === fn)[1];
|
|
labelled = true;
|
|
} else {
|
|
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>';
|
|
select = doc.createElement("select");
|
|
select.className = "md-table-agg";
|
|
select.setAttribute("aria-label", "Summary");
|
|
select.hidden = true;
|
|
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(); });
|
|
sigma.addEventListener("click", () => {
|
|
const on = !foot;
|
|
sigma.setAttribute("aria-pressed", on ? "true" : "false");
|
|
sigma.classList.toggle("is-on", on);
|
|
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.append(sigma, select);
|
|
}
|
|
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); },
|
|
};
|