// Sheet charts read cells only. Source, presentation and destination are persisted independently. import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import type { ReactNode, CSSProperties, MouseEvent } from "react"; import type { WireField } from "../viz/seriesData"; import type { Row } from "../viz/types"; import type { CellMap, SheetChartRange, SheetChartSpec, SheetChartPresentation, SheetChartColor, ChartAxisFormat } from "./types"; import { defaultChartPresentation, SHEET_CHART_STACKING_KINDS } from "./types"; import { addressOf } from "./sheetState"; import "../styles/wave58/sheet.css"; import "../styles/wave59/chart-dialog.css"; export interface SheetChartProps { range: SheetChartRange; source?: SheetChartSpec["source"]; presentation?: SheetChartPresentation; cells: CellMap; kind?: SheetChartSpec["kind"]; stacking?: SheetChartSpec["stacking"]; selected?: boolean; width: number; height: number; /** R3: all frozen-pane projections share one gesture preview. */ preview?: ChartPreview; onPreviewChange?: (preview: ChartPreview) => void; moveSteps?: { left: number; right: number; up: number; down: number }; onMove?: (dx: number, dy: number) => ChartAnchorDelta; /** `ratio` is present ONLY when the gesture must keep the shape (Shift, or Lock aspect ratio). * It has to travel with the delta because the anchor snaps to a cell boundary AFTER the delta is * computed, and only the receiver knows how much the size had to absorb. */ onResize?: (delta: ChartPreview, ratio?: number) => ChartAnchorDelta; onEdit?: () => void; onDelete?: () => void; /** Present only on the sheet. Absent in exports, thumbnails and the editor preview, which render * the same component through `renderToStaticMarkup` where an input would be dead markup. */ onRetitle?: (key: "title" | "xTitle" | "yTitle", value: string) => void; } export interface ChartAnchorDelta { dx: number; dy: number } const textAt = (cells: CellMap, col: number, row: number): string => { const cell = cells[addressOf(col, row)]; if (!cell || cell.state === "refused") return ""; return cell.display ?? (cell.value == null ? (cell.text ?? "") : String(cell.value)); }; const numberAt = (cells: CellMap, col: number, row: number): number | null => { const cell = cells[addressOf(col, row)]; if (!cell || cell.state === "refused" || cell.state === "stale") return null; const raw = cell.value ?? cell.text ?? cell.display; if (typeof raw === "number") return Number.isFinite(raw) ? raw : null; if (typeof raw !== "string") return null; let text = raw.trim(); if (!text) return null; const negative = text.startsWith("(") && text.endsWith(")"); if (negative) text = text.slice(1, -1).trim(); const percent = text.endsWith("%"); if (percent) text = text.slice(0, -1).trim(); text = text.replace(/[,\s]/g, "").replace(/^([$€£])/, ""); if (!/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) return null; const value = Number(text); return Number.isFinite(value) ? (negative ? -value : value) / (percent ? 100 : 1) : null; }; interface ChartCellValue { text: string; number: number | null; col: number; row: number } export interface SheetChartData { fields: WireField[]; rows: Row[]; series: { y: string; label: string; color?: SheetChartColor; sourceKey?: string }[]; error?: string; dateAxis?: boolean; } /** Date-formatted Sheet numbers use epoch milliseconds; a timeline uses Excel days. */ const timelineDate = (cell: CellMap[string] | undefined): number | null => { if (!cell || cell.state === "refused" || cell.state === "stale") return null; const raw = cell.value ?? cell.text; const ms = typeof raw === "number" && cell.style?.format?.kind === "date" ? raw : typeof raw === "string" && /^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(raw) ? Date.parse(raw) : NaN; return Number.isFinite(ms) ? ms / 86400000 + 25569 : null; }; /** Fixed-role families refuse missing or impossible inputs instead of drawing a different chart. */ export function chartShapeError(kind: SheetChartSpec["kind"], data: SheetChartData, p: SheetChartPresentation = {}): string | undefined { if (kind !== "stock" && kind !== "gantt") return undefined; const count = data.series.length; if (kind === "stock" && count !== 3 && count !== 4) return "Stock needs High, Low, Close series, with optional Open first."; if (kind === "gantt" && count !== 2) return "Gantt needs a start series and a duration or end series."; if (!data.rows.length) return "Choose at least one complete data row."; for (const row of data.rows) { const values = data.series.map(s => readNumber(row, s.y)); if (values.some(v => v === null)) return "Every chart row needs all of its numeric values."; const nums = values as number[]; if (kind === "stock") { const [high, low, close] = nums.slice(count === 4 ? 1 : 0); const open = count === 4 ? nums[0] : close; if (low > high || Math.min(open, close) < low || Math.max(open, close) > high) return "Stock values must keep Open and Close between Low and High."; } else if (p.ganttMode === "end" ? nums[1] < nums[0] : nums[1] < 0) { return "A task must end on or after its start and have a nonnegative duration."; } else if (!Number.isFinite(p.ganttMode === "end" ? nums[1] : nums[0] + nums[1])) { return "Task dates must remain within the numeric range."; } } return undefined; } /** Disjoint columns join by row; disjoint rows join by column. Ambiguous rectangles are refused. */ export function chartDataForRange( cells: CellMap, range: SheetChartRange, presentation: SheetChartPresentation = {}, ranges: SheetChartRange[] = [range], kind: SheetChartSpec["kind"] = "column", ): SheetChartData { const empty = (error?: string): SheetChartData => ({ fields: [], rows: [], series: [], error }); if (!ranges.length) return empty("Choose a data range."); if (ranges.reduce((n, r) => n + (Math.abs(r.col1-r.col0)+1)*(Math.abs(r.row1-r.row0)+1), 0) > 50000) return empty("Choose at most 50,000 source cells."); const blocks = ranges.map(r => { const block: ChartCellValue[][] = []; for (let row = Math.min(r.row0,r.row1); row <= Math.max(r.row0,r.row1); row++) { const line: ChartCellValue[] = []; for (let col = Math.min(r.col0,r.col1); col <= Math.max(r.col0,r.col1); col++) line.push({ col, row, text: textAt(cells,col,row), number: (kind === "gantt" ? timelineDate(cells[addressOf(col,row)]) : null) ?? numberAt(cells,col,row) }); block.push(line); } return block; }); let matrix = blocks[0]; if (blocks.length > 1) { const sameRows = ranges.every(r => Math.min(r.row0,r.row1) === Math.min(ranges[0].row0,ranges[0].row1) && Math.max(r.row0,r.row1) === Math.max(ranges[0].row0,ranges[0].row1)); const sameCols = ranges.every(r => Math.min(r.col0,r.col1) === Math.min(ranges[0].col0,ranges[0].col1) && Math.max(r.col0,r.col1) === Math.max(ranges[0].col0,ranges[0].col1)); if (sameRows) matrix = matrix.map((_, i) => blocks.flatMap(b => b[i])); else if (sameCols) matrix = blocks.flat(); else return empty("Separate ranges must share the same rows or columns."); const addresses = matrix.flat().map(v => addressOf(v.col,v.row)); if (new Set(addresses).size !== addresses.length) return empty("Source ranges must not overlap."); } if (presentation.orientation === "rows") matrix = matrix[0].map((_, c) => matrix.map(r => r[c])); if (!matrix.length || !matrix[0].length) return empty(); // A lone row is a numeric run, retaining the legacy one-row selection behavior. if (matrix.length === 1 && !["sunburst", "boxWhisker"].includes(kind)) matrix = matrix[0].map(v => [v]); // [W59-T06] Labels above one numeric run become categories; blanks retain missing values. const headerRowCategories = !["stock", "gantt", "scatter", "bubble", "sunburst", "boxWhisker"].includes(kind) && (presentation.headers ?? "auto") !== "none" && (presentation.categoryLabels ?? "auto") === "auto" && (presentation.orientation ?? "columns") === "columns" && matrix.length === 2 && matrix[0].length > 1 && matrix[0].every(v => v.text.trim() && v.number === null) && matrix[1].some(v => v.number !== null) && matrix[1].every(v => v.number !== null || !v.text.trim()); if (headerRowCategories) matrix = matrix[0].map((_, c) => matrix.map(r => r[c])); const first = matrix[0]; const numericHeaderCols = first.map((_, c) => c).filter(c => matrix.slice(1).some(r => r[c].number !== null)); // [W59-T06] Auto headers have no numbers in value columns; a rotated header is already categories. const header = !headerRowCategories && (presentation.headers === "firstRow" || (presentation.headers !== "none" && first.some(v => v.text.trim() && v.number === null) && numericHeaderCols.length > 0 && numericHeaderCols.every(c => first[c].number === null))); const body = matrix.slice(header ? 1 : 0); // W61-T07: after the optional header and orientation, Sunburst takes exactly three // columns: parent text, child text, numeric value. Both levels are derived from cells, // never stored on the chart spec. Trailing blank rows are harmless; partial rows refuse. if (kind === "sunburst") { while (body.length && body[body.length-1].every(v => !v.text.trim() && v.number === null)) body.pop(); if (first.length !== 3 || !body.length || body.some(line => line[0].number !== null || !line[0].text.trim() || line[1].number !== null || !line[1].text.trim() || line[2].number === null)) return empty("Sunburst needs two text category columns followed by one numeric value column."); } if (!body.length) return empty(); const numericCols = first.map((_, c) => c).filter(c => body.some(r => r[c].number !== null)); const xy = kind === "scatter" || kind === "bubble"; const categoryCol = presentation.categoryLabels === "firstColumn" ? 0 : presentation.categoryLabels === "none" ? null : (kind === "stock" && first.length >= 4) || (kind === "gantt" && first.length >= 3) ? 0 : xy && numericCols.length >= 2 ? numericCols[0] : first.length > 1 && !numericCols.includes(0) ? 0 : null; // Box and whisker takes one sample per numeric column (or row after Switch row/column), // with an optional leading category column. Blanks are missing samples, never zeros; // text in a value column refuses. Keep every series separate: folding into Other would // invent a different distribution. The renderer requires five values in each visible series. const valueCols = (kind === "boxWhisker" ? first.map((_, c) => c) : numericCols).filter(c => c !== categoryCol); if (kind === "boxWhisker" && body.some(line => valueCols.some(c => line[c].number === null && line[c].text.trim()))) return empty("Box and whisker needs numeric value columns; blanks are allowed."); if (!valueCols.length) return empty(["stock", "gantt"].includes(kind) ? "Choose numeric chart values." : undefined); let series = valueCols.map(c => ({ y: `value${c}`, sourceKey: presentation.orientation === "rows" || headerRowCategories ? `row:${first[c].row+1}` : `column:${addressOf(first[c].col,0).replace(/[0-9]+$/, "")}`, label: header ? first[c].text || addressOf(first[c].col,first[c].row) : addressOf(first[c].col,first[c].row).replace(/[0-9]+$/, ""), color: undefined as SheetChartColor | undefined, })); const configured = presentation.series ?? []; const ordered = configured.flatMap(setting => { const found = series.find(s => s.sourceKey === setting.key || s.y === setting.key); return found && !setting.hidden ? [{ ...found, label: setting.label || found.label, color: setting.color }] : []; }); series = [...ordered, ...series.filter(s => !configured.some(c => c.key === s.sourceKey || c.key === s.y))]; const rawSeries = series; const folded = kind === "boxWhisker" ? [] : rawSeries.slice(8); series = kind === "boxWhisker" ? rawSeries : rawSeries.slice(0,8); if (folded.length) series.push({ y: "other", sourceKey: "other", label: "Other", color: undefined }); const lastFilled = body.reduce((last, line, i) => line.some(value => value.text.trim() !== "" || value.number !== null) ? i : last, -1); const rows = body.slice(0, lastFilled + 1).map((line, i) => { const result: Record = { pid: i+1, category: categoryCol === null ? addressOf(line[0].col,line[0].row) : xy ? line[categoryCol].number : line[categoryCol].text || addressOf(line[categoryCol].col,line[categoryCol].row) }; valueCols.forEach(c => { result[`value${c}`] = line[c].number; }); if (kind === "sunburst") { result.category = line[0].text.trim(); result.child = line[1].text.trim(); } if (folded.length) result.other = folded.reduce((sum,s) => sum + Number(result[s.y] ?? 0),0); return result as unknown as Row; }); const fields: WireField[] = [{ key: "category", label: presentation.categoryTitle || (categoryCol !== null && header ? first[categoryCol].text : "Cell"), type: xy ? "int" : "text" }, ...(kind === "sunburst" ? [{ key: "child", label: header ? first[1].text : "Child", type: "text" as const }] : []), ...series.map(s => ({ key: s.y, label: s.label, type: "int" as const }))]; if (xy && categoryCol === null) return empty("Choose a numeric X column and a numeric Y column."); const dateAxis = kind === "gantt" && body.some(line => valueCols.some(c => timelineDate(cells[addressOf(line[c].col,line[c].row)]) !== null)); const result = { fields, rows, series, ...(dateAxis ? { dateAxis: true } : {}) }; return { ...result, error: chartShapeError(kind, result, presentation) }; } const readNumber = (row: Row, key: string): number | null => { const value = (row as unknown as Record)[key]; return typeof value === "number" && Number.isFinite(value) ? value : null; }; const readText = (row: Row, key: string): string => String((row as unknown as Record)[key] ?? ""); /** Percent display units and axis format scale once; other units compose with the format. */ const axisText = (v: number, units: SheetChartPresentation["displayUnits"] = "none", axis: ChartAxisFormat = {}): string => { const percent = axis.format === "percent" || units === "percent"; const scale = percent ? 100 : units === "thousands" ? 1e-3 : units === "millions" ? 1e-6 : 1; const suffix = percent ? "%" : units === "thousands" ? "k" : units === "millions" ? "M" : ""; const n = v * scale; const decimals = typeof axis.decimals === "number" ? Math.max(0, Math.min(6, Math.round(axis.decimals))) : null; const currency = axis.format === "currency"; const options: Intl.NumberFormatOptions = { useGrouping: axis.thousands !== false, ...(currency ? { style: "currency", currency: "USD" } : {}), // ⛔ CURRENCY WITH AUTO DECIMALS IS PINNED TO TWO, and it is pinned here because Excel cannot // say "up to two, trimmed": a format code either always shows the cents or never does. Two on // both sides is the only setting where the tick on the sheet and the tick in the exported // workbook read the same. An explicit decimal count still wins. ...(decimals === null ? (currency ? { minimumFractionDigits: 2, maximumFractionDigits: 2 } : { maximumFractionDigits: 2, notation: Math.abs(n) >= 10000 ? "compact" as const : "standard" as const }) : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }), }; return new Intl.NumberFormat("en", options).format(n) + suffix; }; export function histogramBins(values: number[], count: number) { if (!values.length) return []; const low = Math.min(...values), high = Math.max(...values); const n = low === high ? 1 : Math.max(1, Math.min(50, Math.round(count) || 10)); const step = low === high ? 1 : (high-low)/n; const bins = Array.from({length:n}, (_, i) => ({ low:low+i*step, high:low+(i+1)*step, count:0 })); values.forEach(v => { bins[Math.min(n-1,Math.max(0,Math.floor((v-low)/step)))].count++; }); return bins; } /** W61-T07: linear interpolation at (n - 1) * p, Excel QUARTILE.INC. * Whiskers end at observed samples within 1.5 * IQR, not at the fences themselves. */ export function boxWhiskerStats(values: number[]) { const sorted = values.filter(Number.isFinite).sort((a,b) => a-b); if (sorted.length < 5) return null; const quartile = (p: number) => { const index = (sorted.length - 1) * p, lo = Math.floor(index), fraction = index-lo; return sorted[lo] * (1-fraction) + sorted[Math.min(lo+1,sorted.length-1)] * fraction; }; const q1 = quartile(.25), median = quartile(.5), q3 = quartile(.75), iqr = q3-q1; const inside = sorted.filter(value => value >= q1-1.5*iqr && value <= q3+1.5*iqr); return { q1, median, q3, low: inside[0], high: inside[inside.length-1], outliers: sorted.filter(value => value < q1-1.5*iqr || value > q3+1.5*iqr) }; } export function chartYDomain(values: number[], p: SheetChartPresentation): [number,number] { let low = p.yMin ?? Math.min(0,...values), high = p.yMax ?? Math.max(0,...values); if (low >= high) { if (p.yMin !== undefined && p.yMax === undefined) high = low + Math.max(1, Math.abs(low)*.1); else if (p.yMax !== undefined && p.yMin === undefined) low = high - Math.max(1, Math.abs(high)*.1); else if (low === high) high = low+1; } return [low,high]; } const PURPLE = ["purple"] as const; // ⭐ THE ORDER IS MEASURED, NOT CHOSEN. The dataviz validator scores ADJACENT pairs, and // pink beside red answered deltaE 8.5 under normal vision, below the 15 floor. This order is // the best of all 40,320 permutations of the same eight hexes: deltaE 15.4 normal and 9.7 // deuteranopia, both PASS, with no hue re-stepped. Re-ordering it needs a re-run, not a view. export const CATEGORICAL = ["purple","green","blue","yellow","pink","orange","teal","red"] as const; export type ChartSeriesHue = SheetChartColor | typeof CATEGORICAL[number]; // Keep explicit saved Purple presentations intact while the shared types seam is integrated. export const chartPresentationDefaults = (): SheetChartPresentation => ({...defaultChartPresentation(), palette: "categorical"}); export const colorStyle = (slot: number, p: SheetChartPresentation, color?: ChartSeriesHue): CSSProperties => { const hue = color || (p.palette === "blue" ? "blue" : p.palette === "purple" ? PURPLE[slot % PURPLE.length] : CATEGORICAL[slot % CATEGORICAL.length]); return { "--chart-color": `var(--lp-${hue}${hue === "muted" ? "" : "-deep"})`, "--chart-fill": `var(--lp-${hue}${p.style === "soft" && hue !== "muted" ? "-tint" : ""})`, "--chart-opacity": !p.palette || p.palette === "categorical" || color ? 1 : Math.max(.42,1-slot*.07), } as CSSProperties; }; const short = (value: string, max=20) => value.length > max ? `${value.slice(0,Math.max(1,max-1))}…` : value; const slicePath = (cx:number,cy:number,r:number,inner:number,from:number,sweep:number):string => { const to=from+Math.min(sweep,Math.PI*2-1e-7), big=sweep>Math.PI?1:0; const pt=(radius:number,angle:number)=>`${cx+radius*Math.cos(angle)} ${cy+radius*Math.sin(angle)}`; if (!inner) return `M ${cx} ${cy} L ${pt(r,from)} A ${r} ${r} 0 ${big} 1 ${pt(r,to)} Z`; return `M ${pt(r,from)} A ${r} ${r} 0 ${big} 1 ${pt(r,to)} L ${pt(inner,to)} A ${inner} ${inner} 0 ${big} 0 ${pt(inner,from)} Z`; }; /** How many entries a chart's legend carries: categories for the round kinds, one for the kinds * whose legend is a single curated entry, series otherwise. One entry is not a legend. */ export const chartLegendEntries = (kind: SheetChartSpec["kind"], seriesCount: number, rowCount: number): number => kind==="pie"||kind==="donut"||kind==="polar"||kind==="treemap"||kind==="sunburst" ? rowCount : kind==="gantt"||kind==="bubble" ? 1 : seriesCount; export function DrawnChart({ kind, stacking, rows, series, error: dataError, dateAxis, presentation = {}, width = 640, height = 320, onRetitle }: SheetChartData & { kind: SheetChartSpec["kind"]; stacking?: SheetChartSpec["stacking"]; presentation?: SheetChartPresentation; width?:number; height?:number; /** Present only on the sheet. Absent in exports, thumbnails and the editor preview, which render * the same component through `renderToStaticMarkup` where an input would be dead markup. */ onRetitle?: (key: "title" | "xTitle" | "yTitle", value: string) => void; }) { const id=useId().replace(/:/g,""); const drawingRef = useRef(null); const [renaming, setRenaming] = useState<{ key: "title" | "xTitle" | "yTitle"; value: string; left: number; top: number; width: number; height: number } | null>(null); /** Measure, do not convert. The axis titles live in the SVG's own viewBox units, so hand written * viewBox-to-pixel maths breaks when the chart is resized. Both rects below are real screen * pixels and the browser has already applied every transform. */ const beginRename = (key: "title" | "xTitle" | "yTitle", value: string) => (event: { currentTarget: Element; stopPropagation: () => void; preventDefault: () => void }) => { if (!onRetitle) return; event.stopPropagation(); event.preventDefault(); const host = drawingRef.current?.getBoundingClientRect(); const box = event.currentTarget.getBoundingClientRect(); if (!host) return; setRenaming({ key, value, left: box.left - host.left, top: box.top - host.top, width: Math.max(96, box.width), height: Math.max(20, box.height) }); }; const p={...chartPresentationDefaults(),...presentation}; const W=Math.max(240,width-24), H=Math.max(120,height-24-(p.title?32:0)-((chartLegendEntries(kind,series.length,rows.length)>=2)?44:0)); const direct = series.length>=2 && series.length<=4 && ["bar","column","line","area","combo"].includes(kind); const L=p.layout==="compact"?48:72, R=kind==="gantt"&&p.showDataLabels?96:20, T=16+(direct?series.length*18:0), B=(p.showAxisTitles&&(p.xTitle||p.categoryTitle)?52:36)+(p.layout==="labels"?16:0); const right=W-R, bottom=H-B, pw=right-L, ph=bottom-T; const names=rows.map(r=>readText(r,"category")); const valueAxis = p.valueAxis ?? {}, categoryAxis = p.categoryAxis ?? {}; const stacked = SHEET_CHART_STACKING_KINDS.includes(kind) && (stacking === "stacked" || stacking === "percent"); const percentStack = stacked && stacking === "percent"; const fmt=(n:number)=>percentStack ? axisText(n,"percent",{...valueAxis,format:"percent"}) : axisText(n,p.displayUnits,valueAxis); const catFmt=(n:number)=>axisText(n,p.displayUnits,categoryAxis); const nodes: ReactNode[]=[]; let legend: (SheetChartData["series"][number] & { slot?: number })[]=series.map(s=>({...s})); let error=""; const one=series[0]; const vals=rows.map(r=>readNumber(r,one?.y??"")); const valid=vals.filter((v):v is number=>v!==null); const all=series.flatMap(s=>rows.map(r=>readNumber(r,s.y)).filter((v):v is number=>v!==null)); const stacks = stacked ? rows.map(row => { const values = series.map(s => readNumber(row,s.y)); const total = values.reduce((sum,v) => sum+(v??0),0); // A zero-total category in percent mode draws nothing, never NaN geometry. Mixed signs // use the sum of magnitudes so each share retains its sign and absolute shares sum to 100%. const divisor = percentStack ? values.reduce((sum,v) => sum+Math.abs(v??0),0) : 1; let positive = 0, negative = 0; return values.map(raw => { if (raw === null || (percentStack && total === 0)) return null; const value = raw/divisor; const from = value < 0 ? negative : positive; const to = from+value; if (value < 0) negative = to; else positive = to; return { from, to, value }; }); }) : null; const domainValues = stacks ? stacks.flatMap(row => row.flatMap(s => s ? [s.from,s.to] : [])) : all; const [low,high]=chartYDomain(percentStack ? [domainValues.some(v=>v<0)?-1:0,domainValues.some(v=>v>0)||!domainValues.some(v=>v<0)?1:0] : domainValues,p); const inValueBounds=(v:number)=>v>=low&&v<=high; const y=(v:number)=>bottom-(v-low)/(high-low)*ph; const x=(i:number)=>L+(i+.5)*pw/Math.max(1,rows.length); const clamp=(v:number,a:number,b:number)=>Math.max(a,Math.min(b,v)); const mark=(slot:number,color?:SheetChartColor)=>({className:`sheet-chart-mark style-${p.style}`,style:colorStyle(slot,p,color)}); const title=(label:string,value:number)=>{`${label}: ${fmt(value)}`}; const label=(key:string,text:string,px:number,py:number,anchor:"start"|"middle"|"end"="middle",role?:string,onPick?: (event: MouseEvent) => void,angle?:number)=> { const shown=short(text,Math.min(24,Math.floor((W-8)/10))), span=shown.length*(p.axisFont==="large"?10:8); const low=anchor==="start"?4:anchor==="middle"?4+span/2:4+span; const high=anchor==="end"?W-4:anchor==="middle"?W-4-span/2:W-4-span; const labelX=clamp(px,low,high), labelY=clamp(py,16,H-6); return {shown}{text}; }; const ticks=(a:number,b:number,major?:number)=>{ const step=major&&major>0?major:(b-a)/4; const start=Math.ceil(a/step)*step; return Array.from({length:Math.min(100,Math.max(0,Math.floor((b-start)/step)+1))},(_,i)=>start+i*step); }; const axes=(domain:[number,number]=[low,high], horizontal=false, tickText=fmt)=>{ const [a,b]=domain, yy=(v:number)=>bottom-(v-a)/(b-a)*ph, xx=(v:number)=>L+(v-a)/(b-a)*pw; const major=p.yMajor??(percentStack ? .25 : horizontal&&dateAxis?(b-a)/Math.max(1,Math.floor(pw/110)):undefined); return {valueAxis.gridlines !== false ? ticks(a,b,p.yMinor).filter(v=>p.yMinor&&v>a&&v) : null} {ticks(a,b,major).map((v,i)=>{valueAxis.gridlines !== false ? : null} {label(`v${i}`,tickText(v),horizontal?xx(v):L-8,horizontal?bottom+20:yy(v)+4,horizontal?"middle":"end",undefined,undefined,valueAxis.labelAngle)})} {categoryAxis.gridlines === true && !horizontal ? rows.map((_,i)=>) : null} {p.showAxisTitles&&(p.xTitle||p.categoryTitle)?label("xt",p.xTitle||p.categoryTitle||"",(L+right)/2,H-6,"middle","axis-title",onRetitle ? beginRename("xTitle", p.xTitle || p.categoryTitle || "") : undefined):null} {p.showAxisTitles&&p.yTitle?{short(p.yTitle,24)}:null} ; }; const categoryLabels=(horizontal=false)=>names.map((name,i)=>i%Math.max(1,Math.ceil(names.length/(horizontal?8:Math.max(2,Math.floor(pw/72)))))===0 ?label(`c${i}`,short(name,horizontal?9:Math.max(5,Math.floor(pw/Math.min(names.length,6)/8))),horizontal?L-8:x(i),horizontal?T+(i+.5)*ph/names.length+4:bottom+20,horizontal?"end":"middle",undefined,undefined,categoryAxis.labelAngle):null); const shapeError = chartShapeError(kind, { rows, series, fields: [] }, p); if (dataError || shapeError) error=dataError || shapeError || ""; else if (!["bar","column","line","area","pie","donut","scatter","combo","waterfall","histogram","bubble","bullet","funnel","gauge","polar","radar","treemap","stock","gantt","sunburst","boxWhisker"].includes(kind)) error="That chart kind is not supported."; else if (p.yMin!==undefined&&p.yMax!==undefined&&p.yMin>=p.yMax) error="The Y maximum must exceed the minimum."; else if (!series.length||!rows.length) error="This range has no numeric values to chart."; else if (["pie","donut","funnel","treemap","polar","waterfall","histogram","gauge","sunburst"].includes(kind)&&series.length!==1) error="Select one visible series for this chart type."; else if (["pie","donut","funnel","treemap","polar","radar"].includes(kind)&&all.some(v=>v<0)) error="This chart type needs nonnegative values."; else if (["pie","donut","funnel","treemap","polar"].includes(kind)&&valid.reduce((a,b)=>a+b,0)<=0) error="This chart type needs a positive total."; else if (kind === "sunburst" && rows.some(row => typeof row.category !== "string" || typeof (row as unknown as Record).child !== "string" || !readText(row,"category").trim() || !readText(row,"child").trim() || readNumber(row,one.y) === null)) error="Sunburst needs two text category columns followed by one numeric value column."; else if (kind === "sunburst" && !valid.some(value => value > 0)) error="Sunburst excludes zero and negative values; choose at least one positive value."; else if (kind === "sunburst" && !Number.isFinite(valid.reduce((sum,value) => sum+Math.max(0,value),0))) error="Sunburst needs a finite positive total."; else if (kind === "boxWhisker") { const shortSeries = series.find(s => rows.filter(row => readNumber(row,s.y) !== null).length < 5); if (shortSeries) error=`Box and whisker needs at least five numeric values in ${shortSeries.label}.`; } if (!error && kind === "sunburst") { const parents = new Map>(); rows.forEach(row => { const value = readNumber(row,one.y)!; if (value <= 0) return; const parent = readText(row,"category"), child = readText(row,"child"); if (!parents.has(parent)) parents.set(parent,new Map()); const children = parents.get(parent)!; children.set(child,(children.get(child) ?? 0)+value); }); // Scale before summing so very large finite source values still produce finite angles. const weightScale = Math.max(...valid); const groups = [...parents].map(([name,children]) => ({ name, children: [...children], weight: [...children.values()].reduce((sum,value) => sum+value/weightScale,0) })); const total = groups.reduce((sum,group) => sum+group.weight,0); const radius = Math.max(16,Math.min(pw,ph)/2-8), cx=(L+right)/2, cy=(T+bottom)/2; let angle=-Math.PI/2; legend=[]; const arc = (key:string,name:string,value:number,slot:number,level:number,from:number,sweep:number) => { const inner=radius*(level===1?.18:.58), outer=radius*(level===1?.58:1), middle=(inner+outer)/2; nodes.push({title(name,value)}); // A tangent label must fit both the annular width and the angular span. Never truncate // into an ambiguous category or let the glyph corners cross a neighbouring arc. const textWidth=name.length*(p.axisFont==="large"?10:8), textHeight=p.axisFont==="large"?20:16; const fits=Math.hypot(middle+textHeight/2,textWidth/2)inner+3 && 2*Math.atan2(textWidth/2+4,middle-textHeight/2)90 && rotation<270) rotation+=180; nodes.push({name}); } }; groups.forEach((group,slot) => { const sweep=group.weight/total*Math.PI*2, end=angle+sweep; arc(`parent${slot}`,group.name,group.children.reduce((sum,[,value])=>sum+value,0),slot,1,angle,sweep); group.children.forEach(([child,value],i) => { const childSweep=i===group.children.length-1 ? end-angle : (value/weightScale)/total*Math.PI*2; arc(`child${slot}-${i}`,child,value,slot,2,angle,childSweep); legend.push({y:`child${slot}-${i}`,label:`${group.name} / ${child}`,color:one.color,slot}); angle+=childSweep; }); angle=end; }); // A single yellow category has no multi-entry legend, so retain a visible key even // when its arc is too narrow for text or data labels have been switched off. if (legend.length===1 && one.color==="yellow") nodes.push(label("sunburst-key",legend[0].label,cx,bottom+20)); } else if (!error && kind === "boxWhisker") { nodes.push(axes()); const step=pw/series.length, half=Math.min(28,step*.3); series.forEach((s,si) => { const stats=boxWhiskerStats(rows.map(row=>readNumber(row,s.y)).filter((v):v is number=>v!==null))!; const cx=L+(si+.5)*step; nodes.push( {[stats.low,stats.high].map((value,i)=>)} {stats.outliers.map((value,i)=>{title(s.label,value)})} {`${s.label}: Q1 ${fmt(stats.q1)}, median ${fmt(stats.median)}, Q3 ${fmt(stats.q3)}, whiskers ${fmt(stats.low)} to ${fmt(stats.high)}`} ); nodes.push(label(`box-series${si}`,short(s.label,Math.max(3,Math.floor(step/8))),cx,bottom+20)); }); } else if (!error && kind === "stock") { nodes.push(axes(), ...categoryLabels()); const half = Math.min(12, pw / rows.length * .25); rows.forEach((row,i) => { const values = series.map(s => readNumber(row,s.y)!); const [highValue,lowValue,close] = values.slice(series.length === 4 ? 1 : 0); const open = series.length === 4 ? values[0] : null; if (highValuehigh) return; nodes.push( {open !== null ? : null} {inValueBounds(close) ? : null} {`${names[i]}: ${series.map((s,j)=>`${s.label} ${fmt(values[j])}`).join(", ")}`} ); if (p.showDataLabels&&inValueBounds(close)) nodes.push(label(`stock-close${i}`,`${series[series.length-1].label} ${fmt(close)}`,x(i),y(highValue)-8,"middle","data")); }); } else if (!error && kind === "gantt") { const tasks = rows.map(row => { const start = readNumber(row,series[0].y)!, value = readNumber(row,series[1].y)!; return { start, end: p.ganttMode === "end" ? value : start + value }; }); const a = p.yMin ?? Math.min((p.yMax ?? Infinity)-1,...tasks.map(t=>t.start)); const b = p.yMax ?? Math.max(a+1,...tasks.map(t=>t.end)); const xx = (v:number) => L+(v-a)/(b-a)*pw, step=ph/rows.length; const dateText = (v:number) => { const ms=(v-25569)*86400000; return Math.abs(ms)<=8.64e15 ? new Date(ms).toISOString().slice(0,10) : fmt(v); }; nodes.push(axes([a,b],true,dateAxis?dateText:fmt),...categoryLabels(true)); legend=[{...series[1], label: p.ganttMode === "end" ? "Task duration" : series[1].label}]; tasks.forEach((task,i)=> { if (task.endb) return; const top=T+i*step+step*.2; nodes.push( {`${names[i]}: ${dateAxis?dateText(task.start):fmt(task.start)} to ${dateAxis?dateText(task.end):fmt(task.end)} (${fmt(task.end-task.start)}${dateAxis?" days":""})`} ); if(p.showDataLabels)nodes.push(label(`duration${i}`,`${fmt(task.end-task.start)}${dateAxis?" days":""}`,xx(task.end)+4,top+step*.3+4,"start","data")); }); } else if (!error && (kind==="pie"||kind==="donut"||kind==="polar")) { const total=valid.reduce((a,b)=>a+b,0), radius=Math.max(16,Math.min(pw,ph)/2-12), cx=(L+right)/2,cy=(T+bottom)/2; let angle=-Math.PI/2; legend=rows.map((_,i)=>({y:`slice${i}`,label:names[i]})); vals.forEach((v,i)=>{ if (v===null||v<=0) return; const sweep=kind==="polar"?Math.PI*2/rows.length:v/total*Math.PI*2; const r=kind==="polar"?radius*Math.sqrt(v/Math.max(...valid)):radius; const mid=angle+sweep/2; nodes.push({title(names[i],v)}); if (p.showDataLabels&&rows.length<=8&&sweep>.14) nodes.push(label(`slice${i}`,`${short(names[i],10)} ${fmt(v)}`,cx+Math.cos(mid)*r*.66,cy+Math.sin(mid)*r*.66)); angle+=sweep; }); } else if (!error&&kind==="treemap") { let pos=L; const total=valid.reduce((a,b)=>a+b,0); legend=rows.map((_,i)=>({y:`tile${i}`,label:names[i]})); vals.forEach((v,i)=>{ if(v===null||v<=0)return; const w=pw*v/total; nodes.push({title(names[i],v)}); if(p.showDataLabels&&w>40)nodes.push(label(`tile${i}`,`${short(names[i],Math.floor(w/9))} ${fmt(v)}`,pos+w/2,T+ph/2)); pos+=w; }); } else if(!error&&kind==="funnel") { const max=Math.max(...valid); const step=ph/rows.length,cx=(L+right)/2; vals.forEach((v,i)=>{if(v===null)return; const w=pw*v/max, next=pw*(vals[i+1]??v*.65)/max, top=T+i*step; nodes.push({title(names[i],v)}); if(p.showDataLabels)nodes.push(label(`f${i}`,`${names[i]} ${fmt(v)}`,cx,top+step/2+4)); }); } else if(!error&&kind==="gauge") { if(valid.length!==1)error="A gauge needs one numeric value."; else { const [a,b]=chartYDomain([0,100],p),value=valid[0],fraction=clamp((value-a)/(b-a),0,1); const cx=(L+right)/2,cy=bottom-8,radius=Math.max(20,Math.min(pw/2,ph)-12); nodes.push(); if(fraction>0)nodes.push({title(one.label,value)}); const angle=Math.PI+fraction*Math.PI; nodes.push(); nodes.push(label("value",fmt(value),cx,cy-20),label("min",fmt(a),cx-radius,cy+20),label("max",fmt(b),cx+radius,cy+20)); if(valueb)nodes.push(label("outside","Outside gauge bounds",cx,T+14)); } } else if(!error&&kind==="radar") { if(rows.length<3)error="A radar chart needs at least three categories."; else { const radius=Math.max(16,Math.min(pw,ph)/2-20),cx=(L+right)/2,cy=(T+bottom)/2; const [min,max]=chartYDomain(all,p); const point=(i:number,value:number)=>({x:cx+Math.cos(-Math.PI/2+i/rows.length*Math.PI*2)*radius*clamp((value-min)/(max-min),0,1),y:cy+Math.sin(-Math.PI/2+i/rows.length*Math.PI*2)*radius*clamp((value-min)/(max-min),0,1)}); rows.forEach((_,i)=>{const pt=point(i,max);nodes.push();nodes.push(label(`rad${i}`,names[i],pt.x,pt.y));}); series.forEach((s,si)=>{const pts=rows.map((row,i)=>point(i,readNumber(row,s.y)??0));nodes.push(`${pt.x},${pt.y}`).join(" ")}>{s.label});}); } } else if(!error&&kind==="histogram") { const bins=histogramBins(valid,p.bins??10), domain=chartYDomain(bins.map(b=>b.count),p); nodes.push(axes(domain)); const bw=pw/bins.length; bins.forEach((b,i)=>{const top=bottom-(b.count-domain[0])/(domain[1]-domain[0])*ph; if(i%Math.max(1,Math.ceil(bins.length/6))===0)nodes.push(label(`bin${i}`,fmt(b.low),L+i*bw,bottom+20)); if(b.countdomain[1])return; nodes.push({`${fmt(b.low)} to ${fmt(b.high)}: ${b.count}`}); if(p.showDataLabels&&bins.length<=12)nodes.push(label(`n${i}`,String(b.count),L+(i+.5)*bw,top-6,"middle","data")); }); } else if(!error&&kind==="waterfall") { let total=0; const steps=vals.map(v=>{const from=total;total+=v??0;return {from,to:total};}); const domain=chartYDomain([0,...steps.flatMap(s=>[s.from,s.to])],p); const yy=(v:number)=>bottom-(v-domain[0])/(domain[1]-domain[0])*ph, bw=pw/(rows.length+1); nodes.push(axes(domain)); [...steps,{from:0,to:total}].forEach((s,i)=>{ nodes.push(label(`wc${i}`,short(i===rows.length?"Total":names[i],Math.max(4,Math.floor(bw/8))),L+(i+.5)*bw,bottom+20)); if(Math.max(s.from,s.to)domain[1])return; const delta=s.to-s.from,top=Math.min(yy(s.from),yy(s.to)); nodes.push({title(i===rows.length?"Total":names[i],delta)}); if(s.todomain[1])return; if(i); if(p.showDataLabels)nodes.push(label(`wv${i}`,fmt(delta),L+(i+.5)*bw,top-6,"middle","data")); }); } else if(!error&&kind==="bullet") { if(series.length<2)error="A bullet chart needs actual and target series."; else { const [a,b]=chartYDomain(all,p),xx=(v:number)=>L+(v-a)/(b-a)*pw,step=ph/rows.length; nodes.push(axes([a,b],true),...categoryLabels(true)); rows.forEach((row,i)=>{const actual=readNumber(row,series[0].y),target=readNumber(row,series[1].y),top=T+i*step; if(actual===null||target===null)return; series.slice(2).map(s=>readNumber(row,s.y)).filter((v):v is number=>v!==null).sort((a,b)=>b-a).forEach((v,ri)=>nodes.push()); const actualVisible=inValueBounds(actual),targetVisible=inValueBounds(target); if(actualVisible)nodes.push({title(names[i],actual)}); if(targetVisible)nodes.push(); if(p.showDataLabels&&(actualVisible||targetVisible)) { const text=actualVisible&&targetVisible ? `${fmt(actual)} / ${fmt(target)}` : actualVisible ? `${series[0].label} ${fmt(actual)}` : `${series[1].label} ${fmt(target)}`; nodes.push(label(`b${i}`,text,right-4,top+step*.25,"end","data")); } }); } } else if(!error&&(kind==="scatter"||kind==="bubble")) { if(kind==="bubble"&&series.length<2)error="A bubble chart needs X, Y and size columns."; else if(kind==="bubble"&&rows.some(r=>(readNumber(r,series[1].y)??0)<0))error="Bubble sizes must be nonnegative."; else if(rows.some(r=>readNumber(r,"category")===null))error="The X column must contain numeric values."; else { const markerPad=kind==="bubble"?Math.min(24,ph/6)+2:6; const xs=rows.map(r=>readNumber(r,"category")!),xmin=p.xMin??Math.min(...xs),xmax=p.xMax??Math.max(...xs),xx=(v:number)=>L+markerPad+(v-xmin)/(xmax-xmin||1)*(pw-2*markerPad); const plotted=kind==="bubble"?series.slice(0,1):series; legend=plotted; const [ya,yb]=chartYDomain(plotted.flatMap(s=>rows.map(r=>readNumber(r,s.y)).filter((v):v is number=>v!==null)),p); const padTop=p.yMax===undefined?markerPad:0,padBottom=p.yMin===undefined?markerPad:0; const yy=(v:number)=>bottom-padBottom-(v-ya)/(yb-ya)*(ph-padTop-padBottom); const spanPerPixel=(yb-ya)/(ph-padTop-padBottom); nodes.push(axes([ya-padBottom*spanPerPixel,yb+padTop*spanPerPixel])); ticks(xmin,xmax===xmin?xmin+1:xmax).forEach((v,i)=>nodes.push(label(`x${i}`,catFmt(v),xx(v),bottom+20,"middle",undefined,undefined,categoryAxis.labelAngle))); const maxSize=kind==="bubble"?Math.max(1,...rows.map(r=>readNumber(r,series[1].y)??0)):1; plotted.forEach((s,si)=>rows.forEach((row,i)=>{const v=readNumber(row,s.y);if(v===null)return; // D-736: test the data coordinates before creating either a marker or its label. if (xs[i]xmax||vyb) return; const radius=kind==="bubble"?Math.sqrt((readNumber(row,series[1].y)??0)/maxSize)*Math.min(24,ph/6):4; if(radius<=0)return; nodes.push({title(`${catFmt(xs[i])}, ${s.label}`,v)}); if(p.showDataLabels&&rows.length<=8)nodes.push(label(`xy${i}-${si}`,fmt(v),xx(xs[i])+6,yy(v)-radius-4,"start","data")); })); } } else if(!error) { const horizontal=kind==="bar",xx=(v:number)=>L+(v-low)/(high-low)*pw; nodes.push(axes([low,high],horizontal),...categoryLabels(horizontal)); series.forEach((s,si)=>{ const line=kind==="line"||kind==="area"||(kind==="combo"&&si>0); if(line) { let segment: {x:number;y:number;base:number}[]=[]; const flush=(index:number)=>{ if(!segment.length)return; const points=segment.map(pt=>`${pt.x},${pt.y}`).join(" "); if(kind==="area")nodes.push(`${pt.x},${pt.base}`).join(" ")}`}/>); nodes.push({s.label}); segment=[]; }; rows.forEach((row,i)=>{const v=readNumber(row,s.y), stack=stacks?.[i][si];if(v===null||(stacks&&!stack)){flush(i);return;} const end=stack?.to??v, start=stack?.from??0, value=stack?.value??v; segment.push({x:x(i),y:y(end),base:y(start)}); if(!inValueBounds(end))return; nodes.push({title(`${names[i]}, ${s.label}`,value)}); if(p.showDataLabels&&rows.length<=8)nodes.push(label(`v${s.y}-${i}`,fmt(value),x(i),y(end)-8,"middle","data")); });flush(rows.length); if(direct) { const last=rows.map((row,i)=>({v:readNumber(row,s.y),i})).filter(pt=>pt.v!==null).slice(-1)[0]; if(last)nodes.push(label(`direct${s.y}`,s.label,right-4,16+si*18,"end","direct")); } } else { const slots=stacked||kind==="combo"?1:series.length,step=(horizontal?ph:pw)/Math.max(1,rows.length),bar=step*.72/slots; rows.forEach((row,i)=>{const v=readNumber(row,s.y), stack=stacks?.[i][si];if(v===null||(stacks&&!stack))return; const start=stack?.from??0,end=stack?.to??v,value=stack?.value??v; // D-736: a clustered value outside the requested bounds has no mark or data label. // A stack segment may cross a bound, so preserve its visible intersection. if (stack ? Math.max(start,end)high : !inValueBounds(end)) return; const group=(horizontal?T:L)+i*step+step*.14+(stacked?0:si*bar); nodes.push({title(`${names[i]}, ${s.label}`,value)}); if(p.showDataLabels&&rows.length*series.length<=24&&inValueBounds(end))nodes.push(label(`val${s.y}-${i}`,fmt(value),horizontal?xx(end)+4:group+bar/2,horizontal?group+bar/2+4:y(end)-6,horizontal?"start":"middle","data")); }); } }); if(direct&&!["line","area","combo"].includes(kind)) series.forEach((s,i)=>nodes.push(label(`direct${s.y}`,s.label,right-4,16+i*18,"end","direct"))); } const showLegend=legend.length>=2; return
{p.title?
{p.title}
:null} {error?

{error}

:<> {showLegend?
{legend.map((s,i)=>{s.label})}
:null} {/* D-736: plot clips trim shapes; data labels are suppressed with excluded values above. */} {nodes.map((node,i)=>{node})} } {renaming && onRetitle ? ( event.currentTarget.select()} onPointerDown={event => event.stopPropagation()} onMouseDown={event => event.stopPropagation()} onKeyDown={event => { event.stopPropagation(); if (event.key === "Enter") { onRetitle(renaming.key, event.currentTarget.value.trim()); setRenaming(null); } if (event.key === "Escape") setRenaming(null); }} onBlur={event => { onRetitle(renaming.key, event.currentTarget.value.trim()); setRenaming(null); }} /> ) : null}
; } export type ChartPreview = { dx: number; dy: number; dw: number; dh: number }; export type ChartHandle = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw"; /** Which edges a handle drags. -1 is the top or left edge, so the anchor moves too. */ const HANDLE_AXES: Record = { n: { x: 0, y: -1 }, s: { x: 0, y: 1 }, e: { x: 1, y: 0 }, w: { x: -1, y: 0 }, ne: { x: 1, y: -1 }, nw: { x: -1, y: -1 }, se: { x: 1, y: 1 }, sw: { x: -1, y: 1 }, }; const HANDLE_NAMES: Record = { nw: "Top left", n: "Top", ne: "Top right", w: "Left", e: "Right", sw: "Bottom left", s: "Bottom", se: "Bottom right", }; /** Top and left handles move the anchor by the inverse of the size change to keep the opposite * edge fixed. Ratio is height divided by width; Shift or the aspect lock couples both dimensions. */ export const resizeDelta = (handle: ChartHandle, dx: number, dy: number, ratio: number, keepRatio: boolean): ChartPreview => { const axis = HANDLE_AXES[handle]; let dw = axis.x === 0 ? 0 : axis.x * dx; let dh = axis.y === 0 ? 0 : axis.y * dy; if (keepRatio && ratio > 0) { if (axis.x === 0) dw = dh / ratio; else if (axis.y === 0) dh = dw * ratio; else if (Math.abs(dw) >= Math.abs(dh / ratio)) dh = dw * ratio; else dw = dh / ratio; } return { dx: axis.x === -1 ? -dw : 0, dy: axis.y === -1 ? -dh : 0, dw, dh }; }; type Nudge = ChartPreview; const ZERO: Nudge = { dx: 0, dy: 0, dw: 0, dh: 0 }; const NUDGE_KEYS: (keyof Nudge)[] = ["dx", "dy", "dw", "dh"]; /** rad/s. Higher is a shorter settle; at zeta = 1 there is no overshoot at any speed. */ const OMEGA = 22; /** Below half a pixel and half a pixel per second, the spring has arrived. */ const AT_REST = 0.5; const prefersReducedMotion = (): boolean => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches; export default function SheetChart({ range, cells, source, presentation, stacking, kind = "bar", selected = false, width, height, preview, onPreviewChange, moveSteps, onMove, onResize, onEdit, onDelete, onRetitle, }: SheetChartProps) { const { fields, rows, series, error, dateAxis } = useMemo( () => chartDataForRange(cells, range, presentation, source?.ranges ?? [range], kind), [cells, range, presentation, source, kind], ); const [localNudge, setLocalNudge] = useState(ZERO); const nudge = preview ?? localNudge; const previewWriter = useRef(onPreviewChange); previewWriter.current = onPreviewChange; const setNudge = useCallback((value: Nudge) => { setLocalNudge(value); previewWriter.current?.(value); }, []); const [flash, setFlash] = useState(false); const grab = useRef<{ pointerId: number; originLeft: number; originTop: number; offsetX: number; offsetY: number; mode: "move" | "resize"; handle: ChartHandle; } | null>(null); const frame = useRef(null); const stopSettle = useCallback(() => { if (frame.current !== null && typeof cancelAnimationFrame === "function") { cancelAnimationFrame(frame.current); } frame.current = null; }, []); useEffect(() => stopSettle, [stopSettle]); /** The critically damped return, integrated from the value the finger let go at. */ const settle = useCallback((from: Nudge) => { if (prefersReducedMotion() || typeof requestAnimationFrame !== "function") { // ⛔ Reduced motion replaces the spring with a short opacity change, never with a slide // taken faster: the whole point is that nothing travels across the screen. setNudge(ZERO); setFlash(true); window.setTimeout(() => setFlash(false), 140); return; } let value: Nudge = { ...from }; let velocity: Nudge = { ...ZERO }; let last = performance.now(); const step = (now: number) => { const dt = Math.min(0.032, Math.max(0.001, (now - last) / 1000)); last = now; let moving = false; const nextValue: Nudge = { ...ZERO }; const nextVelocity: Nudge = { ...ZERO }; for (const key of NUDGE_KEYS) { const accel = -2 * OMEGA * velocity[key] - OMEGA * OMEGA * value[key]; nextVelocity[key] = velocity[key] + accel * dt; nextValue[key] = value[key] + nextVelocity[key] * dt; if (Math.abs(nextValue[key]) > AT_REST || Math.abs(nextVelocity[key]) > AT_REST) { moving = true; } } value = nextValue; velocity = nextVelocity; if (!moving) { setNudge(ZERO); frame.current = null; return; } setNudge(value); frame.current = requestAnimationFrame(step); }; frame.current = requestAnimationFrame(step); }, []); const beginDrag = useCallback((mode: "move" | "resize", handle: ChartHandle = "se") => (event: React.PointerEvent) => { if (event.button !== 0) return; event.preventDefault(); event.stopPropagation(); stopSettle(); const rect = event.currentTarget.getBoundingClientRect(); grab.current = { pointerId: event.pointerId, originLeft: rect.left, originTop: rect.top, offsetX: event.clientX - rect.left, offsetY: event.clientY - rect.top, mode, handle, }; event.currentTarget.setPointerCapture(event.pointerId); // ⛔ FOCUS IT BY HAND, because the `preventDefault` two lines up is what stops a pointer from // focusing a button. Every one of these handles promises "or use the arrow keys" in its own // label, and without this the promise is only reachable by tabbing: measured in the browser, // a click on a handle followed by ArrowRight resized the chart by exactly nothing. event.currentTarget.focus(); setNudge(ZERO); }, [stopSettle]); const duringDrag = useCallback((event: React.PointerEvent) => { const held = grab.current; if (!held || held.pointerId !== event.pointerId) return; // 1:1 with the pointer, from the offset it was grabbed at, so pushing back the way it came // undoes the drag exactly rather than starting a new one. const dx = event.clientX - held.offsetX - held.originLeft; const dy = event.clientY - held.offsetY - held.originTop; const ratio = height > 0 && width > 0 ? height / width : 0; const keepRatio = event.shiftKey || presentation?.lockAspect === true; const delta = held.mode === "move" ? { dx, dy, dw: 0, dh: 0 } : resizeDelta(held.handle, dx, dy, ratio, keepRatio); setNudge(delta); }, [height, width, presentation?.lockAspect, setNudge]); const endDrag = useCallback((event: React.PointerEvent) => { const held = grab.current; if (!held || held.pointerId !== event.pointerId) return; grab.current = null; if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } const dx = event.clientX - held.offsetX - held.originLeft; const dy = event.clientY - held.offsetY - held.originTop; const ratio = height > 0 && width > 0 ? height / width : 0; const keepRatio = event.shiftKey || presentation?.lockAspect === true; const delta = held.mode === "move" ? { dx, dy, dw: 0, dh: 0 } : resizeDelta(held.handle, dx, dy, ratio, keepRatio); const snapped = held.mode === "move" ? onMove?.(delta.dx, delta.dy) : onResize?.(delta, keepRatio && ratio > 0 ? ratio : undefined); // The persisted anchor changes in the same release. Keep only the UNSNAPPED residual in the // presentation value, so old anchor + pointer travel equals new anchor + residual and there is // no release-frame jump or double movement. settle({ dx: delta.dx - (snapped?.dx ?? 0), dy: delta.dy - (snapped?.dy ?? 0), dw: 0, dh: 0 }); }, [onMove, onResize, settle, height, width, presentation?.lockAspect]); const cancelDrag = useCallback((event: React.PointerEvent) => { const held = grab.current; if (!held || held.pointerId !== event.pointerId) return; grab.current = null; if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } settle(nudge); }, [nudge, settle]); // ⭐ THE DRAG IS NOT THE ONLY WAY, which DESIGN.md requires: the arrow keys walk the anchor one // cell at a time from the move grip, and each resize handle also accepts arrows. The dialog sets a range // outright. A step is this chart's own width over the columns it spans, which IS one column on // the grid it is sitting on. const stepX = Math.max(8, width / Math.max(1, Math.abs(range.col1 - range.col0) + 1)); const stepY = Math.max(8, height / Math.max(1, Math.abs(range.row1 - range.row0) + 1)); const arrowKeys = useCallback((mode: "move" | "resize", handle: ChartHandle = "se") => (event: React.KeyboardEvent) => { if (mode === "move") { const send = onMove; if (!send) return; const steps = mode === "move" ? moveSteps : undefined; if (event.key === "ArrowLeft") send(steps?.left ?? -stepX, 0); else if (event.key === "ArrowRight") send(steps?.right ?? stepX, 0); else if (event.key === "ArrowUp") send(0, steps?.up ?? -stepY); else if (event.key === "ArrowDown") send(0, steps?.down ?? stepY); else return; } else { if (!onResize) return; const steps: Record = { ArrowLeft: [-stepX, 0], ArrowRight: [stepX, 0], ArrowUp: [0, -stepY], ArrowDown: [0, stepY], }; const step = steps[event.key]; if (!step) return; const ratio = height > 0 && width > 0 ? height / width : 0; const keepRatio = event.shiftKey || presentation?.lockAspect === true; onResize(resizeDelta(handle, step[0], step[1], ratio, keepRatio), keepRatio && ratio > 0 ? ratio : undefined); } event.preventDefault(); }, [onMove, onResize, stepX, stepY, moveSteps, height, width, presentation?.lockAspect]); const tools = (onMove || onResize || onEdit || onDelete) ? (
{onMove ? ( ) : null} {onEdit ? ( ) : null} {onDelete ? ( ) : null} {onResize ? (["nw", "n", "ne", "w", "e", "sw", "s", "se"] as const).map(handle => (
) : null; const shell: React.CSSProperties = { width: Math.max(24, width + nudge.dw), height: Math.max(24, height + nudge.dh), transform: nudge.dx || nudge.dy ? `translate(${nudge.dx}px, ${nudge.dy}px)` : undefined, opacity: flash ? 0.72 : undefined, }; // ⭐ W56-T12, R6 and instruction 9: font-size inside a scaled viewBox is measured in user // units, so a constant token changes size on screen with the person's chart box. Dividing by // this scale keeps axis labels at one legible screen size whatever box they choose. const drawScale = 1; if (!series.length || error) { // Named rather than drawn empty: a chart frame with no series reads as "the data is zero", // which is a different and wrong statement. return (

{error || "This range has no numeric values to chart."}

{tools}
); } return ( // ⭐ THE WRAPPER IS THE SIZING MECHANISM. `SeriesChart` draws into a fixed 720x230 viewBox, so // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays // untouched. `viz/**` belongs to no lane in this wave, and the own-drawn kinds use the same // viewBox for the same reason.
{tools}
); }