reifyui 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "reifyui",
3
- "version": "0.7.2",
3
+ "version": "0.8.0",
4
4
  "description": "The open-source rendering & interaction layer for agentic applications. Stream and render any agent's output as polished, application-native UI \u2014 model-agnostic, framework-agnostic, design-system-native. The foundation for building generative-UI and agent products.",
5
5
  "keywords": [
6
6
  "react",
@@ -46,6 +46,11 @@
46
46
  "import": "./dist/harness.js",
47
47
  "require": "./dist/harness.cjs"
48
48
  },
49
+ "./chart": {
50
+ "types": "./dist/chart.d.ts",
51
+ "import": "./dist/chart.js",
52
+ "require": "./dist/chart.cjs"
53
+ },
49
54
  "./styles/*": "./styles/*",
50
55
  "./package.json": "./package.json"
51
56
  },
@@ -0,0 +1,90 @@
1
+ // Chart — an ECharts option, drawn. That is the whole component.
2
+ //
3
+ // It deliberately knows nothing about series, axes or data shape: the option IS the contract, so
4
+ // anything ECharts can draw, this draws, and the thing that decides what a chart should look like
5
+ // (a person, or an agent writing the option) is not limited by a props table. What it does own is
6
+ // the part every hand-rolled wrapper gets wrong: creating the instance once, disposing it on
7
+ // unmount, and resizing it when its box changes — a chart inside a resizable panel that never
8
+ // hears about the resize is the most common broken dashboard there is.
9
+ //
10
+ // echarts is an OPTIONAL peer, loaded lazily here, which is why this lives at `reifyui/chart` and
11
+ // not in the root index — the same reason `reifyui/slides` is its own entry. An app that imports
12
+ // a Button must not resolve a charting library.
13
+ import { useEffect, useRef, useState } from 'react';
14
+
15
+ /**
16
+ * option the ECharts option. Applied whenever the REFERENCE changes, so build it in a
17
+ * useMemo — a fresh object every render redraws the chart every render
18
+ * renderer 'canvas' (default) or 'svg'; svg stays crisp when the page is printed or scaled
19
+ * notMerge replace the previous option rather than merging into it (default true: a redraw
20
+ * after new data should not inherit last query's series)
21
+ * onInit the instance, once, for the things only the instance can do (export an image)
22
+ * label the chart's accessible name; a canvas has no text for a screen reader to find
23
+ * fallback drawn instead when the chart code cannot be loaded at all
24
+ */
25
+ export function Chart(props) {
26
+ const { option, renderer = 'canvas', notMerge = true, onInit, label, fallback = null, className = '' } = props;
27
+ const host = useRef(null);
28
+ const inst = useRef(null);
29
+ const applied = useRef(null); // the option the instance is currently showing
30
+ const [failed, setFailed] = useState(false);
31
+ // Read through refs inside the init effect so a new option or callback does not tear the
32
+ // instance down and rebuild it.
33
+ const latest = useRef({ option, notMerge, onInit });
34
+ latest.current = { option, notMerge, onInit };
35
+
36
+ useEffect(() => {
37
+ let dead = false;
38
+ (async () => {
39
+ try {
40
+ const mod = await import('echarts');
41
+ const echarts = typeof mod.init === 'function' ? mod : (mod.default || mod);
42
+ if (dead || !host.current) return;
43
+ const chart = echarts.init(host.current, null, { renderer });
44
+ inst.current = chart;
45
+ const { option: opt, notMerge: nm, onInit: cb } = latest.current;
46
+ if (opt) { chart.setOption(opt, nm); applied.current = opt; }
47
+ if (cb) cb(chart);
48
+ } catch {
49
+ if (!dead) setFailed(true); // no chart code: say so, never draw a fake one
50
+ }
51
+ })();
52
+ return () => {
53
+ dead = true;
54
+ try { inst.current?.dispose(); } catch { /* already gone with the DOM */ }
55
+ inst.current = null;
56
+ applied.current = null;
57
+ };
58
+ }, [renderer]);
59
+
60
+ // `applied` keeps this from redrawing the option the init above just drew — the instance
61
+ // arrives asynchronously, so both paths run on the first render that has one.
62
+ useEffect(() => {
63
+ if (!inst.current || !option || applied.current === option) return;
64
+ inst.current.setOption(option, notMerge);
65
+ applied.current = option;
66
+ }, [option, notMerge]);
67
+
68
+ useEffect(() => {
69
+ const el = host.current;
70
+ if (!el || typeof ResizeObserver !== 'function') return undefined;
71
+ let frame = 0;
72
+ const ro = new ResizeObserver(() => {
73
+ // One resize per frame: a drag on a panel corner fires the observer on every pointer move.
74
+ cancelAnimationFrame(frame);
75
+ frame = requestAnimationFrame(() => inst.current?.resize());
76
+ });
77
+ ro.observe(el);
78
+ return () => { cancelAnimationFrame(frame); ro.disconnect(); };
79
+ }, []);
80
+
81
+ if (failed) return <div className={['uic-chart', 'is-unavailable', className].filter(Boolean).join(' ')}>{fallback}</div>;
82
+ return (
83
+ <div
84
+ ref={host}
85
+ className={['uic-chart', className].filter(Boolean).join(' ')}
86
+ role={label ? 'img' : undefined}
87
+ aria-label={label}
88
+ />
89
+ );
90
+ }
@@ -0,0 +1,57 @@
1
+ // Type declarations for `reifyui/chart`.
2
+ //
3
+ // Hand-authored, like the root index: the source is plain JSX, so there is nothing to infer from.
4
+ // The option type is deliberately open — it is ECharts' own object, and narrowing it here would
5
+ // only describe the subset that existed the day this was written.
6
+ import type { ComponentType, ReactNode, RefObject } from 'react';
7
+
8
+ /** An ECharts option object. Typed as-is: install echarts and annotate your own builders with
9
+ * `EChartsOption` if you want the full shape checked at the call site. */
10
+ export type ChartOption = Record<string, unknown>;
11
+
12
+ export interface ChartProps {
13
+ /** Applied whenever the REFERENCE changes — build it in a useMemo, or the chart redraws on
14
+ * every render of the parent. */
15
+ option: ChartOption;
16
+ /** 'svg' stays crisp when the page is printed or scaled; 'canvas' (default) draws faster. */
17
+ renderer?: 'canvas' | 'svg';
18
+ /** Replace the previous option rather than merge into it. Default true. */
19
+ notMerge?: boolean;
20
+ /** The instance, once — for what only the instance can do (getDataURL, connect, …). */
21
+ onInit?: (instance: any) => void;
22
+ /** The chart's accessible name. A canvas has no text for a screen reader to find. */
23
+ label?: string;
24
+ /** Drawn instead when the chart code cannot be loaded at all. */
25
+ fallback?: ReactNode;
26
+ className?: string;
27
+ }
28
+ /** Renders an ECharts option and nothing else: it creates the instance, disposes it, and resizes
29
+ * it with its box. Fills its container, so give it one with a height. */
30
+ export const Chart: ComponentType<ChartProps>;
31
+
32
+ /** The --uic-* theme, as strings a chart option can hold. */
33
+ export interface ChartTokens {
34
+ /** Eight categorical colours. Assign IN ORDER, one per series, and never cycle: past eight,
35
+ * colour has stopped encoding identity — fold the tail into one series or split the chart.
36
+ * On a light surface three of the eight fall below 3:1 against white, so keep the legend or
37
+ * label series directly rather than resting identity on colour alone. */
38
+ palette: string[];
39
+ ink: string;
40
+ ink2: string;
41
+ mute: string;
42
+ line: string;
43
+ lineSoft: string;
44
+ surface: string;
45
+ brand: string;
46
+ ok: string;
47
+ warn: string;
48
+ bad: string;
49
+ font: string;
50
+ }
51
+ /** Resolve the tokens in effect for `el` — pass the element the chart lives in, so a panel inside
52
+ * a dark region resolves the dark values even on a light page. */
53
+ export function chartTokens(el?: Element | null): ChartTokens;
54
+
55
+ /** chartTokens(), re-read when the theme changes (a class/data-* flip on <html> or <body>, or the
56
+ * OS preference). Put the returned ref on the element the chart lives in. */
57
+ export function useChartTokens(): [ChartTokens, RefObject<HTMLElement | null>];
@@ -0,0 +1,10 @@
1
+ // The chart entry — IMPORT VIA SUBPATH ONLY ('reifyui/chart'), never from the root index.
2
+ //
3
+ // echarts is an optional peer and loads lazily inside Chart. A root re-export would put it in the
4
+ // dependency graph of every consumer, so an app that renders a Button and no chart would have to
5
+ // resolve a charting library to build. Same rule, same reason, as 'reifyui/slides'.
6
+ export { Chart } from './Chart.jsx';
7
+ // The theme as strings a chart option can hold — series colours, axis ink, tooltip chrome. CSS
8
+ // variables do not reach inside a canvas; these do.
9
+ export { chartTokens } from './tokens.js';
10
+ export { useChartTokens } from './useChartTokens.js';
@@ -0,0 +1,52 @@
1
+ // The theme, as values a chart library can use.
2
+ //
3
+ // A chart draws into a canvas, where CSS custom properties do not reach: series colours, axis
4
+ // labels and tooltip chrome all arrive as strings in an option object. Without this, every app
5
+ // hardcodes hex in its chart code and the charts are the one part of the product that does not
6
+ // follow the theme. Reading the same --uic-* tokens the stylesheets read keeps them together.
7
+
8
+ // Same policy as the `var(--uic-x, …)` fallbacks in the stylesheets: a host that never loaded a
9
+ // token layer still gets the library's own light palette rather than whatever the chart library
10
+ // defaults to. Values are themes/light.css verbatim.
11
+ const FALLBACK = {
12
+ cat: ['#2a78d6', '#eb6834', '#1baf7a', '#eda100', '#e87ba4', '#008300', '#4a3aa7', '#e34948'],
13
+ ink: '#111317', ink2: '#3A3D45', mute: '#5B5D66',
14
+ line: '#DDDFE6', lineSoft: '#EFF1F4', surface: '#FFFFFF',
15
+ brand: '#285AFF', ok: '#16a34a', warn: '#F59E0B', bad: '#b91c1c',
16
+ font: 'inherit',
17
+ };
18
+
19
+ function read(style, name, fallback) {
20
+ const v = style.getPropertyValue(name).trim();
21
+ return v || fallback;
22
+ }
23
+
24
+ /**
25
+ * Resolve the chart tokens in effect for `el` — pass the element the chart lives in, so a panel
26
+ * inside a dark region resolves the dark values even when the page is light.
27
+ *
28
+ * `palette` is a categorical scale: assign it IN ORDER, one colour per series, and never cycle
29
+ * it. Past eight series, colour has stopped being an encoding — fold the tail into one "other"
30
+ * series or split the chart. On a light surface three of the eight sit below 3:1 against white,
31
+ * so identity must not rest on colour alone: keep the legend, or label the series directly.
32
+ */
33
+ export function chartTokens(el) {
34
+ const target = (el && el.nodeType === 1 ? el : null)
35
+ || (typeof document !== 'undefined' ? document.documentElement : null);
36
+ if (!target || typeof getComputedStyle !== 'function') return { ...FALLBACK, palette: FALLBACK.cat };
37
+ const s = getComputedStyle(target);
38
+ return {
39
+ palette: FALLBACK.cat.map((hex, i) => read(s, `--uic-cat-${i + 1}`, hex)),
40
+ ink: read(s, '--uic-ink', FALLBACK.ink),
41
+ ink2: read(s, '--uic-ink-2', FALLBACK.ink2),
42
+ mute: read(s, '--uic-mute', FALLBACK.mute),
43
+ line: read(s, '--uic-line', FALLBACK.line),
44
+ lineSoft: read(s, '--uic-line-soft', FALLBACK.lineSoft),
45
+ surface: read(s, '--uic-surface', FALLBACK.surface),
46
+ brand: read(s, '--uic-brand', FALLBACK.brand),
47
+ ok: read(s, '--uic-ok', FALLBACK.ok),
48
+ warn: read(s, '--uic-warn', FALLBACK.warn),
49
+ bad: read(s, '--uic-fail-ink', FALLBACK.bad),
50
+ font: read(s, '--uic-font', FALLBACK.font),
51
+ };
52
+ }
@@ -0,0 +1,33 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { chartTokens } from './tokens.js';
3
+
4
+ /**
5
+ * chartTokens(), re-read when the theme changes.
6
+ *
7
+ * A chart's colours are baked into its option at build time, so flipping light↔dark leaves every
8
+ * chart on the page painted for the theme that is gone until something re-renders it. There is no
9
+ * event for "the tokens changed", so this watches the two things that change them: the attributes
10
+ * a theme is switched with (a class or data-* on <html>/<body>), and the OS preference.
11
+ *
12
+ * Returns [tokens, ref] — put the ref on the element the chart lives in, or leave it unused and
13
+ * the document's own tokens are read.
14
+ */
15
+ export function useChartTokens() {
16
+ const ref = useRef(null);
17
+ const [tokens, setTokens] = useState(() => chartTokens(null));
18
+ const reread = useCallback(() => setTokens(chartTokens(ref.current)), []);
19
+
20
+ useEffect(() => {
21
+ reread();
22
+ if (typeof MutationObserver !== 'function') return undefined;
23
+ const obs = new MutationObserver(reread);
24
+ const opts = { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] };
25
+ obs.observe(document.documentElement, opts);
26
+ if (document.body) obs.observe(document.body, opts);
27
+ const mq = typeof matchMedia === 'function' ? matchMedia('(prefers-color-scheme: dark)') : null;
28
+ mq?.addEventListener?.('change', reread);
29
+ return () => { obs.disconnect(); mq?.removeEventListener?.('change', reread); };
30
+ }, [reread]);
31
+
32
+ return [tokens, ref];
33
+ }
@@ -7,9 +7,18 @@
7
7
  //
