/** * TimeSeriesPanel.tsx — owner item 7 (contract C-TS), rebuilt for wave-14 items 16c · 17 · 18. * * ⚠ **HOST-AGNOSTIC ON PURPOSE — it reads no CustomerGrid state, ever.** RECORD re-mounts this * exact component inside the record modal for item 13 (contract C-EMBED) with `pids=[pid]` and * `locked`, so every input arrives as a prop. The moment this file imports a grid hook, the * record-detail Insights tab stops being possible. * * All arithmetic and every honest disclosure live in `timeSeriesData.ts`, which * `web/verify_timeseries.py` gates under node. This file is layout, fetch orchestration and * one chart adapter — deliberately nothing a wrong number could hide in. * * ── What wave 14 changed, and why ────────────────────────────────────────────────────────── * * The panel WAS a chip bar over a fixed table: you toggled metrics on and off above the data, * and the table was a read-only report of whatever survived. The owner asked for a SHEET — * something you build rather than something you filter. So: * * · the metric chips are GONE. A metric is a ROW, added from a "+ Add metric" row at the * bottom the way a spreadsheet grows, and removed from the row itself. The list of what is * on screen and the list of what could be are the same list, in the same place. * · rows carry the server's WINDOW LABEL as a sublabel (R1/C-TSWIN). Under identical month * headings, a year-to-date row and a trailing-90 row are different claims, and nothing on * screen used to say which one you were reading. * · custom NOTE and FORMULA rows (R2) — the reader's own arithmetic, evaluated per column * against the resolved buckets, refusing rather than inventing on every failure. * · "Change vs prior" was ONE toggle producing ONE sub-row. It is now four named comparisons * (item 18), each of which can refuse for its own stated reason. */ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { fetchTimeseries } from "./apiBridge"; import type { SurfaceScope } from "./apiBridge"; import { isStreamlitComponent } from "./hostBridge"; import { DEFAULT_TS_BUCKET, DEFAULT_TS_LAST_N, TS_DELTA_LABELS, buildTsRequest, buildTsSheet, buildTsSnapshotRow, buildTsTable, classifyTsField, formatTsDelta, formatTsValue, resolveTsStyle, sparklinePoints, sparklineSegments, tsDisplayNumber, tsRefusalReason, tsRowToChartModel, } from "./timeSeriesData"; import type { TsDeltaSubRow, TsPayload, TsSheet, TsSheetRow, TsTableRow, } from "./timeSeriesData"; import { TS_BUCKETS, TS_DELTA_KINDS, TS_MAX_CUSTOM_ROWS, TS_MAX_FIELDS, TS_ROW_LABEL_MAX, TS_MAX_EXPR, } from "./types"; import type { DisplaySpec, Field, TsBucket, TsCellStyle, TsCustomRow, TsDeltaKind, } from "./types"; import { FieldSelectButton } from "./FieldSelect"; import { Popover } from "../filter-kit"; import { toVegaLiteSpec } from "../viz/vega/toVegaLiteSpec"; import VegaLiteChart from "../viz/vega/VegaLiteChart"; const BUCKET_LABELS: Record = { week: "Weekly", month: "Monthly", quarter: "Quarterly", year: "Yearly", }; /** The rolling spans offered, per bucket. Capped well inside `TS_MAX_LAST_N`. */ const LAST_N_CHOICES = [6, 12, 24, 36]; /** The sparkline's box. Small enough to sit in a table cell, wide enough to have a shape. */ const SPARK_W = 72; const SPARK_H = 18; /** * wave17 owner item 7 — the Compare popover's mark: a rising step over a baseline. * * Private to this file, the way `Toolbar.tsx` keeps its own `Icon*` set: the toolbar's glyphs * are not exported, and this is the only surface that means "compare with the prior period". * A step rather than an arrow — all four comparisons are period-to-period, and an arrow would * claim a direction the control does not have. */ function IconCompare() { const s = { stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round" as const, strokeLinejoin: "round" as const, fill: "none", }; return ( ); } export interface TimeSeriesPanelProps { scope: SurfaceScope; /** The rows in scope. The server intersects with the caller's book regardless. */ pids: number[]; /** Every field the table has — the panel classifies them itself (item 5 / R9). */ fields: Field[]; /** * wave17 item 5 / R9 — the view's data rows, for SNAPSHOT metrics only. * * ⚠ Does NOT break this file's host-agnostic rule. The rule is that the panel reads no * CustomerGrid STATE; `pids` and `fields` already arrive the same way, and RECORD passes its * one record. It must be the SAME population `pids` came from, or the two halves of one sheet * would answer different questions with nothing going red — CustomerGrid derives both from * `modeDataRows`. */ rows?: readonly Record[]; /** The view's `config.display`; absent keys fall back to the panel's defaults. */ display?: DisplaySpec; /** Persist a display change. Absent = the panel is ephemeral (RECORD's embed, v1). */ onDisplay?: (next: Partial) => void; /** Item 13 — the pid set is the caller's and cannot be widened from here. */ locked?: boolean; /** * owner item 3 (2026-08-03) — publish the built sheet so the view menu's Export can carry it. * Absent = this mount cannot be exported (RECORD's embed), which is the honest default. */ onSheet?: (sheet: TsSheet) => void; } /** * wave17 item 5 / owner R9 — **OFFER EVERYTHING, best-effort.** * * v1 offered `key.startsWith("measure_")`, which was both too narrow and the wrong test. The * classification now lives in `timeSeriesData.classifyTsField` (pure, gated under node) and this * file only groups the result. A formula FIELD is still refused, for the reason it always was: it * has no time dimension of its own, and a formula ROW on this sheet (R2) is a different thing. */ function classifyFields(fields: Field[]): { server: Field[]; snapshot: Field[]; refused: { field: Field; why: string }[]; } { const out = { server: [] as Field[], snapshot: [] as Field[], refused: [] as { field: Field; why: string }[], }; for (const f of fields) { const cls = classifyTsField(f); if (cls === "server") out.server.push(f); else if (cls === "snapshot") out.snapshot.push(f); else out.refused.push({ field: f, why: tsRefusalReason(f) }); } return out; } /** A stable-enough id for a new custom row. `TS_ROW_ID_MAX` is 40; this is 12. */ function newRowId(existing: readonly TsCustomRow[]): string { let n = existing.length + 1; const taken = new Set(existing.map((r) => r.id)); while (taken.has(`tsr_${n}`)) n += 1; return `tsr_${n}`; } export default function TimeSeriesPanel({ scope, pids, fields, rows, display, onDisplay, locked, onSheet, }: TimeSeriesPanelProps) { const classed = useMemo(() => classifyFields(fields), [fields]); // The OFFERED list: everything with a way onto the sheet, server-served first so a real series // is never buried under a flat one in the picker. const eligible = useMemo( () => [...classed.server, ...classed.snapshot], [classed.server, classed.snapshot] ); const snapshotKeys = useMemo( () => new Set(classed.snapshot.map((f) => f.key)), [classed.snapshot] ); const bucket: TsBucket = (TS_BUCKETS as readonly string[]).includes(display?.tsBucket ?? "") ? (display!.tsBucket as TsBucket) : DEFAULT_TS_BUCKET; const lastN = typeof display?.tsSpan?.lastN === "number" ? display.tsSpan.lastN : DEFAULT_TS_LAST_N; const selected = useMemo(() => { const want = display?.tsFields ?? []; const live = want.filter((k) => eligible.some((f) => f.key === k)); // A view whose stored fields have all been deleted falls back to the first eligible // metric rather than to an empty table, which would read as "no data" when the truth is // "no fields chosen". return live.length ? live : eligible.slice(0, 1).map((f) => f.key); }, [display?.tsFields, eligible]); /** * wave17 item 5 — the selection SPLIT by where its answer comes from. * * ⚠ Only `wired` reaches the server. Sending a snapshot key would be answered with * `not_a_measure_field` and rendered as a refusal footnote — telling the reader a field failed * when the panel chose, deliberately, to compute it here. */ const wired = useMemo( () => selected.filter((k) => !snapshotKeys.has(k)), [selected, snapshotKeys] ); const snapshotSelected = useMemo( () => selected.filter((k) => snapshotKeys.has(k)), [selected, snapshotKeys] ); const customRows = useMemo(() => display?.tsRows ?? [], [display?.tsRows]); const deltaKinds = useMemo(() => display?.tsDeltas ?? [], [display?.tsDeltas]); const styles = display?.tsStyles; // ⚠ PRESENCE, not truthiness — `tsGridlines` is `false | undefined` and absent means SHOWN. // `!display?.tsGridlines` would hide the gridlines on every view that never chose. const gridlines = display?.tsGridlines !== false; const sparkline = display?.tsSparkline === true; const [payload, setPayload] = useState(null); const [state, setState] = useState<"idle" | "loading" | "error">("idle"); const [errStatus, setErrStatus] = useState(0); const [charted, setCharted] = useState>(new Set()); // Guards a slow response from overwriting a newer one — the request the user is waiting on // is the LAST one they asked for, not the last one to arrive. const reqRef = useRef(0); const embedded = isStreamlitComponent(); useEffect(() => { if (embedded) return; if (!wired.length || !pids.length) { setPayload(null); setState("idle"); return; } const seq = ++reqRef.current; setState("loading"); const body = buildTsRequest({ pids, bucket, span: { lastN }, fields: wired }); fetchTimeseries(body, scope).then(({ payload: p, status }) => { if (seq !== reqRef.current) return; if (!p) { setPayload(null); setErrStatus(status); setState("error"); return; } setPayload(p); setState("idle"); }); }, [embedded, scope, pids, bucket, lastN, wired]); const served = useMemo(() => buildTsTable(payload), [payload]); /** * wave17 item 5 / R9 — the snapshot rows, spliced in AFTER the server's. * * ⚠ They ride the SERVER's columns. Bucket starts and bucket labels are server math * (`_ts_next`/`_ts_label`), and re-deriving them here would be a second copy with no parity * gate holding it to the first. The consequence — a snapshot-only sheet has no columns to sit * on — is DISCLOSED below rather than papered over; the relaxation that would remove it is a * one-line 400→200 on the TS route, requested as an amendment in the wave doc. */ const table = useMemo(() => { if (!snapshotSelected.length || !served.columns.length) return served; const byKey = new Map(fields.map((f) => [f.key, f])); const extra = snapshotSelected .map((k) => byKey.get(k)) .filter((f): f is Field => !!f) .map((f) => buildTsSnapshotRow(f, rows ?? [], served.columns, payload?.meta?.today)); return { ...served, rows: [...served.rows, ...extra], empty: false }; }, [served, snapshotSelected, fields, rows, payload?.meta?.today]); const sheet: TsSheet = useMemo( () => buildTsSheet(table, { customRows, deltas: deltaKinds, bucket, today: payload?.meta?.today, }), [table, customRows, deltaKinds, bucket, payload?.meta?.today] ); /** * ⭐ owner item 3 (2026-08-03) — the sheet is PUBLISHED, not downloaded from here. * * This panel used to carry its own "Export CSV" button. It was the only view in the product * with a second export door, and the only one offering a single format, while every other * view exports from the "…" menu in the rail with four. So the button is gone and the sheet * goes UP instead: the owner of the view menu builds the file, and the time-series view * exports its SHEET rather than the customer rows underneath it. * * ⚠ A PROP, WHICH IS WHAT KEEPS THIS FILE HOST-AGNOSTIC. The rule at the top of this file is * that the panel reads no CustomerGrid state — a callback the caller supplies is the same * shape `onDisplay` already is. RECORD's embed passes neither and simply cannot export, which * is correct: there is no view menu in a record modal. * * Effect rather than a render-time call: publishing during render would set state in another * component mid-render. `sheet` is a `useMemo`, so this fires on a real change, not per frame. */ useEffect(() => { onSheet?.(sheet); }, [sheet, onSheet]); const toggleChart = useCallback((key: string) => { setCharted((prev) => { const next = new Set(prev); if (next.has(key)) next.delete(key); else next.add(key); return next; }); }, []); // ── display writers. Each one DELETES its key for the default rather than storing a second // spelling of it — the `kanbanClamp` law, which `tsGridlines` and `tsSparkline` inherit // exactly (the host accepts only the literal `false` / literal `true`). const setMetrics = (keys: string[]) => { // Never persist an EMPTY metric list: it would read back as "no data" on the next open. if (!keys.length) return; onDisplay?.({ tsFields: keys.slice(0, TS_MAX_FIELDS) }); }; const setRows = (rows: TsCustomRow[]) => onDisplay?.({ tsRows: rows.length ? rows.slice(0, TS_MAX_CUSTOM_ROWS) : undefined }); const toggleDelta = (kind: TsDeltaKind) => { const next = deltaKinds.includes(kind) ? deltaKinds.filter((k) => k !== kind) : [...deltaKinds, kind]; onDisplay?.({ tsDeltas: next.length ? next : undefined }); }; const setStyle = (rowId: string, patch: TsCellStyle) => { const next: Record = { ...(styles ?? {}) }; const merged = { ...resolveTsStyle(styles, rowId), ...patch }; // A style that reduces to nothing is DELETED, never stored as `{}`: an empty object is the // absent state's second spelling, and 200 of them would evict real emphasis under the cap // (GRID's C-TYPES2 asymmetry #1, mirrored here so a save round-trips unchanged). const kept: TsCellStyle = {}; if (merged.bold) kept.bold = true; if (merged.line) kept.line = true; if (kept.bold || kept.line) next[rowId] = kept; else delete next[rowId]; onDisplay?.({ tsStyles: Object.keys(next).length ? next : undefined }); }; // ── the Streamlit embed. C-TS: an honest placeholder, and above all it must not crash the // component — the grid still runs inside app.py and a throw here would take the page. if (embedded) { return (
The time-series view runs in the web app. Open Loopable in a browser tab to see it.
); } if (!eligible.length) { return (
This table has no number fields to plot. A time series needs either a metric with a period, or a numeric column to snapshot — add one from a column menu, then pick it here.
); } const unused = eligible.filter((f) => !selected.includes(f.key)); const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0); /* wave17 item 5 / R9 — the honest edge, while the TS route still 400s a request with no measure field in it. Snapshot rows are painted under the SERVER's bucket columns, so with no measure metric on the sheet there is nowhere to put them. Said in words, with the fix, rather than rendering an empty table that looks broken. */ const snapshotsUnplaced = snapshotSelected.length > 0 && sheet.columns.length === 0 && state !== "loading"; return (
{/* Item 18 — four named comparisons where there used to be one unnamed toggle. "Change vs prior" could not say WHICH prior, and there are four honest answers. wave17 owner item 7 — those four sat OPEN on the bar as a labelled strip, which made this panel's most consequential control look like nothing else in the product. It is a `Popover` now: the same component Filter / Sort / Group mount, so "the same" is achieved by BEING the same rather than by resembling it (the component's own note). The count rides the label in the `Filter · 2` grammar, and `active` lights the button while any comparison is on — the strip used to be the only way to know. */} } active={deltaKinds.length > 0} > {() => (
Compare each period with
Each choice adds a sub-row under every metric. A comparison that cannot be answered for a metric says so in the footnotes rather than printing a number.
{TS_DELTA_KINDS.map((kind) => ( ))}
)}
{/* ⛔ NO EXPORT BUTTON HERE (owner item 3, 2026-08-03). Export lives in the view's "…" menu, on every view, in four formats — and from a time-series view it now carries THIS SHEET rather than the rows beneath it (see `onSheet` above). A second door on one surface is how "where do I export from?" stops having an answer. */} {locked ? "This record" : `${sheet.pool.toLocaleString()} ${sheet.pool === 1 ? "customer" : "customers"}`}
{state === "error" && (
{errStatus === 400 ? "That span is too wide to bucket. Choose a shorter span or a larger period." : errStatus === 403 ? "None of these records are in your book." : "The time series could not be loaded. Nothing is shown rather than a guess."}
)} {snapshotsUnplaced && (
{snapshotSelected.length === 1 ? "That column has" : "Those columns have"} no period of its own, so {snapshotSelected.length === 1 ? "it is" : "they are"} shown as a snapshot across the periods on the sheet — and this sheet has no periods yet. Add one metric with a period and {snapshotSelected.length === 1 ? "it" : "they"} will appear beside it.
)} {/* wave17 item 5 / R9 — "offered is the ruling, undisclosed is not", and its converse: a field that CANNOT be plotted is NAMED here rather than quietly missing from the picker. A reader who can see "Status" in the table and cannot find it in this list otherwise has no way to tell a refusal from an oversight. ⛔ COLLAPSED, AFTER THE OWNER READ IT AS BROKEN MARKUP (2026-08-03). R9's disclosure was shipped as a bare strip of every refused label — struck through, unheaded, at the small end of the type scale. On the customer table that is ~25 names, and 25 crossed-out words in a row under a toolbar do not read as "these columns have no period"; they read as a stylesheet that failed to load. The strip said WHAT but never WHY IT WAS THERE. A `
` fixes exactly that and nothing else: the disclosure is still complete and still one click from the panel, but it now leads with a SENTENCE that says what the list is, and it is shut until asked. Native rather than a Popover — no state, keyboard and screen-reader behaviour for free, and it degrades to an open list if CSS never arrives, which is the failure this element is being fixed for. */} {classed.refused.length > 0 && (
{classed.refused.length === 1 ? "1 column has no period of its own" : `${classed.refused.length} columns have no period of their own`}
{classed.refused.map(({ field, why }) => ( {field.label} ))}
)} {/* wave17 GRID — item 3 / R6. Only the LOADING note becomes a spinner; the refusal notes above it keep their words, because "could not be loaded" is an answer and R6 is about the wait. A spinner in place of a refusal would spin forever. */} {state === "loading" && !payload && (
)} {payload && (
{sheet.columns.map((c) => ( ))} {sparkline && } {sheet.rows.map((row) => ( r.field === row.id)} onToggleChart={() => toggleChart(row.id)} onStyle={(patch) => setStyle(row.id, patch)} onRemove={() => { if (row.kind === "metric") setMetrics(selected.filter((k) => k !== row.id)); else setRows(customRows.filter((r) => r.id !== row.id)); }} onEditRow={(patch) => setRows(customRows.map((r) => (r.id === row.id ? { ...r, ...patch } : r))) } /> ))} {/* Item 17 — the sheet GROWS from its bottom edge, the way a spreadsheet does. This row is both the list of what could be added and the control that adds it; a picker somewhere else would be a second inventory to keep in sync. */} {onDisplay && ( )}
Metric {c.label} {c.partial && · partial} TotalTrend
{/* C-FLDSEL (item 20) — the type mark travels with the name. `value` is deliberately left UNSET: this control never displays a choice, it only makes one, so the placeholder IS its resting state (which is also the scar the contract names — a native
)} {payload && sheet.empty && (
No metrics returned a series for this span.
)} {sheet.notes.length > 0 && (
    {sheet.notes.map((n) => (
  • {n}
  • ))}
)}
); } /** A row's own controls: emphasis, then removal. Hover-revealed, always in the tab order. */ function RowTools({ style, editable, onStyle, onRemove, label, }: { style: TsCellStyle; editable: boolean; onStyle: (patch: TsCellStyle) => void; onRemove: () => void; label: string; }) { if (!editable) return null; return ( ); } /** * One sheet row: its values, its delta sub-rows, and an optional line chart. * * The chart is built from `tsRowToChartModel`, NOT from `viz/chartData.buildChartData` — see * that function's note. `buildChartData` caps at 12 buckets, which for a time series means * silently deleting periods. */ function TsRowBlock({ row, sheet, style, styles, sparkline, charted, editable, metricRow, onToggleChart, onStyle, onRemove, onEditRow, }: { row: TsSheetRow; sheet: TsSheet; style: TsCellStyle; styles: Record | undefined; sparkline: boolean; charted: boolean; editable: boolean; metricRow: TsTableRow | undefined; onToggleChart: () => void; onStyle: (patch: TsCellStyle) => void; onRemove: () => void; onEditRow: (patch: Partial) => void; }) { const spec = useMemo(() => { if (!charted || !metricRow) return null; const model = tsRowToChartModel(metricRow, sheet.columns); if (!model.points.length) return null; return toVegaLiteSpec({ spec: { id: row.id, kind: "line", agg: (row.agg ?? "sum") as never }, model, yTitle: row.label, formatValue: (n) => n.toLocaleString(undefined, { maximumFractionDigits: 2 }), }); }, [charted, metricRow, sheet.columns, row.id, row.agg, row.label]); const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0); const rowCls = (style.line ? "is-ruled" : "") + (style.bold ? " is-bold" : "") || undefined; // A NOTE row is a label across the sheet — a section heading in a financial model, not a // series with empty cells. Spanning it is what stops twelve blank cells from reading as // twelve unanswerable ones ("—" already means something else here). if (row.kind === "note") { return ( {editable ? ( onEditRow({ label: e.target.value })} /> ) : ( {row.label} )} ); } return ( <> {row.kind === "formula" ? ( editable ? ( onEditRow({ label: e.target.value })} /> ) : ( {row.label} ) ) : ( )} {/* R1 — the metric's OWN window. Two rows under the same month headings can be a cumulative year-to-date and a trailing 90 days; without this line they look like the same kind of number. */} {row.sublabel && {row.sublabel}} {row.kind === "formula" && (editable ? ( onEditRow({ expr: e.target.value })} /> ) : ( {row.expr} ))} {row.cells.map((c, i) => { const col = sheet.columns[i]; const cellStyle = resolveTsStyle(styles, row.id, col?.key); return ( {/* item 6 — `tsDisplayNumber`, never an inline toLocaleString: the CSV calls the same function, and that is the only thing making "the file matches the sheet" a property rather than a coincidence. */} {formatTsValue(c.value, tsDisplayNumber)} ); })} {/* An avg/min/max row has NO total — the cell stays empty rather than carrying an average of averages. See timeSeriesData's header note (2). Formula and note rows carry none either: an arbitrary expression is not additive across periods. */} {row.total == null ? "" : tsDisplayNumber(row.total)} {sparkline && ( c.value)} label={row.label} /> )} {row.deltas.map((d) => ( ))} {charted && ( {spec ? ( ) : (
Nothing to plot — every period for this metric is unanswered.
)} )} ); } /** * One comparison sub-row. * * ONE typography for all four (item 18's "standardized type"): the same 2xs size, the sign * carried by a `-deep` tint, refusals as "—". A comparison that cannot be answered AT ALL * (no year in the span; year-to-date growth asked of a trailing-90 row) renders its dashes and * the sheet's footnotes say why once — the alternative is a column of dashes indistinguishable * from missing data. */ function TsDeltaRow({ delta, sparkline, }: { delta: TsDeltaSubRow; sparkline: boolean; }) { return ( {delta.label} {delta.values.map((v, i) => ( = 0 ? "is-up" : "is-down"}> {delta.percent ? formatTsDelta(v) : v == null ? "—" : `${v > 0 ? "+" : ""}${tsDisplayNumber(v)}`} ))} {sparkline && } ); } /** * The trend column: a hand-rolled polyline, no library. * * ⚠ Gaps BREAK the line rather than being bridged. A stroke drawn straight across an * unanswerable period asserts a value for it — the same lie the table refuses one cell to the * left, at 72 pixels wide. */ function Sparkline({ values, label }: { values: (number | null)[]; label: string }) { const segments = useMemo( () => sparklineSegments(values, SPARK_W, SPARK_H), [values] ); if (!segments.length) return ; const answered = values.filter((v) => v != null).length; return ( {segments.map((s, i) => ( ))} ); }