Files
anonymous_github/public/script/table-chart.js
T
Thomas DurieuxandClaude Opus 5.5 68239afbbb fix(tables): keep text placeholders as values, reset per file, bound scatter labels
- 'none', 'NA' and '-' are empty only in number and date columns; in
  text columns they are categories.
- The table viewer is keyed per file, so a search or filter in one CSV
  doesn't carry over to the next.
- A scatter chart with more than 500 text x values is refused instead of
  measuring every label (and spreading 100k values into Math.max).
- Gist CSV rows are cached per file object instead of a 1 MB string key
  built on every render.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:35:46 +00:00

263 lines
15 KiB
JavaScript

// Chart geometry for the table viewer's Chart view, as plain data the template
// draws in inline SVG (no chart library). Bars are horizontal so category names
// stay readable on a phone; lines and scatter plots share one value axis.
import { aggregate, formatKey, formatNumber, formatDate } from "./table-analysis.js";
// Categorical slots, light and dark steps chosen and validated for this page's
// surfaces (dataviz reference palette, adjacent pairs; scatter uses the first three).
export const SERIES_LIGHT = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"];
export const SERIES_DARK = ["#3987e5", "#d95926", "#199e70", "#c98500"];
export const MAX_SERIES = { bar: 4, line: 4, scatter: 3 };
export const MAX_BARS = 40;
export const MAX_CATEGORIES = 500;
const MAX_POINTS = 2000;
const isIdLike = (column) => column.type === "number" && !!column.identifier;
// The default chart: a bar of the first measure by the first text column (the
// group column once grouped); a line when the x axis is a date or a number.
export function defaultChart(table, grouped) {
const cols = table.columns;
const x = grouped ? cols[0] : cols.find((c) => c.type === "text") || cols.find((c) => c.type === "date") || cols.find((c) => c.type === "number");
const measures = cols.filter((c) => c.type === "number" && c !== x && !(grouped && c.index === 1));
const y = measures.find((c) => !isIdLike(c)) || measures[0];
return { type: x && x.type !== "text" ? "line" : "bar", x: x?.name || null, y: y ? [y.name] : [] };
}
// Round axis bounds and 3-6 ticks at 1/2/5 steps.
export function niceTicks(min, max, count = 5) {
if (!Number.isFinite(min) || !Number.isFinite(max)) return { min: 0, max: 1, ticks: [0, 1], step: 1 };
if (min === max) { const pad = Math.abs(min) * 0.1 || 1; min -= pad; max += pad; }
const raw = (max - min) / count;
const mag = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) || 10 * mag;
const lo = Math.floor(min / step + 1e-9) * step, hi = Math.ceil(max / step - 1e-9) * step;
const ticks = [];
for (let v = lo; v <= hi + step / 2; v += step) ticks.push(Math.abs(v) < step / 1e6 ? 0 : +v.toPrecision(12));
return { min: lo, max: hi, ticks, step };
}
const stepDecimals = (step) => (String(+step.toPrecision(6)).split(".")[1] || "").length;
// Axis labels: full under 10,000, compact (12K, 1.5M) when the axis reaches it.
export function tickLabel(value, step, unit = "") {
const top = Math.abs(value);
if (top >= 10000) {
const [div, suffix] = top >= 1e9 ? [1e9, "B"] : top >= 1e6 ? [1e6, "M"] : [1e3, "K"];
return formatNumber(value / div, Math.max(0, stepDecimals(step / div))) + suffix + unit;
}
return formatNumber(value, stepDecimals(step)) + unit;
}
// Measured text is not available outside the page; an average Inter glyph at 11-12px is close enough to size gutters.
const textWidth = (text, size = 11.5) => String(text).length * size * 0.56;
/**
* table: a model from analyzeTable/groupTable; rows: row indices in view order;
* spec: { type, x, y: [names], agg }; box: { width, dark }.
*/
export function buildChart(table, rows, spec, box) {
const cols = table.columns;
const x = cols.find((c) => c.name === spec.x);
const type = spec.type || "bar";
const ys = (spec.y || []).map((n) => cols.find((c) => c.name === n && c.type === "number")).filter(Boolean).slice(0, MAX_SERIES[type]);
const palette = box.dark ? SERIES_DARK : SERIES_LIGHT;
const width = Math.max(260, Math.floor(box.width || 640));
const base = { type, width, x, ys, notes: [], series: ys.map((c, i) => ({ name: c.name, color: palette[i] })) };
if (!x) return { ...base, empty: "Pick a column for the x axis." };
if (!ys.length) return { ...base, empty: "Pick at least one numeric column to plot." };
if (!rows.length) return { ...base, empty: "No rows match the current filters." };
if ((spec.y || []).length > ys.length) base.notes.push(`Showing the first ${ys.length} series; a chart with more is hard to read.`);
// One value axis only: say so when the series live on very different scales.
const spans = ys.map((y) => Math.max(...rows.slice(0, 5000).map((r) => Math.abs(y.keys[r] ?? 0)))).filter((v) => v > 0);
if (spans.length > 1 && Math.max(...spans) / Math.min(...spans) > 20) base.notes.push("These columns have very different ranges; chart them one at a time to compare their values.");
return type === "bar" ? barChart(table, rows, x, ys, spec, base)
: type === "line" ? lineChart(table, rows, x, ys, spec, base)
: scatterChart(table, rows, x, ys, base);
}
// One entry per x value in first-seen order; repeated x values are combined
// with the chosen aggregate (a chart of "accuracy by model" over seeds).
function categories(table, rows, x, ys, agg) {
const map = new Map();
for (const r of rows) {
const key = x.keys[r] == null ? "" : x.keys[r];
if (!map.has(key)) map.set(key, { key, label: key === "" ? "(empty)" : x.type === "text" ? String(table.body[r][x.index]).trim() : formatKey(x, key), rows: [] });
map.get(key).rows.push(r);
}
const list = [...map.values()];
const repeated = list.some((c) => c.rows.length > 1);
for (const c of list) c.values = ys.map((y) => (repeated ? aggregate(y.keys, c.rows, agg) : y.keys[c.rows[0]]));
return { list, repeated };
}
function valueFormat(y, fn) { return (v) => formatKey(y, v, fn); }
function barChart(table, rows, x, ys, spec, base) {
const agg = spec.agg || "mean";
const { list: all, repeated } = categories(table, rows, x, ys, agg);
const list = all.slice(0, MAX_BARS);
if (repeated) base.notes.unshift(`${aggLabel(agg)} per ${x.name} over ${rows.length} rows.`);
if (all.length > list.length) base.notes.push(`First ${list.length} of ${all.length} ${x.name} values, in table order.`);
const values = list.flatMap((c) => c.values).filter((v) => v != null);
const lo = Math.min(0, ...values), hi = Math.max(0, ...values);
const scale = niceTicks(lo, hi, base.width < 480 ? 4 : 6);
const fmt = ys.map((y) => valueFormat(y, repeated ? agg : undefined));
const labelW = Math.min(Math.max(...list.map((c) => textWidth(c.label, 12))) + 12, Math.round(base.width * 0.38));
const valueW = Math.max(...list.flatMap((c) => c.values.map((v, i) => textWidth(fmt[i](v), 11.5)))) + 10;
const bar = ys.length > 2 ? 12 : 16, gap = 2, pad = 14;
const band = ys.length * bar + (ys.length - 1) * gap + pad;
const top = 8, axisH = 26;
const plot = { x: labelW, y: top, w: Math.max(80, base.width - labelW - valueW - 4), h: list.length * band };
const sx = (v) => plot.x + ((v - scale.min) / (scale.max - scale.min)) * plot.w;
const zero = sx(0);
const marks = [];
list.forEach((c, ci) => {
const y0 = plot.y + ci * band + pad / 2;
c.values.forEach((v, si) => {
if (v == null) return;
const x1 = sx(v), left = Math.min(zero, x1), w = Math.abs(x1 - zero);
marks.push({ key: ci + ":" + si, series: si, cat: ci, x: left, y: y0 + si * (bar + gap), w, h: bar, positive: v >= 0, color: base.series[si].color,
path: roundedBar(left, y0 + si * (bar + gap), w, bar, v >= 0),
label: fmt[si](v), lx: v >= 0 ? x1 + 6 : x1 - 6, anchor: v >= 0 ? "start" : "end", ly: y0 + si * (bar + gap) + bar / 2 });
});
});
return {
...base, kind: "bar", height: plot.y + plot.h + axisH, plot, zero,
categories: list.map((c, ci) => ({ label: c.label, y: plot.y + ci * band + band / 2, hit: { y: plot.y + ci * band, h: band },
tip: { title: c.label, rows: c.values.map((v, si) => ({ name: ys[si].name, color: base.series[si].color, value: fmt[si](v) })), note: repeated ? `${aggLabel(agg)} of ${c.rows.length} ${c.rows.length === 1 ? "row" : "rows"}` : "" } })),
marks, showValues: list.length <= 30,
xTicks: scale.ticks.map((v) => ({ v, x: sx(v), label: tickLabel(v, scale.step, ys.length === 1 ? ys[0].unit : "") })),
axisLabel: ys.length === 1 ? (repeated ? `${aggLabel(agg)} ${ys[0].name}` : measureName(ys[0])) : repeated ? aggLabel(agg) : "",
};
}
// 4px rounded data end, square at the baseline.
function roundedBar(x, y, w, h, positive) {
const r = Math.min(4, w / 2, h / 2);
if (w <= 0.5) return "";
return positive
? `M${x},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h - r}Q${x + w},${y + h} ${x + w - r},${y + h}H${x}Z`
: `M${x + w},${y}H${x + r}Q${x},${y} ${x},${y + r}V${y + h - r}Q${x},${y + h} ${x + r},${y + h}H${x + w}Z`;
}
// A grouped table's columns are aggregates: "Average accuracy".
const measureName = (column) => (column.agg ? `${aggLabel(column.agg)} ${column.name}` : column.name);
const aggLabel = (fn) => ({ mean: "Average", sum: "Sum", median: "Median", min: "Min", max: "Max", count: "Count", std: "Std dev" })[fn] || fn;
function xAxis(points, x, plotW, continuous) {
if (continuous) {
const keys = points.map((p) => p.xv);
const scale = niceTicks(Math.min(...keys), Math.max(...keys), plotW < 360 ? 3 : 6);
let ticks = scale.ticks;
if (x.type === "date") {
const lo = Math.min(...keys), hi = Math.max(...keys), span = hi - lo || 86400000;
// Calendar steps: hours, days, weeks, months (30 days), years.
const HOUR = 3600000, DAY = 24 * HOUR;
const steps = [HOUR, 3 * HOUR, 6 * HOUR, 12 * HOUR, DAY, 2 * DAY, 7 * DAY, 14 * DAY, 30 * DAY, 91 * DAY, 182 * DAY, 365 * DAY, 730 * DAY, 1826 * DAY];
const want = plotW < 360 ? 3 : 6;
const step = steps.find((s) => span / s <= want) || steps[steps.length - 1];
ticks = [];
for (let t = Math.ceil(lo / step) * step; t <= hi; t += step) ticks.push(t);
if (!ticks.length) ticks = [lo];
return { min: lo, max: hi === lo ? lo + DAY : hi, ticks, label: (v) => formatDate(v, step < DAY) };
}
return { min: scale.min, max: scale.max, ticks, label: (v) => tickLabel(v, scale.step, x.unit) };
}
return null;
}
function lineChart(table, rows, x, ys, spec, base) {
const continuous = x.type !== "text";
let points;
if (continuous) {
const usable = rows.filter((r) => x.keys[r] != null);
const repeated = new Set(usable.map((r) => x.keys[r])).size < usable.length;
if (repeated) {
const { list } = categories(table, usable, x, ys, spec.agg || "mean");
points = list.map((c) => ({ xv: c.key, label: c.label, values: c.values, count: c.rows.length }));
base.notes.unshift(`${aggLabel(spec.agg || "mean")} per ${x.name}.`);
} else points = usable.map((r) => ({ xv: x.keys[r], label: formatKey(x, x.keys[r]), values: ys.map((y) => y.keys[r]), count: 1 }));
points.sort((a, b) => a.xv - b.xv);
} else {
const { list, repeated } = categories(table, rows, x, ys, spec.agg || "mean");
points = list.map((c) => ({ label: c.label, values: c.values, count: c.rows.length }));
if (repeated) base.notes.unshift(`${aggLabel(spec.agg || "mean")} per ${x.name}.`);
}
points = thin(points, base);
return xyChart(points, x, ys, base, continuous, "line", spec);
}
function scatterChart(table, rows, x, ys, base) {
const continuous = x.type !== "text";
let points = rows.filter((r) => x.keys[r] != null).map((r) => ({ xv: continuous ? x.keys[r] : null, label: x.type === "text" ? String(table.body[r][x.index]).trim() : formatKey(x, x.keys[r]), values: ys.map((y) => y.keys[r]), count: 1, row: r }));
if (!continuous) {
// Text on the x axis: one position per value in first-seen order.
const order = new Map();
points.forEach((p) => { if (!order.has(p.label)) order.set(p.label, order.size); p.xv = order.get(p.label); });
// An ID-like column has a label per row: no readable axis, and measuring
// every label would stall the tab.
if (order.size > MAX_CATEGORIES) return { ...base, empty: `The x column has ${order.size.toLocaleString("en-US")} different values; choose a number or date column, or group the rows first.` };
base.categoryLabels = [...order.keys()];
}
points = thin(points, base);
return xyChart(points, x, ys, base, true, "scatter");
}
// Long series keep every n-th point so the SVG stays light; the note says so.
function thin(points, base) {
if (points.length <= MAX_POINTS) return points;
const step = Math.ceil(points.length / MAX_POINTS);
base.notes.push(`Showing every ${step}th of ${points.length.toLocaleString("en-US")} points.`);
return points.filter((_, i) => i % step === 0);
}
function xyChart(points, x, ys, base, continuous, kind) {
const values = points.flatMap((p) => p.values).filter((v) => v != null);
if (!values.length) return { ...base, empty: "The selected columns have no values in these rows." };
const narrow = base.width < 480;
const yScale = niceTicks(values.reduce((a, v) => Math.min(a, v), Infinity), values.reduce((a, v) => Math.max(a, v), -Infinity), narrow ? 4 : 5);
const unit = ys.length === 1 ? ys[0].unit : "";
const yLabels = yScale.ticks.map((v) => tickLabel(v, yScale.step, unit));
const left = Math.max(...yLabels.map((l) => textWidth(l))) + 14;
const height = narrow ? 240 : 300;
const plot = { x: left, y: 10, w: base.width - left - 16, h: height - 10 - 30 };
const cats = base.categoryLabels;
let sxv, xTicks;
if (continuous && !cats) {
const axis = xAxis(points, x, plot.w, true);
const span = axis.max - axis.min || 1;
sxv = (v) => plot.x + ((v - axis.min) / span) * plot.w;
xTicks = axis.ticks.map((v) => ({ x: sxv(v), label: axis.label(v) }));
} else {
const n = cats ? cats.length : points.length;
const inset = n > 1 ? Math.min(24, plot.w / (2 * n)) : plot.w / 2;
const stepW = n > 1 ? (plot.w - 2 * inset) / (n - 1) : 0;
sxv = (i) => plot.x + inset + i * stepW;
if (!cats) points.forEach((p, i) => { p.xv = i; });
const labels = cats || points.map((p) => p.label);
const widest = labels.reduce((w, l) => Math.max(w, textWidth(l)), 0);
const maxLabels = Math.max(2, Math.floor(plot.w / (widest + 12)));
const every = Math.ceil(labels.length / maxLabels);
xTicks = labels.map((label, i) => ({ x: sxv(i), label, show: i % every === 0 })).filter((t) => t.show);
}
// Labels near the plot's edges are anchored inside it, never cut off.
xTicks.forEach((t) => { const half = textWidth(t.label) / 2; t.anchor = t.x - half < plot.x - 8 ? "start" : t.x + half > plot.x + plot.w + 12 ? "end" : "middle"; });
const sy = (v) => plot.y + plot.h - ((v - yScale.min) / (yScale.max - yScale.min || 1)) * plot.h;
const fmt = ys.map((y) => (v) => formatKey(y, v, undefined));
const dots = points.length <= 80 || kind === "scatter";
const series = base.series.map((s, si) => {
const pts = points.map((p, i) => (p.values[si] == null ? null : { i, x: sxv(p.xv), y: sy(p.values[si]) }));
let path = "", pen = false;
for (const pt of pts) { if (!pt) { pen = false; continue; } path += (pen ? "L" : "M") + pt.x.toFixed(1) + "," + pt.y.toFixed(1); pen = true; }
return { ...s, path: kind === "line" ? path : "", dots: dots ? pts.filter(Boolean) : [] };
});
const cols = points.map((p) => ({ x: sxv(p.xv), title: (x.type === "text" || cats ? "" : x.name + " ") + p.label,
rows: p.values.map((v, si) => ({ name: ys[si].name, color: base.series[si].color, value: v == null ? "—" : fmt[si](v) })),
note: p.count > 1 ? `${p.count} rows` : "" }));
return {
...base, kind, height, plot, series, points: cols,
yTicks: yScale.ticks.map((v, i) => ({ y: sy(v), label: yLabels[i] })),
xTicks, xLabel: x.name, yLabel: ys.length === 1 ? measureName(ys[0]) : "",
};
}