8
8
  // - transport is injected. The console fetches with an auth header; a kit is same-origin and
9
9
  // needs none. `fetchFile` defaults to a plain fetch, which is right for same-origin callers.
10
- // - markdown and code render through props. The package does not depend on a markdown library,
11
- // and it already ships one code renderer (CodeBlock) — adding a second highlighter to render
12
- // the same text twice is the duplication this component exists to argue against.
10
+ // - markdown, code and SPREADSHEETS render through props. The package does not depend on a
11
+ // markdown library, and it already ships one code renderer (CodeBlock) — adding a second
12
+ // highlighter to render the same text twice is the duplication this component exists to
13
+ // argue against.
14
+ //
15
+ // `parseWorkbook` is the same rule, learned the hard way: this file used to `await
16
+ // import('xlsx')` directly, which put a spreadsheet library in the dependency graph of every
17
+ // app that imports anything from this package's root. A kit that shows slides, or charts,
18
+ // and has never heard of a spreadsheet then fails to BUILD — Rollup cannot resolve a dynamic
19
+ // import of a package that is not installed. The rule the chart entry states ("an app that
20
+ // imports a Button must not resolve a charting library") was already being broken here.
21
+ // Without the prop, spreadsheets fall through to the download, honestly labelled.
13
22
  //
