An open source design system that's fully customizable and agent ready
TypeScript
fix(useResizable): a drag saves its size once, when it ends, not on every move (#7782)
Christopher Chedeau94eb29bea652
diff --git a/.changeset/resizable-save-once-per-drag.md b/.changeset/resizable-save-once-per-drag.mdnew file mode 100644index 0000000000..5a3fbdb36b--- /dev/null+++ b/.changeset/resizable-save-once-per-drag.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] `useResizable` with `autoSaveId` (and `SideNav` with `resizable={{autoSaveId}}`) now saves a dragged size to `localStorage` once, when the drag ends, instead of on every pointer move. Every write reached each other open tab of the site as a `storage` event, so one drag sent dozens of them. The storage key, the stored format and the size saved at the end are unchanged, and keyboard steps, `resize()`, `collapse()` and `expand()` still save at once.++@vjeuxdiff --git a/packages/core/src/Resizable/Resizable.spec.md b/packages/core/src/Resizable/Resizable.spec.mdindex 0131ce6878..47b60b72b7 100644--- a/packages/core/src/Resizable/Resizable.spec.md+++ b/packages/core/src/Resizable/Resizable.spec.md@@ -39,15 +39,15 @@ system_specs: [spec:AST-010, spec:AST-020, spec:AST-085]## Contract at a glance-| Area | Contract |-| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | `useResizable` (size, bounds, collapse, snaps, persistence) and `ResizeHandle` (`direction`, `position`, `isReversed`, `isDisabled`, `hasDivider`, `isAlwaysVisible`, `pillPlacement`, `label`, `resizable`, `children`), plus the `pixel()` and `percent()` size helpers. |-| Behavior | The hook owns a region's size in pixels; the Handle is a focusable window splitter that resizes it by pointer and keyboard. |-| End-user impact | People drag or use the keyboard to resize a panel, collapse and restore it, and have the size remembered, with the divider moving the way the page reads. |-| Builder impact | None; the record describes shipped behavior. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Implementation gaps are listed under Current-state impact. |-| Review checks | Reject a Handle that loses its splitter role, values, or keys, arrows that move against the reading direction, a percentage default that rescales, or state, paint, storage, and ARIA that disagree. |-| Governing rules | `spec:AST-010`; `spec:AST-020` FR15 (APG Window Splitter); `spec:AST-085`; `architecture:interaction-modality`; `architecture:component-theming-surface`; `architecture:public-component-api`. |+| Area | Contract |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `useResizable` (size, bounds, collapse, snaps, persistence) and `ResizeHandle` (`direction`, `position`, `isReversed`, `isDisabled`, `hasDivider`, `isAlwaysVisible`, `pillPlacement`, `label`, `resizable`, `children`), plus the `pixel()` and `percent()` size helpers. |+| Behavior | The hook owns a region's size in pixels; the Handle is a focusable window splitter that resizes it by pointer and keyboard. |+| End-user impact | People drag or use the keyboard to resize a panel, collapse and restore it, and have the size remembered, with the divider moving the way the page reads. |+| Builder impact | None; the record describes shipped behavior. |+| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Implementation gaps are listed under Current-state impact. |+| Review checks | Reject a Handle that loses its splitter role, values, or keys, arrows that move against the reading direction, a percentage default that rescales, or settled state, paint, storage, and ARIA that disagree; storage holds the last settled size and receives the final size once when a drag ends, cancels, or unmounts. |+| Governing rules | `spec:AST-010`; `spec:AST-020` FR15 (APG Window Splitter); `spec:AST-085`; `architecture:interaction-modality`; `architecture:component-theming-surface`; `architecture:public-component-api`. |This table is a review projection; the body below is authoritative.@@ -136,7 +136,7 @@ Consumer migration instructions belong in consumer docs and release notes.| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- || FR1 | ResizeHandle renders one focusable Handle and one enlarged Grab zone (a `--spacing-4` strip on the resize axis); the default render also contains a Grip pill, and caller `children` replace the pill. | Current source, docs, and tests || FR2 | The Handle carries `resize-handle`, the Grip pill carries `resize-handle-pill`, and the Grab zone carries no public target. | Current source and docs |-| FR3 | Pointer drag, keyboard, double-click collapse, snapping, persistence, reversal, and size behavior are owned by ResizeHandle and useResizable; dragging under right-to-left inverts the pointer delta so the divider follows the pointer. A disabled Handle ignores pointer and keyboard input and exposes `aria-disabled`, and keeps its tab stop (`spec:AST-085` FR1). Implementation gap: a disabled Handle sets `tabIndex={-1}` (Current-state impact). | Current source, docs, and tests |+| FR3 | Pointer drag, keyboard, double-click collapse, snapping, persistence, reversal, and size behavior are owned by ResizeHandle and useResizable; dragging under right-to-left inverts the pointer delta so the divider follows the pointer. A disabled Handle ignores pointer and keyboard input and exposes `aria-disabled`, and keeps its tab stop (`spec:AST-085` FR1). With `autoSaveId`, storage holds the last settled size and receives the final size once when a drag ends, cancels, or unmounts. Implementation gap: a disabled Handle sets `tabIndex={-1}` (Current-state impact). | Current source, docs, and tests || FR4 | The Handle reflects the documented `direction` visual state on its target (`architecture:component-theming-surface` INV6). Implementation gap: it reflects no `direction` (Current-state impact). | Current source and docs || FR5 | A `percent(value, {min: pixel(value)})` or `percent(value, {max: pixel(value)})` resolves against one basis — the supplied container, or the viewport when no `containerRef` is given (`spec:AST-010` FR1, FR2); as a default it selects pixels once, and as a bound it stays live and clamps the selected pixels. A descriptor with both or neither bound is invalid. Selected state, persistence, callbacks, paint, and ARIA are pixels. | `spec:AST-010`; current source and tests || FR6 | `minSize` and `maxSize` are the bound props; numeric values are pixels. When resolved bounds conflict, the maximum wins. | `spec:AST-010`; current source and tests |@@ -254,7 +254,7 @@ Consumer migration instructions belong in consumer docs and release notes.| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- || FR1 | `ResizeHandle.test.tsx`; stable visual baseline `core-resizable--horizontal-split` | Default, collapsed, both axes | Handle and Grab zone regressions fail focused tests; a changed default handle comes back changed for review. Gap: no test renders `children` to prove they replace the Grip pill. | `audit:Resizable/anatomy` || FR2 | `themingTargets.test.ts`; source review | Handle, Grip pill, Grab zone | A removed target fails the inventory. `themingTargets.test.ts` catches only a renamed or undocumented target; no check fails if the Handle or Grip pill stops carrying its target. | `audit:Resizable/theming` |-| FR3 | `ResizeHandle.test.tsx` and `useResizable.test.ts` | Pointer, keyboard, snap, collapse, persistence; RTL drag; disabled keyboard | A changed transformation, an RTL drag that moves against the pointer, or keyboard input that resizes a disabled Handle fails. Gap: no test covers disabled pointer input or the disabled tab stop. | `audit:Resizable/behavior` |+| FR3 | `ResizeHandle.test.tsx` and `useResizable.test.ts`; storage timing: `ResizeHandle.test.tsx` ("saves the size once, when a drag ends on …", "saves the dragged size once when the split unmounts mid-drag", "still saves each keyboard step at once") and `useResizable.test.ts` ("writes the size a drag reached once, after … releases it", "writes the final size once when the release comes before the last move renders", "keeps the size a region was dragged to when it unmounts mid-drag", "writes only the re-clamped size when the container shrank mid-drag") | Pointer, keyboard, snap, collapse, persistence; RTL drag; disabled keyboard | A changed transformation, an RTL drag that moves against the pointer, keyboard input that resizes a disabled Handle, or a per-move, stale or missing final storage write fails. Gap: no test covers disabled pointer input or the disabled tab stop. | `audit:Resizable/behavior` || FR4 | Source and docs comparison | Horizontal and vertical Handle | Gap: no test detects that the documented `direction` is not reflected. | `audit:Resizable/theming` || FR5, ORD1–ORD3 | `useResizable.test.ts`, `utils.test.ts`, typecheck | Floor, ceiling, default; invalid shapes; basis changes; numeric container parity | Wrong resolution, a rescaled default, a stale clamp, an observer leak, or state, paint, storage, and ARIA that disagree fails. | `audit:Resizable/behavior` || FR6 | `useResizable.test.ts`; typecheck | Numeric bounds; conflicting bounds | A removed alias that type-checks, a numeric bound that is not pixels, or a minimum that wins a conflict fails. | `audit:Resizable/behavior` |diff --git a/packages/core/src/Resizable/ResizeHandle.test.tsx b/packages/core/src/Resizable/ResizeHandle.test.tsxindex 4496c339d5..3a9c52748c 100644--- a/packages/core/src/Resizable/ResizeHandle.test.tsx+++ b/packages/core/src/Resizable/ResizeHandle.test.tsx@@ -948,6 +948,111 @@ describe('ResizeHandle', () => {expect(document.body.style.userSelect).toBe('');});+ // --- Persistence ---++ it.each([+ ['pointerup', fireEvent.pointerUp],+ ['pointercancel', fireEvent.pointerCancel],+ ['lostpointercapture', fireEvent.lostPointerCapture],+ ])('saves the size once, when a drag ends on %s', (name, finish) => {+ // Every write reaches each other open document of the origin as a+ // `storage` event, so the sizes a drag passes through stay out of+ // storage: only the size it ends on is written.+ const key = `astryx-resizable:drag-${name}`;+ render(+ <Harness+ config={{+ defaultSize: 200,+ minSize: 100,+ maxSize: 400,+ autoSaveId: `drag-${name}`,+ }}+ />,+ );+ const setItem = vi.spyOn(Storage.prototype, 'setItem');+ const writes = () => setItem.mock.calls.filter(([k]) => k === key);+ try {+ const hitArea = getHitArea();+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});+ for (let x = 1; x <= 30; x++) {+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: x, clientY: 0});+ }+ expect(getSeparator()).toHaveAttribute('aria-valuenow', '230');+ expect(writes()).toHaveLength(0);++ finish(hitArea, {pointerId: 1, clientX: 30, clientY: 0});+ expect(writes()).toEqual([+ [key, JSON.stringify({size: 230, isCollapsed: false})],+ ]);+ } finally {+ setItem.mockRestore();+ localStorage.removeItem(key);+ }+ });++ it('saves the dragged size once when the split unmounts mid-drag', () => {+ // The handle's own cleanup ends the gesture, so the size it reached+ // still reaches storage without a per-move write.+ const key = 'astryx-resizable:drag-unmount';+ const {unmount} = render(+ <Harness+ config={{+ defaultSize: 200,+ minSize: 100,+ maxSize: 400,+ autoSaveId: 'drag-unmount',+ }}+ />,+ );+ const setItem = vi.spyOn(Storage.prototype, 'setItem');+ const writes = () => setItem.mock.calls.filter(([k]) => k === key);+ try {+ const hitArea = getHitArea();+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});+ for (let x = 1; x <= 30; x++) {+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: x, clientY: 0});+ }+ expect(getSeparator()).toHaveAttribute('aria-valuenow', '230');+ expect(writes()).toHaveLength(0);++ unmount();+ expect(writes()).toEqual([+ [key, JSON.stringify({size: 230, isCollapsed: false})],+ ]);+ } finally {+ setItem.mockRestore();+ localStorage.removeItem(key);+ }+ });++ it('still saves each keyboard step at once', () => {+ const key = 'astryx-resizable:keyboard-steps';+ render(+ <Harness+ config={{+ defaultSize: 200,+ minSize: 100,+ maxSize: 400,+ autoSaveId: 'keyboard-steps',+ }}+ />,+ );+ const setItem = vi.spyOn(Storage.prototype, 'setItem');+ try {+ for (let i = 0; i < 3; i++) {+ fireEvent.keyDown(getSeparator(), {key: 'ArrowRight'});+ }+ expect(+ setItem.mock.calls+ .filter(([k]) => k === key)+ .map(([, value]) => (JSON.parse(value) as {size: number}).size),+ ).toEqual([210, 220, 230]);+ } finally {+ setItem.mockRestore();+ localStorage.removeItem(key);+ }+ });+// --- RTL pointer-drag direction ---it('drives the region with the raw pointer delta under LTR', () => {diff --git a/packages/core/src/Resizable/useResizable.test.ts b/packages/core/src/Resizable/useResizable.test.tsindex 72e5b2e773..187e9b966f 100644--- a/packages/core/src/Resizable/useResizable.test.ts+++ b/packages/core/src/Resizable/useResizable.test.ts@@ -158,16 +158,72 @@ describe('useResizable persistence', () => {act(() => result.current.resize(300));act(() => result.current.props._onResizeStart());act(() => result.current.props._onResizeMove(-270));-expect(result.current.isCollapsed).toBe(true);- expect(readStored()).toEqual({size: 300, isCollapsed: true});// A continued drag below the threshold must not clobber the saved width.act(() => result.current.props._onResizeMove(-275));+ act(() => result.current.props._onResizeEnd());+ expect(readStored()).toEqual({size: 300, isCollapsed: true});+act(() => result.current.expand());expect(result.current.size).toBe(300);});+ it.each([+ ['_onResizeEnd', (p: ResizableProps) => p._onResizeEnd()],+ ['_onResizeCancel', (p: ResizableProps) => p._onResizeCancel?.()],+ ])(+ 'writes the size a drag reached once, after %s releases it',+ (_name, finish) => {+ const {result} = renderHook(() => useResizable(BASE_CONFIG));+ const setItem = vi.spyOn(Storage.prototype, 'setItem');+ try {+ act(() => result.current.props._onResizeStart());+ act(() => result.current.props._onResizeMove(20));+ act(() => result.current.props._onResizeMove(40));+ expect(result.current.size).toBe(300);+ expect(setItem).not.toHaveBeenCalled();++ act(() => finish(result.current.props));+ expect(setItem.mock.calls).toEqual([+ [KEY, JSON.stringify({size: 300, isCollapsed: false})],+ ]);+ } finally {+ setItem.mockRestore();+ }+ },+ );++ it('writes the final size once when the release comes before the last move renders', () => {+ const {result} = renderHook(() => useResizable(BASE_CONFIG));+ const setItem = vi.spyOn(Storage.prototype, 'setItem');+ try {+ act(() => result.current.props._onResizeStart());+ act(() => result.current.props._onResizeMove(20));+ expect(result.current.size).toBe(280);++ // One batch: the last move has not rendered when the release lands.+ act(() => {+ result.current.props._onResizeMove(40);+ result.current.props._onResizeEnd();+ });+ expect(result.current.size).toBe(300);+ expect(setItem.mock.calls).toEqual([+ [KEY, JSON.stringify({size: 300, isCollapsed: false})],+ ]);+ } finally {+ setItem.mockRestore();+ }+ });++ it('keeps the size a region was dragged to when it unmounts mid-drag', () => {+ const {result, unmount} = renderHook(() => useResizable(BASE_CONFIG));+ act(() => result.current.props._onResizeStart());+ act(() => result.current.props._onResizeMove(40));+ unmount();+ expect(readStored()).toEqual({size: 300, isCollapsed: false});+ });+it('does not touch storage without an autoSaveId', () => {const {result} = renderHook(() =>useResizable({defaultSize: 260, collapsible: true}),@@ -1604,6 +1660,44 @@ describe('useResizable percentage configuration (AST-010)', () => {expect(result.current.props._maxSizePx).toBe(100);expect(result.current.size).toBe(100);});++ it('writes only the re-clamped size when the container shrank mid-drag', () => {+ const key = 'astryx-resizable:pct-release';+ content = 600;+ const containerRef = makeContainer();+ const {result} = renderHook(() =>+ useResizable({+ containerRef,+ defaultSize: 200,+ maxSize: '50%',+ autoSaveId: 'pct-release',+ }),+ );+ expect(result.current.props._maxSizePx).toBe(300);+ const setItem = vi.spyOn(Storage.prototype, 'setItem');+ const writes = () => setItem.mock.calls.filter(([k]) => k === key);+ try {+ act(() => result.current.props._onResizeStart());+ act(() => result.current.props._onResizeMove(80));+ expect(result.current.size).toBe(280);+ // The bound holds at 300 until the release, which re-clamps to 200.+ act(() => {+ content = 400;+ StubResizeObserver.resizeAll();+ });+ expect(result.current.size).toBe(280);+ expect(writes()).toHaveLength(0);++ act(() => result.current.props._onResizeEnd());+ expect(result.current.size).toBe(200);+ expect(writes()).toEqual([+ [key, JSON.stringify({size: 200, isCollapsed: false})],+ ]);+ } finally {+ setItem.mockRestore();+ localStorage.removeItem(key);+ }+ });});});diff --git a/packages/core/src/Resizable/useResizable.ts b/packages/core/src/Resizable/useResizable.tsindex 968ee46f8e..f0a1d158df 100644--- a/packages/core/src/Resizable/useResizable.ts+++ b/packages/core/src/Resizable/useResizable.ts@@ -765,10 +765,14 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {// otherwise move the bound under the pointer; the new basis applies once the// gesture ends.const gestureBasisRef = useRef<number | null>(null);- // Only forces the render that releases the frozen basis when a gesture ends.+ // Only forces the render that ends a gesture: it releases the frozen basis,+ // and its commit writes the size the gesture settled on.const [gestureTick, setGestureTick] = useState(0);void gestureTick;const basis = gestureBasisRef.current ?? liveBasis;+ // The frozen basis also marks a gesture in flight, from `_onResizeStart`+ // until `_onResizeEnd` or `_onResizeCancel`.+ const isGestureActive = gestureBasisRef.current != null;const didWarnMinRef = useRef(false);const didWarnMaxRef = useRef(false);@@ -945,15 +949,52 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {}}, [resolvedMin, resolvedMax]);+ // The size a gesture in flight has reached, for a region that unmounts+ // before the gesture ends.+ const pendingWriteRef = useRef<{+ key: string;+ state: PersistedResizableState;+ } | null>(null);+useEffect(() => {+ // Synchronizes the `autoSaveId` entry in localStorage with the size.// Nothing is written while the basis is still the temporary stand-in. The// size on such a render is a placeholder, and persisting it overwrites the// real saved size with a value derived from a basis that was never real// (AST-010 Platform support, FR9).- if (autoSaveId && isBasisMeasured) {- persistState(autoSaveId, {size, isCollapsed});+ if (!autoSaveId || !isBasisMeasured) {+ pendingWriteRef.current = null;+ return;+ }+ // Nor while a gesture is in flight. A drag commits a new size on every+ // pointer move, and each write reaches every other open document of the+ // origin as a `storage` event.+ if (isGestureActive) {+ pendingWriteRef.current = {key: autoSaveId, state: {size, isCollapsed}};+ return;}- }, [size, isCollapsed, autoSaveId, isBasisMeasured]);+ // A gesture's one write happens here, in the commit that applies its+ // release, not in the handler that ended it: this render is the first to+ // know the final size. A basis that changed mid-gesture applies only at+ // the release and can re-clamp the size (AST-010 FR7), and a move the+ // release arrived before renders together with it. The handler sees+ // neither.+ pendingWriteRef.current = null;+ persistState(autoSaveId, {size, isCollapsed});+ }, [size, isCollapsed, autoSaveId, isBasisMeasured, isGestureActive]);++ // A region that unmounts mid-gesture never commits a release, so the size+ // the gesture reached is written on the way out.+ useEffect(+ () => () => {+ const pending = pendingWriteRef.current;+ pendingWriteRef.current = null;+ if (pending != null) {+ persistState(pending.key, pending.state);+ }+ },+ [],+ );const collapse = useCallback(() => {// The already-collapsed guard keeps a repeated call from re-notifying a@@ -1049,7 +1090,7 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {);// Releasing the frozen basis needs a render to apply whatever the basis- // became during the gesture.+ // became during the gesture; that render's commit writes the final size.const releaseGestureBasis = useCallback(() => {if (gestureBasisRef.current != null) {gestureBasisRef.current = null;@@ -1058,7 +1099,8 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {}, []);const onResizeEnd = useCallback(() => {- // Sizes are already committed during move; only the basis is held.+ // Sizes are already committed during move; the basis is held, and the+ // commit that releases it writes the final size to storage.releaseGestureBasis();}, [releaseGestureBasis]);@@ -1066,7 +1108,8 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {// capture, a handle unmounted mid-drag — is still over. It does not signal a// resize end (that is #5297's contract, and the sizes were committed during// move anyway), but the basis it froze has to come back, or every later- // percentage bound stays pinned to the container size at grab time.+ // percentage bound stays pinned to the container size at grab time, and the+ // size it reached has to reach storage.const onResizeCancel = releaseGestureBasis;// The maximum a handle REPORTS (End uses only a configured maximum). A