Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/sheet/ChartDialog.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 64.7 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/sheet/ChartDialog.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/sheet/ChartDialog.tsx
-
curl -L -o ChartDialog.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/sheet/ChartDialog.tsx
64.7 kB
// sheet/ChartDialog.tsx β the Insert tab's CHART dialog (wave 54, W54-T11, ruling R5).
//
// ββ R5, VERBATIM: "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a
// database source is a second tab in the same dialog. Ship both." So this is ONE dialog with two
// source tabs, and the cell range tab is the one that opens.
//
// ββ HOW THE DATABASE TAB SURVIVES `SheetChart.tsx`'s RULING R9, WHICH SAYS THE OPPOSITE THING
// AND IS STILL TRUE. That file's header reads: "A CHART IS A CAPABILITY, NOT A VIEW TYPE. It
// occupies a rectangle of cells and READS those cells; it has no binding, no database and no query
// of its own. If this file ever calls the sheet preview door it has become a second way to fetch a
// number, and the sheet would then have two answers for one cell."
//
// The two reconcile in exactly one way, and it is the design below: THE DATABASE TAB DOES NOT GIVE
// THE CHART A QUERY. It writes BOUND CELLS into the sheet and then anchors an ordinary cell range
// chart over them. The chart still reads cells. The numbers still come from the one existing
// binding path, evaluated server side for a bound cell exactly as a hand bound cell is. Nothing
// here fetches a value, and `SheetChartSpec` gains no field: it is the same three keys it has
// carried since W49-T08.
//
// β WHAT THE DATABASE TAB WRITES, in ONE call through the door, so it is ONE history step and ONE
// save: a header row of period labels as typed literals, and beneath it one bound cell per period,
// every one carrying the same database, aggregate and scope and its OWN period. Then the chart,
// then a refresh, because a stale cell holds no value until the workbook refreshes.
//
// β THE BINDING VOCABULARY IS COPIED, NOT INVENTED. `BindingEditor.tsx` is the declaration of it
// and the server fixture in `aios-web/api/verify_sheet.py` is the proof; this file reuses the same
// names (`database`, `aggregate.fn`, `aggregate.field`, `scope.filter`, `period.unit`,
// `period.start`, `period.locked`) and imports nothing from that panel, because W54-T11 may not
// reach into lane E's files. A second spelling of the vocabulary would be a second dialect.
//
// β ESCAPE COMES FROM THE KIT AND FROM NOWHERE ELSE. `useOverlayLayer` registers this surface on
// the shared stack and calls `ui/useEscapeClose.ts` itself, which is why there is no local keydown
// listener anywhere in this file. DESIGN.md section 4: a local keydown listener is the defect, not
// the shortcut.
//
// β MOUNTED CONDITIONALLY BY ITS CALLER, never rendered behind an `open` prop. `useOverlayLayer`
// has no active flag: it claims Escape the moment it runs, and the stack hands the key to the LAST
// entry pushed. Mounting late is what puts this dialog above anything already open, and popping it
// on close hands Escape straight back.
//
// β DESIGN CONTRACT (DESIGN.md 2 through 5): centred modal on the base kit's `.lp-dialog` surface,
// tokens only, sentence case, inline SVG in the house vocabulary and never an emoji, a skeleton
// rather than a spinner while the database list is in flight, press feedback that does not change
// layout, reduced motion honoured, and no em dash or en dash in any string that reaches a screen.
import { createContext, Fragment, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useCellRefHighlight } from "./refHighlight";
import { AnchoredOverlay, BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
// The document's own addresser, in SHEET coordinates. A second spelling of A1 in this file would
// be a second answer to a question the document already answers.
import { addressOf } from "./sheetState";
import { parseRange } from "./rules";
import type { Cell, SheetChartRange, SheetChartSpec, SheetTab, SheetChartPresentation, SheetChartColor, ChartAxisFormat } from "./types";
import { SHEET_CHART_STACKING_KINDS, withChartStacking } from "./types";
import { CATEGORICAL, chartPresentationDefaults as defaultChartPresentation, colorStyle, chartDataForRange, chartLegendEntries, DrawnChart } from "./SheetChart";
import type { ChartSeriesHue, SheetChartData } from "./SheetChart";
import "../styles/wave58/sheet.css";
import "../styles/wave59/chart-dialog.css";
export function ChartSeriesColorPicker({ slot, label, presentation, value, onChange }: {
slot: number; label: string; presentation: SheetChartPresentation; value?: ChartSeriesHue;
onChange: (color: ChartSeriesHue | undefined) => void;
}) {
const opener = useRef<HTMLButtonElement>(null);
const listId = useId();
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
// A saved neutral override stays editable; new charts offer Theme and the eight hues.
const choices: (ChartSeriesHue | undefined)[] = [undefined, ...CATEGORICAL, ...(value === "muted" ? [value] : [])];
const name = (color: ChartSeriesHue | undefined) => color ? color[0].toUpperCase()+color.slice(1) : "Theme";
const dot = (color: ChartSeriesHue | undefined) => <span className="sheet-chart-color-dot" aria-hidden="true" style={colorStyle(slot,presentation,color)}/>;
const show = () => { setActive(Math.max(0,choices.indexOf(value))); setOpen(true); };
const close = () => { setOpen(false); opener.current?.focus(); };
return <>
<button ref={opener} type="button" className="sheet-chart-color-trigger" aria-label={label}
aria-haspopup="listbox" aria-expanded={open} aria-controls={open ? listId : undefined}
onClick={() => open ? close() : show()}
onKeyDown={event => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); show(); }
}}>{dot(value)}{name(value)}</button>
{open ? <AnchoredOverlay anchor={opener.current} className="sheet-chart-color-list" role="listbox"
id={listId} ariaLabel={label} onDismiss={close} restoreFocus initialFocus='[tabindex="0"]'
onKeyDown={event => {
const rows = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="option"]'));
const current = rows.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "ArrowDown" ? (current+1)%rows.length
: event.key === "ArrowUp" ? (current-1+rows.length)%rows.length
: event.key === "Home" ? 0 : event.key === "End" ? rows.length-1 : -1;
if (next >= 0) { event.preventDefault(); setActive(next); rows[next]?.focus(); }
if (event.key === "Tab") close();
}}>
{choices.map((color,index) => <button key={color ?? "theme"} type="button" role="option"
className="sheet-chart-color-option" aria-selected={value === color} tabIndex={index === active ? 0 : -1}
onFocus={() => setActive(index)} onClick={() => { onChange(color); close(); }}>
{dot(color)}{name(color)}
</button>)}
</AnchoredOverlay> : null}
</>;
}
/** R-instruction 11: a new chart is born named, so every label is something the user can click and
* rename. A chart saved before this release keeps whatever titles it had, which is why this is
* applied at CREATION and never in `defaultChartPresentation` or at render time. */
const UNTITLED = "Untitled";
const BOUND_KEYS = ["yMin", "yMax", "yMajor", "yMinor", "xMin", "xMax"] as const;
/** The page owns the atomic workbook write; isolated legacy mounts retain their old callback. */
export const ChartWorkbookContext = createContext<{
sheets: SheetTab[]; activeSheetId: string;
saveChart: (chart: SheetChartSpec, cells?: Record<string, Cell>) => Promise<boolean>;
loadSheet: (id: string) => void;
} | null>(null);
export function parseChartRanges(text: string): SheetChartRange[] | null {
const parts = text.split(/[;,]/).map(part => part.trim());
if (!parts.length || parts.some(part => !part)) return null;
const ranges = parts.map(parseRange);
return ranges.every((range): range is SheetChartRange => range !== null) ? ranges : null;
}
export type ChartRange = SheetChartRange;
/**
* All twenty-one kinds are drawn by `SheetChart.tsx::DrawnChart` and survive a save through
* `platform/core/sheets.py::SHEET_CHART_KINDS`. Availability for a particular selection depends
* on its model and the renderer's data requirements, not the unused drawn-kinds export.
*/
export const CHART_KINDS: { kind: SheetChartSpec["kind"]; label: string }[] = [
{ kind: "bar", label: "Bar" },
{ kind: "column", label: "Column" },
{ kind: "line", label: "Line" },
{ kind: "area", label: "Area" },
{ kind: "pie", label: "Pie" },
{ kind: "donut", label: "Donut" },
{ kind: "scatter", label: "Scatter" },
{ kind: "combo", label: "Combo" },
{ kind: "waterfall", label: "Waterfall" }, { kind: "histogram", label: "Histogram" },
{ kind: "bubble", label: "Bubble" }, { kind: "bullet", label: "Bullet" },
{ kind: "funnel", label: "Funnel" }, { kind: "gauge", label: "Gauge" },
{ kind: "polar", label: "Polar" }, { kind: "radar", label: "Radar" },
{ kind: "treemap", label: "Treemap" },
{ kind: "stock", label: "Stock" }, { kind: "gantt", label: "Gantt" },
{ kind: "sunburst", label: "Sunburst" }, { kind: "boxWhisker", label: "Box and whisker" },
];
type ChartKind = SheetChartSpec["kind"];
export interface ChartCandidate { kind: ChartKind; model: SheetChartData }
const CHART_DESCRIPTIONS: Record<ChartKind, string> = {
bar: "Compare values across categories with long labels.",
column: "Compare values across a few categories.",
line: "Follow changes across an ordered sequence.",
area: "Show how values build and change over a sequence.",
pie: "Compare a few categories as shares of a total.",
donut: "Show how a few categories contribute to a total.",
scatter: "Explore the relationship between two numeric measures.",
combo: "Compare series with columns and a line on one scale.",
waterfall: "Show how successive changes build a running total.",
histogram: "See how numeric values fall into intervals.",
bubble: "Compare numeric relationships with size as another measure.",
bullet: "Compare a value with a target on the same scale.",
funnel: "Compare values across successive stages.",
gauge: "Show one value within a bounded scale.",
polar: "Compare category magnitudes around a circle.",
radar: "Compare series profiles across the same categories.",
treemap: "Compare category shares with proportional areas.",
stock: "Compare high, low and closing values over time.",
gantt: "Compare task start times and durations.",
sunburst: "Compare nested category shares as rings.",
boxWhisker: "See a numeric distribution's quartiles, median and outliers.",
};
/**
* ββ THE RENDERER'S OWN REFUSALS, MIRRORED IN ITS OWN ORDER, so the gallery never offers a kind
* whose preview would be a refusal box. Every arm below is a line of `SheetChart.tsx::DrawnChart`:
* the shared preamble at 285-293, then gauge 360, radar 372, bullet 401 and the XY family 414-416.
* β THIS IS A HAND COPY AND HAND COPIES DRIFT. What keeps it honest is the `all charts ... explain
* renderer refusals` leg in `verify_charts.py`, which renders all twenty-one kinds over several
* fixtures and asserts this function agrees with the rendered `role="status"` exactly. If you add a
* refusal to the renderer, that leg reds here until you add it too [W59-T07].
*/
export function chartPreviewError(kind: ChartKind, model: SheetChartData): string | undefined {
if (model.error) return model.error;
if (!model.series.length || !model.rows.length) return "This range has no numeric values to chart.";
const numeric = (row: SheetChartData["rows"][number], key: string) => {
const value = (row as unknown as Record<string, unknown>)[key];
return typeof value === "number" && Number.isFinite(value) ? value : null;
};
// `all` is every series' numbers; `valid` is the FIRST series' alone, exactly as the renderer
// splits them, because gauge counts one series and the share families count the whole selection.
const all = model.series.flatMap(series => model.rows
.map(row => numeric(row, series.y)).filter((value): value is number => value !== null));
const valid = model.rows.map(row => numeric(row, model.series[0].y))
.filter((value): value is number => value !== null);
const oneSeries = ["pie", "donut", "funnel", "treemap", "polar", "waterfall", "histogram", "gauge", "sunburst"];
const nonNegative = ["pie", "donut", "funnel", "treemap", "polar", "radar"];
const positiveTotal = ["pie", "donut", "funnel", "treemap", "polar"];
if (oneSeries.includes(kind) && model.series.length !== 1)
return "Select one visible series for this chart type.";
if (nonNegative.includes(kind) && all.some(value => value < 0))
return "This chart type needs nonnegative values.";
if (positiveTotal.includes(kind) && valid.reduce((sum, value) => sum + value, 0) <= 0)
return "This chart type needs a positive total.";
if (kind === "sunburst" && model.rows.some(row => typeof row.category !== "string"
|| typeof (row as unknown as Record<string, unknown>).child !== "string" || !String(row.category ?? "").trim()
|| !String((row as unknown as Record<string, unknown>).child ?? "").trim() || numeric(row, model.series[0].y) === null))
return "Sunburst needs two text category columns followed by one numeric value column.";
if (kind === "sunburst" && !valid.some(value => value > 0))
return "Sunburst excludes zero and negative values; choose at least one positive value.";
if (kind === "sunburst" && !Number.isFinite(valid.reduce((sum,value) => sum+Math.max(0,value),0)))
return "Sunburst needs a finite positive total.";
if (kind === "boxWhisker") {
const shortSeries = model.series.find(s => model.rows.filter(row => numeric(row,s.y) !== null).length < 5);
if (shortSeries) return `Box and whisker needs at least five numeric values in ${shortSeries.label}.`;
}
if (kind === "gauge" && valid.length !== 1) return "A gauge needs one numeric value.";
if (kind === "radar" && model.rows.length < 3) return "A radar chart needs at least three categories.";
if (kind === "bullet" && model.series.length < 2) return "A bullet chart needs actual and target series.";
if (kind === "bubble" && model.series.length < 2) return "A bubble chart needs X, Y and size columns.";
if (kind === "bubble" && model.rows.some(row => (numeric(row, model.series[1].y) ?? 0) < 0))
return "Bubble sizes must be nonnegative.";
if ((kind === "scatter" || kind === "bubble") && model.rows.some(row => numeric(row, "category") === null))
return "The X column must contain numeric values.";
return undefined;
}
/** Pure data in, ranked kinds out; never recommend a model the preview cannot draw. */
export function recommendChartKinds(candidates: readonly ChartCandidate[]): ChartKind[] {
const drawable = candidates.filter(({ kind, model }) => !chartPreviewError(kind, model));
// Prefer the selection's text categories over an XY reinterpretation of its value columns.
const categories = candidates.find(candidate => candidate.kind === "column")?.model.rows;
const numericCategories = !categories || categories.every(row => {
const category = String(row.category ?? "");
return /^[A-Z]+[1-9]\d*$/.test(category) || (category.trim() !== "" && Number.isFinite(Number(category)));
});
const score = ({ kind, model }: ChartCandidate): number => {
const many = model.rows.length > 8;
const multiple = model.series.length > 1;
if (numericCategories && model.fields[0]?.type === "int") {
if (kind === "scatter") return 120;
if (kind === "bubble") return multiple ? 115 : 85;
}
if (kind === "stock" && ["high", "low", "close"].every(role => model.series.some(series => series.label.toLowerCase().includes(role)))) return 110;
if (kind === "gantt" && model.series.some(series => /start|duration|end|days/i.test(series.label))) return 110;
const preference: Partial<Record<ChartKind, number>> = many
? { line: 100, area: 90, bar: 80, column: 70, combo: multiple ? 85 : 30, histogram: 60 }
: multiple
? { column: 100, line: 90, area: 80, combo: 70, bar: 60, radar: 50 }
: { column: 100, bar: 90, pie: 80, donut: 70, line: 60, area: 50 };
return preference[kind] ?? 10;
};
return drawable.slice().sort((a, b) => score(b) - score(a)).slice(0, 6).map(candidate => candidate.kind);
}
/** Each kind interprets the actual source independently, including fixed-role and XY families. */
export function chartCandidatesForRange(cells: Record<string, Cell>, range: ChartRange,
presentation: SheetChartPresentation, ranges: ChartRange[] = [range]): ChartCandidate[] {
const invalidBounds = [presentation.yMin, presentation.yMax, presentation.yMajor, presentation.yMinor]
.some(value => value !== undefined && !Number.isFinite(value))
|| [presentation.yMajor, presentation.yMinor].some(value => value !== undefined && value <= 0);
const boundsError = invalidBounds ? "Enter finite bounds and positive units."
: presentation.yMin !== undefined && presentation.yMax !== undefined && presentation.yMin >= presentation.yMax
? "The Y maximum must exceed the minimum." : undefined;
return CHART_KINDS.map(({ kind }) => {
const model = chartDataForRange(cells, range, presentation, ranges, kind);
return { kind, model: boundsError ? { ...model, error: boundsError } : model };
});
}
/**
* β THE AGGREGATE VOCABULARY, COPIED FROM `BindingEditor.tsx::AGGREGATES` NAME FOR NAME. The
* server normalizes `aggregate.fn` against this same set, so a name invented here would bind a
* cell the panel could never reopen.
*/
const AGGREGATES: { fn: string; label: string }[] = [
{ fn: "sum", label: "Sum" },
{ fn: "count", label: "Count" },
{ fn: "avg", label: "Average" },
{ fn: "min", label: "Minimum" },
{ fn: "max", label: "Maximum" },
];
type PeriodUnit = "month" | "quarter" | "year";
const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [
{ unit: "month", label: "Month" },
{ unit: "quarter", label: "Quarter" },
{ unit: "year", label: "Year" },
];
/** How many months one step of a unit covers. Same arithmetic the binding panel states. */
const MONTHS_PER_UNIT: Record<PeriodUnit, number> = { month: 1, quarter: 3, year: 12 };
const MONTH_ABBR = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
/**
* β THE FALLBACK RECTANGLE, AND WHY IT IS A FALLBACK RATHER THAN A REFUSAL. A chart OCCUPIES the
* rectangle it reads, so a one cell range is a chart nobody can see and an absent range is no
* chart at all. When the selection is a single cell the range grows from that cell to this size,
* and with no selection at all it starts at A1, which is the only anchor available. The dialog
* SAYS which rectangle it will cover, so the growth is visible before anything is inserted.
*/
const CHART_COLS = 4;
const CHART_ROWS = 6;
/** How many periods the database tab writes, and the fence around what a person may ask for. */
const DEFAULT_PERIODS = 6;
const MIN_PERIODS = 2;
const MAX_PERIODS = 24;
const pad2 = (n: number) => String(n).padStart(2, "0");
const joinYm = (y: number, m: number) => `${y}-${pad2(m)}`;
/** `{y, m}` out of a `"YYYY-MM"`; today when the string is absent or malformed. */
function splitYm(ym: string): { y: number; m: number } {
const hit = /^(\d{4})-(\d{2})$/.exec(ym ?? "");
if (!hit) {
const now = new Date();
return { y: now.getFullYear(), m: now.getMonth() + 1 };
}
const m = Number(hit[2]);
return { y: Number(hit[1]), m: m >= 1 && m <= 12 ? m : 1 };
}
/**
* β `start` IS THE PERIOD'S FIRST MONTH, which is what contract C2 means by it: `unit` and `start`
* have to jointly name exactly one window, so Q3 2026 is `2026-07` and the year 2026 is `2026-01`.
*/
export function periodStartOf(unit: PeriodUnit, ym: string): string {
const { y, m } = splitYm(ym);
if (unit === "year") return joinYm(y, 1);
if (unit === "quarter") return joinYm(y, 1 + 3 * Math.floor((m - 1) / 3));
return joinYm(y, m);
}
/** Move a start by whole periods. Negative steps go back. */
export function shiftPeriod(unit: PeriodUnit, ym: string, steps: number): string {
const { y, m } = splitYm(periodStartOf(unit, ym));
const total = y * 12 + (m - 1) + steps * MONTHS_PER_UNIT[unit];
return joinYm(Math.floor(total / 12), (total % 12) + 1);
}
/** What a header cell says for one period. Sentence case, and no dash anywhere near it. */
export function periodLabel(unit: PeriodUnit, ym: string): string {
const { y, m } = splitYm(periodStartOf(unit, ym));
if (unit === "year") return String(y);
if (unit === "quarter") return `Q${1 + Math.floor((m - 1) / 3)} ${y}`;
return `${MONTH_ABBR[m - 1]} ${y}`;
}
const todayYm = (): string => {
const now = new Date();
return joinYm(now.getFullYear(), now.getMonth() + 1);
};
/** The rectangle a cell range chart occupies, grown to something visible when it has to be. */
export function chartRangeOf(sel: ChartRange | null): ChartRange {
const col0 = sel ? Math.min(sel.col0, sel.col1) : 0;
const row0 = sel ? Math.min(sel.row0, sel.row1) : 0;
const col1 = sel ? Math.max(sel.col0, sel.col1) : 0;
const row1 = sel ? Math.max(sel.row0, sel.row1) : 0;
if (col1 > col0 || row1 > row0) return { col0, row0, col1, row1 };
return { col0, row0, col1: col0 + CHART_COLS - 1, row1: row0 + CHART_ROWS - 1 };
}
/** A chart range as one editable A1 expression. */
export function chartRangeText(range: ChartRange): string {
const first = addressOf(Math.min(range.col0, range.col1), Math.min(range.row0, range.row1));
const last = addressOf(Math.max(range.col0, range.col1), Math.max(range.row0, range.row1));
return first === last ? first : `${first}:${last}`;
}
/** Where a database block lands: the selection's top left, or A1 when there is no selection. */
export function landingOf(sel: ChartRange | null): { col: number; row: number } {
if (!sel) return { col: 0, row: 0 };
return { col: Math.min(sel.col0, sel.col1), row: Math.min(sel.row0, sel.row1) };
}
export interface DatabaseBlockPlan {
cells: Record<string, Cell>;
range: ChartRange;
}
/**
* ββ THE WHOLE OF THE DATABASE TAB'S WRITE, AS A PURE FUNCTION so a reader can see that it
* produces CELLS and a RECTANGLE and never a query. Two rows: period labels on top, one bound cell
* per period beneath. The chart is anchored over both rows, because the header row is the axis.
*/
export function planDatabaseBlock(opts: {
anchor: { col: number; row: number };
database: string;
fn: string;
field: string;
unit: PeriodUnit;
periods: number;
}): DatabaseBlockPlan {
const { anchor, database, fn, field, unit } = opts;
const asked = Math.round(opts.periods);
const count = Math.max(MIN_PERIODS, Math.min(MAX_PERIODS, Number.isFinite(asked) ? asked : DEFAULT_PERIODS));
const latest = periodStartOf(unit, todayYm());
const cells: Record<string, Cell> = {};
for (let i = 0; i < count; i += 1) {
const start = shiftPeriod(unit, latest, i - (count - 1));
const col = anchor.col + i;
cells[addressOf(col, anchor.row)] = {
kind: "literal",
state: "typed",
text: periodLabel(unit, start),
};
cells[addressOf(col, anchor.row + 1)] = {
kind: "bound",
state: "stale",
binding: {
database,
// A count folds no column, exactly as the binding panel writes it.
aggregate: fn === "count" ? { fn } : { fn, field },
scope: { filter: { conj: "and", nodes: [] } },
// LOCKED, and that is not a default worth glossing: each cell names one fixed window, and
// an unlocked period would shift the moment somebody dragged the block sideways, moving a
// number with no edit behind it.
period: { unit, start, locked: true },
},
};
}
return {
cells,
range: { col0: anchor.col, row0: anchor.row, col1: anchor.col + count - 1, row1: anchor.row + 1 },
};
}
// Database plans keep real period labels but stale values, which the chart treats as empty.
// Preview-only samples preserve the labels and chart shape without pretending to be real figures.
const PREVIEW_SAMPLE = [42, 68, 51, 84, 63, 97, 75, 89, 58, 72, 46, 91];
export function previewDatabaseCells(plan: DatabaseBlockPlan): Record<string, Cell> {
const cells = { ...plan.cells };
let i = 0;
for (let col = plan.range.col0; col <= plan.range.col1; col += 1) {
for (let row = plan.range.row0; row <= plan.range.row1; row += 1) {
const address = addressOf(col, row);
if (cells[address]?.state === "stale") {
cells[address] = {
kind: "literal", state: "typed", text: String(PREVIEW_SAMPLE[i % PREVIEW_SAMPLE.length]),
};
i += 1;
}
}
}
return cells;
}
type SourceTab = "range" | "database";
const SOURCE_TABS: { id: SourceTab; label: string }[] = [
{ id: "range", label: "A cell range" },
{ id: "database", label: "A database" },
];
export interface ChartDialogProps {
/** The current selection, in SHEET coordinates, or null when there is none. */
selection: ChartRange | null;
/** Present when this is the same dialog reopened for an existing chart. */
chart?: SheetChartSpec;
/** A ribbon chart-kind shortcut opens the chart section on this kind. */
initialKind?: SheetChartSpec["kind"];
/** Escape, the close mark, or Cancel. All converge on the same event. */
onClose: () => void;
/**
* The one door out. `cells` is present only on the database tab, and the caller commits it in a
* single call so the block, the chart and the refresh are one step.
*/
onCreate?: (
kind: SheetChartSpec["kind"],
range: ChartRange,
cells?: Record<string, Cell>,
) => void;
/** The existing chart's one persisted settings write. */
onUpdate?: (chart: SheetChartSpec) => void;
/**
* R6's delete door. The mount supplies it for an existing chart, and the control stays hidden
* when the mount cannot delete.
*/
onDelete?: () => void;
/** Ribbon openers restore themselves; a chart settings button delegates restoration here. */
restoreFocus?: boolean;
}
export default function ChartDialog({
selection,
chart,
initialKind,
onClose,
onCreate,
onUpdate,
onDelete,
restoreFocus = false,
}: ChartDialogProps) {
const workbook = useContext(ChartWorkbookContext);
const panelRef = useRef<HTMLDivElement>(null);
const titleId = useId();
const editing = chart !== undefined;
const seedRange = chart?.source?.ranges[0] ?? chart?.range ?? selection ?? { col0: 0, row0: 0, col1: 0, row1: 0 };
const [opening] = useState(() => {
if (initialKind) return { section: "Chart", kind: initialKind };
const fallback = { section: "Data", kind: chart?.kind ?? "bar" as ChartKind };
if (editing || !selection || (selection.col0 === selection.col1 && selection.row0 === selection.row1)) return fallback;
const cells = workbook?.sheets.find(sheet => sheet.id === workbook.activeSheetId)?.cells ?? {};
const recommended = recommendChartKinds(chartCandidatesForRange(cells, selection, defaultChartPresentation()));
return recommended.length ? { section: "Chart", kind: recommended[0] } : fallback;
});
const [presentation, setPresentation] = useState<SheetChartPresentation>(() => ({...defaultChartPresentation(),...chart?.presentation}));
const [sourceSheetId, setSourceSheetId] = useState(chart?.source?.sheetId ?? workbook?.activeSheetId ?? "");
const [destination, setDestination] = useState(chart?.sheetId ?? workbook?.activeSheetId ?? "");
const [newName, setNewName] = useState("Chart");
const [anchor, setAnchor] = useState(() => addressOf(chart?.geometry?.col ?? 0, chart?.geometry?.row ?? 0));
const [chartWidth, setChartWidth] = useState(String(chart?.geometry?.width ?? 640));
const [chartHeight, setChartHeight] = useState(String(chart?.geometry?.height ?? 360));
const [section, setSection] = useState(opening.section);
const [galleryTab, setGalleryTab] = useState<"recommended" | "all">(editing || initialKind ? "all" : "recommended");
const [bounds, setBounds] = useState<Record<string,string>>(() => Object.fromEntries(BOUND_KEYS.map(k=>[k,String(chart?.presentation?.[k]??"")])));
const setOption = <K extends keyof SheetChartPresentation>(key: K, value: SheetChartPresentation[K]) =>
setPresentation(current => ({...current,[key]:value}));
const setAxis = (axis: "valueAxis" | "categoryAxis", patch: Partial<ChartAxisFormat>) =>
setOption(axis, { ...(presentation[axis] ?? {}), ...patch });
const [tab, setTab] = useState<SourceTab>("range");
const [kind, setKind] = useState<SheetChartSpec["kind"]>(opening.kind);
const [stacking, setStacking] = useState<SheetChartSpec["stacking"]>(chart?.stacking);
const chartStacking = SHEET_CHART_STACKING_KINDS.includes(kind) ? stacking : undefined;
const [rangeDraft, setRangeDraft] = useState(() => (chart?.source?.ranges ?? [seedRange]).map(chartRangeText).join(", "));
// The data range and the anchor cell are outlined on the grid while the dialog is open.
useCellRefHighlight([tab === "range" ? rangeDraft : "", anchor]);
const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
const [loading, setLoading] = useState(!editing);
const [database, setDatabase] = useState("");
const [fn, setFn] = useState("count");
const [field, setField] = useState("");
const [unit, setUnit] = useState<PeriodUnit>("month");
const [periods, setPeriods] = useState(String(DEFAULT_PERIODS));
useEffect(() => { if (sourceSheetId) workbook?.loadSheet(sourceSheetId); }, [sourceSheetId,workbook?.loadSheet]);
// β RESTORE FOCUS IS OFF, AND THAT IS THE RIBBON'S RULE RATHER THAN AN OMISSION. Every ribbon
// button prevents default on mouse down so that pressing it never blurs the grid canvas, so the
// element this dialog would restore is the CANVAS. `Ribbon.tsx::closePop` already returns focus
// to the trigger on close, and it must win.
useOverlayLayer({
panelRef,
onDismiss: onClose,
// This is a modal settings surface. A stray click must not discard a half-edited range.
dismissOnOutside: false,
initialFocus: "first",
restoreFocus,
trapFocus: true,
});
/**
* β THE SAME DOOR THE RAIL AND THE BINDING PANEL READ, spelled the same way `SheetPage.tsx`
* spells it. FAILS SOFT ON PURPOSE: a refused or broken fetch leaves the picker with nothing to
* offer and the panel says so, which is a refusal a person can act on. A thrown error inside a
* dialog is not.
*/
useEffect(() => {
if (editing) return undefined;
let live = true;
(async () => {
try {
const res = await fetch("/api/v1/nav", { credentials: "same-origin" });
if (!res.ok) return;
const body = (await res.json()) as { pages?: { key: string; label: string }[] };
if (!live) return;
const rows = (body.pages ?? [])
.filter((p) => p && typeof p.key === "string")
.map((p) => ({ key: p.key, label: p.label || p.key }));
setDatabases(rows);
setDatabase(rows[0]?.key ?? "");
} catch {
/* the picker simply offers nothing, and the panel says so */
} finally {
if (live) setLoading(false);
}
})();
return () => { live = false; };
}, [editing]);
const ranges = useMemo(() => parseChartRanges(rangeDraft), [rangeDraft]);
const range = ranges?.[0] ?? null;
const location = parseRange(anchor);
const sourceCells = workbook?.sheets.find(s => s.id === sourceSheetId)?.cells ?? {};
const candidates = useMemo(() => chartCandidatesForRange(sourceCells, range ?? seedRange, presentation, ranges ?? [seedRange]), [sourceCells,range,presentation,ranges]);
const model = candidates.find(candidate => candidate.kind === kind)!.model;
const recommended = useMemo(() => range ? recommendChartKinds(candidates) : [], [candidates,range]);
const previewError = range ? chartPreviewError(kind, model) : "Enter a valid data range.";
const databasePlan = useMemo(() => tab === "database" ? planDatabaseBlock({
anchor: landingOf(selection), database, fn, field: field.trim(), unit, periods: Number(periods),
}) : null, [tab, selection, database, fn, field, unit, periods]);
const databasePresentation = useMemo<SheetChartPresentation>(() => ({
...presentation, orientation: "rows", headers: "none", categoryLabels: "firstColumn",
}), [presentation]);
const databaseModel = useMemo(() => databasePlan ? chartDataForRange(
previewDatabaseCells(databasePlan), databasePlan.range, databasePresentation, [databasePlan.range], kind,
) : null, [databasePlan, databasePresentation, kind]);
const previewModel = tab === "database" && databaseModel ? databaseModel : model;
const previewPresentation = tab === "database" ? databasePresentation : presentation;
const previewMessage = tab === "range" ? previewError
: !database || !databaseModel ? "Choose a database to see a preview." : chartPreviewError(kind, databaseModel);
const previewNote = previewMessage || (tab === "database"
? "Sample values. The chart reads the real figures once the periods land in the sheet."
: CHART_DESCRIPTIONS[kind]);
const galleryKinds = galleryTab === "recommended" ? recommended : CHART_KINDS.map(entry => entry.kind);
const thumbnailPresentation: SheetChartPresentation = {
...presentation, showLegend: false, showDataLabels: false, showAxisTitles: false, layout: "compact",
};
useEffect(() => {
if (section === "Chart" && tab === "range" && galleryTab === "recommended" && recommended.length && !recommended.includes(kind))
setKind(recommended[0]);
}, [section,tab,galleryTab,recommended,kind]);
// [W59-T08] A ribbon chart-kind shortcut can select a kind that sits below the rail's fold, and a
// selection nobody can see is not "visibly focused". `nearest` so an already-visible thumbnail
// never jumps under the pointer.
const railRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
railRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')
?.scrollIntoView({ block: "nearest" });
}, [kind, galleryTab, section, tab]);
const offeredModel = useMemo(() => chartDataForRange(sourceCells, range ?? seedRange, {...presentation,series:[]}, ranges ?? [seedRange], kind), [sourceCells,range,presentation,ranges,kind]);
const offeredSeries = offeredModel.series;
const configuredSeries = (presentation.series ?? []).flatMap(setting => {
const offered = offeredSeries.find(s => s.sourceKey === setting.key || s.y === setting.key);
return offered ? [{...setting,key:offered.sourceKey || offered.y}] : [];
});
const settings: NonNullable<SheetChartPresentation["series"]> = [...configuredSeries,
...offeredSeries.filter(s => !configuredSeries.some(c => c.key === (s.sourceKey||s.y))).map(s => ({key:s.sourceKey||s.y}))];
const legendEntries = chartLegendEntries(kind, settings.filter(s => !s.hidden).length, offeredModel.rows.length);
const seriesName = (s: NonNullable<SheetChartPresentation["series"]>[number]) =>
s.label || offeredSeries.find(offer => (offer.sourceKey||offer.y) === s.key)?.label || s.key;
const updateSeries = (key: string, patch: Partial<NonNullable<SheetChartPresentation["series"]>[number]>) =>
setOption("series",settings.map(s => s.key === key ? {...s,...patch} : s));
const moveSeries = (index:number, direction:number) => {
const reordered = [...settings], other=index+direction;
[reordered[index],reordered[other]]=[reordered[other],reordered[index]];
setOption("series",reordered);
};
const boundsError = BOUND_KEYS.some(key=>bounds[key]!==""&&(!Number.isFinite(Number(bounds[key]))||((key==="yMajor"||key==="yMinor")&&Number(bounds[key])<=0)))
? "Enter finite bounds and positive units."
: bounds.yMin!==""&&bounds.yMax!==""&&Number(bounds.yMin)>=Number(bounds.yMax) ? "The Y maximum must exceed the minimum."
: bounds.xMin!==""&&bounds.xMax!==""&&Number(bounds.xMin)>=Number(bounds.xMax) ? "The X maximum must exceed the minimum." : "";
const validGeometry = location && location.col0===location.col1 && location.row0===location.row1
&& Number(chartWidth)>=320 && Number(chartWidth)<=2400 && Number(chartHeight)>=240 && Number(chartHeight)<=1600;
const newNameError = destination==="__new__" && (!newName.trim() || [...newName].some(c => "[]:*?/\\\\'".includes(c)) || workbook?.sheets.some(s=>s.name.toLowerCase()===newName.trim().toLowerCase()));
const wantsField = fn !== "count";
const ready = Boolean(validGeometry) && !boundsError && !newNameError && (tab === "range"
? range !== null && !previewError
: Boolean(database) && (!wantsField || field.trim().length > 0) && Number(periods)>=MIN_PERIODS && Number(periods)<=MAX_PERIODS);
const create = async () => {
if (!ready || !location) return;
const plan = tab === "database" ? planDatabaseBlock({
anchor: landingOf(selection), database, fn, field:field.trim(), unit, periods:Number(periods),
}) : null;
const dataRanges = plan ? [plan.range] : ranges!;
const display = {...presentation, series: configuredSeries};
for (const key of BOUND_KEYS) {
if (bounds[key] === "") delete display[key]; else display[key] = Number(bounds[key]);
}
if (!editing) for (const key of ["title", "xTitle", "yTitle"] as const)
if (!display[key]) display[key] = UNTITLED;
if (plan) { display.orientation = "rows"; display.headers = "none"; display.categoryLabels = "firstColumn"; }
const next = withChartStacking({
...chart, id: chart?.id ?? `chart-${crypto.randomUUID()}`, kind, range:dataRanges[0],
source:{ranges:dataRanges,sheetId:plan ? workbook?.activeSheetId : sourceSheetId || undefined},
geometry:{col:location.col0,row:location.row0,width:Number(chartWidth),height:Number(chartHeight)},
presentation:display, sheetId:destination==="__new__" ? `new:${newName.trim()}` : destination || undefined,
}, chartStacking);
if (workbook) { if (await workbook.saveChart(next,plan?.cells)) onClose(); }
else if (editing) onUpdate?.(next);
else onCreate?.(kind,next.range,plan?.cells);
};
const group = (name: string, body: ReactNode, busy?: boolean) => (
<section className="sheet-chart-group" aria-label={name} aria-busy={busy}>
<h3 className="sheet-chart-group-name">{name}</h3>
<div className="sheet-chart-fields">{body}</div>
</section>
);
const rangeFieldRows = (
<>
<label className="sheet-chart-label" htmlFor={`${titleId}-range`}>Data range</label>
<input
id={`${titleId}-range`}
className="sheet-chart-text"
type="text"
value={rangeDraft}
aria-invalid={range === null}
aria-describedby={range === null
? `${titleId}-range-note ${titleId}-range-error`
: `${titleId}-range-note`}
onChange={(event) => setRangeDraft(event.target.value)}
/>
<p className="sheet-chart-caption" id={`${titleId}-range-note`}>
Separate ranges with commas, such as A1:A8, C1:D8.
</p>
{range === null ? (
<p className="sheet-chart-caption" id={`${titleId}-range-error`} role="alert">
Enter ranges such as B2:E8 or A1:A8, C1:C8.
</p>
) : null}
</>
);
const kindPicker = <label className="sheet-chart-setting">Chart type<select aria-label="Chart type" value={kind} onChange={event=>setKind(event.target.value as SheetChartSpec["kind"])}>{CHART_KINDS.map(entry=><option key={entry.kind} value={entry.kind}>{entry.label}</option>)}</select></label>;
const subtypePicker = SHEET_CHART_STACKING_KINDS.includes(kind)
? <label className="sheet-chart-setting">Chart sub-type<select aria-label="Chart sub-type" value={chartStacking ?? "clustered"}
onChange={event=>setStacking(event.target.value === "clustered" ? undefined : event.target.value as SheetChartSpec["stacking"])}>
<option value="clustered">Clustered</option><option value="stacked">Stacked</option><option value="percent">100% stacked</option>
</select></label> : null;
const chartGallery = <div className="sheet-chart-chooser">
<div className="sheet-chart-chooser-tabs" role="tablist" aria-label="Chart choices">
{([['recommended', 'Recommended charts'], ['all', 'All charts']] as const).map(([id, label]) =>
<button type="button" role="tab" key={id} id={`${titleId}-choices-${id}`}
className="sheet-chart-chooser-tab" aria-selected={galleryTab === id}
aria-controls={`${titleId}-choices-panel`} onClick={() => {
setGalleryTab(id);
if (id === "recommended" && recommended.length) setKind(recommended[0]);
}}>{label}</button>)}
</div>
<div className="sheet-chart-chooser-body" id={`${titleId}-choices-panel`} role="tabpanel"
aria-labelledby={`${titleId}-choices-${galleryTab}`}>
{/* [W60-T16] The sentence used to live under the gallery's own preview, which moved out to
the dialog's right column. An empty tablist is not an answer, so it is said here. */}
{galleryKinds.length ? <div className="sheet-chart-thumbnail-rail" ref={railRef} role="tablist" aria-label="Chart types" aria-orientation="vertical">
{galleryKinds.map(candidateKind => {
const candidateModel = candidates.find(candidate => candidate.kind === candidateKind)!.model;
const error = range ? chartPreviewError(candidateKind, candidateModel) : "Enter a valid data range.";
const label = CHART_KINDS.find(entry => entry.kind === candidateKind)!.label;
return <button type="button" role="tab" key={candidateKind} id={`${titleId}-kind-${candidateKind}`}
className="sheet-chart-thumbnail" aria-label={label} aria-selected={kind === candidateKind}
aria-controls={`${titleId}-live-preview`} onClick={() => setKind(candidateKind)}>
<span className="sheet-chart-thumbnail-name">{label}</span>
{error ? <span className="sheet-chart-thumbnail-error">{error}</span>
: <span className="sheet-chart-thumbnail-drawing" aria-hidden="true">
<DrawnChart {...candidateModel} kind={candidateKind} presentation={thumbnailPresentation} width={480} height={320}/>
</span>}
</button>;
})}
</div> : <p className="sheet-chart-live-description" role="status">Choose a range with numeric values to see recommendations.</p>}
</div>
</div>;
const select = <K extends keyof SheetChartPresentation>(label: string,key:K,choices: readonly (readonly [string,string])[]) =>
<label className="sheet-chart-setting">{label}<select aria-label={label} value={String(presentation[key]??(key==="ganttMode"?"duration":""))} onChange={e=>setOption(key,e.target.value as SheetChartPresentation[K])}>{choices.map(([value,label])=><option key={value} value={value}>{label}</option>)}</select></label>;
const text = (label: string,key:"title"|"xTitle"|"yTitle"|"categoryTitle") =>
<label className="sheet-chart-setting">{label}<input aria-label={label} maxLength={160} value={presentation[key]??""} onChange={e=>setOption(key,e.target.value)}/></label>;
const toggle = (label:string,key:"showLegend"|"showAxisTitles"|"showDataLabels") =>
<label className="sheet-chart-check"><input type="checkbox" checked={presentation[key]!==false} onChange={e=>setOption(key,e.target.checked)}/>{label}</label>;
const axisFields = (axis: "valueAxis" | "categoryAxis") => {
const format = presentation[axis] ?? {};
const fieldId = (name: string) => `${titleId}-${axis}-${name}`;
const value = axis === "valueAxis";
return <>
{BOUND_KEYS.filter(key => value
? key.startsWith("y") && (!["gauge", "radar"].includes(kind) || key === "yMin" || key === "yMax")
: key.startsWith("x") && ["scatter", "bubble"].includes(kind)).map(key => <Fragment key={key}>
<label className="sheet-chart-label" htmlFor={fieldId(key)}>{key.endsWith("Min") ? "Minimum" : key.endsWith("Max") ? "Maximum" : key === "yMajor" ? "Major unit" : "Minor unit"}</label>
<input id={fieldId(key)} type="number" step="any" placeholder="Auto" value={bounds[key]} onChange={event => {
const next = event.target.value;
setBounds(current => ({...current, [key]: next}));
setOption(key, next === "" ? undefined : Number(next));
}}/>
</Fragment>)}
<label className="sheet-chart-label" htmlFor={fieldId("decimals")}>Decimal places</label>
<input id={fieldId("decimals")} type="number" min={0} max={6} step={1} placeholder="Auto" value={format.decimals ?? ""}
onChange={event => setAxis(axis, {decimals: event.target.value === "" ? null : Number(event.target.value)})}/>
<label className="sheet-chart-label" htmlFor={fieldId("format")}>Format</label>
<select id={fieldId("format")} value={format.format ?? "number"} onChange={event => setAxis(axis, {format: event.target.value as ChartAxisFormat["format"]})}>
{([["number", "Number"], ["currency", "Currency"], ["percent", "Percent"]] as const).map(([key, name]) => <option key={key} value={key}>{name}</option>)}
</select>
<label className="sheet-chart-check"><input type="checkbox" checked={format.thousands !== false}
onChange={event => setAxis(axis, {thousands: event.target.checked})}/>Thousands separator</label>
<label className="sheet-chart-check"><input type="checkbox" checked={value ? format.gridlines !== false : format.gridlines === true}
onChange={event => setAxis(axis, {gridlines: event.target.checked})}/>Gridlines</label>
<label className="sheet-chart-label" htmlFor={fieldId("angle")}>Label angle</label>
<select id={fieldId("angle")} value={format.labelAngle ?? 0} onChange={event => setAxis(axis, {labelAngle: Number(event.target.value) as ChartAxisFormat["labelAngle"]})}>
{[["0", "0 degrees"], ["45", "45 degrees"], ["90", "90 degrees"], ["-45", "Minus 45 degrees"], ["-90", "Minus 90 degrees"]].map(([key, name]) => <option key={key} value={key}>{name}</option>)}
</select>
{value ? <>
<label className="sheet-chart-label" htmlFor={fieldId("units")}>Display units</label>
<select id={fieldId("units")} value={presentation.displayUnits ?? "none"} onChange={event => setOption("displayUnits", event.target.value as SheetChartPresentation["displayUnits"])}>
{[["none", "None"], ["thousands", "Thousands"], ["millions", "Millions"], ["percent", "Percent"]].map(([key, name]) => <option key={key} value={key}>{name}</option>)}
</select>
</> : null}
</>;
};
const resetFormatting = () => {
const defaults=defaultChartPresentation();
setPresentation({...defaults,headers:presentation.headers,categoryLabels:presentation.categoryLabels,orientation:presentation.orientation,
series:configuredSeries.map(s=>({key:s.key,label:s.label,hidden:s.hidden})),ganttMode:presentation.ganttMode,title:presentation.title,xTitle:presentation.xTitle,yTitle:presentation.yTitle,categoryTitle:presentation.categoryTitle});
setBounds(Object.fromEntries(BOUND_KEYS.map(key => [key, ""])));
};
const settingsPanel = <div className="sheet-chart-settings">
{section==="Chart"?<><div className="sheet-chart-type-settings">{kindPicker}{subtypePicker}</div>{tab==="range" ? chartGallery : null}
<details className="sheet-chart-formatting" open={tab==="database" ? true : undefined}>
<summary>Formatting</summary>
<div className="sheet-chart-settings">
{kind==="gantt"?<>{select("Task values","ganttMode",[["duration","Start and duration"],["end","Start and end"]])}<p className="sheet-chart-caption">Select task names, then start and duration or end. Dates use durations in days.</p></>:null}
{select("Layout","layout",[["standard","Standard"],["compact","Compact"],["labels","Labels"]])}
{select("Colors","palette",[["categorical","Categorical"],["purple","Purple"],["blue","Blue"]])}
{select("Style","style",[["filled","Filled"],["outline","Outline"],["soft","Soft"]])}
{kind==="histogram"?<label className="sheet-chart-setting">Bins<input aria-label="Bins" type="number" min={1} max={50} value={presentation.bins??10} onChange={e=>setOption("bins",Math.max(1,Math.min(50,Number(e.target.value)||1)))}/></label>:null}
<button type="button" className="sheet-chart-quiet" onClick={resetFormatting}>Reset formatting</button>
</div>
</details>
</>:null}
{section==="Text"?<>{text("Chart title","title")}{text("X axis title","xTitle")}{text("Y axis title","yTitle")}{text("Category name","categoryTitle")}
{legendEntries>=2?toggle("Show legend","showLegend"):null}{toggle("Show axis titles","showAxisTitles")}{toggle("Show data labels","showDataLabels")}
{legendEntries>=2?select("Legend position","legendPosition",[["bottom","Bottom"],["top","Top"],["right","Right"]]):null}
{legendEntries>=2?select("Legend font","legendFont",[["small","Small"],["medium","Medium"],["large","Large"]]):null}
{select("Axis font","axisFont",[["small","Small"],["medium","Medium"],["large","Large"]])}
{legendEntries>=2?<p className="sheet-chart-caption">Charts with two or more series always keep their legend.</p>:null}
</>:null}
{section==="Axes"?<>{["pie","donut","funnel","treemap","polar"].includes(kind)?<p className="sheet-chart-caption">This chart type has no value axis.</p>:<>
{group("Value axis", axisFields("valueAxis"))}
{group("Category axis", axisFields("categoryAxis"))}
</>}</>:null}
{section==="Series"?<>{settings.length?settings.map((s,i)=><div className="sheet-chart-series-row" key={s.key}>
<label className="sheet-chart-check"><input type="checkbox" aria-label={`Show ${seriesName(s)}`} checked={!s.hidden} onChange={e=>updateSeries(s.key,{hidden:!e.target.checked})}/></label>
<input aria-label={`Series ${i+1} name`} value={seriesName(s)} onChange={e=>updateSeries(s.key,{label:e.target.value})}/>
<ChartSeriesColorPicker label={`Series ${i+1} color`} value={s.color} presentation={presentation}
slot={settings.slice(0,i).filter(setting => !setting.hidden).length}
// Integration widens SheetChartColor in types.ts; this assertion preserves the new stored value.
onChange={color => updateSeries(s.key,{color:color as SheetChartColor | undefined})}/>
<button type="button" className="sheet-chart-quiet" disabled={i===0} aria-label={`Move ${seriesName(s)} up`} onClick={()=>moveSeries(i,-1)}>Up</button>
<button type="button" className="sheet-chart-quiet" disabled={i===settings.length-1} aria-label={`Move ${seriesName(s)} down`} onClick={()=>moveSeries(i,1)}>Down</button>
</div>):<p className="sheet-chart-caption">Choose cells with numeric values to name and order series.</p>}</>:null}
{section==="Location"?<>
{workbook?<label className="sheet-chart-setting">Worksheet<select aria-label="Worksheet" value={destination} onChange={e=>setDestination(e.target.value)}>{workbook.sheets.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}<option value="__new__">New worksheet</option></select></label>:null}
{destination==="__new__"?<label className="sheet-chart-setting">Sheet name<input aria-label="Sheet name" value={newName} maxLength={80} onChange={e=>setNewName(e.target.value)}/></label>:null}
<label className="sheet-chart-setting">Anchor cell<input aria-label="Anchor cell" value={anchor} onChange={e=>setAnchor(e.target.value)}/></label>
<label className="sheet-chart-setting">Width<input aria-label="Width" type="number" min={320} max={2400} step={8} value={chartWidth} onChange={e=>setChartWidth(e.target.value)}/></label>
<label className="sheet-chart-setting">Height<input aria-label="Height" type="number" min={240} max={1600} step={8} value={chartHeight} onChange={e=>setChartHeight(e.target.value)}/></label>
<label className="sheet-chart-check"><input type="checkbox" aria-label="Lock aspect ratio" checked={presentation.lockAspect === true}
onChange={e=>setOption("lockAspect", e.target.checked)}/>Lock aspect ratio</label>
</>:null}
</div>;
const previewPane = (
<div
className="sheet-chart-live-preview"
id={`${titleId}-live-preview`}
role="tabpanel"
aria-label="Chart preview"
{...(section === "Chart" && tab === "range" && galleryKinds.includes(kind)
? { "aria-labelledby": `${titleId}-kind-${kind}` } : {})}
>
<h3 className="sheet-chart-live-heading">{CHART_KINDS.find(entry => entry.kind === kind)!.label}</h3>
<p className="sheet-chart-live-description">{previewNote}</p>
{previewMessage ? null : (
<div className="sheet-chart-live-drawing">
<DrawnChart {...previewModel} kind={kind} stacking={chartStacking} presentation={previewPresentation}
width={Number(chartWidth) || 640} height={Number(chartHeight) || 360}/>
</div>
)}
</div>
);
return (
<BodyPortal>
<div className="lp-dialog-scrim">
<div
ref={panelRef}
className="lp-dialog sheet-chart-dialog"
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
data-overlay-kind="sheet-chart"
>
<div className="lp-dialog-head">
<h2 className="lp-dialog-title" id={titleId}>
{editing ? "Chart settings" : "Insert a chart"}
</h2>
<button
type="button"
className="lp-dialog-x"
aria-label="Close the chart dialog"
onClick={onClose}
>
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
<path
d="M4 4l8 8M12 4l-8 8"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
/>
</svg>
</button>
</div>
{/* [W60-T16, R23] The one split: settings scroll on the left, the preview never hides on
the right. The two strips and the panel below are UNCHANGED and simply sit one level
deeper; the children keep their old indentation so the move stays readable as a diff. */}
<div className="sheet-chart-body">
<div className="sheet-chart-settings-column">
{section==="Data" && !editing ? (
<div className="sheet-chart-tabs" role="tablist" aria-label="What the chart reads">
{SOURCE_TABS.map((entry) => (
<button
key={entry.id}
type="button"
role="tab"
id={`${titleId}-tab-${entry.id}`}
className="sheet-chart-tab"
aria-selected={tab === entry.id}
aria-controls={`${titleId}-panel`}
onClick={() => setTab(entry.id)}
>
{entry.label}
</button>
))}
</div>
) : null}
<div className="sheet-chart-section-tabs" role="tablist" aria-label="Chart settings sections">
{["Data","Chart","Text","Series","Axes","Location"].map(name=><button key={name} id={`${titleId}-section-${name}`} type="button" role="tab" aria-selected={section===name} aria-controls={`${titleId}-panel`} className="sheet-chart-quiet" onClick={()=>{
setSection(name);
if (name === "Chart" && tab === "range" && galleryTab === "recommended" && recommended.length) setKind(recommended[0]);
}}>{name}</button>)}
</div>
<div
className="sheet-chart-panel"
id={`${titleId}-panel`}
role="tabpanel"
aria-labelledby={section === "Data" && !editing ? `${titleId}-tab-${tab}` : `${titleId}-section-${section}`}
>
{section!=="Data" ? settingsPanel : tab === "range" ? (
<>
{workbook ? group("Source", <>
<label className="sheet-chart-label" htmlFor={`${titleId}-sheet`}>Source worksheet</label>
<select id={`${titleId}-sheet`} className="sheet-chart-select" value={sourceSheetId}
onChange={e=>{setSourceSheetId(e.target.value);setOption("series",[]);}}>
{workbook.sheets.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</>) : null}
{group("Range", rangeFieldRows)}
{group("Headers and categories", <>
<label className="sheet-chart-label" htmlFor={`${titleId}-headers`}>Headings</label>
<select id={`${titleId}-headers`} className="sheet-chart-select" value={presentation.headers ?? ""}
onChange={e=>setOption("headers",e.target.value as SheetChartPresentation["headers"])}>
<option value="auto">Automatic</option>
<option value="firstRow">First row</option>
<option value="none">None</option>
</select>
<label className="sheet-chart-label" htmlFor={`${titleId}-categories`}>Category labels</label>
<select id={`${titleId}-categories`} className="sheet-chart-select" value={presentation.categoryLabels ?? ""}
onChange={e=>setOption("categoryLabels",e.target.value as SheetChartPresentation["categoryLabels"])}>
<option value="auto">Automatic</option>
<option value="firstColumn">First column</option>
<option value="none">None</option>
</select>
</>)}
{group("Series orientation", <>
<label className="sheet-chart-label" htmlFor={`${titleId}-orientation`}>Series in</label>
<select id={`${titleId}-orientation`} className="sheet-chart-select" value={presentation.orientation ?? ""}
onChange={e=>setOption("orientation",e.target.value as SheetChartPresentation["orientation"])}>
<option value="columns">Columns</option>
<option value="rows">Rows</option>
</select>
<span className="sheet-chart-label" aria-hidden="true" />
<button type="button" className="sheet-chart-switch"
onClick={()=>setOption("orientation",presentation.orientation==="rows"?"columns":"rows")}>
Switch row and column
</button>
</>)}
</>
) : (
<>
{group("Source", <>
<label className="sheet-chart-label" htmlFor={`${titleId}-db`}>Database</label>
{loading ? (
<div className="sheet-chart-skeleton" />
) : databases.length === 0 ? (
<p className="sheet-chart-caption">No databases are available to read.</p>
) : (
<select
id={`${titleId}-db`}
// `sheet-chart-db` carries no rule: it is the name a screenshot waits on,
// so a shot of this tab cannot be taken while the list is still in flight.
className="sheet-chart-select sheet-chart-db"
value={database}
onChange={(event) => setDatabase(event.target.value)}
>
{databases.map((db) => (
<option key={db.key} value={db.key}>{db.label}</option>
))}
</select>
)}
<label className="sheet-chart-label" htmlFor={`${titleId}-fn`}>Total</label>
<select
id={`${titleId}-fn`}
className="sheet-chart-select"
value={fn}
onChange={(event) => setFn(event.target.value)}
>
{AGGREGATES.map((agg) => (
<option key={agg.fn} value={agg.fn}>{agg.label}</option>
))}
</select>
{wantsField && (
<>
<label className="sheet-chart-label" htmlFor={`${titleId}-field`}>
Column
</label>
<input
id={`${titleId}-field`}
className="sheet-chart-text"
type="text"
value={field}
placeholder="amount_total"
onChange={(event) => setField(event.target.value)}
/>
</>
)}
<label className="sheet-chart-label" htmlFor={`${titleId}-kind`}>Chart type</label>
<select id={`${titleId}-kind`} className="sheet-chart-select" value={kind}
onChange={event=>setKind(event.target.value as SheetChartSpec["kind"])}>
{CHART_KINDS.map(entry=><option key={entry.kind} value={entry.kind}>{entry.label}</option>)}
</select>
{subtypePicker ? <div className="sheet-chart-data-subtype">{subtypePicker}</div> : null}
</>, loading)}
{group("Range", <>
<label className="sheet-chart-label" htmlFor={`${titleId}-unit`}>Period</label>
<select
id={`${titleId}-unit`}
className="sheet-chart-select"
value={unit}
onChange={(event) => setUnit(event.target.value as PeriodUnit)}
>
{PERIOD_UNITS.map((p) => (
<option key={p.unit} value={p.unit}>{p.label}</option>
))}
</select>
<label className="sheet-chart-label" htmlFor={`${titleId}-count`}>
How many
</label>
<input
id={`${titleId}-count`}
className="sheet-chart-number"
type="number"
min={MIN_PERIODS}
max={MAX_PERIODS}
value={periods}
onChange={(event) => setPeriods(event.target.value)}
/>
</>)}
{/* β SAID AT THE POINT OF CREATION, because a person who expected only a picture
must not be surprised to find a block of numbers. One sentence, not a
paragraph (DESIGN.md section 4: never over-explain). */}
<p className="sheet-chart-note">
The periods are written into the sheet as cells, and the chart reads them.
</p>
</>
)}
{boundsError?<p role="alert" className="sheet-chart-caption">{boundsError}</p>:null}
{!validGeometry?<p role="alert" className="sheet-chart-caption">Choose one anchor cell, width 320 to 2400 and height 240 to 1600.</p>:null}
{newNameError?<p role="alert" className="sheet-chart-caption">Choose a unique, valid sheet name.</p>:null}
</div>{/* .sheet-chart-panel */}
</div>{/* .sheet-chart-settings-column */}
{previewPane}
</div>{/* .sheet-chart-body */}
<div className="lp-dialog-actions">
{editing && onDelete ? (
<button
type="button"
className="lp-dialog-btn sheet-chart-delete"
onClick={() => {
onDelete();
onClose();
}}
>
Delete chart
</button>
) : null}
<button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" onClick={onClose}>
Cancel
</button>
<button
type="button"
className="lp-dialog-btn lp-dialog-btn-primary"
disabled={!ready}
onClick={create}
>
{editing ? "Save chart" : "OK"}
</button>
</div>
</div>
</div>
</BodyPortal>
);
}
// sheet/ChartDialog.tsx β the Insert tab's CHART dialog (wave 54, W54-T11, ruling R5).
//
// ββ R5, VERBATIM: "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a
// database source is a second tab in the same dialog. Ship both." So this is ONE dialog with two
// source tabs, and the cell range tab is the one that opens.
//
// ββ HOW THE DATABASE TAB SURVIVES `SheetChart.tsx`'s RULING R9, WHICH SAYS THE OPPOSITE THING
// AND IS STILL TRUE. That file's header reads: "A CHART IS A CAPABILITY, NOT A VIEW TYPE. It
// occupies a rectangle of cells and READS those cells; it has no binding, no database and no query
// of its own. If this file ever calls the sheet preview door it has become a second way to fetch a
// number, and the sheet would then have two answers for one cell."
//
// The two reconcile in exactly one way, and it is the design below: THE DATABASE TAB DOES NOT GIVE
// THE CHART A QUERY. It writes BOUND CELLS into the sheet and then anchors an ordinary cell range
// chart over them. The chart still reads cells. The numbers still come from the one existing
// binding path, evaluated server side for a bound cell exactly as a hand bound cell is. Nothing
// here fetches a value, and `SheetChartSpec` gains no field: it is the same three keys it has
// carried since W49-T08.
//
// β WHAT THE DATABASE TAB WRITES, in ONE call through the door, so it is ONE history step and ONE
// save: a header row of period labels as typed literals, and beneath it one bound cell per period,
// every one carrying the same database, aggregate and scope and its OWN period. Then the chart,
// then a refresh, because a stale cell holds no value until the workbook refreshes.
//
// β THE BINDING VOCABULARY IS COPIED, NOT INVENTED. `BindingEditor.tsx` is the declaration of it
// and the server fixture in `aios-web/api/verify_sheet.py` is the proof; this file reuses the same
// names (`database`, `aggregate.fn`, `aggregate.field`, `scope.filter`, `period.unit`,
// `period.start`, `period.locked`) and imports nothing from that panel, because W54-T11 may not
// reach into lane E's files. A second spelling of the vocabulary would be a second dialect.
//
// β ESCAPE COMES FROM THE KIT AND FROM NOWHERE ELSE. `useOverlayLayer` registers this surface on
// the shared stack and calls `ui/useEscapeClose.ts` itself, which is why there is no local keydown
// listener anywhere in this file. DESIGN.md section 4: a local keydown listener is the defect, not
// the shortcut.
//
// β MOUNTED CONDITIONALLY BY ITS CALLER, never rendered behind an `open` prop. `useOverlayLayer`
// has no active flag: it claims Escape the moment it runs, and the stack hands the key to the LAST
// entry pushed. Mounting late is what puts this dialog above anything already open, and popping it
// on close hands Escape straight back.
//
// β DESIGN CONTRACT (DESIGN.md 2 through 5): centred modal on the base kit's `.lp-dialog` surface,
// tokens only, sentence case, inline SVG in the house vocabulary and never an emoji, a skeleton
// rather than a spinner while the database list is in flight, press feedback that does not change
// layout, reduced motion honoured, and no em dash or en dash in any string that reaches a screen.
import { createContext, Fragment, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useCellRefHighlight } from "./refHighlight";
import { AnchoredOverlay, BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
// The document's own addresser, in SHEET coordinates. A second spelling of A1 in this file would
// be a second answer to a question the document already answers.
import { addressOf } from "./sheetState";
import { parseRange } from "./rules";
import type { Cell, SheetChartRange, SheetChartSpec, SheetTab, SheetChartPresentation, SheetChartColor, ChartAxisFormat } from "./types";
import { SHEET_CHART_STACKING_KINDS, withChartStacking } from "./types";
import { CATEGORICAL, chartPresentationDefaults as defaultChartPresentation, colorStyle, chartDataForRange, chartLegendEntries, DrawnChart } from "./SheetChart";
import type { ChartSeriesHue, SheetChartData } from "./SheetChart";
import "../styles/wave58/sheet.css";
import "../styles/wave59/chart-dialog.css";
export function ChartSeriesColorPicker({ slot, label, presentation, value, onChange }: {
slot: number; label: string; presentation: SheetChartPresentation; value?: ChartSeriesHue;
onChange: (color: ChartSeriesHue | undefined) => void;
}) {
const opener = useRef<HTMLButtonElement>(null);
const listId = useId();
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
// A saved neutral override stays editable; new charts offer Theme and the eight hues.
const choices: (ChartSeriesHue | undefined)[] = [undefined, ...CATEGORICAL, ...(value === "muted" ? [value] : [])];
const name = (color: ChartSeriesHue | undefined) => color ? color[0].toUpperCase()+color.slice(1) : "Theme";
const dot = (color: ChartSeriesHue | undefined) => <span className="sheet-chart-color-dot" aria-hidden="true" style={colorStyle(slot,presentation,color)}/>;
const show = () => { setActive(Math.max(0,choices.indexOf(value))); setOpen(true); };
const close = () => { setOpen(false); opener.current?.focus(); };
return <>
<button ref={opener} type="button" className="sheet-chart-color-trigger" aria-label={label}
aria-haspopup="listbox" aria-expanded={open} aria-controls={open ? listId : undefined}
onClick={() => open ? close() : show()}
onKeyDown={event => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); show(); }
}}>{dot(value)}{name(value)}</button>
{open ? <AnchoredOverlay anchor={opener.current} className="sheet-chart-color-list" role="listbox"
id={listId} ariaLabel={label} onDismiss={close} restoreFocus initialFocus='[tabindex="0"]'
onKeyDown={event => {
const rows = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="option"]'));
const current = rows.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "ArrowDown" ? (current+1)%rows.length
: event.key === "ArrowUp" ? (current-1+rows.length)%rows.length
: event.key === "Home" ? 0 : event.key === "End" ? rows.length-1 : -1;
if (next >= 0) { event.preventDefault(); setActive(next); rows[next]?.focus(); }
if (event.key === "Tab") close();
}}>
{choices.map((color,index) => <button key={color ?? "theme"} type="button" role="option"
className="sheet-chart-color-option" aria-selected={value === color} tabIndex={index === active ? 0 : -1}
onFocus={() => setActive(index)} onClick={() => { onChange(color); close(); }}>
{dot(color)}{name(color)}
</button>)}
</AnchoredOverlay> : null}
</>;
}