14
23
  // `officePdfUrl` is how a caller offers a server-rendered PDF for formats no browser draws
15
24
  // (pptx, docx, odp). Without it those fall through to the download, honestly labelled.
@@ -78,8 +87,13 @@ const defaultDownload = (url, name) => {
78
87
  document.body.appendChild(a); a.click(); a.remove();
79
88
  };
80
89
 
90
+ /**
91
+ * `parseWorkbook(arrayBuffer)` → `[{ name, filled, rows }]`, one entry per tab, where `rows` is
92
+ * an array-of-arrays (header row first) and `filled` says whether the tab has anything in it at
93
+ * all. Async, so the caller can load its spreadsheet library lazily.
94
+ */
81
95
  export function FilePreview({
82
- file, onClose, fetchFile, officePdfUrl, renderMarkdown, onDownload, title,
96
+ file, onClose, fetchFile, officePdfUrl, renderMarkdown, parseWorkbook, onDownload, title,
83
97
  }) {
84
98
  const { url, name } = file || {};
85
99
  const [st, setSt] = useState({ kind: 'loading' });
@@ -113,18 +127,12 @@ export function FilePreview({
113
127
  return;
114
128
  }
115
129
  if (kind === 'sheet') {
130
+ if (!parseWorkbook) {
131
+ setSt({ kind: 'binary', error: 'This format has no inline preview here — download it to open it.' });
132
+ return;
133
+ }
116
134
  try {
117
- const buf = await res.arrayBuffer();
118
- const XLSX = await import('xlsx');
119
- const wb = XLSX.read(buf, { type: 'array' });
120
- // sheet_to_json THROWS on a sheet with no '!ref' — an empty one — and losing that threw
121
- // away the whole workbook rather than one tab. Tools routinely leave an empty default
122
- // Sheet1 in front of the real data, so this was most spreadsheets.
123
- const sheets = wb.SheetNames.map((n) => {
124
- const ws = wb.Sheets[n] || {};
125
- const filled = Boolean(ws['!ref']);
126
- return { name: n, filled, rows: filled ? XLSX.utils.sheet_to_json(ws, { header: 1, raw: false }) : [] };
127
- });
135
+ const sheets = await parseWorkbook(await res.arrayBuffer());
128
136
  // Open on the first sheet that has something: opening on an empty one reads as a broken
129
137
  // preview rather than as an empty tab.
130
138
  const first = sheets.findIndex((s) => s.filled);
@@ -147,7 +155,7 @@ export function FilePreview({
147
155
  })().catch(() => { if (alive) setSt({ kind: 'binary', error: 'Could not load this file.' }); });
148
156
 
149
157
  return () => { alive = false; if (obj) URL.revokeObjectURL(obj); };
150
- }, [url, name, fetchFile, officePdfUrl]);
158
+ }, [url, name, fetchFile, officePdfUrl, parseWorkbook]);
151
159
 
