Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(Resizable): one internal createResizable factory, which useResizable's configuration-object form and ResizeHandle's resizable path go through (#9297)

Christopher Chedeauf9a696545762
diff --git a/.changeset/create-resizable-internal.md b/.changeset/create-resizable-internal.md
new file mode 100644
index 0000000000..75f7b70ba3
--- /dev/null
+++ b/.changeset/create-resizable-internal.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] The configuration-object `useResizable` builds on one internal resize region, through the same size model as before, so the region's state has one implementation.
+
+@vjeux
diff --git a/.changeset/resizable-percentage-default-after-hydration.md b/.changeset/resizable-percentage-default-after-hydration.md
new file mode 100644
index 0000000000..dcdceb7f8a
--- /dev/null
+++ b/.changeset/resizable-percentage-default-after-hydration.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A server-rendered `useResizable` region whose `defaultSize` is a percentage and that has no `containerRef` hydrates with the server's markup, then resolves the percentage against the window, instead of keeping the size the server resolved.
+
+@vjeux
diff --git a/.changeset/resizable-saved-size-after-hydration.md b/.changeset/resizable-saved-size-after-hydration.md
new file mode 100644
index 0000000000..c8379bc81e
--- /dev/null
+++ b/.changeset/resizable-saved-size-after-hydration.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A server-rendered `useResizable` region with an `autoSaveId` hydrates with the server's markup and takes its saved size in the next commit, so hydration no longer reports a mismatch and the handle announces the saved size.
+
+@vjeux
diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
index 5758b7021f..28de171077 100644
--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json
@@ -845,23 +845,7 @@
"spec quote"
],
"packages/core/src/Resizable/resizableModel.ts": ["#4790"],
- "packages/core/src/Resizable/useResizable.ts": [
- "#5297",
- "#5297",
- "AST-010",
- "AST-010",
- "AST-010",
- "AST-010",
- "FR10",
- "FR11",
- "FR6",
- "FR7",
- "FR9",
- "component:Resizable",
- "component:Resizable",
- "spec quote",
- "spec quote"
- ],
+ "packages/core/src/Resizable/useResizable.ts": ["#5297", "AST-010", "FR11"],
"packages/core/src/SegmentedControl/SegmentedControl.tsx": [
"FR1",
"FR2",
diff --git a/packages/core/src/Resizable/ResizeHandle.test.tsx b/packages/core/src/Resizable/ResizeHandle.test.tsx
index 7deb5483c8..3872c76778 100644
--- a/packages/core/src/Resizable/ResizeHandle.test.tsx
+++ b/packages/core/src/Resizable/ResizeHandle.test.tsx
@@ -2,8 +2,8 @@
/**
* @file ResizeHandle.test.tsx
- * @input Uses vitest, @testing-library/react, useResizable, ResizeHandle
- * @output Unit tests for ResizeHandle keyboard operability and ARIA state
+ * @input Uses vitest, @testing-library/react, react-dom, useResizable, ResizeHandle
+ * @output Unit tests for ResizeHandle keyboard operability, ARIA state and hydration
* @position Testing; validates ResizeHandle.tsx implementation
*
* SYNC: When ResizeHandle.tsx changes, update tests to match new behavior
@@ -51,6 +51,48 @@ function getHitArea(): HTMLElement {
return getSeparator().firstElementChild as HTMLElement;
}
+/**
+ * Hydrates `probe` over `serverHTML` and waits for the separator to announce
+ * `expected`, with no hydration mismatch on the way.
+ */
+async function hydrateExpecting(
+ probe: React.ReactElement,
+ serverHTML: string,
+ expected: string,
+): Promise<void> {
+ const container = document.createElement('div');
+ container.innerHTML = serverHTML;
+ document.body.appendChild(container);
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const recoverableErrors: unknown[] = [];
+ let root: ReturnType<typeof hydrateRoot>;
+ try {
+ await act(async () => {
+ root = hydrateRoot(container, probe, {
+ onRecoverableError: error => recoverableErrors.push(error),
+ });
+ });
+ await waitFor(() =>
+ expect(container.querySelector('[role="separator"]')).toHaveAttribute(
+ 'aria-valuenow',
+ expected,
+ ),
+ );
+ expect(recoverableErrors).toEqual([]);
+ expect(
+ consoleError.mock.calls.filter(call =>
+ String(call[0] ?? '')
+ .toLowerCase()
+ .includes('hydrat'),
+ ),
+ ).toEqual([]);
+ } finally {
+ await act(async () => root!.unmount());
+ consoleError.mockRestore();
+ container.remove();
+ }
+}
+
/** Stub region props, so drag assertions read the calls directly. */
function makeResizable(): ResizableProps {
return {
@@ -199,6 +241,48 @@ describe('ResizeHandle', () => {
}
});
+ it('hydrates a saved size with the server markup, then announces the saved size', async () => {
+ // The server has no storage, so it renders the default.
+ localStorage.clear();
+ const probe = (
+ <Harness
+ config={{
+ defaultSize: 200,
+ minSize: 100,
+ maxSize: 400,
+ autoSaveId: 'hydrate-saved',
+ }}
+ />
+ );
+ const serverHTML = renderToString(probe);
+ expect(serverHTML).toContain('aria-valuenow="200"');
+ localStorage.setItem(
+ 'astryx-resizable:hydrate-saved',
+ JSON.stringify({size: 300, isCollapsed: false}),
+ );
+ try {
+ await hydrateExpecting(probe, serverHTML, '300');
+ } finally {
+ localStorage.clear();
+ }
+ });
+
+ it('hydrates a percentage default with no container with the server markup, then resolves it against the window', async () => {
+ const previous = window.innerWidth;
+ const probe = <Harness config={{defaultSize: '30%', minSize: 100}} />;
+ try {
+ // The server has no window: a percentage resolves against its 1200px
+ // basis, which a 1200px window reproduces here.
+ window.innerWidth = 1200;
+ const serverHTML = renderToString(probe);
+ expect(serverHTML).toContain('aria-valuenow="360"');
+ window.innerWidth = 800;
+ await hydrateExpecting(probe, serverHTML, '240');
+ } finally {
+ window.innerWidth = previous;
+ }
+ });
+
it('never reports a maximum below the current size, and End does not shrink the region', () => {
const previous = window.innerWidth;
window.innerWidth = 500;
diff --git a/packages/core/src/Resizable/createResizable.server.test.tsx b/packages/core/src/Resizable/createResizable.server.test.tsx
new file mode 100644
index 0000000000..301fa5d724
--- /dev/null
+++ b/packages/core/src/Resizable/createResizable.server.test.tsx
@@ -0,0 +1,53 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file createResizable.server.test.tsx
+ * @input vitest (jsdom, with the document and window reads trapped),
+ * createResizable's module
+ * @output Checks that importing the resize factory does no DOM work, so it is
+ * safe on the server (spec:AST-107 FR6)
+ * @position Server tests for createResizable.ts
+ */
+
+import {describe, expect, it, vi} from 'vitest';
+
+describe('createResizable on the server (spec:AST-107 FR6)', () => {
+ it('does no DOM work at import', async () => {
+ vi.resetModules();
+ const touched: string[] = [];
+ const trapped: [object, string][] = [
+ [globalThis, 'document'],
+ [window, 'localStorage'],
+ [window, 'getComputedStyle'],
+ [globalThis, 'ResizeObserver'],
+ ];
+ const restore = trapped.map(([owner, name]) => {
+ const descriptor = Object.getOwnPropertyDescriptor(owner, name);
+ // A document, a storage, a function or a class: an object each.
+ const value = (owner as Record<string, object | undefined>)[name];
+ Object.defineProperty(owner, name, {
+ configurable: true,
+ get(): object | undefined {
+ touched.push(name);
+ return value;
+ },
+ });
+ return () => {
+ if (descriptor) {
+ Object.defineProperty(owner, name, descriptor);
+ } else {
+ Reflect.deleteProperty(owner, name);
+ }
+ };
+ });
+ try {
+ const factory = await import('./createResizable');
+ expect(typeof factory.createResizable).toBe('function');
+ } finally {
+ for (const undo of restore) {
+ undo();
+ }
+ }
+ expect(touched).toEqual([]);
+ });
+});
diff --git a/packages/core/src/Resizable/createResizable.test.ts b/packages/core/src/Resizable/createResizable.test.ts
new file mode 100644
index 0000000000..fb65709aae
--- /dev/null
+++ b/packages/core/src/Resizable/createResizable.test.ts
@@ -0,0 +1,387 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file createResizable.test.ts
+ * @input vitest (jsdom), createResizable with its internal channel, a stubbed
+ * ResizeObserver for a percentage basis
+ * @output Checks the non-React resize region: collapse, expand and resize on
+ * request, a gesture through its model, bounds and snap points, a
+ * percentage basis, saving, update(), subscribe() and destroy
+ * @position Unit tests for createResizable.ts
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {
+ createResizable,
+ readResizableInternals,
+ type CreateResizableOptions,
+ type ResizableController,
+} from './createResizable';
+import type {ResizeGestureModel} from './resizeGesture';
+
+const controllers: ResizableController[] = [];
+
+function create(options?: CreateResizableOptions): ResizableController {
+ const controller = createResizable(options);
+ controllers.push(controller);
+ return controller;
+}
+
+/** The region's side of a gesture, as a ResizeHandle drives it. */
+function modelOf(resizable: ResizableController): ResizeGestureModel {
+ const model = readResizableInternals(resizable)?.model;
+ if (model == null) {
+ throw new Error('no internal channel');
+ }
+ return model;
+}
+
+/** What the region reports to a React form: its bounds included. */
+function snapshotOf(resizable: ResizableController) {
+ return readResizableInternals(resizable)?.snapshot();
+}
+
+/** A whole gesture through the model: a start, each move, and the end. */
+function drag(resizable: ResizableController, ...deltas: number[]): void {
+ const model = modelOf(resizable);
+ model.start();
+ for (const delta of deltas) {
+ model.move(delta);
+ }
+ model.end();
+}
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+afterEach(() => {
+ for (const controller of controllers.splice(0)) {
+ controller.destroy();
+ }
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('createResizable without React', () => {
+ it('answers collapse, expand, resize and subscribe, and touches no element', () => {
+ const added = vi.spyOn(EventTarget.prototype, 'addEventListener');
+ const onSizeChange = vi.fn();
+ const resizable = create({
+ defaultSize: 200,
+ collapsible: true,
+ onSizeChange,
+ });
+ const listener = vi.fn();
+ resizable.subscribe(listener);
+ resizable.collapse();
+ expect(resizable.isCollapsed).toBe(true);
+ expect(resizable.size).toBe(0);
+ resizable.expand();
+ expect(resizable.size).toBe(200);
+ resizable.resize(260);
+ expect(resizable.size).toBe(260);
+ expect(onSizeChange).toHaveBeenLastCalledWith(260);
+ expect(listener).toHaveBeenCalledTimes(3);
+ expect(added).not.toHaveBeenCalled();
+ });
+
+ it('collapses, expands and resizes on request, reporting each change', () => {
+ const onSizeChange = vi.fn();
+ const onCollapseChange = vi.fn();
+ const resizable = create({
+ defaultSize: 200,
+ minSize: 100,
+ maxSize: 400,
+ collapsible: true,
+ onSizeChange,
+ onCollapseChange,
+ });
+ resizable.resize(320);
+ expect(resizable.size).toBe(320);
+ expect(onSizeChange).toHaveBeenLastCalledWith(320);
+ resizable.collapse();
+ expect(resizable.isCollapsed).toBe(true);
+ expect(onCollapseChange).toHaveBeenLastCalledWith(true);
+ resizable.expand();
+ expect(resizable.size).toBe(320);
+ expect(onCollapseChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('reports a collapse it does not make when the caller controls the collapse state', () => {
+ const onCollapseChange = vi.fn();
+ const resizable = create({
+ defaultSize: 200,
+ collapsible: true,
+ isCollapsed: false,
+ onCollapseChange,
+ });
+ resizable.collapse();
+ expect(onCollapseChange).toHaveBeenLastCalledWith(true);
+ expect(resizable.isCollapsed).toBe(false);
+ resizable.update({
+ defaultSize: 200,
+ collapsible: true,
+ isCollapsed: true,
+ onCollapseChange,
+ });
+ expect(resizable.isCollapsed).toBe(true);
+ });
+
+ it('resizes through its model, clamped to its bounds, and rests only on a snap point when it has them', () => {
+ const onSizeChange = vi.fn();
+ const resizable = create({
+ defaultSize: 200,
+ minSize: 100,
+ maxSize: 400,
+ onSizeChange,
+ });
+ drag(resizable, 40);
+ expect(resizable.size).toBe(240);
+ expect(onSizeChange).toHaveBeenLastCalledWith(240);
+ drag(resizable, 500);
+ expect(resizable.size).toBe(400);
+ drag(resizable, -500);
+ expect(resizable.size).toBe(100);
+
+ const snapping = create({
+ defaultSize: 150,
+ minSize: 100,
+ maxSize: 400,
+ snaps: [150, 300],
+ });
+ drag(snapping, 100);
+ expect(snapping.size).toBe(300);
+ });
+
+ it('collapses a collapsible region dragged under its collapse size, and a drag reopens it', () => {
+ const onCollapseChange = vi.fn();
+ const resizable = create({
+ defaultSize: 200,
+ minSize: 100,
+ collapsible: true,
+ collapsedSize: 40,
+ onCollapseChange,
+ });
+ drag(resizable, -180);
+ expect(resizable.isCollapsed).toBe(true);
+ expect(resizable.size).toBe(0);
+ expect(onCollapseChange).toHaveBeenLastCalledWith(true);
+ drag(resizable, 150);
+ expect(resizable.isCollapsed).toBe(false);
+ expect(resizable.size).toBe(150);
+ expect(onCollapseChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('takes new options with update()', () => {
+ const resizable = create({defaultSize: 300, minSize: 100, maxSize: 400});
+ resizable.update({defaultSize: 300, minSize: 100, maxSize: 250});
+ expect(resizable.size).toBe(250);
+ expect(snapshotOf(resizable)?.maxPx).toBe(250);
+ });
+
+ it('takes the full set of options in update(): the region keeps its size and collapse state, and an option left out returns to its default', () => {
+ const options = {
+ defaultSize: 300,
+ minSize: 200,
+ maxSize: 400,
+ collapsible: true,
+ };
+ const resizable = create(options);
+ resizable.resize(350);
+ resizable.collapse();
+ resizable.update({...options, maxSize: 380});
+ expect(resizable.isCollapsed).toBe(true);
+ expect(snapshotOf(resizable)?.minPx).toBe(200);
+ resizable.update(options);
+ resizable.expand();
+ expect(resizable.size).toBe(350);
+ // Left out, as on a new render: the bounds return to their defaults.
+ resizable.update({defaultSize: 300});
+ expect(snapshotOf(resizable)?.minPx).toBe(50);
+ expect(resizable.size).toBe(350);
+ });
+
+ it('calls subscribers after every change to its size or collapse state', () => {
+ const resizable = create({defaultSize: 200, collapsible: true});
+ const listener = vi.fn();
+ const unsubscribe = resizable.subscribe(listener);
+ drag(resizable, 10);
+ expect(listener).toHaveBeenCalledTimes(1);
+ resizable.collapse();
+ expect(listener).toHaveBeenCalledTimes(2);
+ unsubscribe();
+ resizable.expand();
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('createResizable: a percentage basis', () => {
+ // jsdom lays nothing out and ships no ResizeObserver.
+ class StubResizeObserver {
+ static instances: StubResizeObserver[] = [];
+ callback: ResizeObserverCallback;
+ targets: Element[] = [];
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ StubResizeObserver.instances.push(this);
+ }
+ observe(el: Element) {
+ this.targets.push(el);
+ }
+ unobserve(el: Element) {
+ this.targets = this.targets.filter(t => t !== el);
+ }
+ disconnect() {
+ this.targets = [];
+ }
+ static resizeAll(inlineSize: number) {
+ for (const o of StubResizeObserver.instances) {
+ o.callback(
+ o.targets.map(
+ target =>
+ ({
+ target,
+ contentBoxSize: [{inlineSize, blockSize: 300}],
+ }) as unknown as ResizeObserverEntry,
+ ),
+ o,
+ );
+ }
+ }
+ }
+
+ let width = 1000;
+
+ beforeEach(() => {
+ width = 1000;
+ StubResizeObserver.instances = [];
+ vi.stubGlobal('ResizeObserver', StubResizeObserver);
+ // The first measurement reads the content box from the element.
+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({
+ paddingTop: '0px',
+ paddingBottom: '0px',
+ paddingLeft: '0px',
+ paddingRight: '0px',
+ direction: 'ltr',
+ } as CSSStyleDeclaration);
+ });
+
+ function makeContainer(): {current: HTMLElement} {
+ const node = document.createElement('div');
+ document.body.append(node);
+ Object.defineProperty(node, 'clientWidth', {get: () => width});
+ Object.defineProperty(node, 'clientHeight', {get: () => 300});
+ return {current: node};
+ }
+
+ it('resolves a percentage against the container it is given', () => {
+ const resizable = create({
+ containerRef: makeContainer(),
+ defaultSize: '30%',
+ maxSize: '50%',
+ });
+ expect(resizable.size).toBe(300);
+ expect(snapshotOf(resizable)?.maxPx).toBe(500);
+ // A percentage bound follows its basis and clamps the selection.
+ width = 400;
+ StubResizeObserver.resizeAll(400);
+ expect(resizable.size).toBe(200);
+ });
+
+ it('tells subscribers about a correction its basis makes, and reports no interaction for it', () => {
+ width = 0;
+ const onSizeChange = vi.fn();
+ const resizable = create({
+ containerRef: makeContainer(),
+ defaultSize: '25%',
+ onSizeChange,
+ });
+ const listener = vi.fn();
+ resizable.subscribe(listener);
+ width = 800;
+ StubResizeObserver.resizeAll(800);
+ expect(resizable.size).toBe(200);
+ expect(listener).toHaveBeenCalled();
+ expect(onSizeChange).not.toHaveBeenCalled();
+ });
+});
+
+describe('createResizable: persistence', () => {
+ it('saves its size once, when a gesture ends, and a new factory on the same key restores it', () => {
+ const resizable = create({defaultSize: 200, autoSaveId: 'sidebar'});
+ const setItem = vi.spyOn(Storage.prototype, 'setItem');
+ const model = modelOf(resizable);
+ model.start();
+ model.move(20);
+ model.move(40);
+ model.move(60);
+ expect(setItem).not.toHaveBeenCalled();
+ model.end();
+ expect(setItem).toHaveBeenCalledTimes(1);
+ expect(
+ JSON.parse(localStorage.getItem('astryx-resizable:sidebar') ?? ''),
+ ).toEqual({size: 260, isCollapsed: false});
+ expect(create({defaultSize: 200, autoSaveId: 'sidebar'}).size).toBe(260);
+ });
+
+ it('a cancelled gesture is still over: the size it reached is saved once', () => {
+ const resizable = create({defaultSize: 200, autoSaveId: 'pane'});
+ const setItem = vi.spyOn(Storage.prototype, 'setItem');
+ const model = modelOf(resizable);
+ model.start();
+ model.move(30);
+ model.cancel();
+ expect(resizable.size).toBe(230);
+ expect(setItem).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('createResizable: destroy', () => {
+ it('ends a gesture in flight and keeps the size it reached, then answers nothing', () => {
+ const onSizeChange = vi.fn();
+ const resizable = createResizable({
+ defaultSize: 200,
+ autoSaveId: 'mid-gesture',
+ onSizeChange,
+ });
+ const model = modelOf(resizable);
+ model.start();
+ model.move(25);
+ onSizeChange.mockClear();
+
+ resizable.destroy();
+ expect(
+ JSON.parse(localStorage.getItem('astryx-resizable:mid-gesture') ?? ''),
+ ).toEqual({size: 225, isCollapsed: false});
+ // Nothing answers afterwards, and a second destroy does nothing.
+ resizable.resize(300);
+ resizable.collapse();
+ expect(onSizeChange).not.toHaveBeenCalled();
+ resizable.destroy();
+ });
+
+ it('stops observing its container', () => {
+ const observe = vi.fn();
+ const unobserve = vi.fn();
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = observe;
+ unobserve = unobserve;
+ disconnect() {}
+ },
+ );
+ const container = document.createElement('div');
+ document.body.append(container);
+ Object.defineProperty(container, 'clientWidth', {get: () => 600});
+ const resizable = createResizable({
+ containerRef: {current: container},
+ maxSize: '50%',
+ });
+ expect(observe).toHaveBeenCalledWith(container);
+ resizable.destroy();
+ expect(unobserve).toHaveBeenCalledWith(container);
+ });
+});
diff --git a/packages/core/src/Resizable/createResizable.ts b/packages/core/src/Resizable/createResizable.ts
new file mode 100644
index 0000000000..817586944b
--- /dev/null
+++ b/packages/core/src/Resizable/createResizable.ts
@@ -0,0 +1,831 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file createResizable.ts
+ * @input A region's options
+ * @output createResizable; readInitialResizableState for the hook's first
+ * render; createResizableAs and the internal channel for the hook
+ * @position The Resizable family's region, internal to the package. The
+ * configuration-object useResizable builds on it, and ResizeHandle drives
+ * it through resizeGesture.ts's model. Importing it does no DOM work
+ */
+
+import {observeResize} from '../utils/sharedResizeObserver';
+import {devWarn} from '../utils/devWarning';
+import type {SizeValue} from '../utils/types';
+import {
+ DEFAULT_COLLAPSED_SIZE,
+ DEFAULT_MIN,
+ DEFAULT_SIZE_FALLBACK,
+ RESIZABLE_SIZE_GUIDANCE,
+ SERVER_BASIS,
+ clampSize,
+ dependsOnBasis,
+ loadPersistedState,
+ measureContentBox,
+ parseSize,
+ persistState,
+ resolveBound,
+ type PersistedResizableState,
+ type ResizableDirection,
+} from './resizableModel';
+import type {ResizeGestureModel, ResizeGestureState} from './resizeGesture';
+import type {ResizableSize} from './utils';
+
+export interface CreateResizableOptions {
+ /**
+ * Initial size. A number or an exact `Npx` is pixels, and an exact `N%` is
+ * a share of the basis. `percent(value, {min | max: pixel(value)})` adds one
+ * pixel floor or ceiling. A value that depends on the basis resolves once
+ * into pixels. @default 250
+ */
+ defaultSize?: ResizableSize | SizeValue;
+ /** The minimum size, in the same forms. @default 50 */
+ minSize?: ResizableSize;
+ /** The maximum size, in the same forms. Unbounded when omitted. */
+ maxSize?: ResizableSize;
+ /** Pixel values the region rests on; it can rest only on one of them. */
+ snaps?: number[];
+ /** Whether the region can collapse to 0. @default false */
+ collapsible?: boolean;
+ /** Size in px under which a drag collapses the region. @default 40 */
+ collapsedSize?: number;
+ /**
+ * The element a percentage is a share of, read as `containerRef.current`.
+ * Omitted, percentages are a share of the viewport. A plain `{current}`
+ * object serves outside React.
+ */
+ containerRef?: {readonly current: HTMLElement | null};
+ /** The axis the region resizes along. @default 'horizontal' */
+ direction?: ResizableDirection;
+ /** Key under which the size and collapse state persist in localStorage. */
+ autoSaveId?: string;
+ /** Initial collapse state; a persisted entry wins over it. */
+ defaultIsCollapsed?: boolean;
+ /**
+ * Controlled collapse state. When set, the caller owns collapse. A collapse
+ * or expand request reports through `onCollapseChange`. Nothing changes
+ * until the caller passes the new value through `update`.
+ */
+ isCollapsed?: boolean;
+ /** Called when an interaction changes the size. */
+ onSizeChange?: (size: number) => void;
+ /** Called when an interaction collapses or expands the region. */
+ onCollapseChange?: (isCollapsed: boolean) => void;
+}
+
+export interface ResizableController {
+ /** The region's size in px, 0 while collapsed. */
+ readonly size: number;
+ readonly isCollapsed: boolean;
+ /** Collapses the region, when it is collapsible. */
+ collapse(): void;
+ /** Expands the region to the size it had before it collapsed. */
+ expand(): void;
+ /** Resizes the region to `size` px, within its bounds. */
+ resize(size: number): void;
+ /**
+ * Takes the full set of options, as a new render does: an option left out
+ * returns to its default. The region keeps its size and collapse state,
+ * within the new options.
+ */
+ update(options: CreateResizableOptions): void;
+ /**
+ * Calls `listener` after every change to `size` or `isCollapsed`, a
+ * correction a newly measured basis makes included. Returns the function
+ * that stops it.
+ */
+ subscribe(listener: () => void): () => void;
+ /** Stops every observer the factory started; a gesture in flight ends. */
+ destroy(): void;
+}
+
+/** The viewport width, the basis without a container. */
+function readViewportBasis(): number {
+ return typeof window === 'undefined' ? SERVER_BASIS : window.innerWidth;
+}
+
+/** The window's extent along the axis, for an unbounded region's maximum. */
+function readWindowExtent(direction: ResizableDirection): number | null {
+ if (typeof window === 'undefined') {
+ return null;
+ }
+ return direction === 'vertical' ? window.innerHeight : window.innerWidth;
+}
+
+/** A warning already given, so a resolution repeated silently stays quiet. */
+const QUIET = {current: true};
+
+/**
+ * The state a region with `options` starts in: the server's render and a
+ * hook's first render. A container is not measured
+ * yet, so a percentage of it resolves against the deterministic 1200px basis
+ * until the factory measures it. `'server'` reads the state the server
+ * rendered, for a render that hydrates it: the 1200px basis for a viewport
+ * percentage too, and nothing saved.
+ */
+export function readInitialResizableState(
+ options: CreateResizableOptions = {},
+ environment: 'client' | 'server' = 'client',
+): ResizableSnapshot {
+ const {
+ defaultSize,
+ minSize,
+ maxSize,
+ containerRef,
+ collapsible = false,
+ snaps = [],
+ autoSaveId,
+ defaultIsCollapsed,
+ isCollapsed: controlled,
+ } = options;
+ const isServer = environment === 'server';
+ const persisted =
+ autoSaveId && !isServer ? loadPersistedState(autoSaveId) : null;
+ const parsedDefault = parseSize(defaultSize);
+ const parsedMin = parseSize(minSize);
+ const parsedMax = parseSize(maxSize);
+ const hasContainer = containerRef != null;
+ const needsContainer =
+ hasContainer &&
+ (dependsOnBasis(parsedMin) ||
+ dependsOnBasis(parsedMax) ||
+ (persisted?.size == null && dependsOnBasis(parsedDefault)));
+ const basis = hasContainer || isServer ? SERVER_BASIS : readViewportBasis();
+ const min = resolveBound(
+ minSize,
+ parsedMin,
+ basis,
+ DEFAULT_MIN,
+ 'minSize',
+ RESIZABLE_SIZE_GUIDANCE,
+ QUIET,
+ );
+ const max = resolveBound(
+ maxSize,
+ parsedMax,
+ basis,
+ Infinity,
+ 'maxSize',
+ RESIZABLE_SIZE_GUIDANCE,
+ QUIET,
+ );
+ const defaultPx = resolveBound(
+ defaultSize,
+ parsedDefault,
+ basis,
+ DEFAULT_SIZE_FALLBACK,
+ 'defaultSize',
+ RESIZABLE_SIZE_GUIDANCE,
+ QUIET,
+ );
+ const chosen =
+ persisted?.size ??
+ (needsContainer ? null : clampSize(defaultPx, min, max, snaps));
+ const size = clampSize(chosen ?? defaultPx, min, max, snaps);
+ const isCollapsed =
+ collapsible &&
+ (controlled !== undefined
+ ? controlled
+ : (persisted?.isCollapsed ?? defaultIsCollapsed ?? false));
+ // A container is not measured yet; without one the window's extent stands
+ // in for a missing maximum, as the factory reports it.
+ const windowExtent =
+ hasContainer || isServer
+ ? null
+ : readWindowExtent(options.direction ?? 'horizontal');
+ return {
+ size: isCollapsed ? 0 : size,
+ isCollapsed,
+ expandedSize: size,
+ minPx: min,
+ maxPx: max,
+ effectiveMaxPx:
+ max !== Infinity
+ ? max
+ : windowExtent == null
+ ? undefined
+ : Math.max(windowExtent, isCollapsed ? min : size),
+ };
+}
+
+/**
+ * What a React form of the region renders. A change to any part replaces it
+ * as a whole. It holds the size (0 while collapsed), the collapse state, the
+ * size as expanded, and the bounds the handle announces.
+ */
+export interface ResizableSnapshot {
+ readonly size: number;
+ readonly isCollapsed: boolean;
+ readonly expandedSize: number;
+ readonly minPx: number;
+ readonly maxPx: number;
+ /** The maximum the handle reports: a configured one, or a measured extent. */
+ readonly effectiveMaxPx: number | undefined;
+}
+
+/**
+ * The package's own channel into a factory, for useResizable: kept off the
+ * exported ResizableController, so it adds no public member.
+ */
+interface ResizableInternals {
+ snapshot(): ResizableSnapshot;
+ /** Calls `listener` after every change to the snapshot. */
+ subscribeSnapshot(listener: () => void): () => void;
+ /**
+ * Follows the element behind `containerRef` when it has changed without
+ * new options, as a React caller's commit may have swapped it.
+ */
+ syncContainer(): void;
+ /**
+ * Lets go of the page and keeps the region. A gesture in flight ends as
+ * cancelled, and the observers go. Collapse, expand and resize still apply
+ * and report. For a React caller whose component unmounts or an
+ * `<Activity>` hides.
+ */
+ suspend(): void;
+ /** Takes the page back after `suspend`: the observers. */
+ resume(): void;
+ /**
+ * The region's side of a ResizeHandle's gesture: the drag and keys of a
+ * ResizeHandle given the configuration object's props.
+ */
+ model: ResizeGestureModel;
+}
+
+const internals = new WeakMap<ResizableController, ResizableInternals>();
+
+/** The factory's internal channel, or undefined for anything else. */
+export function readResizableInternals(
+ controller: ResizableController,
+): ResizableInternals | undefined {
+ return internals.get(controller);
+}
+
+/**
+ * A resizable region, without React. The factory never sizes the panel: it
+ * reports the size, and the caller applies it. It resolves, clamps, snaps,
+ * collapses and saves the size, and a percentage follows its basis.
+ * `destroy` stops its observers.
+ */
+export function createResizable(
+ options: CreateResizableOptions = {},
+): ResizableController {
+ return createResizableAs('createResizable', options);
+}
+
+/**
+ * Who a factory's development warnings speak for: the bare factory, or the
+ * configuration-object useResizable built on it, whose warnings keep the
+ * hook's name and words.
+ */
+export type ResizableWarningSource = 'createResizable' | 'useResizable';
+
+/**
+ * createResizable, with its development warnings in the words of `source`:
+ * the package's own entry, for useResizable.
+ */
+export function createResizableAs(
+ source: ResizableWarningSource,
+ options: CreateResizableOptions = {},
+): ResizableController {
+ // The configuration-object useResizable keeps its warnings word for word.
+ const isHook = source === 'useResizable';
+ let opts = options;
+ let isDestroyed = false;
+ // Let go of the page by `suspend`, with the region kept.
+ let isSuspended = false;
+ const listeners = new Set<() => void>();
+ const didWarn = {
+ min: {current: false},
+ max: {current: false},
+ defaultSize: {current: false},
+ inverted: false,
+ };
+
+ let persistedKey = opts.autoSaveId;
+ let persisted: PersistedResizableState | null = persistedKey
+ ? loadPersistedState(persistedKey)
+ : null;
+
+ // The percentage basis. The container is followed through the shared
+ // observer only while some option needs it; the viewport only while a
+ // percentage bound needs it.
+ let containerElement: HTMLElement | null = null;
+ let observedDirection: ResizableDirection | null = null;
+ let containerBasis: number | null = null;
+ let stopObservingContainer: (() => void) | null = null;
+ let isSubscribing = false;
+ let isObservingViewport = false;
+
+ // One stable basis per gesture: a container that resizes mid-drag would
+ // otherwise move the bound under the pointer.
+ let gestureBasis: number | null = null;
+ let isGestureActive = false;
+ let dragStartSize = 0;
+
+ let initialDefault: {px: number; isFinal: boolean} | null = null;
+ let chosenSize: number | null | undefined;
+ let committedBounds: {min: number; max: number} | null = null;
+ let uncontrolledIsCollapsed =
+ persisted?.isCollapsed ?? opts.defaultIsCollapsed ?? false;
+
+ // What the region last computed, notified and wrote.
+ let derived = {
+ size: 0,
+ isCollapsed: false,
+ min: DEFAULT_MIN,
+ max: Infinity,
+ effectiveMax: undefined as number | undefined,
+ isBasisMeasured: true,
+ };
+ let notified: {size: number; isCollapsed: boolean} | null = null;
+ let written: {key: string; size: number; isCollapsed: boolean} | null = null;
+ let mustWrite = false;
+ let snapshot: ResizableSnapshot | null = null;
+ const snapshotListeners = new Set<() => void>();
+
+ const direction = (): ResizableDirection => opts.direction ?? 'horizontal';
+ const collapsible = (): boolean => opts.collapsible ?? false;
+ const isControlled = (): boolean => opts.isCollapsed !== undefined;
+ const snaps = (): number[] => opts.snaps ?? [];
+
+ const onViewportResize = () => {
+ commit();
+ };
+
+ /** Which bases the options need followed right now. */
+ function observation() {
+ const parsedDefault = parseSize(opts.defaultSize);
+ const boundsDependOnBasis =
+ dependsOnBasis(parseSize(opts.minSize)) ||
+ dependsOnBasis(parseSize(opts.maxSize));
+ const defaultNeedsInitialBasis =
+ persisted?.size == null &&
+ dependsOnBasis(parsedDefault) &&
+ initialDefault?.isFinal !== true;
+ const hasContainer = opts.containerRef != null;
+ return {
+ hasContainer,
+ container:
+ hasContainer && (boundsDependOnBasis || defaultNeedsInitialBasis),
+ viewport: !hasContainer && boundsDependOnBasis,
+ };
+ }
+
+ /** Follow the bases `observation()` names, and nothing else. */
+ function syncObservation(): void {
+ const needs = observation();
+ const element = needs.container
+ ? (opts.containerRef?.current ?? null)
+ : null;
+ if (element !== containerElement || observedDirection !== direction()) {
+ stopObservingContainer?.();
+ stopObservingContainer = null;
+ containerElement = element;
+ containerBasis = null;
+ observedDirection = direction();
+ if (element != null) {
+ // The observer measures once as it registers; that measurement is
+ // read by the computation this call is part of.
+ isSubscribing = true;
+ const observed = element;
+ stopObservingContainer = observeResize(observed, entry => {
+ containerBasis = measureContentBox(observed, direction(), entry);
+ if (!isSubscribing) {
+ commit();
+ }
+ });
+ isSubscribing = false;
+ }
+ }
+ const watchViewport = needs.viewport && typeof window !== 'undefined';
+ if (watchViewport && !isObservingViewport) {
+ window.addEventListener('resize', onViewportResize);
+ isObservingViewport = true;
+ } else if (!watchViewport && isObservingViewport) {
+ window.removeEventListener('resize', onViewportResize);
+ isObservingViewport = false;
+ }
+ }
+
+ /** The region's state from its options, its basis and its selection. */
+ function compute(): void {
+ const needs = observation();
+ const hasPositiveMeasurement = containerBasis != null && containerBasis > 0;
+ // Before a supplied container is measured, the deterministic 1200px
+ // stands in. It also stands in while the container measures 0, as a
+ // hidden or detached one does. The first real measurement replaces it.
+ const liveBasis = needs.hasContainer
+ ? hasPositiveMeasurement
+ ? (containerBasis as number)
+ : SERVER_BASIS
+ : readViewportBasis();
+ const isBasisMeasured = needs.container ? hasPositiveMeasurement : true;
+ const basis = gestureBasis ?? liveBasis;
+
+ const min = resolveBound(
+ opts.minSize,
+ parseSize(opts.minSize),
+ basis,
+ DEFAULT_MIN,
+ 'minSize',
+ RESIZABLE_SIZE_GUIDANCE,
+ didWarn.min,
+ source,
+ );
+ const max = resolveBound(
+ opts.maxSize,
+ parseSize(opts.maxSize),
+ basis,
+ Infinity,
+ 'maxSize',
+ RESIZABLE_SIZE_GUIDANCE,
+ didWarn.max,
+ source,
+ );
+ // A basis-dependent default resolves ONCE into a pixel size; it is final
+ // once its basis is real.
+ if (initialDefault == null || !initialDefault.isFinal) {
+ initialDefault = {
+ px: resolveBound(
+ opts.defaultSize,
+ parseSize(opts.defaultSize),
+ basis,
+ DEFAULT_SIZE_FALLBACK,
+ 'defaultSize',
+ RESIZABLE_SIZE_GUIDANCE,
+ didWarn.defaultSize,
+ source,
+ ),
+ isFinal: isBasisMeasured,
+ };
+ }
+ const defaultPx = initialDefault.px;
+ if (chosenSize === undefined) {
+ chosenSize =
+ persisted?.size ??
+ (isBasisMeasured ? clampSize(defaultPx, min, max, snaps()) : null);
+ }
+ if (isBasisMeasured && chosenSize == null) {
+ // The container is measured now: the selection the temporary basis
+ // stood in for is made against the real one. Not an interaction, so it
+ // reports nothing through onSizeChange.
+ chosenSize = clampSize(defaultPx, min, max, snaps());
+ }
+ // A re-resolved bound clamps the SELECTION, once the basis is final and
+ // no gesture holds it.
+ if (
+ isBasisMeasured &&
+ gestureBasis == null &&
+ (committedBounds == null ||
+ committedBounds.min !== min ||
+ committedBounds.max !== max)
+ ) {
+ committedBounds = {min, max};
+ if (chosenSize != null) {
+ chosenSize = clampSize(chosenSize, min, max, snaps());
+ }
+ }
+ const size = clampSize(chosenSize ?? defaultPx, min, max, snaps());
+ const isCollapsed =
+ collapsible() &&
+ (isControlled() ? Boolean(opts.isCollapsed) : uncontrolledIsCollapsed);
+
+ if (min > max && !didWarn.inverted) {
+ didWarn.inverted = true;
+ devWarn(
+ source,
+ `the resolved minimum (${min}px) is above the resolved maximum ` +
+ `(${max}px). The maximum wins${isHook ? ', as it always has' : ''}.`,
+ );
+ }
+
+ // The maximum the handle REPORTS: a configured maximum, or a measured
+ // extent standing in for it, never below what the handle announces.
+ const measuredForMax = needs.hasContainer
+ ? hasPositiveMeasurement && needs.container
+ ? containerBasis
+ : null
+ : readWindowExtent(direction());
+ const effectiveMax =
+ max !== Infinity
+ ? max
+ : measuredForMax == null
+ ? undefined
+ : Math.max(measuredForMax, isCollapsed ? min : size);
+
+ derived = {size, isCollapsed, min, max, effectiveMax, isBasisMeasured};
+ }
+
+ /** Recompute, then bring the observers, storage and subscribers along. */
+ function commit(): void {
+ if (isDestroyed) {
+ return;
+ }
+ if (isSuspended) {
+ // No observers: the last measured basis stands.
+ compute();
+ } else {
+ // The observation a computation needs can change with it (a default
+ // made final stops following its container): settle both.
+ for (let pass = 0; pass < 3; pass++) {
+ const before = observation();
+ syncObservation();
+ compute();
+ const after = observation();
+ if (
+ before.container === after.container &&
+ before.viewport === after.viewport
+ ) {
+ break;
+ }
+ }
+ }
+ persist();
+ const reported = {
+ size: derived.isCollapsed ? 0 : derived.size,
+ isCollapsed: derived.isCollapsed,
+ };
+ const next: ResizableSnapshot = {
+ size: reported.size,
+ isCollapsed: reported.isCollapsed,
+ expandedSize: derived.size,
+ minPx: derived.min,
+ maxPx: derived.max,
+ effectiveMaxPx: derived.effectiveMax,
+ };
+ const isSnapshotChanged =
+ snapshot == null ||
+ (Object.keys(next) as (keyof ResizableSnapshot)[]).some(
+ key => snapshot?.[key] !== next[key],
+ );
+ if (isSnapshotChanged) {
+ snapshot = next;
+ }
+ if (
+ notified == null ||
+ notified.size !== reported.size ||
+ notified.isCollapsed !== reported.isCollapsed
+ ) {
+ const isFirst = notified == null;
+ notified = reported;
+ if (!isFirst) {
+ for (const listener of [...listeners]) {
+ listener();
+ }
+ }
+ }
+ if (isSnapshotChanged) {
+ for (const listener of [...snapshotListeners]) {
+ listener();
+ }
+ }
+ }
+
+ /** Nothing is written while the basis stands in, nor while a gesture runs. */
+ function persist(): void {
+ const key = opts.autoSaveId;
+ if (key == null || key === '' || !derived.isBasisMeasured) {
+ return;
+ }
+ if (isGestureActive) {
+ return;
+ }
+ const next = {key, size: derived.size, isCollapsed: derived.isCollapsed};
+ if (
+ mustWrite ||
+ written == null ||
+ written.key !== next.key ||
+ written.size !== next.size ||
+ written.isCollapsed !== next.isCollapsed
+ ) {
+ mustWrite = false;
+ written = next;
+ persistState(key, {size: next.size, isCollapsed: next.isCollapsed});
+ }
+ }
+
+ const setCollapsed = (value: boolean) => {
+ if (!isControlled()) {
+ uncontrolledIsCollapsed = value;
+ }
+ };
+
+ function collapse(): void {
+ if (isDestroyed || !collapsible() || derived.isCollapsed) {
+ return;
+ }
+ setCollapsed(true);
+ commit();
+ opts.onCollapseChange?.(true);
+ opts.onSizeChange?.(0);
+ }
+
+ function expand(): void {
+ if (isDestroyed) {
+ return;
+ }
+ const wasCollapsed = derived.isCollapsed;
+ setCollapsed(false);
+ commit();
+ if (wasCollapsed) {
+ opts.onCollapseChange?.(false);
+ }
+ opts.onSizeChange?.(derived.size);
+ }
+
+ function resize(next: number): void {
+ if (isDestroyed) {
+ return;
+ }
+ // An invalid size repairs nothing: it must not replace a legal selection
+ // with NaN, which would reach storage and aria-valuenow.
+ if (!Number.isFinite(next) || next < 0) {
+ devWarn(
+ source,
+ `resize(${String(next)}) is not a pixel size. Keeping the current ` +
+ `size. Percentages configure the ${isHook ? 'hook' : 'region'}; ` +
+ 'they are not a programmatic input.',
+ );
+ return;
+ }
+ const clamped = clampSize(next, derived.min, derived.max, snaps());
+ const wasCollapsed = derived.isCollapsed;
+ chosenSize = clamped;
+ setCollapsed(false);
+ commit();
+ // Resizing out of the collapsed state is an implicit expand.
+ if (wasCollapsed) {
+ opts.onCollapseChange?.(false);
+ }
+ opts.onSizeChange?.(clamped);
+ }
+
+ const model: ResizeGestureModel = {
+ state(): ResizeGestureState {
+ return {
+ size: derived.isCollapsed ? 0 : derived.size,
+ isCollapsed: derived.isCollapsed,
+ minPx: derived.min,
+ maxPx: derived.max,
+ snaps: snaps(),
+ collapsedSize: opts.collapsedSize ?? DEFAULT_COLLAPSED_SIZE,
+ collapsible: collapsible(),
+ };
+ },
+ start() {
+ // The basis holds still for the whole gesture.
+ gestureBasis = readLiveBasis();
+ isGestureActive = true;
+ dragStartSize = derived.isCollapsed ? 0 : derived.size;
+ },
+ move(delta) {
+ const raw = dragStartSize + delta;
+ const collapsedSize = opts.collapsedSize ?? DEFAULT_COLLAPSED_SIZE;
+ if (collapsible() && raw < collapsedSize) {
+ if (!derived.isCollapsed) {
+ setCollapsed(true);
+ commit();
+ opts.onCollapseChange?.(true);
+ opts.onSizeChange?.(0);
+ }
+ return;
+ }
+ const reopens = derived.isCollapsed && raw >= collapsedSize;
+ if (reopens) {
+ setCollapsed(false);
+ }
+ const clamped = clampSize(raw, derived.min, derived.max, snaps());
+ chosenSize = clamped;
+ commit();
+ if (reopens) {
+ opts.onCollapseChange?.(false);
+ }
+ opts.onSizeChange?.(clamped);
+ },
+ end() {
+ endGesture();
+ },
+ // A cancelled gesture is still over: the basis it held comes back, and
+ // the size it reached is saved once, like a completed one.
+ cancel() {
+ endGesture();
+ },
+ collapse,
+ expand,
+ };
+
+ function readLiveBasis(): number {
+ const needs = observation();
+ if (!needs.hasContainer) {
+ return readViewportBasis();
+ }
+ return containerBasis != null && containerBasis > 0
+ ? containerBasis
+ : SERVER_BASIS;
+ }
+
+ function endGesture(): void {
+ if (!isGestureActive) {
+ return;
+ }
+ gestureBasis = null;
+ isGestureActive = false;
+ mustWrite = true;
+ commit();
+ }
+
+ /** The observers go; a gesture in flight has ended first. */
+ function letGoOfPage(): void {
+ stopObservingContainer?.();
+ stopObservingContainer = null;
+ containerElement = null;
+ if (isObservingViewport) {
+ window.removeEventListener('resize', onViewportResize);
+ isObservingViewport = false;
+ }
+ }
+
+ commit();
+
+ const controller: ResizableController = {
+ get size() {
+ return derived.isCollapsed ? 0 : derived.size;
+ },
+ get isCollapsed() {
+ return derived.isCollapsed;
+ },
+ collapse,
+ expand,
+ resize,
+ update(next) {
+ if (isDestroyed) {
+ return;
+ }
+ opts = next;
+ if (opts.autoSaveId !== persistedKey) {
+ persistedKey = opts.autoSaveId;
+ persisted = persistedKey ? loadPersistedState(persistedKey) : null;
+ }
+ commit();
+ },
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ destroy() {
+ if (isDestroyed) {
+ return;
+ }
+ // A gesture a ResizeHandle drove through the region's model ends first,
+ // so the size it reached is saved.
+ endGesture();
+ isDestroyed = true;
+ if (!isSuspended) {
+ letGoOfPage();
+ }
+ listeners.clear();
+ snapshotListeners.clear();
+ },
+ };
+ internals.set(controller, {
+ snapshot: () => snapshot as ResizableSnapshot,
+ subscribeSnapshot(listener) {
+ snapshotListeners.add(listener);
+ return () => {
+ snapshotListeners.delete(listener);
+ };
+ },
+ model,
+ suspend() {
+ if (isDestroyed || isSuspended) {
+ return;
+ }
+ endGesture();
+ isSuspended = true;
+ letGoOfPage();
+ },
+ resume() {
+ if (isDestroyed || !isSuspended) {
+ return;
+ }
+ isSuspended = false;
+ commit();
+ },
+ syncContainer() {
+ if (isDestroyed || isSuspended) {
+ return;
+ }
+ const element = observation().container
+ ? (opts.containerRef?.current ?? null)
+ : null;
+ if (element !== containerElement) {
+ commit();
+ }
+ },
+ });
+ return controller;
+}
diff --git a/packages/core/src/Resizable/useResizable.test.ts b/packages/core/src/Resizable/useResizable.test.ts
index 187e9b966f..9e68c78844 100644
--- a/packages/core/src/Resizable/useResizable.test.ts
+++ b/packages/core/src/Resizable/useResizable.test.ts
@@ -11,14 +11,24 @@
* SYNC: When useResizable changes, update tests to match new behavior
*/
-import {createElement, useLayoutEffect, useRef} from 'react';
+import {
+ Activity,
+ createElement,
+ useLayoutEffect,
+ useRef,
+ type ComponentProps,
+} from 'react';
import {createRoot, hydrateRoot} from 'react-dom/client';
import {flushSync} from 'react-dom';
import {renderToString} from 'react-dom/server';
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
import {render, renderHook, act, waitFor} from '@testing-library/react';
import {useResizable} from './useResizable';
-import type {ResizableProps, UseResizableSingleConfig} from './useResizable';
+import type {
+ ResizableProps,
+ ResizableRegion,
+ UseResizableSingleConfig,
+} from './useResizable';
import {percent, pixel} from './utils';
import type {ResizableSize} from './utils';
@@ -762,6 +772,33 @@ describe('useResizable percentage configuration (AST-010)', () => {
expect(result.current.size).toBe(80);
});
+ it('warns as useResizable, in the words it always used', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const inverted = renderHook(() =>
+ useResizable({defaultSize: 200, minSize: 300, maxSize: 100}),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'useResizable: the resolved minimum (300px) is above the resolved ' +
+ 'maximum (100px). The maximum wins, as it always has.',
+ );
+ act(() => {
+ inverted.result.current.resize(Number.NaN);
+ });
+ expect(warn).toHaveBeenCalledWith(
+ 'useResizable: resize(NaN) is not a pixel size. Keeping the current ' +
+ 'size. Percentages configure the hook; they are not a programmatic ' +
+ 'input.',
+ );
+ inverted.unmount();
+ warn.mockClear();
+ renderHook(() => useResizable({defaultSize: pixel(-1)}));
+ expect(warn.mock.calls.length).toBeGreaterThan(0);
+ for (const [message] of warn.mock.calls) {
+ expect(String(message)).toMatch(/^useResizable: /);
+ }
+ warn.mockRestore();
+ });
+
it('permanently re-clamps a caller-recomputed numeric maxSize', () => {
// #5934: a table-inbox reading pane derives `maxSize` itself, as
// `Math.max(paneFloor, surfaceWidth - listFloor)`, from a plain
@@ -1558,6 +1595,23 @@ describe('useResizable percentage configuration (AST-010)', () => {
expect(result.current.props._maxSizePx).toBe(399);
});
+ it('follows a container swapped behind the ref with a configuration object kept across renders', () => {
+ // A module constant or a memoized object: no new options reach the
+ // region when the element behind its ref changes.
+ const first = makeSized(398);
+ const second = makeSized(798);
+ const containerRef: {current: HTMLElement | null} = {current: first};
+ const config = {containerRef, defaultSize: 150, maxSize: '50%'} as const;
+ const {result, rerender} = renderHook(() => useResizable(config));
+ expect(result.current.props._maxSizePx).toBe(199);
+
+ act(() => {
+ containerRef.current = second;
+ });
+ rerender();
+ expect(result.current.props._maxSizePx).toBe(399);
+ });
+
it('stops observing the element it left behind', () => {
const first = makeSized(398);
const second = makeSized(798);
@@ -1615,6 +1669,44 @@ describe('useResizable percentage configuration (AST-010)', () => {
localStorage.clear();
});
+ it('resolves a percentage default against its container once measured, after an <Activity> hid and showed the region before then', () => {
+ // The temporary 1200px basis stands in while the container is not laid
+ // out. A factory made for the reveal must not take the size the old one
+ // showed against it as a selection.
+ content = 0;
+ const containerRef = makeContainer();
+ let region: ResizableRegion | undefined;
+ function Panel() {
+ region = useResizable({
+ containerRef,
+ defaultSize: '30%',
+ autoSaveId: 'pct-activity',
+ });
+ return null;
+ }
+ // Activity's props type requires children, which the third argument
+ // passes.
+ const host = (mode: 'visible' | 'hidden') =>
+ createElement(
+ Activity,
+ {mode} as ComponentProps<typeof Activity>,
+ createElement(Panel),
+ );
+ const view = render(host('visible'));
+ expect(region?.size).toBe(360);
+ view.rerender(host('hidden'));
+ view.rerender(host('visible'));
+ content = 800;
+ act(() => {
+ StubResizeObserver.resizeAll();
+ });
+ expect(region?.size).toBe(240);
+ expect(localStorage.getItem('astryx-resizable:pct-activity')).toBe(
+ JSON.stringify({size: 240, isCollapsed: false}),
+ );
+ localStorage.clear();
+ });
+
it('still persists for a pixel-only region that supplies a container', () => {
// The "is the basis measured yet" guard must not disable persistence for
// a region that never asks for a percentage in the first place.
diff --git a/packages/core/src/Resizable/useResizable.ts b/packages/core/src/Resizable/useResizable.ts
index f4dd3b1f14..1192dd762a 100644
--- a/packages/core/src/Resizable/useResizable.ts
+++ b/packages/core/src/Resizable/useResizable.ts
@@ -6,39 +6,33 @@
* @file useResizable.ts
* @input Resize configuration (defaultSize, minSize, maxSize, snaps), with
* removed pixel-bound aliases rejected even through assembled objects, and
- * collapse configuration (collapsible,
- * defaultIsCollapsed, isCollapsed)
- * @output Hook return: size, isCollapsed, collapse/expand/resize methods, props for handle
+ * collapse configuration (collapsible, defaultIsCollapsed, isCollapsed)
+ * @output Hook return: size, isCollapsed, collapse/expand/resize methods, props
+ * for handle, over the internal resize factory (createResizable)
* @position Public hook; consumed by layout components via `resizable` prop
*/
import {
useCallback,
- useEffect,
+ useReducer,
useRef,
useState,
useSyncExternalStore,
type RefObject,
} from 'react';
-import {observeResize} from '../utils/sharedResizeObserver';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
-import {devWarn} from '../utils/devWarning';
import type {SizeValue} from '../utils/types';
import type {ResizableSize} from './utils';
+import {
+ createResizableAs,
+ readInitialResizableState,
+ readResizableInternals,
+ type CreateResizableOptions,
+ type ResizableController,
+ type ResizableSnapshot,
+} from './createResizable';
import {
DEFAULT_COLLAPSED_SIZE,
- DEFAULT_MIN,
- DEFAULT_SIZE_FALLBACK,
- RESIZABLE_SIZE_GUIDANCE,
- SERVER_BASIS,
- clampSize,
- dependsOnBasis,
- loadPersistedState,
- measureContentBox,
- parseSize,
- persistState,
- resolveBound,
- type PersistedResizableState,
type ResizableDirection,
} from './resizableModel';
@@ -211,633 +205,66 @@ export interface ResizableProps {
_isResizableProps: true;
}
-/** A store that never changes on its own; the snapshot is re-read on render. */
-const noopSubscribe = () => () => {};
-
-// The window snapshots are module functions, so their identity is stable:
-// React re-reads a snapshot after the commit whenever getSnapshot is a new
-// function, and a window size read after the DOM changed forces a layout of
-// the whole page. With these, the window is read during render only.
-
-/** The viewport width, the basis without a container. */
-function readViewportBasis(): number {
- return typeof window === 'undefined' ? SERVER_BASIS : window.innerWidth;
-}
-
-function readServerBasis(): number {
- return SERVER_BASIS;
-}
-
-/** The window's extent along a horizontal hook's axis. */
-function readWindowWidth(): number | null {
- return typeof window === 'undefined' ? null : window.innerWidth;
-}
-
-/** The window's extent along a vertical hook's axis. */
-function readWindowHeight(): number | null {
- return typeof window === 'undefined' ? null : window.innerHeight;
-}
-
-function readNoWindowExtent(): null {
- return null;
-}
// =============================================================================
-// Single-region hook
+// Single-region hook: the configuration object, on the factory
// =============================================================================
-function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
- const {
- defaultSize,
- minSize,
- maxSize,
- containerRef,
- direction = 'horizontal',
- collapsible = false,
- collapsedSize = DEFAULT_COLLAPSED_SIZE,
- snaps: configuredSnaps,
- autoSaveId,
- defaultIsCollapsed,
- isCollapsed: controlledIsCollapsed,
- onSizeChange,
- onCollapseChange,
- } = config;
- const emptySnapsRef = useRef<number[]>([]);
- const snaps = configuredSnaps ?? emptySnapsRef.current;
-
- const rawMin = minSize;
- const rawMax = maxSize;
-
- const parsedDefault = parseSize(defaultSize);
- const parsedMin = parseSize(minSize);
- const parsedMax = parseSize(maxSize);
- const hasContainer = containerRef != null;
- const persisted = autoSaveId ? loadPersistedState(autoSaveId) : null;
- const initialDefaultRef = useRef<{px: number; isFinal: boolean} | null>(null);
- const [, setDefaultBasisCleanupTick] = useState(0);
-
- const defaultDependsOnBasis = dependsOnBasis(parsedDefault);
- const boundsDependOnBasis =
- dependsOnBasis(parsedMin) || dependsOnBasis(parsedMax);
- // A default needs a live container only until its initial pixel choice is
- // final. A persisted pixel choice wins without measuring the unused default.
- // Bounds are different: percentages keep following the basis so they can
- // re-clamp the selected pixel size.
- const defaultNeedsInitialBasis =
- persisted?.size == null &&
- defaultDependsOnBasis &&
- initialDefaultRef.current?.isFinal !== true;
- const observeContainerBasis =
- hasContainer && (boundsDependOnBasis || defaultNeedsInitialBasis);
- const observeViewportBasis = !hasContainer && boundsDependOnBasis;
-
- // The container basis, read through the shared observer. `useSyncExternalStore`
- // rather than an effect: the store IS the measurement, so there is no render
- // that paints before the basis is known and no `setState` in an effect.
- //
- // The subscription depends on the ELEMENT, not on the ref object. A ref is
- // stable across an element swap, so `containerRef.current` can become a
- // different node — a remount behind the same ref, a conditional branch, a
- // portal moving — without any input to this hook changing. Keyed on the ref,
- // the old detached node stayed observed (and a detached node measures 0,
- // which is how a replacement zeroed the bounds) and the new one was never
- // observed at all.
- const containerElementRef = useRef<HTMLElement | null>(null);
- // DOM ref changes are invisible to React. This state is only a version tick
- // while basis observation is active; the element itself lives in a ref so it
- // can be released without adding a cleanup render.
- const [, setContainerElementVersion] = useState(0);
- const containerBasisRef = useRef<number | null>(null);
- const containerElement = observeContainerBasis
- ? containerElementRef.current
- : null;
-
- // Follow the ref only while some configuration needs its basis. A numeric-only
- // region never reads the ref. Once observation stops, drop both the element
- // and its measurement without a state update; a later percentage starts from
- // the ref's then-current element and a fresh basis.
- useIsomorphicLayoutEffect(() => {
- if (!observeContainerBasis) {
- containerElementRef.current = null;
- containerBasisRef.current = null;
- return;
- }
- const element = containerRef?.current ?? null;
- if (element !== containerElementRef.current) {
- containerBasisRef.current = null;
- containerElementRef.current = element;
- setContainerElementVersion(version => version + 1);
- }
- });
-
- const subscribeToContainer = useCallback(
- (onStoreChange: () => void) => {
- if (
- !observeContainerBasis ||
- containerElement == null ||
- containerElement !== containerRef?.current
- ) {
- return () => {};
- }
- // Unsubscribe by callback: several regions share one container, and any
- // number of unrelated hooks may observe the same node.
- return observeResize(containerElement, entry => {
- containerBasisRef.current = measureContentBox(
- containerElement,
- direction,
- entry,
- );
- onStoreChange();
- });
- },
- [containerElement, observeContainerBasis, direction, containerRef],
- );
- const readContainerBasis = useCallback(() => {
- if (!observeContainerBasis || containerElement == null) {
- // An inactive subscription owns no current measurement. Clearing this is
- // important when a percentage bound is added later: the first active
- // render must measure the container as it is now, not clamp against the
- // last basis seen by a default-only subscription.
- containerBasisRef.current = null;
- return null;
- }
- // Cached in a ref so the snapshot is referentially stable between resizes;
- // returning a fresh measurement every call would loop the store.
- if (containerBasisRef.current == null) {
- containerBasisRef.current = measureContentBox(
- containerElement,
- direction,
- );
- }
- return containerBasisRef.current;
- }, [containerElement, observeContainerBasis, direction]);
- const containerBasis = useSyncExternalStore(
- subscribeToContainer,
- readContainerBasis,
- () => null,
- );
-
- // The viewport basis is always readable synchronously. Percentage-dependent
- // BOUNDS subscribe to later resizes (FR6); a default reads the initial
- // snapshot only, because it becomes a pixel choice immediately.
- const subscribeToViewport = useCallback(
- (onStoreChange: () => void) => {
- if (
- hasContainer ||
- !observeViewportBasis ||
- typeof window === 'undefined'
- ) {
- return () => {};
- }
- window.addEventListener('resize', onStoreChange);
- return () => window.removeEventListener('resize', onStoreChange);
- },
- [hasContainer, observeViewportBasis],
- );
- const viewportBasis = useSyncExternalStore(
- subscribeToViewport,
- readViewportBasis,
- readServerBasis,
- );
-
- // The window's extent along the hook's axis, for the REPORTED maximum of an
- // unbounded region (never for clamping). Read through the same store shape
- // so a server-rendered handle hydrates with no maximum and gains the real
- // one on the first client render, instead of a hydration mismatch. It takes
- // no resize subscription: an unbounded pixel region observes nothing
- // (component:Resizable Performance and resources).
- const windowExtent = useSyncExternalStore(
- noopSubscribe,
- direction === 'vertical' ? readWindowHeight : readWindowWidth,
- readNoWindowExtent,
- );
-
- // With a container, its content box is the basis; without one, the released
- // viewport basis. Before a supplied container has been measured — the first
- // render, the server, and any moment it is display:none or detached — the
- // deterministic 1200px stands in, and the first real measurement replaces it.
- //
- // A zero measurement is not a measurement. A hidden or detached container
- // reports 0, and resolving `'50%'` against it produced a real maximum of 0:
- // the panel collapsed and, with `autoSaveId`, that 0 was written over a
- // perfectly good saved width. Treating 0 as unmeasured keeps the temporary
- // basis until the container is actually laid out (AST-010 Platform support).
- const needsContainerBasis = observeContainerBasis;
- const hasPositiveMeasurement = containerBasis != null && containerBasis > 0;
- const liveBasis = hasContainer
- ? hasPositiveMeasurement
- ? containerBasis
- : SERVER_BASIS
- : viewportBasis;
- const isBasisMeasured = needsContainerBasis ? hasPositiveMeasurement : true;
-
- // One stable basis per gesture. A container that resizes mid-drag would
- // 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 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);
- const didWarnDefaultRef = useRef(false);
- const didWarnInvertedRef = useRef(false);
-
- // Bounds re-resolve from the live basis on every render — that is the whole
- // point of a percentage bound — and clamp the pixel selection below.
- const resolvedMin = resolveBound(
- rawMin,
- parsedMin,
- basis,
- DEFAULT_MIN,
- 'minSize',
- RESIZABLE_SIZE_GUIDANCE,
- didWarnMinRef,
- );
- const resolvedMax = resolveBound(
- rawMax,
- parsedMax,
- basis,
- Infinity,
- 'maxSize',
- RESIZABLE_SIZE_GUIDANCE,
- didWarnMaxRef,
- );
-
- // A basis-dependent default is resolved ONCE into a pixel size. Latched in a
- // ref (React's sanctioned lazy-init shape) rather than recomputed, because a
- // default that kept tracking its basis would be a second, responsive sizing
- // mode — the thing this API deliberately does not have.
- //
- // Not final while a supplied container is still unmeasured: that render used
- // the temporary 1200px stand-in, and the first real measurement replaces it.
- // Once final, a default-only subscription is removed. The correction is not a
- // user interaction, so it neither persists the placeholder nor fires
- // `onSizeChange`.
- if (initialDefaultRef.current == null || !initialDefaultRef.current.isFinal) {
- initialDefaultRef.current = {
- px: resolveBound(
- defaultSize,
- parsedDefault,
- basis,
- DEFAULT_SIZE_FALLBACK,
- 'defaultSize',
- RESIZABLE_SIZE_GUIDANCE,
- didWarnDefaultRef,
- ),
- isFinal: isBasisMeasured,
- };
- }
- const initialDefaultPx = initialDefaultRef.current.px;
-
- // The size the user has settled on, or null while a container-relative
- // default is still waiting for its first positive measurement. Once that
- // basis is real, the default becomes an ordinary pixel selection — including
- // any clamp applied at initialization. Leaving it represented by `null`
- // allowed the raw default to be re-read later: 321px first clamped to 200px
- // in a 400px container, then revived to 321px when the container grew.
- //
- // Initialized outright whenever the basis is already real on the first
- // render — every pixel-only configuration, and the no-container percentage
- // path. Only a supplied container needs a measurement that does not exist
- // until after commit, so only it starts null. Initializing lazily in all
- // cases cost every legacy pixel-only mount a second render pass, because the
- // adjustment below then had to run on the first render to fill the value in.
- const [chosenSize, setChosenSize] = useState<number | null>(() => {
- if (persisted?.size != null) {
- return persisted.size;
- }
- return isBasisMeasured
- ? clampSize(initialDefaultPx, resolvedMin, resolvedMax, snaps)
- : null;
- });
-
- if (
- hasContainer &&
- !boundsDependOnBasis &&
- isBasisMeasured &&
- defaultNeedsInitialBasis &&
- chosenSize != null
- ) {
- // A programmatic resize may have selected pixels while the container was
- // still unmeasured, so chosenSize can already be non-null here. Force the
- // render that re-evaluates and removes the now-finished default subscription.
- setDefaultBasisCleanupTick(tick => tick + 1);
- }
-
- if (isBasisMeasured && chosenSize == null) {
- // The supplied container has now been measured, so the selection latched
- // against the temporary basis is replaced by one against the real one.
- // Render-phase adjustment is deliberate: React re-runs this render before
- // paint, so the corrected selection, paint, persistence, and ARIA all see
- // the same pixel value. It fires no interaction callback.
- setChosenSize(clampSize(initialDefaultPx, resolvedMin, resolvedMax, snaps));
- }
-
- // A re-resolved bound clamps the SELECTION, not just the paint. Deriving
- // alone was not enough: the stored choice survived, so a container that
- // shrank and grew again revived the pre-clamp size — measured 320px
- // reviving to 560px. The clamp has to be committed to be permanent.
- //
- // Adjusting state during render (React's documented shape for "a prop
- // changed, so state must follow") rather than in an effect: React re-runs
- // this render before painting, so nothing shows at the stale size, and no
- // interaction callback fires for what is only a layout correction (FR10).
- //
- // Held until the basis is final. Before a supplied container is measured the
- // bounds come from the temporary 1200px stand-in, and committing against
- // that would move a persisted size to fit a basis that was never real.
- const [committedBounds, setCommittedBounds] = useState({
- min: resolvedMin,
- max: resolvedMax,
- });
- if (
- isBasisMeasured &&
- gestureBasisRef.current == null &&
- (committedBounds.min !== resolvedMin || committedBounds.max !== resolvedMax)
- ) {
- setCommittedBounds({min: resolvedMin, max: resolvedMax});
- setChosenSize(current =>
- current == null
- ? null
- : clampSize(current, resolvedMin, resolvedMax, snaps),
- );
- }
-
- // Derived for paint, so the clamp above and the rendered size agree on the
- // very render that observes a new basis.
- const size = clampSize(
- chosenSize ?? initialDefaultPx,
- resolvedMin,
- resolvedMax,
- snaps,
- );
- const [uncontrolledIsCollapsed, setUncontrolledIsCollapsed] = useState(
- () => persisted?.isCollapsed ?? defaultIsCollapsed ?? false,
- );
-
- const isControlled = controlledIsCollapsed !== undefined;
- const isCollapsed =
- collapsible &&
- (isControlled ? controlledIsCollapsed : uncontrolledIsCollapsed);
- const dragStartSizeRef = useRef(size);
-
- // Mirrors isCollapsed so the callbacks below read the live value instead of
- // the one their last render captured. Two cases reach them from a stale
- // closure: two imperative calls in one tick, and a drag — ResizeHandle
- // registers its pointermove listener once at pointer down, so a whole
- // gesture runs against one props snapshot.
- const isCollapsedRef = useRef(isCollapsed);
- isCollapsedRef.current = isCollapsed;
-
- // Controlled callers own the state; collapse() and a drag past the
- // threshold report through onCollapseChange and change nothing here.
- const setCollapsed = useCallback(
- (value: boolean) => {
- if (!isControlled) {
- isCollapsedRef.current = value;
- setUncontrolledIsCollapsed(value);
- }
- },
- [isControlled],
- );
-
- useEffect(() => {
- if (resolvedMin > resolvedMax && !didWarnInvertedRef.current) {
- didWarnInvertedRef.current = true;
- devWarn(
- 'useResizable',
- `the resolved minimum (${resolvedMin}px) is above the resolved ` +
- `maximum (${resolvedMax}px). The maximum wins, as it always has.`,
- );
- }
- }, [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) {
- 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;
- }
- // 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
- // transition that already happened.
- if (!collapsible || isCollapsedRef.current) {
- return;
- }
- setCollapsed(true);
- onCollapseChange?.(true);
- onSizeChange?.(0);
- }, [collapsible, setCollapsed, onCollapseChange, onSizeChange]);
-
- const expand = useCallback(() => {
- const wasCollapsed = isCollapsedRef.current;
- setCollapsed(false);
- if (wasCollapsed) {
- onCollapseChange?.(false);
- }
- onSizeChange?.(size);
- }, [setCollapsed, size, onCollapseChange, onSizeChange]);
-
- const resize = useCallback(
- (newSize: number) => {
- // An invalid programmatic size repairs nothing — it must not replace a
- // legal selection with NaN, which would then reach paint, storage and
- // `aria-valuenow`.
- if (!Number.isFinite(newSize) || newSize < 0) {
- devWarn(
- 'useResizable',
- `resize(${String(newSize)}) is not a pixel size. Keeping the ` +
- 'current size. Percentages configure the hook; they are not a ' +
- 'programmatic input.',
- );
- return;
- }
- const clamped = clampSize(newSize, resolvedMin, resolvedMax, snaps);
- const wasCollapsed = isCollapsedRef.current;
- setChosenSize(clamped);
- setCollapsed(false);
- // Resizing out of the collapsed state is an implicit expand — notify
- // like the drag path does when it crosses back over the threshold.
- if (wasCollapsed) {
- onCollapseChange?.(false);
- }
- onSizeChange?.(clamped);
- },
- [
- resolvedMin,
- resolvedMax,
- snaps,
- setCollapsed,
- onCollapseChange,
- onSizeChange,
- ],
- );
+const EMPTY_SNAPS: number[] = [];
+/**
+ * The configuration-object form: createResizable with no handle of its own,
+ * so the region's state has one copy, the factory's. The props it returns
+ * carry what the factory reports, and a ResizeHandle given them drives the
+ * factory's region through them.
+ */
+function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
+ const {getResizable, size, isCollapsed, snapshot, collapse, expand, resize} =
+ useResizableController(config);
+ // The region's side of the handle's gesture, read at each input, so a whole
+ // drag reaches the factory as it is now.
+ const model = useCallback(() => {
+ const current = getResizable();
+ return current == null ? undefined : readResizableInternals(current)?.model;
+ }, [getResizable]);
const onResizeStart = useCallback(() => {
- // Freeze the basis for the whole gesture so a container resizing mid-drag
- // cannot move the bound out from under the pointer.
- gestureBasisRef.current = liveBasis;
- dragStartSizeRef.current = isCollapsedRef.current ? 0 : size;
- }, [size, liveBasis]);
-
+ model()?.start();
+ }, [model]);
const onResizeMove = useCallback(
(delta: number) => {
- const raw = dragStartSizeRef.current + delta;
- if (collapsible && raw < collapsedSize) {
- if (!isCollapsedRef.current) {
- setCollapsed(true);
- onCollapseChange?.(true);
- onSizeChange?.(0);
- }
- return;
- }
- if (isCollapsedRef.current && raw >= collapsedSize) {
- setCollapsed(false);
- onCollapseChange?.(false);
- }
- const clamped = clampSize(raw, resolvedMin, resolvedMax, snaps);
- setChosenSize(clamped);
- onSizeChange?.(clamped);
+ model()?.move(delta);
},
- [
- collapsible,
- collapsedSize,
- setCollapsed,
- resolvedMin,
- resolvedMax,
- snaps,
- onSizeChange,
- onCollapseChange,
- ],
+ [model],
);
-
- // Releasing the frozen basis needs a render to apply whatever the basis
- // became during the gesture; that render's commit writes the final size.
- const releaseGestureBasis = useCallback(() => {
- if (gestureBasisRef.current != null) {
- gestureBasisRef.current = null;
- setGestureTick(tick => tick + 1);
- }
- }, []);
-
const onResizeEnd = useCallback(() => {
- // Sizes are already committed during move; the basis is held, and the
- // commit that releases it writes the final size to storage.
- releaseGestureBasis();
- }, [releaseGestureBasis]);
-
- // A gesture that is cancelled rather than completed — pointercancel, a lost
- // 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, and the
- // size it reached has to reach storage.
- const onResizeCancel = releaseGestureBasis;
-
- // The maximum a handle REPORTS (End uses only a configured maximum). A
- // configured maximum wins. Otherwise a measured extent stands in — the
- // container's content box while a percentage bound already observes it, or
- // the window's extent along the axis — and never drops below the current size, so
- // `aria-valuenow` can never exceed `aria-valuemax` (a saved, default, or
- // pre-resize size may already be larger than the window). An unobserved
- // container reports nothing: measuring it would add an observer to an
- // atomic pixel path.
- const measuredBasisForMax = hasContainer
- ? hasPositiveMeasurement && observeContainerBasis
- ? containerBasis
- : null
- : windowExtent;
- // Never below the announced value either: a collapsed pane announces the
- // resolved minimum as its value, so the stand-in floors there as well, and
- // `aria-valuemax` can never fall under `aria-valuemin`.
- const effectiveMaxPx =
- resolvedMax !== Infinity
- ? resolvedMax
- : measuredBasisForMax == null
- ? undefined
- : Math.max(measuredBasisForMax, isCollapsed ? resolvedMin : size);
+ model()?.end();
+ }, [model]);
+ const onResizeCancel = useCallback(() => {
+ model()?.cancel();
+ }, [model]);
const props: ResizableProps = {
- _size: isCollapsed ? 0 : size,
+ _size: size,
_isCollapsed: isCollapsed,
_onResizeStart: onResizeStart,
_onResizeMove: onResizeMove,
_onResizeEnd: onResizeEnd,
_onResizeCancel: onResizeCancel,
- _minSizePx: resolvedMin,
- _maxSizePx: resolvedMax,
- _snaps: snaps,
- _collapsedSize: collapsedSize,
- _collapsible: collapsible,
- _direction: direction,
+ _minSizePx: snapshot.minPx,
+ _maxSizePx: snapshot.maxPx,
+ _snaps: config.snaps ?? EMPTY_SNAPS,
+ _collapsedSize: config.collapsedSize ?? DEFAULT_COLLAPSED_SIZE,
+ _collapsible: config.collapsible ?? false,
+ _direction: config.direction ?? 'horizontal',
_isResizableProps: true,
};
collapseControls.set(props, {collapse, expand});
- // Without a configured maximum the basis stands in — only when it is a
- // real measurement (an observed container, or the window), never the
- // temporary 1200px placeholder (component:Resizable Performance: atomic
- // pixel paths add no observer, so an unobserved container stays unknown).
- // The released no-container basis is the window WIDTH on both axes; a
- // vertical region's reported maximum reads the window height instead.
- if (effectiveMaxPx != null) {
- effectiveMaxima.set(props, effectiveMaxPx);
+ // Without a configured maximum a measured extent stands in, only once it
+ // is a real measurement (an observed container, or the window).
+ if (snapshot.effectiveMaxPx != null) {
+ effectiveMaxima.set(props, snapshot.effectiveMaxPx);
}
- return {
- size: isCollapsed ? 0 : size,
- isCollapsed,
- collapse,
- expand,
- resize,
- props,
- };
+ return {size, isCollapsed, collapse, expand, resize, props};
}
// =============================================================================
@@ -949,6 +376,248 @@ type MultiResizableArgument<Config extends UseResizableMultiConfig> =
}
: never;
+// =============================================================================
+// The resize factory in React
+// =============================================================================
+
+interface ResizableEntry {
+ readonly resizable: ResizableController;
+ /** The options the factory has now: those it was created with, or updated to. */
+ passed: CreateResizableOptions;
+}
+
+/**
+ * The factory a hook holds, and one store over it for React. It follows the
+ * factory the slot holds now and reads the snapshot that factory reports.
+ * Before there is one, it reads the state the region starts in. A reading
+ * equal in every part to the last one is the last one. So a mount that
+ * settles where it started renders once.
+ */
+interface ResizableSlot {
+ get(): ResizableEntry | null;
+ set(next: ResizableEntry | null): void;
+ subscribe(listener: () => void): () => void;
+ read(): ResizableSnapshot;
+}
+
+function sameSnapshot(a: ResizableSnapshot, b: ResizableSnapshot): boolean {
+ return (
+ a.size === b.size &&
+ a.isCollapsed === b.isCollapsed &&
+ a.expandedSize === b.expandedSize &&
+ a.minPx === b.minPx &&
+ a.maxPx === b.maxPx &&
+ a.effectiveMaxPx === b.effectiveMaxPx
+ );
+}
+
+function createSlot(initial: ResizableSnapshot): ResizableSlot {
+ let current: ResizableEntry | null = null;
+ let last: ResizableSnapshot = initial;
+ const listeners = new Set<() => void>();
+ let stopFactory: (() => void) | null = null;
+ const notify = () => {
+ for (const listener of [...listeners]) {
+ listener();
+ }
+ };
+ const follow = () => {
+ stopFactory?.();
+ stopFactory = null;
+ if (current != null && listeners.size > 0) {
+ const {resizable} = current;
+ const channel = readResizableInternals(resizable);
+ stopFactory =
+ channel != null
+ ? channel.subscribeSnapshot(notify)
+ : resizable.subscribe(notify);
+ }
+ };
+ return {
+ get: () => current,
+ set(next) {
+ current = next;
+ follow();
+ notify();
+ },
+ subscribe(listener) {
+ listeners.add(listener);
+ if (listeners.size === 1) {
+ follow();
+ }
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ stopFactory?.();
+ stopFactory = null;
+ }
+ };
+ },
+ read() {
+ if (current == null) {
+ return last;
+ }
+ const {resizable} = current;
+ // A stand-in controller without the internal channel reports only its
+ // size and collapse state.
+ const next = readResizableInternals(resizable)?.snapshot() ?? {
+ ...initial,
+ size: resizable.size,
+ isCollapsed: resizable.isCollapsed,
+ expandedSize: resizable.size,
+ };
+ if (!sameSnapshot(last, next)) {
+ last = next;
+ }
+ return last;
+ },
+ };
+}
+
+/** What the hook renders from its factory. */
+interface ResizableReading {
+ /** The region's size in px, 0 while collapsed. */
+ readonly size: number;
+ readonly isCollapsed: boolean;
+ readonly collapse: () => void;
+ readonly expand: () => void;
+ readonly resize: (size: number) => void;
+ /** The bounds the handle announces, and the size as expanded. */
+ readonly snapshot: ResizableSnapshot;
+ /** The factory the region has now: null before its first commit. */
+ readonly getResizable: () => ResizableController | null;
+}
+
+/**
+ * createResizable in React, with nothing of its own. It creates the factory as
+ * it mounts, passes later options through `update` and returns what the
+ * factory reports.
+ * Before its first commit (the server, the first render, a hydrating render)
+ * it returns the state the factory starts in. While it is unmounted or an
+ * `<Activity>` hides it, the factory lets go of the page and keeps the region.
+ * So collapse, expand and resize apply and report whenever they are called, as
+ * React state did. A call before the first commit starts the factory early.
+ *
+ * A controlled `isCollapsed` is read from the options in the render that
+ * passes it, before `update` reaches the factory. So the size and collapse
+ * state a parent renders land in the same commit as the state its
+ * `onCollapseChange` set.
+ */
+function useResizableController(
+ options: CreateResizableOptions,
+): ResizableReading {
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+ const [slot] = useState(() => createSlot(readInitialResizableState(options)));
+ const [serverInitial] = useState(() =>
+ readInitialResizableState(options, 'server'),
+ );
+ // The hook keeps one factory. After an unmount or an `<Activity>` hide, the
+ // same factory takes the page back (`resume`).
+ const follow = useCallback(() => {
+ const entry = slot.get();
+ if (entry != null) {
+ readResizableInternals(entry.resizable)?.resume();
+ return;
+ }
+ const passed = optionsRef.current;
+ const resizable = createResizableAs('useResizable', passed);
+ slot.set({resizable, passed});
+ }, [slot]);
+ useIsomorphicLayoutEffect(() => {
+ follow();
+ });
+ // On unmount, or when an `<Activity>` hides the component, the factory lets
+ // go of the page and keeps the region. Calls meanwhile apply, and a reveal
+ // goes on from where the region stands. A stand-in without the internal
+ // channel goes.
+ useIsomorphicLayoutEffect(
+ () => () => {
+ const entry = slot.get();
+ if (entry == null) {
+ return;
+ }
+ const channel = readResizableInternals(entry.resizable);
+ if (channel != null) {
+ channel.suspend();
+ } else {
+ slot.set(null);
+ entry.resizable.destroy();
+ }
+ },
+ [slot],
+ );
+ // The factory, a store outside React: each new options object reaches it
+ // through update().
+ useIsomorphicLayoutEffect(() => {
+ const entry = slot.get();
+ if (entry != null && options !== entry.passed) {
+ entry.passed = options;
+ entry.resizable.update(options);
+ }
+ }, [slot, options]);
+ // A container swapped behind `containerRef` with the same options: the
+ // factory follows it at each commit, as it follows new options.
+ useIsomorphicLayoutEffect(() => {
+ const entry = slot.get();
+ if (entry != null) {
+ readResizableInternals(entry.resizable)?.syncContainer();
+ }
+ });
+
+ const snapshot = useSyncExternalStore(
+ slot.subscribe,
+ slot.read,
+ () => serverInitial,
+ );
+ // When an `<Activity>` shows this component, React subscribes to the slot
+ // again but does not read it. The factory resumes and reports in that same
+ // commit. Render again with what it reports.
+ const [, rerender] = useReducer((count: number) => count + 1, 0);
+ useIsomorphicLayoutEffect(() => {
+ if (slot.read() !== snapshot) {
+ rerender();
+ }
+ });
+ const isControlled = options.isCollapsed !== undefined;
+ const isCollapsed = isControlled
+ ? (options.collapsible ?? false) && Boolean(options.isCollapsed)
+ : snapshot.isCollapsed;
+ const size = isControlled
+ ? isCollapsed
+ ? 0
+ : snapshot.expandedSize
+ : snapshot.size;
+
+ const getResizable = useCallback(() => slot.get()?.resizable ?? null, [slot]);
+ // A call before the first commit, from a child's layout effect say, starts
+ // the factory now. The factory stays off the page until that commit.
+ const ensureResizable = useCallback((): ResizableController => {
+ const entry = slot.get();
+ if (entry != null) {
+ return entry.resizable;
+ }
+ const passed = optionsRef.current;
+ const resizable = createResizableAs('useResizable', passed);
+ readResizableInternals(resizable)?.suspend();
+ slot.set({resizable, passed});
+ return resizable;
+ }, [slot]);
+ const collapse = useCallback(() => {
+ ensureResizable().collapse();
+ }, [ensureResizable]);
+ const expand = useCallback(() => {
+ ensureResizable().expand();
+ }, [ensureResizable]);
+ const resize = useCallback(
+ (next: number) => {
+ ensureResizable().resize(next);
+ },
+ [ensureResizable],
+ );
+ return {snapshot, getResizable, size, isCollapsed, collapse, expand, resize};
+}
+
export function useResizable<const Config extends UseResizableSingleConfig>(
config: SingleResizableArgument<Config>,
): ResizableRegion;
diff --git a/packages/core/src/Resizable/useResizableConfig.test.tsx b/packages/core/src/Resizable/useResizableConfig.test.tsx
new file mode 100644
index 0000000000..52e4b1c972
--- /dev/null
+++ b/packages/core/src/Resizable/useResizableConfig.test.tsx
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useResizableConfig.test.tsx
+ * @input vitest (jsdom), Testing Library, the configuration-object
+ * useResizable over a stand-in createResizable
+ * @output Checks that useResizable(config) builds on createResizable: it
+ * creates one factory, so the region's state has one copy, passes later
+ * options through update(), destroys it on unmount, and returns what the
+ * factory reports
+ * @position Unit tests for the configuration-object signature of
+ * useResizable.ts
+ */
+
+import {act, render} from '@testing-library/react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import type * as CreateResizableModule from './createResizable';
+import type {
+ CreateResizableOptions,
+ ResizableController,
+} from './createResizable';
+import type {ResizableRegion, UseResizableSingleConfig} from './useResizable';
+
+interface FakeController extends ResizableController {
+ emit(): void;
+ setState(next: {size?: number; isCollapsed?: boolean}): void;
+}
+
+const created: {options: CreateResizableOptions}[] = [];
+let fake: FakeController;
+
+vi.mock('./createResizable', async importOriginal => {
+ const original = await importOriginal<typeof CreateResizableModule>();
+ const createStandIn = (options: CreateResizableOptions = {}) => {
+ created.push({options});
+ const listeners = new Set<() => void>();
+ let state = {size: 123, isCollapsed: false};
+ fake = {
+ get size() {
+ return state.size;
+ },
+ get isCollapsed() {
+ return state.isCollapsed;
+ },
+ collapse: vi.fn(),
+ expand: vi.fn(),
+ resize: vi.fn(),
+ update: vi.fn(),
+ destroy: vi.fn(),
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ emit: () => {
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ setState: next => {
+ state = {...state, ...next};
+ },
+ };
+ return fake;
+ };
+ return {
+ ...original,
+ createResizable: vi.fn(createStandIn),
+ // useResizable's own entry, which names its warnings.
+ createResizableAs: vi.fn(
+ (_source: string, options?: CreateResizableOptions) =>
+ createStandIn(options),
+ ),
+ };
+});
+
+const {useResizable} = await import('./useResizable');
+
+afterEach(() => {
+ created.length = 0;
+});
+
+function ConfigSplit({
+ config,
+ onRegion,
+}: {
+ config: UseResizableSingleConfig;
+ onRegion: (region: ResizableRegion) => void;
+}) {
+ const region = useResizable(config);
+ onRegion(region);
+ return <div data-testid="pane" style={{width: region.size}} />;
+}
+
+describe('useResizable(config) builds on createResizable too, so the region state has one copy (spec:AST-107 FR6; architecture:public-component-api INV22)', () => {
+ it('creates one factory from the configuration, updates it, and destroys it on unmount', () => {
+ const first: UseResizableSingleConfig = {
+ defaultSize: 200,
+ minSize: 100,
+ collapsible: true,
+ };
+ const view = render(<ConfigSplit config={first} onRegion={() => {}} />);
+ expect(created).toHaveLength(1);
+ expect(created[0].options).toMatchObject(first);
+
+ const second: UseResizableSingleConfig = {
+ defaultSize: 200,
+ minSize: 150,
+ collapsible: true,
+ };
+ view.rerender(<ConfigSplit config={second} onRegion={() => {}} />);
+ expect(created).toHaveLength(1);
+ expect(fake.update).toHaveBeenLastCalledWith(
+ expect.objectContaining(second),
+ );
+
+ view.unmount();
+ expect(fake.destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it('passes a configuration it was created with to the factory again, after another one came between', () => {
+ const wide: UseResizableSingleConfig = {defaultSize: 300, maxSize: 500};
+ const narrow: UseResizableSingleConfig = {defaultSize: 300, maxSize: 200};
+ const view = render(<ConfigSplit config={wide} onRegion={() => {}} />);
+ view.rerender(<ConfigSplit config={narrow} onRegion={() => {}} />);
+ expect(fake.update).toHaveBeenLastCalledWith(narrow);
+ view.rerender(<ConfigSplit config={wide} onRegion={() => {}} />);
+ expect(fake.update).toHaveBeenLastCalledWith(wide);
+ expect(created).toHaveLength(1);
+ });
+
+ it('returns what the factory reports, in its size, collapse state and props, and its methods call the factory', () => {
+ let region: ResizableRegion | undefined;
+ render(
+ <ConfigSplit
+ config={{defaultSize: 200, collapsible: true}}
+ onRegion={next => {
+ region = next;
+ }}
+ />,
+ );
+ expect(region?.size).toBe(123);
+ expect(region?.props._size).toBe(123);
+ act(() => {
+ fake.setState({size: 0, isCollapsed: true});
+ fake.emit();
+ });
+ expect(region?.isCollapsed).toBe(true);
+ expect(region?.props._isCollapsed).toBe(true);
+ expect(region?.props._size).toBe(0);
+ region?.collapse();
+ region?.expand();
+ region?.resize(250);
+ expect(fake.collapse).toHaveBeenCalledTimes(1);
+ expect(fake.expand).toHaveBeenCalledTimes(1);
+ expect(fake.resize).toHaveBeenCalledWith(250);
+ });
+});
diff --git a/packages/core/src/Resizable/useResizableForms.test.tsx b/packages/core/src/Resizable/useResizableForms.test.tsx
new file mode 100644
index 0000000000..ad6777b18a
--- /dev/null
+++ b/packages/core/src/Resizable/useResizableForms.test.tsx
@@ -0,0 +1,260 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useResizableForms.test.tsx
+ * @input vitest (jsdom), Testing Library, the configuration-object
+ * useResizable over the real createResizable, and ResizeHandle
+ * @output Checks that the configuration-object form reports size and
+ * isCollapsed in the same commit as onCollapseChange, controlled or not
+ * (component:Resizable FR8: unchanged), keeps its size and collapse
+ * state across an `<Activity>` that hides and shows it, and applies
+ * collapse(), expand() and resize() called before its first layout effect
+ * or while hidden, reporting them at once, as before
+ * @position Integration tests for useResizable.ts and createResizable.ts
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {Activity, useLayoutEffect, useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {ResizeHandle} from './ResizeHandle';
+import {useResizable, type ResizableRegion} from './useResizable';
+
+interface Commit {
+ reported: boolean;
+ isCollapsed: boolean;
+ size: number;
+}
+
+let commits: Commit[] = [];
+let region: Pick<
+ ResizableRegion,
+ 'collapse' | 'expand' | 'isCollapsed' | 'size'
+> | null = null;
+
+/** Records what every commit shows: the parent's state and the hook's. */
+function useRecord(reported: boolean, isCollapsed: boolean, size: number) {
+ useLayoutEffect(() => {
+ commits.push({reported, isCollapsed, size});
+ });
+}
+
+function Pane({size}: {size: number}) {
+ return <div data-testid="pane" style={{width: size}} />;
+}
+
+function ConfigSplit({isControlled}: {isControlled: boolean}) {
+ const [reported, setReported] = useState(false);
+ const value = useResizable({
+ defaultSize: 200,
+ collapsible: true,
+ ...(isControlled ? {isCollapsed: reported} : {}),
+ onCollapseChange: setReported,
+ });
+ region = value;
+ useRecord(reported, value.isCollapsed, value.size);
+ return (
+ <>
+ <Pane size={value.size} />
+ <ResizeHandle resizable={value.props} label="Resize pane" />
+ </>
+ );
+}
+
+const separator = () => screen.getByRole('separator', {name: 'Resize pane'});
+const grabZone = () => separator().firstElementChild as HTMLElement;
+
+/** Every commit shows the parent's reported state and the hook's together. */
+function expectInStep(): void {
+ expect(commits.length).toBeGreaterThan(0);
+ for (const commit of commits) {
+ expect(commit, JSON.stringify(commits)).toMatchObject({
+ isCollapsed: commit.reported,
+ });
+ if (commit.isCollapsed) {
+ expect(commit.size).toBe(0);
+ } else {
+ expect(commit.size).toBeGreaterThan(0);
+ }
+ }
+}
+
+beforeEach(() => {
+ commits = [];
+ region = null;
+ localStorage.clear();
+});
+
+afterEach(() => {
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+});
+
+describe('size and isCollapsed land in the same commit as onCollapseChange (component:Resizable FR8)', () => {
+ for (const [form, Split] of [
+ ['useResizable(config)', ConfigSplit],
+ ] as const) {
+ for (const isControlled of [true, false]) {
+ it(`${form}, ${isControlled ? 'controlled' : 'uncontrolled'}: collapse(), Enter, expand(), a double-click and a drag past the threshold`, () => {
+ render(<Split isControlled={isControlled} />);
+ act(() => {
+ region?.collapse();
+ });
+ expect(region?.isCollapsed).toBe(true);
+ expectInStep();
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ expect(region?.isCollapsed).toBe(false);
+ expectInStep();
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ expect(region?.isCollapsed).toBe(true);
+ act(() => {
+ region?.expand();
+ });
+ expect(region?.isCollapsed).toBe(false);
+ fireEvent.doubleClick(separator());
+ expect(region?.isCollapsed).toBe(true);
+ fireEvent.doubleClick(separator());
+ expect(region?.isCollapsed).toBe(false);
+ expectInStep();
+ fireEvent.pointerDown(grabZone(), {pointerId: 1, clientX: 300});
+ fireEvent.pointerMove(grabZone(), {pointerId: 1, clientX: 110});
+ expect(region?.isCollapsed).toBe(true);
+ fireEvent.pointerMove(grabZone(), {pointerId: 1, clientX: 320});
+ fireEvent.pointerUp(grabZone(), {pointerId: 1, clientX: 320});
+ expect(region?.isCollapsed).toBe(false);
+ expectInStep();
+ });
+ }
+ }
+});
+
+describe('collapse(), expand() and resize() on a configuration-object region apply whenever they are called (behavior unchanged)', () => {
+ it("apply when called before the hook's first layout effect, and report at once", () => {
+ const onCollapseChange = vi.fn();
+ const onSizeChange = vi.fn();
+ let held: ResizableRegion | undefined;
+ /** A child's layout effect runs before its parent's. */
+ function Early({target}: {target: ResizableRegion}) {
+ const [initial] = useState(target);
+ useLayoutEffect(() => {
+ initial.resize(300);
+ initial.collapse();
+ }, [initial]);
+ return null;
+ }
+ function Split() {
+ const value = useResizable({
+ defaultSize: 200,
+ collapsible: true,
+ onCollapseChange,
+ onSizeChange,
+ });
+ held = value;
+ return (
+ <>
+ <ResizeHandle resizable={value.props} label="Resize pane" />
+ <Early target={value} />
+ </>
+ );
+ }
+ render(<Split />);
+ expect(onSizeChange.mock.calls).toEqual([[300], [0]]);
+ expect(onCollapseChange.mock.calls).toEqual([[true]]);
+ expect(held?.isCollapsed).toBe(true);
+ expect(held?.size).toBe(0);
+ act(() => {
+ held?.expand();
+ });
+ expect(held?.size).toBe(300);
+ expect(separator()).toHaveAttribute('aria-valuenow', '300');
+ });
+
+ it('apply while an <Activity> hides the region, report at once, and show after the reveal', () => {
+ const onCollapseChange = vi.fn();
+ let held: ResizableRegion | undefined;
+ function Panel() {
+ held = useResizable({
+ defaultSize: 250,
+ collapsible: true,
+ onCollapseChange,
+ });
+ return <ResizeHandle resizable={held.props} label="Resize pane" />;
+ }
+ function Host({isVisible}: {isVisible: boolean}) {
+ return (
+ <Activity mode={isVisible ? 'visible' : 'hidden'}>
+ <Panel />
+ </Activity>
+ );
+ }
+ const view = render(<Host isVisible />);
+ const visibleRegion = held;
+ view.rerender(<Host isVisible={false} />);
+ act(() => {
+ visibleRegion?.collapse();
+ });
+ expect(onCollapseChange.mock.calls).toEqual([[true]]);
+ view.rerender(<Host isVisible />);
+ expect(held?.isCollapsed).toBe(true);
+ view.rerender(<Host isVisible={false} />);
+ act(() => {
+ visibleRegion?.resize(320);
+ });
+ expect(onCollapseChange.mock.calls).toEqual([[true], [false]]);
+ view.rerender(<Host isVisible />);
+ expect(held?.isCollapsed).toBe(false);
+ expect(held?.size).toBe(320);
+ expect(separator()).toHaveAttribute('aria-valuenow', '320');
+ });
+});
+
+describe('a configuration-object region under an Activity', () => {
+ it('keeps its size and collapse state across a hide and a show', () => {
+ let held: ReturnType<typeof useResizableRegion> | undefined;
+ function useResizableRegion() {
+ return useResizable({defaultSize: 250, collapsible: true});
+ }
+ function Panel() {
+ held = useResizableRegion();
+ return <ResizeHandle resizable={held.props} />;
+ }
+ function Host() {
+ const [isVisible, setIsVisible] = useState(true);
+ return (
+ <>
+ <button type="button" onClick={() => setIsVisible(!isVisible)}>
+ visibility
+ </button>
+ <Activity mode={isVisible ? 'visible' : 'hidden'}>
+ <Panel />
+ </Activity>
+ </>
+ );
+ }
+ const toggle = () => {
+ act(() => {
+ screen.getByRole('button', {name: 'visibility'}).click();
+ });
+ };
+ render(<Host />);
+ act(() => {
+ held?.resize(300);
+ });
+ toggle();
+ toggle();
+ expect(held?.size).toBe(300);
+ expect(screen.getByRole('separator')).toHaveAttribute(
+ 'aria-valuenow',
+ '300',
+ );
+ act(() => {
+ held?.collapse();
+ });
+ toggle();
+ toggle();
+ expect(held?.isCollapsed).toBe(true);
+ act(() => {
+ held?.expand();
+ });
+ expect(held?.size).toBe(300);
+ });
+});