// The table viewer shared by CSV/TSV files (explorer, gists, the author's // preview) and "Open as table" on Markdown and notebook tables: sort, filter, // summary row, group by, column stats, charts and export. Everything runs on // the anonymized text already in the page; nothing is sent anywhere. import { reactive, computed, watch, ref, onMounted, onBeforeUnmount, nextTick, createApp, h } from "vue"; import { analyzeTable, filterIndices, sortIndices, groupTable, summarize, columnStats, distinctValues, formatKey, formatNumber, toDelimited, toMarkdown, readHashState, writeHashState, isTableHash, AGGREGATES, AGGREGATE_LABEL, aggregateShort, } from "./table-analysis.js"; import { buildChart, defaultChart, MAX_SERIES } from "./table-chart.js"; import { redactParts } from "./outline.js"; import { render as dataTableTemplate } from "../partials/dataTable.htm"; import { setTableOpener } from "./table-enhance.js"; export const PAGE_SIZE = 200; const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }; const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (ch) => ESCAPES[ch]); export const cellHtml = (text) => { const value = text == null ? "" : String(text); if (value.indexOf("XXXX-") === -1) return escapeHtml(value); return redactParts(value).map((seg) => (seg.n ? `${seg.n}` : escapeHtml(seg.t))).join(""); }; const CHIP_LIMIT = 24; export const DataTable = { name: "DataTable", props: { rows: { type: Array, default: () => [] }, name: String, stateKey: String, view: { type: String, default: "table" }, label: String }, setup(props) { const fromHash = props.stateKey ? readHashState(window.location.hash, props.stateKey) : null; const s = reactive({ query: fromHash?.query || "", sort: fromHash?.sort || null, group: fromHash?.group || null, agg: fromHash?.agg || "mean", ranges: fromHash?.ranges || {}, values: fromHash?.values || {}, sums: fromHash?.sums || {}, sum: fromHash?.sum || "mean", numeric: fromHash?.numeric || [], chart: fromHash?.chart || null, x: fromHash?.x || null, y: fromHash?.y || [], limit: PAGE_SIZE, menu: null, toolsOpen: false, copyOpen: false, copied: "", tip: null, }); const base = computed(() => analyzeTable(props.rows)); const byName = (table, name) => table.columns.find((c) => c.name === name); const indexed = (map) => Object.fromEntries(Object.entries(map).map(([name, v]) => [byName(base.value, name)?.index, v]).filter(([i]) => i != null)); const filtered = computed(() => filterIndices(base.value, { query: s.query, ranges: indexed(s.ranges), values: indexed(s.values) })); const groupColumn = computed(() => (s.group ? byName(base.value, s.group) : null)); // Identifier columns (seed, run, fold...) are not measures unless the reader says so. const isMeasure = (c) => c.type === "number" && (!c.identifier || (!table.value?.grouped && s.numeric.includes(c.name))); const isBaseMeasure = (c) => c.type === "number" && (!c.identifier || s.numeric.includes(c.name)); const table = computed(() => (groupColumn.value ? groupTable(base.value, filtered.value, groupColumn.value.index, s.agg, isBaseMeasure) : base.value)); const rowsInView = computed(() => (groupColumn.value ? table.value.body.map((_, i) => i) : filtered.value)); const sortColumn = computed(() => (s.sort ? byName(table.value, s.sort.column) : null)); const sorted = computed(() => (sortColumn.value ? sortIndices(table.value, rowsInView.value, sortColumn.value.index, s.sort.dir) : rowsInView.value)); const visible = computed(() => sorted.value.slice(0, s.limit)); // One aggregate for the whole summary row; a column can override it from its menu. const summary = computed(() => table.value.columns.map((c) => summarize(c, rowsInView.value, s.sums[c.name] || s.sum, isMeasure))); const sumOverride = (c) => (s.sums[c.name] && s.sums[c.name] !== s.sum ? s.sums[c.name] : null); // The row's single "Average ▾" goes in the first column when it holds no // value (a name, a group), else in the row-number column. const sumInFirst = computed(() => !!groupColumn.value || !isMeasure(table.value.columns[0] || {})); const hasSummary = computed(() => summary.value.some((x) => x.kind === "number")); const numericColumns = computed(() => table.value.columns.filter((c) => isMeasure(c))); // ---- Sorting: ascending, descending, then the file's order ---- const sortState = (column) => (s.sort && s.sort.column === column.name ? s.sort.dir : null); const cycleSort = (column) => { const dir = sortState(column); s.sort = dir === "asc" ? { column: column.name, dir: "desc" } : dir === "desc" ? null : { column: column.name, dir: "asc" }; }; const setSort = (column, dir) => { s.sort = dir ? { column: column.name, dir } : null; }; const ariaSort = (column) => ({ asc: "ascending", desc: "descending" })[sortState(column)] || "none"; // ---- Filters ---- const sourceColumn = (column) => (groupColumn.value ? (column.source != null ? base.value.columns[column.source] : null) : column); const setRange = (column, end, value) => { const source = sourceColumn(column); if (!source) return; const text = String(value ?? "").trim(); const number = text === "" ? null : Number(text.replace(/,/g, "")); const current = s.ranges[source.name] || [null, null]; const next = end === 0 ? [Number.isFinite(number) ? number : null, current[1]] : [current[0], Number.isFinite(number) ? number : null]; const ranges = { ...s.ranges }; if (next[0] == null && next[1] == null) delete ranges[source.name]; else ranges[source.name] = next; s.ranges = ranges; }; const rangeValue = (column, end) => { const r = s.ranges[sourceColumn(column)?.name]; return r && r[end] != null ? String(r[end]) : ""; }; const chipValues = (column) => { const source = sourceColumn(column); if (!source || source.type === "number") return []; const counts = distinctValues(source); if (counts.size > CHIP_LIMIT) return []; return [...counts.entries()].map(([value, count]) => ({ value, count, label: source.type === "date" ? formatKey(source, value) : value })); }; const chipOn = (column, value) => (s.values[sourceColumn(column)?.name] || []).includes(String(value)); const toggleChip = (column, value) => { const source = sourceColumn(column); if (!source) return; const list = new Set(s.values[source.name] || []); const key = String(value); if (list.has(key)) list.delete(key); else list.add(key); const values = { ...s.values }; if (list.size) values[source.name] = [...list]; else delete values[source.name]; s.values = values; }; const activeFilters = computed(() => [ ...Object.entries(s.ranges).map(([name, [min, max]]) => { const c = byName(base.value, name); const f = (v) => formatNumber(v, Math.max(c?.decimals || 0, String(v).split(".")[1]?.length || 0), c?.unit || ""); return { key: "r:" + name, name, text: min != null && max != null ? `${f(min)}–${f(max)}` : min != null ? `≥ ${f(min)}` : `≤ ${f(max)}`, clear: () => { const r = { ...s.ranges }; delete r[name]; s.ranges = r; } }; }), ...Object.entries(s.values).map(([name, list]) => { const c = byName(base.value, name); const labels = list.map((v) => (c?.type === "date" ? formatKey(c, Number(v)) : v)); return { key: "v:" + name, name, text: labels.length <= 2 ? labels.join(", ") : `${labels.length} values`, clear: () => { const v = { ...s.values }; delete v[name]; s.values = v; } }; }), ]); const clearFilters = () => { s.query = ""; s.ranges = {}; s.values = {}; }; const filtering = computed(() => !!(s.query || activeFilters.value.length)); // ---- Group by ---- // Text and dates, plus whole-number columns with few values (seed, fold, epoch). const groupable = computed(() => base.value.columns.filter((c) => c.type !== "number" || (c.decimals === 0 && !c.unit && distinctValues(c).size <= 50))); const setGroup = (name) => { s.group = name || null; s.sort = null; s.limit = PAGE_SIZE; s.menu = null; resetChartAxes(); }; const setAgg = (fn) => { s.agg = fn; }; const setSum = (column, fn) => { const sums = { ...s.sums }; if (!fn || fn === s.sum) delete sums[column.name]; else sums[column.name] = fn; s.sums = sums; }; const setRowSum = (fn) => { s.sum = fn; }; const treatAsNumber = (column, on) => { const list = new Set(s.numeric); if (on) list.add(column.name); else list.delete(column.name); s.numeric = [...list]; }; // ---- Column menu (stats, sort, filter, group) ---- const menuColumn = computed(() => (s.menu ? table.value.columns[s.menu.index] : null)); const menuStats = computed(() => { const column = menuColumn.value; if (!column) return null; const stats = columnStats(column, rowsInView.value); const fmt = (v) => formatKey(column, v); const peak = Math.max(1, ...(stats.histogram || []).map((b) => b.count)); return { ...stats, typeLabel: column.type === "number" ? (column.identifier && !isMeasure(column) ? "Identifier" : column.decimals ? `Number · ${column.decimals} ${column.decimals === 1 ? "decimal" : "decimals"}` : "Whole number") + (column.unit ? " · %" : "") : column.type === "date" ? "Date" : "Text", rows: [ ["Values", formatNumber(stats.count)], ["Empty", formatNumber(stats.empty)], ["Distinct", formatNumber(stats.distinct)], ...(stats.min != null ? [["Min", fmt(stats.min)], ["Max", fmt(stats.max)]] : []), ...(stats.mean != null && isMeasure(column) ? [["Mean", formatKey(column, stats.mean, "mean")]] : []), ...(stats.std != null && isMeasure(column) ? [["Std dev", formatKey(column, stats.std, "std")]] : []), ], bars: (stats.histogram || []).map((b, i, all) => ({ x: (i * 216) / all.length + 1, w: Math.max(1, 216 / all.length - 2), h: Math.max(b.count ? 2 : 0, (b.count / peak) * 40), count: b.count, title: `${fmt(b.from)} – ${fmt(b.to)}: ${b.count} ${b.count === 1 ? "row" : "rows"}` })), histFrom: stats.histogram ? fmt(stats.min) : "", histTo: stats.histogram ? fmt(stats.max) : "", top: (stats.top || []).map(([value, count]) => ({ value, count, share: (count / Math.max(1, stats.count)) * 100 })), }; }); const openMenu = (index, event) => { if (s.menu?.index === index) { s.menu = null; return; } const th = event.currentTarget.closest("th") || event.currentTarget; const r = th.getBoundingClientRect(); const width = 260, vw = window.innerWidth; s.menu = { index, left: Math.max(8, Math.min(r.left, vw - width - 8)), top: r.bottom + 4 }; nextTick(() => window.document.querySelector(".dt-menu")?.focus()); }; const closeMenus = () => { s.menu = null; s.toolsOpen = false; s.copyOpen = false; }; // ---- Export ---- const exportRows = () => { const t = table.value; const header = t.columns.map((c) => c.name); const body = sorted.value.map((i) => t.columns.map((c) => t.body[i][c.index] ?? "")); return { header, body }; }; const flash = (what) => { s.copied = what; window.setTimeout(() => { if (s.copied === what) s.copied = ""; }, 1600); }; const copyAs = async (format) => { const { header, body } = exportRows(); const text = format === "md" ? toMarkdown(header, body, table.value.columns.map((c) => c.type === "number")) : toDelimited(header, body, ","); closeMenus(); try { await window.navigator.clipboard.writeText(text); flash(format); } catch { flash("error"); } }; const fileBase = () => String(props.name || "table").replace(/\.[^.]+$/, "") || "table"; const download = () => { const { header, body } = exportRows(); const blob = new window.Blob([toDelimited(header, body, ",")], { type: "text/csv;charset=utf-8" }); const url = window.URL.createObjectURL(blob); const a = window.document.createElement("a"); a.href = url; a.download = fileBase() + (isChanged() ? "-view" : "") + ".csv"; window.document.body.appendChild(a); a.click(); a.remove(); window.setTimeout(() => window.URL.revokeObjectURL(url), 1000); closeMenus(); }; const isChanged = () => !!(filtering.value || s.sort || s.group); // ---- Chart ---- const chartWidth = ref(0); const chartHost = ref(null); const chartSpec = computed(() => { const fallback = defaultChart(table.value, !!groupColumn.value); const x = s.x && byName(table.value, s.x) ? s.x : fallback.x; const y = s.y.filter((n) => byName(table.value, n)?.type === "number"); return { type: s.chart || fallback.type, x, y: y.length ? y : fallback.y, agg: s.agg }; }); const chart = computed(() => (props.view === "chart" && chartWidth.value ? buildChart(table.value, sorted.value, chartSpec.value, { width: chartWidth.value }) : null)); const resetChartAxes = () => { s.x = null; s.y = []; }; watch(chart, () => { s.tip = null; }); const setChartType = (type) => { s.chart = type; s.tip = null; }; const setX = (name) => { s.x = name; s.tip = null; }; const yOn = (name) => chartSpec.value.y.includes(name); const toggleY = (name) => { const current = chartSpec.value.y; const next = current.includes(name) ? current.filter((n) => n !== name) : [...current, name]; if (!next.length) return; s.y = next.slice(-MAX_SERIES[chartSpec.value.type]); s.tip = null; }; const seriesIndex = (name) => chartSpec.value.y.indexOf(name); let observer; const observe = (el) => { observer?.disconnect(); if (!el) return; const measure = () => { const w = el.clientWidth; if (w && Math.abs(w - chartWidth.value) > 1) chartWidth.value = w; }; measure(); if (window.ResizeObserver) { observer = new window.ResizeObserver(measure); observer.observe(el); } }; watch(chartHost, observe); // Hover and keyboard: bars by category, lines by the nearest x, scatter by the nearest point. const tipAt = (index, x, y) => { const c = chart.value; if (!c) return; const item = c.kind === "bar" ? c.categories[index]?.tip : c.points[index]; if (!item) { s.tip = null; return; } s.tip = { index, ...item, x, y, crossX: c.kind === "line" ? c.points[index].x : null }; }; const pointerAt = (event) => { const c = chart.value; const svg = event.currentTarget.ownerSVGElement || event.currentTarget; const box = svg.getBoundingClientRect(); const px = event.clientX - box.left, py = event.clientY - box.top; if (c.kind === "bar") { const index = c.categories.findIndex((cat) => py >= cat.hit.y && py < cat.hit.y + cat.hit.h); if (index < 0) { s.tip = null; return; } tipAt(index, px, c.categories[index].y); return; } let best = -1, bestD = Infinity; if (c.kind === "scatter") { c.series.forEach((ser) => ser.dots.forEach((d) => { const dd = (d.x - px) ** 2 + (d.y - py) ** 2; if (dd < bestD) { bestD = dd; best = d.i; } })); if (bestD > 40 * 40) { s.tip = null; return; } } else c.points.forEach((p, i) => { const dd = Math.abs(p.x - px); if (dd < bestD) { bestD = dd; best = i; } }); tipAt(best, c.kind === "scatter" ? c.points[best].x : c.points[best].x, py); }; const keyStep = (event) => { const c = chart.value; if (!c || c.empty) return; const count = c.kind === "bar" ? c.categories.length : c.points.length; const delta = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1, Home: -Infinity, End: Infinity }[event.key]; if (event.key === "Escape") { s.tip = null; return; } if (delta == null) return; event.preventDefault(); const current = s.tip ? s.tip.index : -1; const next = delta === -Infinity ? 0 : delta === Infinity ? count - 1 : Math.max(0, Math.min(count - 1, current + delta)); if (c.kind === "bar") tipAt(next, c.plot.x + 8, c.categories[next].y); else tipAt(next, c.points[next].x, c.plot.y + 20); }; const tipStyle = computed(() => { if (!s.tip || !chart.value) return {}; const w = chartWidth.value, left = s.tip.x + 14; return left + 200 > w ? { right: Math.max(4, w - s.tip.x + 14) + "px", top: s.tip.y + 8 + "px" } : { left: left + "px", top: s.tip.y + 8 + "px" }; }); const chartSummary = computed(() => { const c = chart.value; if (!c || c.empty) return ""; const what = c.series.map((x) => x.name).join(", "); return `${{ bar: "Bar chart", line: "Line chart", scatter: "Scatter plot" }[c.kind]} of ${what} by ${c.x.name}`; }); // ---- Shareable state in the URL fragment ---- const snapshot = () => ({ view: props.view, query: s.query, sort: s.sort, group: s.group, agg: s.agg, ranges: s.ranges, values: s.values, sum: s.sum, sums: s.sums, numeric: s.numeric, chart: s.chart, x: s.x, y: s.y, }); if (props.stateKey) { let timer; watch(() => JSON.stringify(snapshot()), () => { window.clearTimeout(timer); timer = window.setTimeout(() => { const hash = writeHashState(props.stateKey, snapshot()); const current = window.location.hash; // Leave other fragments (#L12, a heading) alone unless we are replacing our own. if (!hash && !isTableHash(current)) return; if (hash && current && !isTableHash(current) && current !== "#") return; if (hash === current) return; window.history.replaceState(window.history.state, "", window.location.pathname + window.location.search + hash); }, 250); }); } // ---- Phone toolbar and menus ---- const onDocClick = (event) => { if (!event.target.closest?.(".dt-menu, .dt-col-btn")) s.menu = null; if (!event.target.closest?.(".dt-tools-menu, .dt-tools-btn")) s.toolsOpen = false; if (!event.target.closest?.(".dt-copy-menu, .dt-copy-btn")) s.copyOpen = false; }; const onKey = (event) => { if (event.key === "Escape" && (s.menu || s.toolsOpen || s.copyOpen)) { const back = s.menu ? window.document.querySelector(`.dt-col-btn[data-col="${s.menu.index}"]`) : null; closeMenus(); back?.focus(); } }; const onScroll = (event) => { if (s.menu && !event.target?.closest?.(".dt-menu")) s.menu = null; }; onMounted(() => { window.document.addEventListener("click", onDocClick); window.document.addEventListener("keydown", onKey); window.addEventListener("scroll", onScroll, { capture: true, passive: true }); }); onBeforeUnmount(() => { window.document.removeEventListener("click", onDocClick); window.document.removeEventListener("keydown", onKey); window.removeEventListener("scroll", onScroll, { capture: true }); observer?.disconnect(); }); watch(() => [s.query, s.ranges, s.values], () => { s.limit = PAGE_SIZE; }, { deep: true }); // The visible rows as one HTML string: thousands of cells patch far faster // this way than as component vnodes. Cell text is escaped; XXXX-n becomes // the same slot as everywhere else in the viewer. const bodyHtml = computed(() => { const t = table.value, cols = t.columns, grouped = !!groupColumn.value; const out = []; for (const ri of visible.value) { out.push(""); if (!grouped) out.push('', String(ri + 1), ""); const row = t.body[ri]; for (const c of cols) out.push(c.type === "number" ? '' : "", cellHtml(row[c.index]), ""); out.push(""); } return out.join(""); }); const rowCountText = computed(() => { const total = base.value.size, shown = filtered.value.length; const rows = shown === total ? `${formatNumber(total)} ${total === 1 ? "row" : "rows"}` : `${formatNumber(shown)} of ${formatNumber(total)} rows`; return groupColumn.value ? `${formatNumber(table.value.size)} ${table.value.size === 1 ? "group" : "groups"} · ${rows}` : rows; }); return { s, props, base, table, sorted, visible, summary, numericColumns, filtered, groupColumn, rowsInView, redactParts, cycleSort, setSort, sortState, ariaSort, setRange, rangeValue, chipValues, chipOn, toggleChip, activeFilters, clearFilters, filtering, groupable, setGroup, setAgg, setSum, setRowSum, treatAsNumber, isMeasure, sumOverride, sumInFirst, hasSummary, AGGREGATES, AGGREGATE_LABEL, aggregateShort, menuColumn, menuStats, openMenu, closeMenus, sourceColumn, copyAs, download, isChanged, bodyHtml, rowCountText, chart, chartSpec, chartHost, setChartType, setX, yOn, toggleY, seriesIndex, pointerAt, keyStep, tipStyle, chartSummary, MAX_SERIES, PAGE_SIZE, formatNumber, showMore: () => { s.limit += PAGE_SIZE; }, showAll: () => { s.limit = Infinity; }, leaveChart: () => { s.tip = null; }, }; }, render: dataTableTemplate, }; // "Open as table" for a Markdown or notebook table: the full viewer in a dialog. export function openTableDialog(rows, title) { const host = window.document.createElement("div"); window.document.body.appendChild(host); const opener = window.document.activeElement; let app; const close = () => { app.unmount(); host.remove(); window.document.removeEventListener("keydown", onKey); opener?.focus?.(); }; const onKey = (event) => { if (event.key === "Escape" && !window.document.querySelector(".dt-menu, .dt-tools-menu, .dt-copy-menu")) close(); // Keep Tab inside the dialog. if (event.key !== "Tab") return; const items = [...host.querySelectorAll("button, select, input, [tabindex='0']")].filter((el) => !el.disabled && el.offsetParent !== null); if (!items.length) return; const first = items[0], last = items[items.length - 1], active = window.document.activeElement; if (!host.contains(active) || (event.shiftKey ? active === first || active === host.querySelector(".dt-dialog") : active === last)) { event.preventDefault(); (event.shiftKey ? last : first).focus(); } }; window.document.addEventListener("keydown", onKey); app = createApp({ setup() { const view = ref("table"); onMounted(() => host.querySelector(".dt-dialog")?.focus()); return () => h("div", { class: "dt-dialog-backdrop", onClick: (e) => { if (e.target === e.currentTarget) close(); } }, h("div", { class: "dt-dialog", role: "dialog", "aria-modal": "true", "aria-label": title || "Table", tabindex: "-1" }, [ h("header", { class: "dt-dialog-head" }, [ h("span", { class: "dt-dialog-title" }, title || "Table"), h("div", { class: "seg-filter dt-view-toggle", role: "radiogroup", "aria-label": "View" }, ["table", "chart"].map((v) => h("button", { type: "button", role: "radio", class: ["seg-chip", { active: view.value === v }], "aria-checked": view.value === v ? "true" : "false", onClick: () => { view.value = v; } }, v === "table" ? "Table" : "Chart"))), h("button", { type: "button", class: "btn btn-sm btn-ghost btn-icon-only dt-dialog-close", "aria-label": "Close", onClick: close }, h("svg", { class: "ui-icon", "aria-hidden": "true" }, h("use", { href: "#project-icon-close" }))), ]), h(DataTable, { rows, name: (title || "table").replace(/[^\w.-]+/g, "-").toLowerCase(), view: view.value, label: title }), ])); }, }); app.mount(host); return close; } setTableOpener(openTableDialog);