152
160
  const download = () => (onDownload ? onDownload(url, name) : defaultDownload(url, name));
153
161
 
@@ -0,0 +1,82 @@
1
+ // Panel — the frame around one thing on a board: a header you can grab, a body, and the two
2
+ // states that body spends most of its life in.
3
+ //
4
+ // The states are the reason this exists. A panel whose content is being fetched has to hold its
5
+ // box (a grid that reflows as four requests land in four different orders is unreadable), and a
6
+ // panel whose content FAILED has to show why, verbatim and selectable. Products keep replacing
7
+ // that second one with "Something went wrong", which throws away the one string that tells the
8
+ // person what to fix.
9
+ //
10
+ // `loading` blanks the body — the first fetch, when there is nothing to keep. `busy` leaves the
11
+ // content up and marks the header — a refresh, where blanking a chart the person is reading to
12
+ // redraw the same chart is worse than waiting.
13
+ import { Button } from './form.jsx';
14
+
15
+ /**
16
+ * title the panel's name
17
+ * titleAs heading level, so a board fits YOUR document outline ('h3')
18
+ * meta quiet second line under the title (when it was refreshed, what it counts)
19
+ * actions controls in the header, after the title — never drag the panel
20
+ * footer quiet strip under the body
21
+ * loading no content yet: the body is a placeholder of the same size
22
+ * busy content is up but being refreshed: the header shows it
23
+ * error what went wrong, verbatim. Shown in monospace, selectable, and scrollable —
24
+ * a query error is a thing people copy
25
+ * errorDetail extra context under the message, folded away (the statement that failed)
26
+ * onRetry absent → no retry control is drawn, rather than a dead one
27
+ */
28
+ export function Panel(props) {
29
+ const {
30
+ title, titleAs: Heading = 'h3', meta, actions, footer,
31
+ loading = false, loadingLabel = 'Loading',
32
+ busy = false, busyLabel = 'Refreshing',
33
+ error = null, errorTitle = 'This panel could not load',
34
+ errorDetail = null, detailLabel = 'Details',
35
+ onRetry, retryLabel = 'Try again',
36
+ className = '', classNames = {}, children,
37
+ } = props;
38
+
39
+ const body = loading ? (
40
+ <div className="uic-panel-load">
41
+ <span className="uic-panel-load-bar" />
42
+ <span className="uic-panel-load-bar" />
43
+ <span className="uic-panel-load-bar" />
44
+ <span className="uic-sr">{loadingLabel}</span>
45
+ </div>
46
+ ) : error ? (
47
+ <div className="uic-panel-fail">
48
+ <p className="uic-panel-fail-t">{errorTitle}</p>
49
+ <pre className="uic-panel-fail-m">{error}</pre>
50
+ {errorDetail ? (
51
+ <details className="uic-panel-fail-d">
52
+ <summary>{detailLabel}</summary>
53
+ <div className="uic-panel-fail-dd">{errorDetail}</div>
54
+ </details>
55
+ ) : null}
56
+ {onRetry ? (
57
+ <div className="uic-panel-fail-act">
58
+ <Button size="sm" onClick={onRetry}>{retryLabel}</Button>
59
+ </div>
60
+ ) : null}
61
+ </div>
62
+ ) : children;
63
+
64
+ return (
65
+ <section
66
+ className={['uic-panel', className, classNames.root || ''].filter(Boolean).join(' ')}
67
+ aria-busy={loading || busy || undefined}
68
+ >
69
+ <header className={['uic-panel-head', classNames.head || ''].filter(Boolean).join(' ')}>
70
+ <div className="uic-panel-titles">
71
+ {title ? <Heading className="uic-panel-title">{title}</Heading> : null}
72
+ {meta ? <p className="uic-panel-meta">{meta}</p> : null}
73
+ </div>
74
+ {actions ? <div className="uic-panel-acts">{actions}</div> : null}
75
+ </header>
76
+ {/* One indeterminate line, not a percentage: nothing here knows how far along a refresh is. */}
77
+ {busy ? <div className="uic-panel-busy" role="status" aria-label={busyLabel} /> : null}
78
+ <div className={['uic-panel-body', classNames.body || ''].filter(Boolean).join(' ')}>{body}</div>
79
+ {footer ? <footer className="uic-panel-foot">{footer}</footer> : null}
80
+ </section>
81
+ );
82
+ }
@@ -0,0 +1,232 @@
1
+ // PanelGrid — a column grid of panels you can drag and resize, and a read-only mode that is the
2
+ // default. The layout is a prop: this component never owns it, it proposes the next one.
3
+ //
4
+ // Written here rather than taken from react-grid-layout on purpose. What a dashboard needs is
5
+ // this file: cells → pixels, a pointer drag, a resize corner, and gravity. What the dependency
6
+ // adds around that is three more packages (draggable / resizable / a deep-equal), a stylesheet
7
+ // with its own hardcoded colours (its drop placeholder is literally `background: red`), and no
8
+ // keyboard path at all. It is also not a peer any host here already owns, so every app that
9
+ // imports a Button would pay for it. The subset below has no dependencies, themes from the same
10
+ // --uic-* tokens as everything else, and arranges a panel from the keyboard.
11
+ import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
12
+ import { compact, layoutRows, moveItem, nudgeItem, resizeItem, sameLayout, sortLayout } from './layout.js';
13
+
14
+ /** Measure the box we actually get. A grid inside a scroller that also holds a side panel gets a
15
+ * stale width from anything that measures once — the observer reports every change. */
16
+ function useMeasuredWidth() {
17
+ const ref = useRef(null);
18
+ const [width, setWidth] = useState(0);
19
+ useLayoutEffect(() => {
20
+ const el = ref.current;
21
+ if (!el) return undefined;
22
+ const measure = () => setWidth(el.clientWidth);
23
+ measure();
24
+ const ro = new ResizeObserver(measure);
25
+ ro.observe(el);
26
+ return () => ro.disconnect();
27
+ }, []);
28
+ return [ref, width];
29
+ }
30
+
31
+ // A press that lands on one of these is that control's press, not the start of a drag.
32
+ const NO_DRAG = 'button, a, input, select, textarea, [data-uic-nodrag]';
33
+
34
+ /**
35
+ * layout [{i, x, y, w, h, minW?, minH?, maxW?, maxH?, static?}] — cells, not pixels
36
+ * children one element per layout entry, matched by `key`
37
+ * cols columns across the full width (12)
38
+ * rowHeight px per row (40)
39
+ * gap px between cells (12)
40
+ * editable false (default): nothing drags, nothing resizes, no handle is drawn
41
+ * dragHandle selector a press must land inside to start a move ('.uic-panel-head')
42
+ * stackAt below this container width the grid becomes ONE column in layout order and stops
43
+ * being arrangeable — twelve columns across a phone is 32px each, and dragging a
44
+ * panel between two cells nobody can see is not an interaction worth keeping
45
+ * resizeLabel (id) => the handle's accessible name; name the panel in it
46
+ * onLayoutChange(next) fires ONCE per interaction, on release — not per pixel, because the host
47
+ * is usually writing the result to a document
48
+ */
49
+ export function PanelGrid(props) {
50
+ const {
51
+ layout = [], children, cols = 12, rowHeight = 40, gap = 12,
52
+ editable = false, dragHandle = '.uic-panel-head', stackAt = 640,
53
+ onLayoutChange, resizeLabel, className = '',
54
+ } = props;
55
+
56
+ const [wrapRef, width] = useMeasuredWidth();
57
+ // {id, mode, origin, px, py, dx, dy, preview} while a pointer interaction is live, else null.
58
+ // The ref is what the pointer handlers read and write (they run between renders); the state is
59
+ // the same value, kept only so React redraws.
60
+ const [drag, setDrag] = useState(null);
61
+ const dragRef = useRef(null);
62
+ // A drag ends in a click on whatever was under the pointer. Swallow exactly that one.
63
+ const swallowClick = useRef(false);
64
+
65
+ const stacked = width > 0 && width < stackAt;
66
+ const arrangeable = editable && !stacked;
67
+ const live = drag ? drag.preview : layout;
68
+
69
+ const colW = width > 0 ? (width - gap * (cols - 1)) / cols : 0;
70
+ const cellW = colW + gap;
71
+ const cellH = rowHeight + gap;
72
+ const rowsToPx = (h) => h * rowHeight + (h - 1) * gap;
73
+
74
+ // Stacked: one column, in reading order, each panel keeping its own height.
75
+ const stack = useMemo(() => {
76
+ if (!stacked) return null;
77
+ const tops = new Map();
78
+ let y = 0;
79
+ for (const it of sortLayout(live)) {
80
+ tops.set(it.i, y);
81
+ y += rowsToPx(it.h || 1) + gap;
82
+ }
83
+ return { tops, height: Math.max(0, y - gap) };
84
+ }, [stacked, live, rowHeight, gap]);
85
+
86
+ const rows = layoutRows(live);
87
+ const height = stacked ? stack.height : (rows ? rowsToPx(rows) : 0);
88
+
89
+ const commit = useCallback((next) => {
90
+ if (onLayoutChange && !sameLayout(next, layout)) onLayoutChange(next);
91
+ }, [onLayoutChange, layout]);
92
+
93
+ // ── pointer interaction ───────────────────────────────────────────────────
94
+ // The listeners go on in the pointerdown handler itself, NOT in an effect keyed on the drag
95
+ // state: an effect runs after React has re-rendered, and every pointer move that arrived in
96
+ // between is simply gone. A quick flick then moves nothing at all.
97
+ const detach = useRef(null);
98
+ useEffect(() => () => detach.current?.(), []); // a drag must not outlive the grid
99
+
100
+ const start = (id, mode) => (e) => {
101
+ if (!arrangeable || e.button !== 0) return;
102
+ const item = layout.find((it) => it.i === id);
103
+ if (!item || item.static) return;
104
+ if (mode === 'move' && (!e.target.closest(dragHandle) || e.target.closest(NO_DRAG))) return;
105
+ e.preventDefault();
106
+ detach.current?.();
107
+ const begin = { id, mode, origin: item, px: e.clientX, py: e.clientY, dx: 0, dy: 0, preview: layout };
108
+ dragRef.current = begin;
109
+ setDrag(begin);
110
+
111
+ const onMove = (ev) => {
112
+ const d = dragRef.current;
113
+ if (!d) return;
114
+ const dx = ev.clientX - d.px;
115
+ const dy = ev.clientY - d.py;
116
+ if (Math.abs(dx) > 3 || Math.abs(dy) > 3) swallowClick.current = true;
117
+ const cx = Math.round(dx / cellW);
118
+ const cy = Math.round(dy / cellH);
119
+ const preview = d.mode === 'move'
120
+ ? moveItem(layout, d.id, d.origin.x + cx, d.origin.y + cy, cols)
121
+ : resizeItem(layout, d.id, d.origin.w + cx, d.origin.h + cy, cols);
122
+ dragRef.current = { ...d, dx, dy, preview };
123
+ setDrag(dragRef.current);
124
+ };
125
+ const end = (commitIt) => () => {
126
+ const d = dragRef.current;
127
+ dragRef.current = null;
128
+ off();
129
+ setDrag(null);
130
+ if (d && commitIt) commit(d.preview);
131
+ };
132
+ const onUp = end(true);
133
+ // Escape abandons the interaction: the preview is dropped and nothing is committed.
134
+ const onKey = (ev) => { if (ev.key === 'Escape') end(false)(); };
135
+ function off() {
136
+ detach.current = null;
137
+ window.removeEventListener('pointermove', onMove);
138
+ window.removeEventListener('pointerup', onUp);
139
+ window.removeEventListener('pointercancel', onUp);
140
+ window.removeEventListener('keydown', onKey);
141
+ }
142
+ detach.current = off;
143
+ window.addEventListener('pointermove', onMove);
144
+ window.addEventListener('pointerup', onUp);
145
+ window.addEventListener('pointercancel', onUp);
146
+ window.addEventListener('keydown', onKey);
147
+ };
148
+
149
+ const onClickCapture = (e) => {
150
+ if (!swallowClick.current) return;
151
+ swallowClick.current = false;
152
+ e.stopPropagation();
153
+ e.preventDefault();
154
+ };
155
+
156
+ // ── keyboard interaction ──────────────────────────────────────────────────
157
+ // The same handle answers arrows (resize) and shift+arrows (move): a panel that can only be
158
+ // arranged by dragging cannot be arranged by everyone.
159
+ const onHandleKey = (id) => (e) => {
160
+ const step = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];
161
+ if (!step) return;
162
+ const item = layout.find((it) => it.i === id);
163
+ if (!item) return;
164
+ e.preventDefault();
165
+ commit(e.shiftKey
166
+ ? nudgeItem(layout, id, step[0], step[1], cols)
167
+ : resizeItem(layout, id, item.w + step[0], item.h + step[1], cols));
168
+ };
169
+
170
+ const boxOf = (it) => (stacked
171
+ ? { left: 0, top: stack.tops.get(it.i), width, height: rowsToPx(it.h || 1) }
172
+ : { left: it.x * cellW, top: it.y * cellH, width: it.w * colW + (it.w - 1) * gap, height: rowsToPx(it.h) });
173
+
174
+ const byId = new Map(live.map((it) => [it.i, it]));
175
+ const ghost = drag && drag.mode === 'move' && byId.has(drag.id) ? boxOf(byId.get(drag.id)) : null;
176
+ const cls = ['uic-pg', arrangeable ? 'is-editable' : '', stacked ? 'is-stacked' : '', className]
177
+ .filter(Boolean).join(' ');
178
+
179
+ return (
180
+ <div
181
+ ref={wrapRef}
182
+ className={cls}
183
+ style={{ height }}
184
+ onClickCapture={onClickCapture}
185
+ // A cancelled pointer (a phone call, a lost pointer capture) leaves no click to swallow.
186
+ // Clearing on the next press means a stale flag can never eat someone else's click.
187
+ onPointerDownCapture={() => { swallowClick.current = false; }}
188
+ >
189
+ {ghost ? <div className="uic-pg-ghost" aria-hidden="true" style={ghost} /> : null}
190
+ {width > 0 && React.Children.map(children, (child) => {
191
+ if (!React.isValidElement(child) || child.key == null) return null;
192
+ const id = String(child.key).replace(/^\.\$/, '');
193
+ const it = byId.get(id);
194
+ if (!it) return null; // no cell for this child: nowhere to put it
195
+ const moving = drag && drag.id === id;
196
+ // While moving, the panel follows the pointer in pixels and the ghost marks the cell it
197
+ // would land in; a resize snaps, so the corner never lags the pointer's own cell.
198
+ const offset = moving && drag.mode === 'move'
199
+ ? { transform: `translate(${drag.dx}px, ${drag.dy}px)` } : null;
200
+ return (
201
+ <div
202
+ className={'uic-pg-item' + (moving ? ' is-moving' : '')}
203
+ style={{ ...boxOf(it), ...offset }}
204
+ onPointerDown={arrangeable ? start(id, 'move') : undefined}
205
+ >
206
+ {child}
207
+ {arrangeable && !it.static ? (
208
+ <button
209
+ type="button"
210
+ className="uic-pg-handle"
211
+ aria-label={resizeLabel ? resizeLabel(id) : 'Resize panel. Arrow keys resize it; shift with arrow keys moves it past its neighbours.'}
212
+ onPointerDown={start(id, 'resize')}
213
+ onKeyDown={onHandleKey(id)}
214
+ >
215
+ <svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true">
216
+ <path d="M9 1v8H1" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
217
+ </svg>
218
+ </button>
219
+ ) : null}
220
+ </div>
221
+ );
222
+ })}
223
+ </div>
224
+ );
225
+ }
226
+
227
+ /** Gravity applied to a layout you built yourself. A new panel added with `y: Infinity` lands at
228
+ * the bottom; this is what turns that into a real row. */
229
+ export function packLayout(layout, cols = 12) {
230
+ const bottom = layoutRows(layout.filter((it) => Number.isFinite(it.y)));
231
+ return compact(layout.map((it) => (Number.isFinite(it.y) ? it : { ...it, y: bottom })), cols);
232
+ }