loopable / web /src /sheet /SheetChartLayer.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
0e600b9 verified
Raw History Blame Contribute Delete
11.3 kB
/** Persist one document box; project its unchanged drawing through each frozen quadrant. */
import "../styles/wave56/charts.css";
import "../styles/wave58/sheet.css";
import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import SheetChart from "./SheetChart";
import type { ChartAnchorDelta, ChartPreview } from "./SheetChart";
import { ChartWorkbookContext } from "./ChartDialog";
import { chartPaneProjections, lockstepScrollX } from "./sheetState";
import { chartDocumentGeometry } from "./types";
import { useEscapeClose } from "../ui/useEscapeClose";
import type { CellMap, SheetChartSpec } from "./types";
export interface SheetChartLayerProps {
charts: SheetChartSpec[];
cells: CellMap;
visCols: number[];
/** All visible rows, including the frozen band. */
visRows: number[];
columns: readonly { width: number }[];
columnX: (index: number) => number;
/** All-visible-row index, using the same wrapped height as either canvas. */
rowHeightAt: (index: number) => number;
frozenCols: number;
bandRows: number;
headerHeight: number;
/** Screen pixels per stored document pixel. */
zoom: number;
viewport: { x: number; y: number; tx: number; ty: number };
onWriteCharts: (next: SheetChartSpec[]) => void;
onEditChart: (id: string) => void;
/** The chart the user has selected. Owned by SheetGrid, because the ribbon needs to see it. */
selectedChartId: string | null;
onSelectChart: (id: string | null) => void;
onCopyChart: (id: string) => void;
}
const ZERO: ChartPreview = { dx: 0, dy: 0, dw: 0, dh: 0 };
/** Hidden anchors collapse to the next visible cell boundary, but keep their real coordinates. */
const visibleBoundary = (visible: number[], real: number) => {
const next = visible.findIndex(index => index >= real);
return next < 0 ? visible.length : next;
};
export default function SheetChartLayer({ charts, cells, visCols, visRows, columns, columnX,
rowHeightAt, frozenCols, bandRows, headerHeight, zoom, viewport, onWriteCharts, onEditChart,
selectedChartId, onSelectChart, onCopyChart,
}: SheetChartLayerProps) {
const workbook = useContext(ChartWorkbookContext);
const root = useRef<HTMLDivElement>(null);
const [size, setSize] = useState({ width: 0, height: 0 });
const selectedId = selectedChartId;
useEscapeClose(selectedId !== null, () => onSelectChart(null), {
container: () => root.current,
});
const [previews, setPreviews] = useState<Record<string, ChartPreview>>({});
useLayoutEffect(() => {
const node = root.current;
if (!node) return;
const measure = () => setSize({ width: node.clientWidth, height: node.clientHeight });
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, []);
useEffect(() => {
for (const chart of charts) if (chart.source?.sheetId) workbook?.loadSheet(chart.source.sheetId);
}, [charts, workbook?.loadSheet]);
const deleteChart = useCallback((id: string) => {
onWriteCharts(charts.filter(chart => chart.id !== id));
if (selectedChartId === id) onSelectChart(null);
}, [charts, onSelectChart, onWriteCharts, selectedChartId]);
useEffect(() => {
if (selectedId === null) return;
const outside = (event: PointerEvent) => {
if (!(event.target instanceof Element)) { onSelectChart(null); return; }
if (event.target.closest(".sheet-chart-anchor") || event.target.closest(".sheet-ribbon-shell")) return;
onSelectChart(null);
};
const key = (event: KeyboardEvent) => {
if (event.target instanceof Element && event.target.closest('[role="dialog"], input, textarea, select')) return;
if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.key === "c" || event.key === "C")) {
event.preventDefault(); event.stopPropagation(); onCopyChart(selectedId); return;
}
if (event.key !== "Delete" && event.key !== "Backspace") return;
event.preventDefault(); event.stopPropagation(); deleteChart(selectedId);
};
document.addEventListener("pointerdown", outside, true);
document.addEventListener("keydown", key, true);
return () => {
document.removeEventListener("pointerdown", outside, true);
document.removeEventListener("keydown", key, true);
};
}, [deleteChart, onCopyChart, onSelectChart, selectedId]);
const rowOffsets = useMemo(() => {
const offsets = [0];
for (let i = 0; i < visRows.length; i++) offsets.push(offsets[i] + rowHeightAt(i));
return offsets;
}, [rowHeightAt, visRows.length]);
const rowY = useCallback((index: number) => rowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0,
[rowOffsets, visRows.length]);
const scrollX = lockstepScrollX(columns.map(column => column.width), frozenCols, viewport.x, viewport.tx);
const frozenHeight = rowY(bandRows);
const scrollY = rowY(bandRows + viewport.y) - frozenHeight - viewport.ty;
const nudgeChart = (chart: SheetChartSpec, delta: ChartPreview, mode: "move" | "resize",
ratio?: number): ChartAnchorDelta => {
const box = chartDocumentGeometry(chart);
// Sizes persist in document pixels; snapping and the returned preview offset stay on screen.
const dw = delta.dw / zoom, dh = delta.dh / zoom, dx = delta.dx / zoom, dy = delta.dy / zoom;
const col = visibleBoundary(visCols, box.col), row = visibleBoundary(visRows, box.row);
const nearest = (count: number, offset: (i: number) => number, target: number) => {
let best = 0;
for (let i = 1; i < count; i++) if (Math.abs(offset(i) - target) < Math.abs(offset(best) - target)) best = i;
return best;
};
const nextCol = delta.dx ? nearest(visCols.length, columnX, columnX(col) + delta.dx) : col;
const nextRow = delta.dy ? nearest(visRows.length, rowY, rowY(row) + delta.dy) : row;
const movedX = columnX(nextCol) - columnX(col), movedY = rowY(nextRow) - rowY(row);
const anchor = {
col: delta.dx ? visCols[nextCol] ?? box.col : box.col,
row: delta.dy ? visRows[nextRow] ?? box.row : box.row,
};
if (mode === "move") {
onWriteCharts(charts.map(c => c.id === chart.id ? { ...c, geometry: { ...box, ...anchor } } : c));
return { dx: movedX, dy: movedY };
}
// Absorb anchor snapping in the size so a top or left drag keeps the opposite edge fixed.
// ⛔ ROUNDED, because a kept ratio divides. A south drag on a 640 by 360 chart with the ratio
// locked derives a width of 853.3333333333334, and that number is not an abstraction: it lands
// in the Location section's Width box exactly as written. Chart geometry is CSS pixels and a
// pixel is a whole number here.
let width = Math.round(Math.max(320, Math.min(2400, box.width + dw + dx - movedX / zoom)));
let height = Math.round(Math.max(240, Math.min(1600, box.height + dh + dy - movedY / zoom)));
// ⛔⛔ A KEPT RATIO SURVIVES THE SNAP ONLY IF IT IS RE-DERIVED HERE. `resizeDelta` returns a
// delta that already holds the shape, but the anchor then snaps to the nearest COLUMN or ROW
// boundary and the size absorbs the difference, so the dimension whose edge moved is the only
// one that is still true. Re-derive the other from it. A clamp ends the proportional drag the
// same way Excel's does, which is why the derived value is clamped too.
if (ratio && ratio > 0) {
if (delta.dy && !delta.dx) width = Math.max(320, Math.min(2400, Math.round(height / ratio)));
else height = Math.max(240, Math.min(1600, Math.round(width * ratio)));
}
onWriteCharts(charts.map(c => c.id === chart.id ? { ...c, geometry: { ...box, ...anchor, width, height } } : c));
return { dx: movedX, dy: movedY };
};
return <div className="sheet-chart-layer" ref={root}>
{charts.map(chart => {
const box = chartDocumentGeometry(chart);
const width = box.width * zoom, height = box.height * zoom;
const col = visibleBoundary(visCols, box.col), row = visibleBoundary(visRows, box.row);
const projections = chartPaneProjections({ left: columnX(col), top: headerHeight + rowY(row) }, {
...size, markerWidth: columnX(0), headerHeight,
frozenWidth: columnX(frozenCols) - columnX(0), frozenHeight, scrollX, scrollY,
});
const preview = previews[chart.id] ?? ZERO;
// Each toolbar control has exactly one keyboard owner. Offscreen copies remain drawings.
const contains = (p: typeof projections[number], x: number, y: number) =>
p.chartLeft + x >= 0 && p.chartLeft + x < p.width
&& p.chartTop + y >= 0 && p.chartTop + y < p.height;
const moveOwner = projections.reduce<typeof projections[number] | undefined>((best, p) => {
const overlap = (part: typeof p) => part.chartTop + 12 >= 0 && part.chartTop + 12 < part.height
? Math.max(0, Math.min(part.width, part.chartLeft + width - 76) - Math.max(0, part.chartLeft + 4)) : 0;
return overlap(p) > (best ? overlap(best) : 0) ? p : best;
}, undefined)?.pane;
const chartCells = chart.source?.sheetId && chart.source.sheetId !== workbook?.activeSheetId
? workbook?.sheets.find(s => s.id === chart.source?.sheetId)?.cells ?? {} : cells;
return projections.map(p => <div key={`${chart.id}:${p.pane}`} className="sheet-chart-pane" data-pane={p.pane}
style={{ left: p.left, top: p.top, width: p.width, height: p.height }}>
<div className="sheet-chart-anchor sheet-chart-hit" data-chart-id={chart.id} data-pane={p.pane}
data-selected={chart.id === selectedId ? "true" : undefined}
data-document-col={box.col} data-document-row={box.row}
onPointerDown={event => { event.preventDefault(); event.stopPropagation(); onSelectChart(chart.id); }}
onMouseDown={event => { event.preventDefault(); event.stopPropagation(); }}
style={{ left: p.chartLeft, top: p.chartTop, width, height }}>
<SheetChart range={chart.range} cells={chartCells} source={chart.source} presentation={chart.presentation}
kind={chart.kind} stacking={chart.stacking} width={width} height={height} selected={chart.id === selectedId}
preview={preview} onPreviewChange={value => setPreviews(before => ({ ...before, [chart.id]: value }))}
moveSteps={{ left: columnX(Math.max(0, col - 1)) - columnX(col),
right: columnX(Math.min(visCols.length - 1, col + 1)) - columnX(col),
up: rowY(Math.max(0, row - 1)) - rowY(row),
down: rowY(Math.min(visRows.length - 1, row + 1)) - rowY(row) }}
onMove={p.pane === moveOwner ? (dx, dy) => nudgeChart(chart, { dx, dy, dw: 0, dh: 0 }, "move") : undefined}
onResize={p.pane === moveOwner ? (delta, ratio) => nudgeChart(chart, delta, "resize", ratio) : undefined}
onEdit={contains(p, width - 60, 12) ? () => onEditChart(chart.id) : undefined}
onDelete={contains(p, width - 36, 12) ? () => deleteChart(chart.id) : undefined}
onRetitle={(key, value) => onWriteCharts(charts.map(item => item.id === chart.id
? { ...item, presentation: { ...item.presentation, [key]: value } } : item))}
/>
</div>
</div>);
})}
</div>;
}