Skip to content

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

TypeScript

fix(useResizable): add structured percentage sizing (#5783)

freddymeta311deefcafeb
diff --git a/.changeset/resizable-percentage-config.md b/.changeset/resizable-percentage-config.md
new file mode 100644
index 0000000000..8151cec147
--- /dev/null
+++ b/.changeset/resizable-percentage-config.md
@@ -0,0 +1,29 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] useResizable: percentage configuration with an explicit basis (AST-010)
+
+Implements the accepted [AST-010](../docs/specs/AST-010/spec.md) contract. Percentages **configure** a pixel size; they never create a second, responsive sizing mode.
+
+- **`minSize` / `maxSize`** join `defaultSize` in one vocabulary: a non-negative finite number, an exact `Npx`, an exact `N%` from 0–100, Table's existing `pixel(value)`, or `percent(value, {min: pixel(value)})` / `percent(value, {max: pixel(value)})` for a percentage with exactly one pixel floor or ceiling. `percent()` requires its options; `'40%'` remains the only unbounded percentage spelling. `minSizePx`/`maxSizePx` remain deprecated aliases, each an exact mutually-exclusive TypeScript union with its replacement; if untyped code supplies both, the unified prop wins and development names the ignored alias.
+- **`containerRef`** (caller-owned) changes only what a percentage is a share of: that element's **content-box** size on the active axis, `direction` selecting inline or block. Omitted, percentages keep the released one-time `window.innerWidth` resolution with its 1200px server fallback.
+- **A percentage default resolves once** into a pixel selection, applying its optional structured floor or ceiling exactly once. Percentage **bounds** re-resolve with their basis, apply that one pixel bound, and clamp the selection — they never rescale it. A basis change is not a user interaction: it fires no `onSizeChange` and persists only resolved pixels.
+- **Everything else stays pixels**, exactly as released: pointer, keyboard, snaps, collapse/expand, persistence, callbacks, and `resize(number)`. `resize('50%')` remains a type error, and `resize(NaN)`, `resize(Infinity)` or a negative now warn and keep the last legal size instead of poisoning state.
+- **Invalid configuration** repairs deterministically — 250px for a default, 50px for a minimum, unbounded for a maximum — identically in development and production, warning only in development. Explicit `maxSize: Infinity` and `maxSizePx: Infinity` keep the released unbounded behavior. The deprecated aliases retain their released exact atomic-string behavior for untyped callers. An inverted pair warns and the maximum wins, preserving the released clamp order.
+
+The structured API follows Table's existing shape rather than parsing CSS expressions: `Resizable/utils` is a server-safe subpath that re-exports the exact same `pixel()` binding and `PixelWidth` type as `Table/utils`, alongside Resizable's `percent()` and types. `pixel(value)` is the canonical structured static size; raw numbers and exact `Npx` remain compatible. `proportional()` remains Table-only because it describes sibling weight, not a literal percentage of one measured basis. CSS `min()` / `max()` strings are deliberately unsupported.
+
+The defect this closes: a percentage ceiling could previously only be written in CSS, and CSS stops the paint but not the state. `ResizeHandle` publishes the hook's size as `aria-valuenow`, so the separator announced a width the panel did not have — measured at **899.5 against a 434px panel**. Bounds now clamp the state, so paint, persistence and ARIA describe one geometry.
+
+`ResizeHandle` also warns in development when its `direction` disagrees with its region's, which previously failed silently. Existing vertical panels must pass `direction: 'vertical'` to `useResizable` as well as `direction="vertical"` to the handle.
+
+The container basis follows the ref, not the element it first pointed at: replacing the element behind the same `containerRef` re-resolves against the replacement, and the element left behind is unobserved. A container that is not laid out yet — unmounted, `display:none`, detached — measures 0, which is not a measurement: percentages hold the documented temporary 1200px basis until it is real, and nothing is written to `autoSaveId` storage from it. Once the first real basis resolves, the default is committed as a pixel selection with its initial clamp included; a 321px default clamped to 200px therefore stays 200px when the container later grows instead of reviving the raw default.
+
+A gesture that is cancelled rather than completed — `pointercancel`, a lost pointer capture, a handle unmounted mid-drag — releases the basis it froze through a new optional `_onResizeCancel` on `ResizableProps`. It is not a resize end (a cancelled drag deliberately signals none, per #5297), but it is the end of the gesture. `_onResizeCancel` and `_direction` are both optional: `ResizableProps` is exported, so an object literal that satisfied the released type still compiles.
+
+Not in scope, per the spec: SideNav's simplified `defaultWidth`/`minWidth`/`maxWidth` stays pixel-only.
+
+A pixel-only configuration keeps its single render pass even when a `containerRef` is supplied. With no percentage anywhere there is no basis to observe or ref identity to follow, so the pixel selection is made at mount; only a basis-dependent configuration with a supplied container defers until that measurement exists.
+
+@freddymeta
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index afcb97cd29..fe712ca7e8 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -114,6 +114,28 @@
"next": "button[aria-label=\"Next\"]"
}
},
+ {
+ "component": "Layout",
+ "storyId": "core-layout--dual-panels",
+ "dims": [
+ "D2"
+ ],
+ "selectors": {
+ "prev": ".astryx-layout-panel:first-of-type",
+ "next": ".astryx-layout-panel:last-of-type"
+ }
+ },
+ {
+ "component": "Resizable",
+ "storyId": "lab-resizable--horizontal-split",
+ "dims": [
+ "D4"
+ ],
+ "selectors": {
+ "overlay": ".astryx-resize-handle",
+ "overlayRoot": ".astryx-layout"
+ }
+ },
{
"component": "Stepper",
"storyId": "core-stepper--default-horizontal",
diff --git a/apps/storybook/stories/Resizable.stories.tsx b/apps/storybook/stories/Resizable.stories.tsx
index 2953412f09..6b245df063 100644
--- a/apps/storybook/stories/Resizable.stories.tsx
+++ b/apps/storybook/stories/Resizable.stories.tsx
@@ -98,6 +98,7 @@ export const VerticalSplit: Story = {
defaultSize: 250,
minSizePx: 100,
maxSizePx: 350,
+ direction: 'vertical',
});
return (
<div {...stylex.props(ps.shell)}>
@@ -204,6 +205,7 @@ export const ThreePanelIDE: Story = {
defaultSize: 280,
minSizePx: 100,
maxSizePx: 350,
+ direction: 'vertical',
});
return (
<div {...stylex.props(ps.shell)}>
diff --git a/apps/storybook/stories/useResizable.stories.tsx b/apps/storybook/stories/useResizable.stories.tsx
index 24857ee2fc..f786bee757 100644
--- a/apps/storybook/stories/useResizable.stories.tsx
+++ b/apps/storybook/stories/useResizable.stories.tsx
@@ -1,5 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {useEffect, useRef, useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import * as stylex from '@stylexjs/stylex';
import {
@@ -8,6 +9,7 @@ import {
spacingVars,
} from '@astryxdesign/core/theme/tokens.stylex';
import {useResizable, ResizeHandle} from '@astryxdesign/core/Resizable';
+import {percent, pixel} from '@astryxdesign/core/Resizable/utils';
import {Layout, LayoutContent, LayoutPanel} from '@astryxdesign/core/Layout';
const s = stylex.create({
@@ -29,12 +31,152 @@ const s = stylex.create({
borderRadius: radiusVars['--radius-container'],
margin: spacingVars['--spacing-2'],
},
+ structuredStack: {
+ display: 'grid',
+ gap: spacingVars['--spacing-4'],
+ },
+ structuredFrame: {height: 180},
+ structuredLayout: {height: 80},
});
function HookDemo({children}: {children: React.ReactNode}) {
return <div>{children}</div>;
}
+function StructuredPercentProbe({
+ kind,
+ width,
+}: {
+ kind: 'default-wide' | 'default-narrow' | 'minimum' | 'maximum';
+ width: number;
+}) {
+ const frameRef = useRef<HTMLDivElement>(null);
+ const isDefault = kind.startsWith('default');
+ const isMinimum = kind === 'minimum';
+ const storageKey = `storybook-structured-percent-${kind}`;
+ const region = useResizable({
+ ...(isDefault
+ ? {defaultSize: percent(40, {min: pixel(333)})}
+ : isMinimum
+ ? {defaultSize: 0, minSize: percent(40, {min: pixel(333)})}
+ : {defaultSize: 500, maxSize: percent(10, {max: pixel(400)})}),
+ containerRef: frameRef,
+ direction: 'horizontal',
+ autoSaveId: storageKey,
+ });
+ const resolvedBound = isDefault
+ ? null
+ : isMinimum
+ ? region.props._minSizePx
+ : region.props._maxSizePx;
+ const label = isDefault
+ ? `defaultSize: percent(40, {min: pixel(333)})`
+ : isMinimum
+ ? `minSize: percent(40, {min: pixel(333)})`
+ : `maxSize: percent(10, {max: pixel(400)})`;
+
+ return (
+ <div
+ ref={frameRef}
+ data-testid={`structured-percent-${kind}-frame`}
+ data-width={width}
+ data-size={region.size}
+ data-resolved-bound={resolvedBound ?? undefined}
+ data-storage-key={`astryx-resizable:${storageKey}`}
+ {...stylex.props(s.shell, s.structuredFrame)}
+ style={{width}}>
+ <div {...stylex.props(s.card)}>
+ <strong>
+ {width}px outer / {width - 2}px content
+ </strong>
+ <div>
+ <code>{label}</code>
+ </div>
+ <div>
+ {Math.round(region.size)}px selected
+ {resolvedBound == null
+ ? ' initially'
+ : ` · ${Math.round(resolvedBound)}px resolved bound`}
+ </div>
+ </div>
+ <div {...stylex.props(s.structuredLayout)}>
+ <Layout
+ height="fill"
+ start={
+ <>
+ <LayoutPanel
+ width={region.size}
+ hasDivider={false}
+ data-testid={`structured-percent-${kind}-panel`}>
+ {Math.round(region.size)}px
+ </LayoutPanel>
+ <ResizeHandle
+ direction="horizontal"
+ hasDivider
+ label={`Resize structured percent ${kind} example`}
+ resizable={region.props}
+ />
+ </>
+ }
+ content={
+ <LayoutContent>
+ {isDefault
+ ? 'Later basis changes do not rescale this selected pixel size.'
+ : 'The percentage bound follows later basis changes.'}
+ </LayoutContent>
+ }
+ />
+ </div>
+ </div>
+ );
+}
+
+function StructuredPercentSizingStory() {
+ const [storageReady, setStorageReady] = useState(false);
+ const [resized, setResized] = useState(false);
+
+ useEffect(() => {
+ for (const kind of [
+ 'default-wide',
+ 'default-narrow',
+ 'minimum',
+ 'maximum',
+ ]) {
+ localStorage.removeItem(
+ `astryx-resizable:storybook-structured-percent-${kind}`,
+ );
+ }
+ setStorageReady(true);
+ }, []);
+
+ if (!storageReady) {
+ return null;
+ }
+
+ return (
+ <div
+ data-testid="structured-percent-sizing"
+ {...stylex.props(s.structuredStack)}>
+ <button
+ type="button"
+ data-testid="structured-percent-toggle-bases"
+ onClick={() => setResized(value => !value)}>
+ {resized ? 'Restore initial bases' : 'Change bases'}
+ </button>
+ <StructuredPercentProbe
+ kind="default-wide"
+ width={resized ? 500 : 1000}
+ />
+ <StructuredPercentProbe
+ kind="default-narrow"
+ width={resized ? 1000 : 500}
+ />
+ <StructuredPercentProbe kind="minimum" width={resized ? 1000 : 500} />
+ <StructuredPercentProbe kind="maximum" width={resized ? 500 : 1000} />
+ </div>
+ );
+}
+
const meta: Meta<typeof HookDemo> = {
title: 'Core/Hooks/useResizable',
component: HookDemo,
@@ -91,6 +233,7 @@ export const Vertical: Story = {
defaultSize: 150,
minSizePx: 60,
maxSizePx: 250,
+ direction: 'vertical',
});
return (
<div {...stylex.props(s.shell)}>
@@ -176,6 +319,7 @@ export const Nested: Story = {
defaultSize: 200,
minSizePx: 80,
maxSizePx: 250,
+ direction: 'vertical',
});
return (
<div {...stylex.props(s.shell)}>
@@ -277,6 +421,7 @@ export const MixedContainers: Story = {
defaultSize: 200,
minSizePx: 80,
maxSizePx: 250,
+ direction: 'vertical',
});
return (
<div {...stylex.props(s.shell)}>
@@ -329,3 +474,90 @@ export const MixedContainers: Story = {
);
},
};
+
+/**
+ * Percentage configuration, resolved against a container.
+ *
+ * `containerRef` marks what a percentage is a share of. The panel starts at 40%
+ * of the frame's content box and cannot be dragged past 60% of it. Narrow the
+ * frame and the BOUNDS follow — but the size you dragged to stays the pixel
+ * size you chose, clamped rather than rescaled. That is the whole contract:
+ * percentages configure pixels, they do not create a responsive mode.
+ */
+export const PercentageSizing: Story = {
+ render: () => {
+ const frameRef = useRef<HTMLDivElement>(null);
+ const region = useResizable({
+ defaultSize: '40%',
+ minSize: '15%',
+ maxSize: '60%',
+ containerRef: frameRef,
+ });
+ return (
+ <div ref={frameRef} {...stylex.props(s.shell)}>
+ <Layout
+ height="fill"
+ start={
+ <>
+ <LayoutPanel width={region.size} hasDivider={false}>
+ <div {...stylex.props(s.card)}>{Math.round(region.size)}px</div>
+ </LayoutPanel>
+ <ResizeHandle
+ direction="horizontal"
+ hasDivider
+ resizable={region.props}
+ />
+ </>
+ }
+ content={<LayoutContent>Content</LayoutContent>}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * Structured percentages support one explicit pixel floor or ceiling.
+ *
+ * `defaultSize: percent(40, {min: pixel(333)})` is an initial choice only. The same
+ * value on `minSize` remains a live floor, while `percent(10, {max: pixel(400)})` on
+ * `maxSize` remains a live ceiling. Numbers and exact `Npx` remain pixels; state,
+ * storage, callbacks, panel geometry, and ARIA all use resolved pixel values.
+ */
+export const StructuredPercentSizing: Story = {
+ render: () => <StructuredPercentSizingStory />,
+};
+
+/**
+ * The compatibility path: a percentage with no `containerRef`.
+ *
+ * This is what shipped before percentages could name a container, and it is
+ * unchanged — `'25%'` resolves once against `window.innerWidth` (1200px on the
+ * server), then behaves as pixels. Resize the window and the panel stays where
+ * it is; only a percentage BOUND would follow.
+ */
+export const ViewportPercentage: Story = {
+ render: () => {
+ const region = useResizable({defaultSize: '25%', minSize: 80});
+ return (
+ <div {...stylex.props(s.shell)} data-testid="viewport-pct">
+ <Layout
+ height="fill"
+ start={
+ <>
+ <LayoutPanel width={region.size} hasDivider={false}>
+ <div {...stylex.props(s.card)}>{Math.round(region.size)}px</div>
+ </LayoutPanel>
+ <ResizeHandle
+ direction="horizontal"
+ hasDivider
+ resizable={region.props}
+ />
+ </>
+ }
+ content={<LayoutContent>Content</LayoutContent>}
+ />
+ </div>
+ );
+ },
+};
diff --git a/docs/specs/AST-010/spec.md b/docs/specs/AST-010/spec.md
index 9231a3f448..df7d3fae07 100644
--- a/docs/specs/AST-010/spec.md
+++ b/docs/specs/AST-010/spec.md
@@ -16,14 +16,17 @@ affects_contributing: []
affects_consumer_docs: [Resizable]
---
-# Percentage-based useResizable configuration system spec
+# Structured percentage useResizable configuration system spec
## Intent
A person resizing a panel should get the same panel size that the handle presents
and assistive technology announces. Builders may configure an initial size or
-bounds as percentages, but every user-selected size remains pixels so pointer,
-keyboard, persistence, and programmatic behavior stay predictable.
+bounds as percentages, optionally with one explicit pixel floor or ceiling through
+`percent(value, {min: pixel(value)})` or
+`percent(value, {max: pixel(value)})`. Every user-selected size
+remains pixels so pointer, keyboard, persistence, and programmatic behavior stay
+predictable.
This spec preserves the released meaning of `defaultSize: 'N%'` when no
`containerRef` is supplied: resolve once against `window.innerWidth` (or the
@@ -43,7 +46,8 @@ record is updated alongside that implementation.
- Preserving a percentage ratio after pointer, keyboard, or programmatic resize.
- Automatically distributing remaining space or requiring independently sized
regions to total 100%.
-- Supporting arbitrary CSS units such as `rem`, `vw`, or `calc()`.
+- Supporting arbitrary CSS units, functions, expressions, or recursive composition,
+ including `rem`, `vw`, `calc()`, CSS `min()`, and CSS `max()`.
- Adding percentage snap points or percentage collapse thresholds.
- Adding controlled size state; current controlled collapse behavior is
unchanged.
@@ -58,11 +62,12 @@ record is updated alongside that implementation.
## Requirements
- **FR1 — Percentage configuration uses an explicit basis.** Without
- `containerRef`, a percentage `defaultSize` MUST resolve once against
+ `containerRef`, a percentage leaf in `defaultSize` MUST resolve once against
`window.innerWidth`, or 1200px when `window` is unavailable, preserving the
released fallback. With `containerRef`, it MUST resolve once against that
- container's measured content-box active axis. After either resolution, the
- selected size is pixels and MUST NOT scale when the viewport or container
+ container's first positive measured content-box active axis. A structured
+ percentage MUST then apply its single pixel floor or ceiling. After resolution,
+ the selected size is pixels and MUST NOT scale when the viewport or container
changes.
- **FR2 — Direction selects the container basis.** With `containerRef`,
horizontal resizing MUST use the container's content-box inline size and
@@ -70,18 +75,20 @@ record is updated alongside that implementation.
delta, but MUST NOT change the percentage basis. Without `containerRef`, the
compatibility basis remains `window.innerWidth` regardless of direction.
- **FR3 — Interactions remain pixel-based.** Numeric defaults and every result of
- a percentage default resolve to pixels. Pointer, keyboard, snap, collapse,
- expand, persistence, callback, and programmatic resize paths MUST continue to
- read and write pixel selections exactly as the released API does. No
+ an atomic or structured percentage default resolve to pixels. Pointer, keyboard,
+ snap, collapse, expand, persistence, callback, and programmatic resize paths MUST
+ continue to read and write pixel selections exactly as the released API does. No
interaction may create or preserve a percentage-selected mode.
-- **FR4 — Mixed bounds remain valid.** Builders MAY combine pixel and percentage
- values across `defaultSize`, `minSize`, and `maxSize`. Numeric bounds remain
- pixels. Percentage bounds resolve against the same viewport or container basis
- as FR1 and MUST re-resolve whenever that basis changes. Re-resolved bounds clamp
- the existing pixel selection; they MUST NOT scale it proportionally. If the
- resolved minimum exceeds the resolved maximum, development MUST warn and the
- maximum MUST win, preserving the released `Math.min(max, Math.max(min, size))`
- ordering and guaranteeing finite, non-`NaN` geometry.
+- **FR4 — Mixed bounds remain valid.** Builders MAY combine pixel, atomic
+ percentage, and structured percentage values across `defaultSize`, `minSize`,
+ and `maxSize`. Numeric bounds remain pixels. Percentage values resolve against
+ the same viewport or container basis as FR1; a structured value then applies its
+ one pixel floor or ceiling. Percentage bounds MUST re-resolve whenever that basis
+ changes. Re-resolved bounds clamp the existing pixel selection; they MUST NOT
+ scale it proportionally. If the resolved minimum exceeds the resolved maximum,
+ development MUST warn and the maximum MUST win, preserving the released
+ `Math.min(max, Math.max(min, size))` ordering and guaranteeing finite,
+ non-`NaN` geometry.
- **FR5 — Effective geometry stays synchronized.** The effective selected pixel
size, LayoutPanel or caller-rendered size, persisted expanded value, and
ResizeHandle's `aria-valuenow`, `aria-valuemin`, and `aria-valuemax` MUST describe
@@ -89,11 +96,12 @@ record is updated alongside that implementation.
painted bounds is prohibited. Existing controlled-collapse callbacks remain an
explicit exception: they report a rejected collapse or expand intent without
claiming that the controlled owner changed the rendered size.
-- **FR6 — Basis changes update only percentage constraints.** Once a percentage
- default has initialized the selected pixel size, a viewport or container resize
- MUST NOT re-resolve that default. Percentage bounds MUST re-resolve and clamp the
- selected pixel size. A basis-only layout change MUST NOT fire an interaction
- callback or otherwise claim that a person selected a new size.
+- **FR6 — Basis changes update only percentage constraints.** Once an atomic or
+ structured percentage default has initialized the selected pixel size, a viewport
+ or container resize MUST NOT re-resolve that default. Percentage bounds MUST
+ re-resolve, apply their optional pixel floor or ceiling, and clamp the selected
+ pixel size. A basis-only layout change MUST NOT fire an interaction callback or
+ otherwise claim that a person selected a new size.
- **FR7 — Pointer gestures preserve released behavior.** Pointer deltas continue
from the selected pixel size. Percentage bounds MUST use one stable basis during
a gesture; a basis change during the gesture takes effect after the gesture ends
@@ -118,15 +126,18 @@ record is updated alongside that implementation.
ratio preservation, or a 100% total invariant.
- **FR12 — Invalid configuration has safe deterministic fallbacks.** Accepted
configuration is a non-negative finite number, an exact non-negative finite
- `Npx` string, or an exact `N%` string from 0% through 100%. An invalid,
- malformed, negative, or non-finite `defaultSize` MUST use 250px before normal
- bounds clamping; an invalid `minSize` or `minSizePx` MUST use 50px; and an
- invalid `maxSize` or `maxSizePx` MUST use unbounded `Infinity`. Explicit
- `maxSizePx: Infinity` remains valid for compatibility because a shipped template
- uses it. Development MUST warn for every fallback; production MUST use the same
- fallback without warning. After initialization, an invalid raw value MUST NOT
- directly replace a persisted or otherwise legal selected pixel size; a
- fallback-normalized bound may affect that size only through normal clamping.
+ `Npx` string, an exact `N%` string from 0% through 100%, or a structured
+ `percent()` value whose percentage is finite and within 0–100 and whose one
+ `min` or `max` value is a finite non-negative `PixelWidth`. A structured value
+ with neither bound, both bounds, another discriminator, or any invalid number is
+ invalid. An invalid `defaultSize` MUST use 250px before normal bounds clamping;
+ an invalid `minSize` or `minSizePx` MUST use 50px; and an invalid `maxSize` or
+ `maxSizePx` MUST use unbounded `Infinity`. Explicit `maxSizePx: Infinity`
+ remains valid for compatibility because a shipped template uses it.
+ Development MUST warn for every fallback; production MUST use the same fallback
+ without warning. After initialization, an invalid raw value MUST NOT directly
+ replace a persisted or otherwise legal selected pixel size; a fallback-normalized
+ bound may affect that size only through normal clamping.
### Public API requirements
@@ -143,25 +154,58 @@ record is updated alongside that implementation.
axis. ResizeHandle direction and hook direction MUST agree; the implementation
MUST make a mismatch detectable in development. Direction affects the
container basis only when `containerRef` is present.
-- **API3 — One configuration vocabulary covers both units.** Add `minSize` and
- `maxSize` with the same `number | string` shape as `defaultSize`. Accepted
- numbers are finite and non-negative. Accepted strings match the complete input:
- a finite non-negative `Npx`, or `N%` from 0% through 100%; partial parses,
- trailing text, other units, negatives, and non-finite values are invalid. The
- deprecated `maxSizePx` alone additionally accepts explicit `Infinity` to
- preserve released usage. Apply FR12's role-specific fallback in development and
- production, warning only in development. Do not add parallel
- `defaultSizePercent`, `minSizePercent`, or `maxSizePercent` props.
+- **API3 — One explicit Resizable vocabulary covers pixels and bounded
+ percentages.** Add the server-safe helper and types:
+
+ ```ts
+ type ResizablePercentSize = {
+ type: 'percent';
+ value: number;
+ } & ({min: PixelWidth; max?: never} | {min?: never; max: PixelWidth});
+
+ type ResizableSize =
+ number | `${number}px` | `${number}%` | PixelWidth | ResizablePercentSize;
+
+ function percent(
+ value: number,
+ options: {min: PixelWidth; max?: never} | {min?: never; max: PixelWidth},
+ ): ResizablePercentSize;
+ ```
+
+ `minSize` and `maxSize` use `ResizableSize`. `defaultSize` keeps its released
+ broad `SizeValue` and adds `PixelWidth | ResizablePercentSize`, preserving every
+ existing `number | string` caller while runtime validation remains authoritative.
+ Reuse Table's exact `pixel()` binding and `PixelWidth`; do not create a second
+ fixed-size helper. The `percent()` options argument is REQUIRED and carries
+ exactly one `min` or `max` whose value is a valid `PixelWidth`. An unbounded
+ percentage keeps the existing canonical `N%` spelling; `percent(40)` is
+ deliberately not a second spelling for `'40%'`. Numbers, exact `Npx`, and
+ `pixel(value)` remain pixels. Exact `N%` and `percent()` percentages are finite
+ and 0–100. Do not accept `proportional()` (a sibling weight, not a literal
+ percentage), CSS functions, arithmetic, variables, other units, both `min` and
+ `max`, or neither bound. Do not add parallel percentage props.
+
+ Configuration mapping:
+
+ - `333` or `'333px'` → unchanged; `pixel(333)` is the canonical structured
+ static form for new compositions;
+ - `'40%'` → unchanged canonical unbounded percentage;
+ - `max(40%, 333px)` intent → `percent(40, {min: pixel(333)})`;
+ - `min(10%, 400px)` intent → `percent(10, {max: pixel(400)})`.
+
- **API4 — Pixel aliases are exactly mutually exclusive with unified bounds.**
- `minSizePx` and `maxSizePx` remain supported but become deprecated. TypeScript
+ `minSizePx` and `maxSizePx` remain supported but become deprecated. Their public
+ type remains numeric. Untyped callers keep the released exact `Npx` / `N%`
+ runtime acceptance; this is compatibility only, not a new documented spelling.
+ TypeScript
MUST encode each old/new pair as an exact union, equivalent to:
```ts
type MinSizeConfig =
- | {minSize?: SizeValue; minSizePx?: never}
+ | {minSize?: ResizableSize; minSizePx?: never}
| {minSize?: never; minSizePx?: number};
type MaxSizeConfig =
- | {maxSize?: SizeValue; maxSizePx?: never}
+ | {maxSize?: ResizableSize; maxSizePx?: never}
| {maxSize?: never; maxSizePx?: number};
```
@@ -184,14 +228,15 @@ record is updated alongside that implementation.
### Invalid configuration behavior
-| Input | Accepted values | Invalid fallback | Development behavior | Production behavior |
-| ---------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------ | ---------------------------------- |
-| `defaultSize` | non-negative finite number; exact non-negative finite `Npx`; exact `N%` from 0–100 | 250px, then normal bounds clamp | warn and use fallback | use same fallback without warning |
-| `minSize` / `minSizePx` | non-negative finite number; unified prop also accepts exact `Npx` and 0–100 `N%` | 50px | warn and use fallback | use same fallback without warning |
-| `maxSize` | non-negative finite number; exact non-negative finite `Npx`; exact `N%` from 0–100 | unbounded `Infinity` | warn and use fallback | use same fallback without warning |
-| `maxSizePx` | non-negative finite number or explicit `Infinity` | unbounded `Infinity` | warn for invalid values; do not warn for explicit `Infinity` | use same fallback without warning |
-| old/new bound pair supplied together through untyped input | unified value is authoritative | ignore deprecated alias | warn and name the ignored alias | unified value wins without warning |
-| resolved minimum above resolved maximum | both values are individually valid | maximum wins | warn and use released clamp order | use same ordering without warning |
+| Input | Accepted values | Invalid fallback | Development behavior | Production behavior |
+| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------ | ---------------------------------- |
+| `defaultSize` | released `SizeValue` plus `PixelWidth` or `ResizablePercentSize`; structured default resolves once | 250px, then normal bounds clamp | warn and use fallback | use same fallback without warning |
+| `minSize` | `ResizableSize`; full-match atomic strings; valid `pixel(value)` or `percent(value, {min XOR max: PixelWidth})` | 50px | warn and use fallback | use same fallback without warning |
+| `minSizePx` | public type: non-negative finite number; untyped runtime also preserves exact `Npx` / `N%` strings | 50px | warn and use fallback | use same fallback without warning |
+| `maxSize` | `ResizableSize`; full-match atomic strings; valid structured values; explicit `Infinity` remains unbounded | unbounded `Infinity` | warn and use fallback | use same fallback without warning |
+| `maxSizePx` | public type: non-negative finite number or `Infinity`; untyped runtime also preserves exact `Npx` / `N%` strings | unbounded `Infinity` | warn for invalid values; do not warn for explicit `Infinity` | use same fallback without warning |
+| old/new bound pair supplied together through untyped input | unified value is authoritative | ignore deprecated alias | warn and name the ignored alias | unified value wins without warning |
+| resolved minimum above resolved maximum | both values are individually valid | maximum wins | warn and use released clamp order | use same ordering without warning |
A fallback repairs configuration; it is not a new user selection. After
initialization, an invalid raw value never directly replaces persisted or otherwise
@@ -203,20 +248,23 @@ through normal clamping.
- Supported feature/engine floor: every browser supported by Astryx Core with
`ResizeObserver`; the shared observer remains the one runtime owner for a
supplied container.
-- Before a supplied container has a positive measurement, percentage configuration
- MAY use the released deterministic 1200px basis as a temporary fallback. The
- first valid measurement resolves the percentage default to its final initial
- pixel size and resolves percentage bounds without persisting or announcing the
- temporary fallback.
-- Browser evidence: real Chromium MUST verify nested containers, horizontal and
- vertical axes, pointer and keyboard resizing, live basis changes, and the
- unchanged viewport-compatibility and pixel paths. jsdom geometry stubs alone are
- not sufficient.
-- SSR: without `containerRef`, percentage defaults preserve the released 1200px
- server basis and client viewport initialization behavior. With `containerRef`,
- the server uses the same temporary 1200px basis until the first client
- measurement. Hydration MAY make one documented correction, but MUST NOT write the
- temporary fallback to storage or fire `onSizeChange` for that correction.
+- Before a supplied container has a positive measurement, basis-dependent
+ configuration MAY use the released deterministic 1200px basis as a temporary
+ fallback. The first valid measurement resolves a basis-dependent default to its
+ final initial pixel size and resolves percentage bounds without persisting or
+ announcing the temporary fallback. A default-only observer MUST be removed after
+ that initial choice; persisted pixel state MUST skip an otherwise unused default
+ measurement.
+- Browser evidence: real Chromium MUST verify the three canonical structured calls,
+ wide and narrow initial containers, later basis changes, storage and ARIA, plus
+ the unchanged viewport-compatibility and pixel paths. jsdom geometry stubs alone
+ are not sufficient.
+- SSR: without `containerRef`, atomic and structured percentage defaults preserve
+ the released 1200px server basis and client initialization behavior. With
+ `containerRef`, the server uses the same temporary 1200px basis until the first
+ client measurement. Hydration MAY make one documented correction, but MUST NOT
+ write the temporary fallback to storage or fire `onSizeChange` for that
+ correction.
## Current-state impact
@@ -270,91 +318,106 @@ interface PersistedResizableState {
}
```
-A percentage default becomes a pixel selection before it is persisted. A
-persisted pixel selection wins over `defaultSize` on restore and is clamped by the
-currently resolved bounds. A legacy plain `0` remains a collapse marker with no
-expanded size, so expand falls back to the configured default; when collapse is
-disabled it supplies no usable saved size. Pointer, keyboard, collapse, expand, and
-numeric programmatic resize continue to persist pixels. Basis changes never write
-a percentage or relative intent.
+An atomic or structured percentage default becomes a pixel selection before it is
+persisted. A persisted pixel selection wins over `defaultSize` on restore and is
+clamped by the currently resolved bounds. A legacy plain `0` remains a collapse
+marker with no expanded size, so expand falls back to the configured default; when
+collapse is disabled it supplies no usable saved size. Pointer, keyboard, collapse,
+expand, and numeric programmatic resize continue to persist pixels. Basis changes
+never write a percentage descriptor or relative intent.
### Implementation requirements
-1. Preserve the current no-ref resolver for valid percentage defaults:
+1. Preserve the current no-ref resolver for every percentage default:
`window.innerWidth` on the client and 1200px when `window` is unavailable.
-2. Parse the complete configuration value, apply FR12's 250px/50px/`Infinity`
- fallbacks before clamping, and warn only in development. Preserve explicit
+2. Parse complete atomic strings and validate the complete `percent()` descriptor,
+ including its XOR bound shape. Apply FR12's 250px/50px/`Infinity` fallbacks
+ before clamping and warn only in development. Preserve explicit
`maxSizePx: Infinity` as valid legacy input.
-3. Encode each unified/deprecated bound pair as the exact API4 union. At runtime,
+3. Export `percent`, `ResizablePercentSize`, and `ResizableSize` from Resizable;
+ expose `percent`, the same Table `pixel` binding, `PixelWidth`, and the
+ Resizable types from the server-safe `Resizable/utils` subpath.
+4. Encode each unified/deprecated bound pair as the exact API4 union. At runtime,
prefer a unified bound over a simultaneously supplied alias and warn in
development with the ignored alias's name.
-4. When `containerRef` is supplied, measure its content box on the configured axis
+5. When `containerRef` is supplied, measure its content box on the configured axis
and observe it through Astryx's shared ResizeObserver.
-5. Resolve a percentage default once into selected pixel state. Re-resolve only
- percentage bounds when their viewport or container basis changes, then clamp
- the selected pixel state so paint, persistence, and ARIA stay synchronized.
-6. Preserve the released maximum-wins clamp order when a resolved minimum exceeds
+6. Resolve a percentage default once into selected pixel state. Remove default-only
+ observation once that selection is final. Re-resolve only percentage bounds when
+ their viewport or container basis changes, apply their one pixel floor or
+ ceiling, then clamp selected pixel state so paint, persistence, and ARIA stay
+ synchronized.
+7. Refresh a stale cached basis before a newly activated percentage bound can clamp,
+ and remove default-only observation even when `resize()` selected pixels before
+ the first positive measurement.
+8. Preserve the released maximum-wins clamp order when a resolved minimum exceeds
its maximum, warn in development, and never emit `NaN` or invalid geometry.
-7. Keep pointer, keyboard, snap, collapse, expand, callback, persistence, and
+9. Keep pointer, keyboard, snap, collapse, expand, callback, persistence, and
`resize(number)` behavior pixel-based. Do not add a relative mode or widen
`resize()` to strings. Invalid later configuration must not replace persisted or
otherwise legal selected state.
-8. Preserve all current controlled-collapse and legacy persistence behavior not
- explicitly changed by this spec.
-9. If multiple hooks must observe the same container, update the shared observer
- to support independent callbacks and remove only the unmounting callback. Keep
- that reusable prerequisite independently reviewable.
-10. Update `component:Resizable`, `useResizable.doc.mjs`, aggregate Resizable docs,
- stories, release notes, and focused tests in the implementation pull request.
+10. Preserve all current controlled-collapse and legacy persistence behavior not
+ explicitly changed by this spec.
11. Keep SideNav's simplified resize configuration pixel-only until a separate
integration spec or compatibility decision authorizes widening it.
## Verification
-| Contract | Verification | Representative states | Mutation or failure expectation |
-| ---------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| FR1, API1 | Focused hook tests plus Chromium geometry | no ref at 1200px viewport; nested container; first positive measurement | no-ref default changes semantics, or supplied ref measures viewport/panel/handle ancestor |
-| FR2, API2 | Axis tests and Chromium interaction | horizontal/vertical; LTR/RTL; reversed handle; no-ref vertical compatibility | vertical container sizing reads width, or compatibility stops using `innerWidth` |
-| FR3, FR6-FR8 | Interaction and basis-change tests | percentage default before/after drag; viewport/container resize; Arrow, Shift+Arrow, Home, End; collapse/expand | selected size preserves a ratio, basis change scales it, or existing pixel interactions change |
-| FR4 | Mixed-bound and invalid-order tests | percent default + pixel minimum; pixel default + percent maximum; percentage min + pixel max; min above max | bounds use different bases, selection scales instead of clamps, maximum does not win, warning is absent, or geometry becomes invalid |
-| FR5 | Hook, LayoutPanel, persistence, and ResizeHandle assertions | below/at/above max; basis shrink; controlled collapse intent | effective paint, state, storage, and ARIA diverge, or controlled rejection changes owned state |
-| FR9 | Persistence compatibility tests | positive number; legacy zero; legacy object; percentage default; corrupt entry | stored shape changes, a percentage is persisted, or old state changes meaning |
-| FR10, API5 | Callback tests | initialization; hydration correction; basis-only re-clamp; pointer/keyboard/programmatic change | callback receives a percentage or reports a non-interaction layout correction |
-| FR11 | Multi-region and shared-observer tests | two regions on one container; another hook observing the same node | regions use different bases, selected ratios are introduced, or one subscription removes another |
-| FR12 | Production/development parser and state-preservation tests | negative/non-finite number; partial/malformed string; wrong unit; invalid rerender; persisted selection; explicit legacy Infinity | fallback differs by build, warning occurs in production, invalid input replaces legal state, or any path produces `NaN` |
-| API3, API4, API6 | Type, runtime validation, and development-warning tests | exact valid strings; old-only aliases; exact-union duplicate rejection; JS/`any`/spread conflicts; `resize('50%')` | duplicate pairs type-check, deprecated alias overrides unified input, warning omits ignored alias, exact parsing is skipped, or resize accepts strings |
-| Platform/SSR | Server render, hydration test, and Chromium evidence | no ref; ref not measured; hidden/zero container; first positive measurement | 1200px fallback changes, temporary fallback persists, or correction fires `onSizeChange` |
-| Compatibility | Existing Resizable, LayoutPanel, SideNav, and template suites | current pixel-only callsites and no-ref percentage default | existing numeric configuration, percentage fallback, output, interaction, or persistence changes |
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| ---------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1, API1 | Focused hook tests plus Chromium geometry | atomic/structured default; no ref at 1200px; wide/narrow initial container; first positive measurement; later resize | default uses the wrong basis, rescales after initialization, or supplied ref measures the wrong element |
+| FR2, API2 | Axis tests and Chromium interaction | horizontal/vertical; LTR/RTL; reversed handle; no-ref vertical compatibility | vertical container sizing reads width, or compatibility stops using `innerWidth` |
+| FR3, FR6-FR8 | Interaction and basis-change tests | structured default before/after interaction; viewport/container resize; Arrow, Shift+Arrow, Home, End; collapse/expand | selected state preserves a ratio, basis change rescales it, or existing pixel interactions change |
+| FR4 | Structured floor/ceiling, mixed-bound, and invalid-order tests | canonical `percent(40, {min: pixel(333)})` / `percent(10, {max: pixel(400)})`; mixed units; min above max | descriptor bound is applied in the wrong direction, bounds use different bases, selection scales instead of clamps, or maximum does not win |
+| FR5 | Hook, LayoutPanel, persistence, and ResizeHandle assertions | below/at/above max; basis shrink; controlled collapse intent | effective paint, state, storage, and ARIA diverge, or controlled rejection changes owned state |
+| FR9 | Persistence compatibility tests | positive number; legacy zero; legacy object; structured default; corrupt entry | stored shape changes, a descriptor is persisted, an unused default measures a basis, or old state changes meaning |
+| FR10, API5 | Callback tests | initialization; hydration correction; basis-only re-clamp; pointer/keyboard/programmatic change | callback receives a descriptor or reports a non-interaction layout correction |
+| FR11 | Multi-region and shared-observer tests | two regions on one container; another hook observing the same node | regions use different bases, selected ratios are introduced, or one subscription removes another |
+| FR12 | Production/development validation and state-preservation tests | malformed strings; missing/both descriptor bounds; invalid percent/pixels; invalid rerender; persisted selection; legacy Infinity | fallback differs by build, warning occurs in production, invalid input replaces legal state, or any path produces `NaN` |
+| API3, API4, API6 | Type, export, runtime-validation, and warning tests | required helper options; XOR bound; server-safe subpath; old-only aliases; JS/`any` conflicts; `resize('50%')` | `percent(40)` or both bounds type-check, server import gains a client directive, alias overrides unified input, or `resize` accepts non-pixel input |
+| Platform/SSR | Server render, hydration test, and Chromium evidence | no ref; ref not measured; hidden/zero container; first positive measurement; resize before layout; later bound activation | temporary basis persists, correction fires `onSizeChange`, default-only observation leaks, or a newly active bound clamps from a stale cached measurement |
+| Compatibility | Existing Resizable, LayoutPanel, SideNav, and template suites | current pixel-only callsites; no-ref atomic percentage default; released broad `defaultSize` string | existing numeric/atomic percentage behavior, broad default typing, output, interaction, or persistence changes |
### Completion criteria
This spec moves from `accepted` to `shipped` only when:
-- no-ref percentage defaults preserve one-time `window.innerWidth` resolution and
- the 1200px SSR fallback without tracking viewport resize;
-- supplied-container percentage defaults resolve once against the content-box
- active axis, then remain pixel selections through basis changes and every
- interaction path;
-- percentage bounds in both basis modes re-resolve and clamp existing pixel state
- without proportionally scaling it;
+- no-ref atomic and structured percentage defaults preserve one-time
+ `window.innerWidth` resolution and the 1200px SSR fallback without tracking
+ viewport resize;
+- supplied-container structured defaults resolve once against the first positive
+ content-box active axis, remove default-only observation after that choice, and
+ remain pixel selections through basis changes and every interaction path;
+- atomic and structured percentage bounds re-resolve in both basis modes, apply
+ their optional pixel floor or ceiling, and clamp existing pixel state without
+ proportionally scaling it;
+- `percent()` requires options and exactly one of `min` / `max`, carrying a valid
+ `PixelWidth`, in both the type system and runtime validation; `percent(40)` is not
+ an alias for `'40%'`;
+- `Resizable/utils` remains server-safe, re-exports Table's exact `pixel` binding
+ and `PixelWidth`, and exports `percent` plus the Resizable types; the root package
+ resolves one `pixel` symbol and one `percent` symbol without collision;
- pointer, keyboard, snap, collapse, expand, persistence, callbacks, and
`resize(number)` preserve released pixel semantics;
- old-only `minSizePx` and `maxSizePx` callers remain unchanged, each old/new
pair is an exact mutually exclusive TypeScript union, and untyped conflicts
prefer the unified value with a clear ignored-alias warning;
- exact parsing accepts only non-negative finite numbers, complete `Npx` strings,
- and 0–100 `N%` strings; invalid values use the documented 250px, 50px, or
- `Infinity` fallback in every build without replacing persisted/legal selected
- state, while explicit legacy `maxSizePx: Infinity` remains valid;
+ and 0–100 `N%` strings; descriptor validation rejects a missing/both pixel bound
+ or invalid numeric field. Invalid values use the documented 250px, 50px, or
+ `Infinity` fallback without replacing persisted/legal selected state, while
+ explicit legacy `maxSizePx: Infinity` remains valid;
- inverted resolved bounds warn in development, deterministically choose the
maximum, and never produce `NaN` or invalid geometry;
- mixed bounds keep effective state, paint, storage, and separator ARIA aligned,
while controlled-collapse callbacks preserve released intent reporting;
+- default-only subscriptions terminate even after a pre-measurement `resize()`,
+ and newly activated percentage bounds measure the current basis before clamping;
- single and multi-region subscriptions coexist with every other observer of the
same element;
- focused tests fail against the old implementation and pass against the new one;
-- real Chromium proves both container-basis behavior and unchanged compatibility
- and pixel paths; and
+- real Chromium proves the three canonical structured calls across wide/narrow
+ bases, later resizes, storage, and ARIA, plus unchanged compatibility paths; and
- `component:Resizable` and consumer docs describe the shipped contract in the
same pull request as the implementation.
@@ -386,10 +449,13 @@ caller did not request.
**Reference:** `spec:AST-010/DEC-2`
**Decider:** `cixzhang`, `2026-08-31`
-Add `minSize` and `maxSize` with the same accepted vocabulary as `defaultSize`.
-Numbers remain static pixels; strings accept finite non-negative `Npx` or `N%`;
-and mixing units across the initial size and bounds is valid. This gives builders
-one predictable size vocabulary without parallel percentage props.
+Add `minSize` and `maxSize` with the same atomic values as `defaultSize` and the
+structured `ResizablePercentSize` descriptor. Numbers and exact `Npx` remain
+pixels; strings also accept finite 0–100 `N%`; Table's existing `pixel(value)` is
+the canonical structured static value; `percent(value, {min: pixel(value)})` adds
+one pixel floor and `percent(value, {max: pixel(value)})` adds one pixel ceiling.
+Mixing units across the initial size and bounds is valid. This gives builders one
+predictable vocabulary without parallel percentage props or duplicate helpers.
Preserve `minSizePx` and `maxSizePx` as deprecated compatibility aliases so
old-only callers behave unchanged. TypeScript encodes each old/new pair as an exact
@@ -408,6 +474,31 @@ the maximum wins under the released clamp order. These rules keep malformed inpu
conflicts, and inverted bounds from producing `NaN` or replacing persisted/legal
selected state.
+### DEC-3 — Bounded percentages use one explicit structured helper
+
+**Reference:** `spec:AST-010/DEC-3`
+**Decider:** `cixzhang`, `2026-09-03`
+
+Use a Table-style discriminated value created by `percent()`, not a JavaScript
+parser for CSS functions. The descriptor carries a percentage and exactly one
+`min` or `max` whose value is Table's existing `PixelWidth`. Its options argument
+is required: the existing exact `N%` string remains the only spelling for an
+unbounded percentage.
+
+```ts
+pixel(333);
+percent(40, {min: pixel(333)});
+percent(10, {max: pixel(400)});
+```
+
+Reuse Table's exact `pixel()` binding; do not create another fixed-value helper.
+Do not reuse `proportional()`: it represents relative weight among sibling columns,
+not a literal percentage of one measured basis. This fixed shape exposes every
+supported combination to TypeScript, remains constant-time to validate and resolve,
+and does not imply arbitrary CSS composition. Rejected: recursive CSS `min()` /
+`max()` strings, optional helper options, descriptors with both bounds, and separate
+percentage props.
+
## Open questions
None. Changing the released 1200px server fallback or adding a persistent
diff --git a/packages/cli/assets/templates/pages/ide/page.tsx b/packages/cli/assets/templates/pages/ide/page.tsx
index 68ab11259d..d0b6c13721 100644
--- a/packages/cli/assets/templates/pages/ide/page.tsx
+++ b/packages/cli/assets/templates/pages/ide/page.tsx
@@ -220,6 +220,7 @@ export default function ResizableWorkspacePage() {
defaultSize: 300,
minSizePx: 80,
maxSizePx: Infinity,
+ direction: 'vertical',
collapsible: true,
collapsedSize: 40,
});
diff --git a/packages/core/package.json b/packages/core/package.json
index 41b2294b7b..33e63655a7 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -629,6 +629,11 @@
"types": "./dist/PowerSearch/utils.d.ts",
"default": "./dist/PowerSearch/utils.js"
},
+ "./Resizable/utils": {
+ "source": "./src/Resizable/utils.ts",
+ "types": "./dist/Resizable/utils.d.ts",
+ "default": "./dist/Resizable/utils.js"
+ },
"./Selector/utils": {
"source": "./src/Selector/utils.ts",
"types": "./dist/Selector/utils.d.ts",
diff --git a/packages/core/src/Layout/LayoutPanel.doc.mjs b/packages/core/src/Layout/LayoutPanel.doc.mjs
index 2efd0c5ebd..ea3a290567 100644
--- a/packages/core/src/Layout/LayoutPanel.doc.mjs
+++ b/packages/core/src/Layout/LayoutPanel.doc.mjs
@@ -52,7 +52,7 @@ export const docs = {
name: 'resizable',
type: 'ResizableProps',
description:
- 'Resize props from useResizable(). When provided, the hook drives the panel width and a ResizeHandle should be placed adjacent to the panel.',
+ "Resize props from useResizable(). When provided, the hook drives the panel width and a ResizeHandle should be placed adjacent to the panel. Carries the region's axis ('horizontal' | 'vertical'), which must match the adjacent ResizeHandle's direction.",
},
],
};
@@ -105,7 +105,7 @@ export const docsZh = {
name: 'resizable',
type: 'ResizableProps',
description:
- '来自 useResizable() 的调整大小属性。提供时面板宽度由 hook 驱动,应在面板旁放置 ResizeHandle。',
+ "来自 useResizable() 的调整大小属性。提供时面板宽度由 hook 驱动,应在面板旁放置 ResizeHandle。其中携带区域的轴向('horizontal' | 'vertical'),必须与相邻 ResizeHandle 的 direction 一致。",
},
],
};
@@ -118,7 +118,8 @@ export const docsDense = {
propDescriptions: {
children: 'Panel content.',
hasDivider: 'Border on appropriate edge.',
- padding: 'Internal padding on spacing scale. Overrides layout container default.',
+ padding:
+ 'Internal padding on spacing scale. Overrides layout container default.',
isScrollable: 'Enable scrollable overflow.',
label: 'Accessible label for landmark element.',
role: 'ARIA landmark role.',
diff --git a/packages/core/src/Resizable/Resizable.doc.mjs b/packages/core/src/Resizable/Resizable.doc.mjs
index 55282a431b..7519f78ef7 100644
--- a/packages/core/src/Resizable/Resizable.doc.mjs
+++ b/packages/core/src/Resizable/Resizable.doc.mjs
@@ -47,6 +47,11 @@ export const docs = {
'and ResizeHandle provides the interactive pill-grip separator. ' +
'Pass resize props to existing layout components via their resizable prop.',
bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) when a percentage needs exactly one pixel floor or ceiling. Reuse Table’s pixel() helper; numbers, exact Npx, and pixel(value) remain pixels. State, persistence, callbacks, paint, and ARIA remain resolved pixels.',
+ },
{
guidance: true,
description:
@@ -80,24 +85,79 @@ export const docs = {
description:
'Hook that manages resize state for one or more panel regions. ' +
'Returns size, isCollapsed, collapse/expand/resize methods, and props to pass to handles.',
+ examples: [
+ {
+ label: 'Structured fixed pixels',
+ code: `const region = useResizable({
+ defaultSize: pixel(333),
+ containerRef,
+});`,
+ },
+ {
+ label: 'One-time structured default',
+ code: `import {useRef} from 'react';
+import {ResizeHandle, useResizable} from '@astryxdesign/core/Resizable';
+import {percent, pixel} from '@astryxdesign/core/Resizable/utils';
+
+const containerRef = useRef<HTMLDivElement>(null);
+
+const region = useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef,
+});
+
+<ResizeHandle direction="horizontal" resizable={region.props} />;`,
+ },
+ {
+ label: 'Live percentage floor',
+ code: `const region = useResizable({
+ defaultSize: 0,
+ minSize: percent(40, {min: pixel(333)}),
+ containerRef,
+});`,
+ },
+ {
+ label: 'Live percentage ceiling',
+ code: `const region = useResizable({
+ defaultSize: 500,
+ maxSize: percent(10, {max: pixel(400)}),
+ containerRef,
+});`,
+ },
+ ],
props: [
{
name: 'defaultSize',
- type: 'number | string',
+ type: 'SizeValue | ResizableSize',
description:
- 'Initial size in pixels or percentage string (e.g. "20%").',
+ 'Initial size. Numbers, exact Npx, and pixel(value) are pixels; exact N% has no additional pixel bound; percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) adds exactly one and resolves once.',
default: '250',
},
+ {
+ name: 'minSize',
+ type: 'ResizableSize',
+ description:
+ 'Live minimum. Numbers, exact Npx, and pixel(value) remain pixels; exact N% has no additional pixel bound; percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) adds exactly one.',
+ default: '50',
+ },
+ {
+ name: 'maxSize',
+ type: 'ResizableSize',
+ description:
+ 'Live maximum. Numbers, exact Npx, and pixel(value) remain pixels; exact N% has no additional pixel bound; percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) adds exactly one.',
+ default: 'Infinity',
+ },
{
name: 'minSizePx',
type: 'number',
- description: 'Minimum size in pixels.',
+ description: 'Deprecated pixel-only alias for minSize.',
default: '50',
},
{
name: 'maxSizePx',
type: 'number',
- description: 'Maximum size in pixels.',
+ description:
+ 'Deprecated pixel-only alias for maxSize. Explicit Infinity remains valid.',
default: 'Infinity',
},
{
@@ -190,7 +250,7 @@ export const docs = {
name: 'resizable',
type: 'ResizableProps',
description:
- 'Resize props from useResizable: connects handle to panel.',
+ "Resize props from useResizable: connects handle to panel. Carries the region's axis ('horizontal' | 'vertical'), which must match this handle's direction.",
required: true,
},
{
@@ -242,9 +302,12 @@ export const docsDense = {
description:
'Hook managing resize state for one or more panel regions. Returns size, isCollapsed, collapse/expand/resize methods, + props to pass to handles.',
propDescriptions: {
- defaultSize: 'initial size in px or % string (e.g. "20%")',
- minSizePx: 'minimum size in px',
- maxSizePx: 'maximum size in px',
+ defaultSize:
+ 'initial pixels, exact N%, or percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)}); resolves once',
+ minSize:
+ 'live minimum: pixels, exact N%, or percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)})',
+ maxSize:
+ 'live maximum: pixels, exact N%, or percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)})',
collapsible: 'region can collapse to size 0?',
collapsedSize: 'px threshold triggering collapse during drag',
snaps: 'px values to snap to during resize',
diff --git a/packages/core/src/Resizable/Resizable.spec.md b/packages/core/src/Resizable/Resizable.spec.md
index b30fd753d3..947ef97341 100644
--- a/packages/core/src/Resizable/Resizable.spec.md
+++ b/packages/core/src/Resizable/Resizable.spec.md
@@ -14,6 +14,8 @@ verified_by:
[
packages/core/src/Resizable/ResizeHandle.test.tsx,
packages/core/src/Resizable/useResizable.test.ts,
+ packages/core/src/Resizable/shippedDirections.test.ts,
+ packages/core/src/Resizable/utils.test.ts,
packages/core/src/theme/themingTargets.test.ts,
scripts/check-knowledge.mjs,
]
@@ -27,7 +29,7 @@ architecture:
architecture:public-component-api,
]
contributing: []
-system_specs: []
+system_specs: [spec:AST-010]
---
# Resizable component contract
@@ -36,17 +38,20 @@ system_specs: []
Resizable combines the useResizable state and behavior hook with a focusable
ResizeHandle. The handle presents a default Grip pill over an enlarged invisible
-Grab zone. This draft records current consumer anatomy and theming ownership
-without changing resize semantics, runtime behavior, styling, targets, or public
-API.
+Grab zone. AST-010 adds explicit pixel and percentage configuration while keeping
+selected state, persistence, callbacks, paint, and ARIA in resolved pixels.
## Compatibility and migration
-- Released default preserved: `yes`
-- Compatibility class: additive documentation only; runtime, DOM, styling,
- targets, aliases, and public API remain unchanged
+- Released default preserved: `yes`; numeric and exact `Npx` stay pixels, exact
+ `N%` retains released one-time default behavior, and the broad `defaultSize`
+ string type remains source-compatible
+- Compatibility class: additive `minSize` / `maxSize`, structured percentage helper,
+ and optional container basis; deprecated pixel aliases remain supported
- Controlled/uncontrolled behavior: unchanged
-- Migration decision: none
+- Migration decision: CSS-like `min()` / `max()` strings are not supported. Use
+ `percent(value, {min: pixel(value)})` or
+ `percent(value, {max: pixel(value)})`.
Consumer migration instructions belong in consumer docs and release notes.
@@ -67,21 +72,34 @@ Consumer migration instructions belong in consumer docs and release notes.
- Layout-region topology, inset, divider, or scrolling rules.
- A public target for the Grab zone; none exists on current `main`.
- Fixing the missing runtime reflection for the documented Handle `direction`
- theming state in this documentation-only change.
+ theming state; that remains a separate theming follow-up.
## Public concepts
-No new public concept is introduced. Consumer props, hook outputs, and usage
-remain documented in `Resizable.doc.mjs` and `useResizable.doc.mjs`.
+`ResizableSize` is a Resizable-specific union: pixel number, exact `Npx`, exact
+`N%`, `PixelWidth`, or `ResizablePercentSize`.
+`pixel(value)` is Table's existing canonical structured pixel helper;
+`percent(value, {min: pixel(value)})` creates a literal percentage with a pixel
+floor; `percent(value, {max: pixel(value)})` creates one with a pixel ceiling.
+The options argument is required and the two bounds are mutually exclusive.
+`defaultSize` retains its released broad `SizeValue` type and adds the structured
+`PixelWidth` and `ResizablePercentSize` values; runtime validation remains
+authoritative for legacy strings.
+
+Numbers and exact `Npx` remain pixels. A descriptor default resolves once; a
+descriptor bound remains live. Consumer props, outputs, and examples are documented
+in `Resizable.doc.mjs` and `useResizable.doc.mjs`.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------- |
-| FR1 | ResizeHandle renders one focusable Handle and one enlarged Grab zone; the default render also contains a Grip pill, while caller-provided children replace that pill. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | Handle carries `resize-handle`, Grip pill carries `resize-handle-pill`, and Grab zone carries no public target. | Current source and public docs | Verified current target inventory; no target change |
-| FR3 | Pointer, keyboard, collapse, snap, persistence, reversal, and size behavior remain owned by ResizeHandle and useResizable rather than layout-regions collaborators. | Current source, docs, and tests | Verified current ownership; resize semantics remain unchanged |
-| FR4 | Resizable metadata advertises `direction` as a Handle visual state, but current runtime calls `themeProps('resize-handle')` without reflecting that value, so direction selectors cannot match. | Current source and public docs | Verified audit gap; deliberately not fixed in this change |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------- |
+| FR1 | ResizeHandle renders one focusable Handle and one enlarged Grab zone; the default render also contains a Grip pill, while caller-provided children replace that pill. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | Handle carries `resize-handle`, Grip pill carries `resize-handle-pill`, and Grab zone carries no public target. | Current source and public docs | Verified current target inventory; no target change |
+| FR3 | Pointer, keyboard, collapse, snap, persistence, reversal, and size behavior remain owned by ResizeHandle and useResizable rather than layout-regions collaborators. | Current source, docs, and tests | Verified current ownership; resize semantics remain unchanged |
+| FR4 | Resizable metadata advertises `direction` as a Handle visual state, but current runtime calls `themeProps('resize-handle')` without reflecting that value, so direction selectors cannot match. | Current source and public docs | Verified audit gap; deliberately not fixed in this change |
+| FR5 | `percent(value, {min: pixel(value)})` and `percent(value, {max: pixel(value)})` resolve against the AST-010 basis; a default selects pixels once, while a bound re-resolves and clamps selected pixels. Both/neither bounds are invalid. | AST-010, source, tests, Chromium | New structured sizing behavior; selected state remains pixels |
+| FR6 | Deprecated pixel aliases remain source-compatible and mutually exclusive with unified bounds; untyped exact atomic strings keep their released runtime behavior, and untyped conflicts prefer the unified value and warn. | AST-010, source, tests | Additive migration with deterministic precedence |
### Allowed variation
@@ -93,6 +111,9 @@ remain documented in `Resizable.doc.mjs` and `useResizable.doc.mjs`.
changing Handle or Grab zone ownership.
- **AV4 — Divider.** Handle may paint its current divider treatment; a composing
region remains responsible for avoiding a duplicate adjacent divider.
+- **AV5 — Structured percentage bound.** A descriptor carries exactly one `min`
+ or `max`, whose value is a `PixelWidth`. Atomic percentages use the existing
+ exact `N%` string; arbitrary CSS expressions are outside this contract.
### Representative states
@@ -106,18 +127,30 @@ remain documented in `Resizable.doc.mjs` and `useResizable.doc.mjs`.
### Transformation and precedence order
-- No new clamp, snap, collapse, persistence, reversal, pointer, or keyboard order
- is introduced.
+- Parse atomic strings exactly; validate `percent()` descriptors as a finite 0–100
+ percentage with exactly one finite non-negative pixel bound.
+- Resolve percentages against one active basis, then apply the descriptor's floor or
+ ceiling.
+- Commit a structured default as one initial pixel choice; keep percentage bounds
+ live and clamp with `Math.min(max, Math.max(min, size))`.
+- Maximum wins when resolved bounds conflict; interaction and persistence stay
+ pixel-only.
### Performance and resources
-- No new listener, storage, observer, or render requirement is introduced.
+- Atomic pixel paths add no observer or render work.
+- A structured default observes a supplied container only until its initial pixel
+ choice is final; persisted pixels skip that measurement.
+- Percentage bounds reuse the shared ResizeObserver and remain subscribed while
+ live. Structured validation and resolution are constant-time; no CSS parser is
+ introduced.
## Accessibility contract
-This draft does not change or extend ResizeHandle's existing separator role,
-label, orientation, value, collapsed value text, focus, pointer, or keyboard
-behavior.
+The structured API does not change ResizeHandle's separator role, label,
+orientation, collapsed value text, focus, pointer, or keyboard behavior. Its
+`aria-valuemin`, `aria-valuemax`, and `aria-valuenow` remain the same resolved pixel
+values used by hook state and painted geometry.
## Design relationships
@@ -153,8 +186,11 @@ not emit the documented target state.
- `architecture:component-theming-surface` owns anatomy qualification, target
mapping, and target-state reflection requirements.
-- `architecture:interaction-modality` and `architecture:public-component-api`
- own shared modality and API boundaries; this draft changes neither.
+- `architecture:interaction-modality` owns shared modality behavior;
+ `architecture:public-component-api` owns the additive structured API and
+ compatibility boundary.
+- `Resizable/utils` is server-safe and re-exports Table's exact `pixel()` binding
+ plus `PixelWidth`, alongside Resizable's `percent()` and structured types.
- `family:layout-regions` lists useResizable and ResizeHandle as collaborators
that may drive a LayoutPanel's size. Resizable is not a layout-regions member,
and that family does not own or redefine resize state, snapping, persistence,
@@ -162,13 +198,15 @@ not emit the documented target state.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | -------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -------------------------- |
-| FR1 | `ResizeHandle.test.tsx` plus source inspection | Default, custom, collapsed, disabled, both axes | Handle and Grab zone regressions fail focused tests; custom Grip replacement currently relies on source review. | `audit:Resizable/anatomy` |
-| FR2 | Source inspection and `themingTargets.test.ts` | Handle, Grip pill, and Grab zone | Removing a target or documenting an unshipped Grab zone target fails evidence or inventory. | `audit:Resizable/theming` |
-| FR3 | `ResizeHandle.test.tsx` and `useResizable.test.ts` | Pointer, keyboard, snap, collapse, persistence | Moving resize ownership or changing current transformations fails focused behavior coverage. | `audit:Resizable/behavior` |
-| FR4 | Source and public metadata comparison | Horizontal and vertical Handle | No current test detects that documented `direction` is absent from runtime target-state reflection. | `audit:Resizable/theming` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and two current targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:Resizable/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
+| FR1 | `ResizeHandle.test.tsx` plus source inspection | Default, custom, collapsed, disabled, both axes | Handle and Grab zone regressions fail focused tests; custom Grip replacement currently relies on source review. | `audit:Resizable/anatomy` |
+| FR2 | Source inspection and `themingTargets.test.ts` | Handle, Grip pill, and Grab zone | Removing a target or documenting an unshipped Grab zone target fails evidence or inventory. | `audit:Resizable/theming` |
+| FR3 | `ResizeHandle.test.tsx` and `useResizable.test.ts` | Pointer, keyboard, snap, collapse, persistence | Moving resize ownership or changing current transformations fails focused behavior coverage. | `audit:Resizable/behavior` |
+| FR4 | Source and public metadata comparison | Horizontal and vertical Handle | No current test detects that documented `direction` is absent from runtime target-state reflection. | `audit:Resizable/theming` |
+| FR5 | Hook/utils tests, typecheck, and Chromium | Canonical floor/ceiling/default; invalid XOR shape; SSR/hydration; basis changes; numeric `containerRef` parity | Wrong resolution, rescaling defaults, stale clamps, observer leaks, extra numeric renders/ref reads, or state/paint/storage/ARIA divergence fails. | `audit:Resizable/behavior` |
+| FR6 | Hook type/runtime tests | Old-only aliases; untyped exact atomic strings; typed and untyped conflicts | Alias incompatibility, ambiguous config, or wrong precedence fails focused tests. | `audit:Resizable/behavior` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and two current targets | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:Resizable/theming` |
Current tests exercise Handle and Grab zone structure and behavior but do not
render `children` to prove that custom content replaces Grip pill. That branch is
@@ -178,8 +216,21 @@ cover its missing runtime reflection; that mismatch is currently unguarded.
## Decision log
-None. This draft records current facts and introduces no component-local design,
-API, resize, layout-family, or theming decision.
+### Structured percentages use a Table-style helper
+
+**Decision:** `percent(value, {min: pixel(value)})` or
+`percent(value, {max: pixel(value)})` represents a percentage with exactly one
+pixel bound. Reuse Table's exact `pixel()` binding and `PixelWidth`; do not create
+a parallel static helper. The required options and XOR type avoid a second
+spelling for plain percentages and make every supported combination explicit.
+The pure helper is available with the same `pixel()` binding from the server-safe
+`Resizable/utils` subpath, matching Table's established helper/export pattern.
+`proportional()` is deliberately not reused because it means sibling weight, not a
+literal percentage.
+
+**Rejected:** parsing recursive CSS `min()` / `max()` strings. That would create a
+partial second CSS implementation without a demonstrated need for arbitrary
+composition.
## Open questions
diff --git a/packages/core/src/Resizable/ResizeHandle.test.tsx b/packages/core/src/Resizable/ResizeHandle.test.tsx
index 40424ed137..a7d4002960 100644
--- a/packages/core/src/Resizable/ResizeHandle.test.tsx
+++ b/packages/core/src/Resizable/ResizeHandle.test.tsx
@@ -141,7 +141,12 @@ describe('ResizeHandle', () => {
it('resizes along the block axis for a vertical handle', () => {
render(
<Harness
- config={{defaultSize: 200, minSizePx: 100, maxSizePx: 400}}
+ config={{
+ defaultSize: 200,
+ minSizePx: 100,
+ maxSizePx: 400,
+ direction: 'vertical',
+ }}
handleProps={{direction: 'vertical'}}
/>,
);
@@ -157,6 +162,25 @@ describe('ResizeHandle', () => {
expect(separator).toHaveAttribute('aria-valuenow', '200');
});
+ it('warns when the handle and hook use different axes', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ render(
+ <Harness
+ config={{
+ defaultSize: 200,
+ direction: 'vertical',
+ }}
+ handleProps={{direction: 'horizontal'}}
+ />,
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'ResizeHandle: direction="horizontal" but its useResizable region is ' +
+ '"vertical". They must match: the hook measures one axis and the ' +
+ 'handle drags the other.',
+ );
+ warn.mockRestore();
+ });
+
it('collapses on Enter when the region is collapsible', () => {
render(
<Harness
@@ -296,6 +320,48 @@ describe('ResizeHandle', () => {
expect(resizable._onResizeMove).not.toHaveBeenCalled();
});
+ it.each([
+ ['pointercancel', fireEvent.pointerCancel],
+ ['lostpointercapture', fireEvent.lostPointerCapture],
+ ])('tells the region the gesture is over on %s', (_name, fire) => {
+ // A cancelled drag is not a resize end, but it IS the end of the gesture:
+ // the region freezes its percentage basis for the duration of a drag, and
+ // without this it stays frozen at the container size from grab time.
+ const resizable = {...makeResizable(), _onResizeCancel: vi.fn()};
+ render(<ResizeHandle resizable={resizable} label="Resize" />);
+ const hitArea = getHitArea();
+
+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});
+ fire(hitArea, {pointerId: 1});
+ expect(resizable._onResizeCancel).toHaveBeenCalledTimes(1);
+ expect(resizable._onResizeEnd).not.toHaveBeenCalled();
+ });
+
+ it('does not report a cancel for a drag that ended normally', () => {
+ const resizable = {...makeResizable(), _onResizeCancel: vi.fn()};
+ render(<ResizeHandle resizable={resizable} label="Resize" />);
+ const hitArea = getHitArea();
+
+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});
+ fireEvent.pointerUp(hitArea, {pointerId: 1, clientX: 30, clientY: 0});
+ expect(resizable._onResizeEnd).toHaveBeenCalledTimes(1);
+ // lostpointercapture follows every release; the drag is already cleared.
+ fireEvent.lostPointerCapture(hitArea, {pointerId: 1});
+ expect(resizable._onResizeCancel).not.toHaveBeenCalled();
+ });
+
+ it('tells the region the gesture is over when unmounted mid-drag', () => {
+ // The region outlives the handle here, so nothing else would release it.
+ const resizable = {...makeResizable(), _onResizeCancel: vi.fn()};
+ const {unmount} = render(
+ <ResizeHandle resizable={resizable} label="Resize" />,
+ );
+ fireEvent.pointerDown(getHitArea(), {pointerId: 1, clientX: 0, clientY: 0});
+ unmount();
+ expect(resizable._onResizeCancel).toHaveBeenCalledTimes(1);
+ expect(resizable._onResizeEnd).not.toHaveBeenCalled();
+ });
+
it('stops driving the region and releases body styles when unmounted mid-drag', () => {
const resizable = makeResizable();
const {unmount} = render(
@@ -397,7 +463,17 @@ describe('ResizeHandle', () => {
['horizontal' as const, 'translateX'],
['vertical' as const, 'translateY'],
])('offsets the %s grab zone along the pill axis only', (direction, axis) => {
- render(<Harness handleProps={{direction, pillPlacement: 'start'}} />);
+ render(
+ <Harness
+ config={{
+ defaultSize: 200,
+ minSizePx: 100,
+ maxSizePx: 400,
+ direction,
+ }}
+ handleProps={{direction, pillPlacement: 'start'}}
+ />,
+ );
const hitArea = getSeparator().firstElementChild as HTMLElement;
const translates = (hitArea.getAttribute('style') ?? '')
.split(';')
diff --git a/packages/core/src/Resizable/ResizeHandle.tsx b/packages/core/src/Resizable/ResizeHandle.tsx
index 46e7cd9023..bf30df658c 100644
--- a/packages/core/src/Resizable/ResizeHandle.tsx
+++ b/packages/core/src/Resizable/ResizeHandle.tsx
@@ -36,6 +36,7 @@ import {useCallback, useEffect, useRef, useState} from 'react';
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
+import {devWarn} from '../utils/devWarning';
import {
colorVars,
durationVars,
@@ -426,6 +427,28 @@ export function ResizeHandle({
const isInteracting = isHovered || isFocused;
+ // A handle whose axis disagrees with its hook drags along one axis while the
+ // hook measures percentage bounds on the other. `ResizableProps` is exported,
+ // so `_direction` is optional for old hand-built objects; absent means there
+ // is no hook axis to compare, not that the hook is horizontal.
+ const didWarnAxisRef = useRef(false);
+ useEffect(() => {
+ const hookDirection = resizable?._direction;
+ if (
+ hookDirection != null &&
+ hookDirection !== direction &&
+ !didWarnAxisRef.current
+ ) {
+ didWarnAxisRef.current = true;
+ devWarn(
+ 'ResizeHandle',
+ `direction="${direction}" but its useResizable region is ` +
+ `"${hookDirection}". They must match: the hook measures one axis ` +
+ 'and the handle drags the other.',
+ );
+ }
+ }, [direction, resizable]);
+
// --- Pointer drag ---
const clearDrag = useCallback(() => {
dragRef.current = null;
@@ -489,8 +512,11 @@ export function ResizeHandle({
return;
}
clearDrag();
+ // Not a resize end, but still the end of the gesture: the region froze
+ // state for the duration of the drag and has to be told it is over.
+ resizable?._onResizeCancel?.();
},
- [clearDrag],
+ [clearDrag, resizable],
);
// --- Keyboard ---
@@ -568,12 +594,16 @@ export function ResizeHandle({
// its listeners with it, so an in-flight drag stops driving the region on
// its own. The body cursor/user-select overrides are not on the element,
// though, so they have to be released here or they stick after the handle
- // is gone.
+ // is gone — and the region, which outlives this handle, still has to hear
+ // that its gesture is over.
+ const cancelOnUnmountRef = useRef<(() => void) | undefined>(undefined);
+ cancelOnUnmountRef.current = resizable?._onResizeCancel;
useEffect(() => {
return () => {
if (dragRef.current) {
dragRef.current = null;
clearBodyDragStyles();
+ cancelOnUnmountRef.current?.();
}
};
}, []);
diff --git a/packages/core/src/Resizable/index.ts b/packages/core/src/Resizable/index.ts
index b1ae35aef8..9b2deddf18 100644
--- a/packages/core/src/Resizable/index.ts
+++ b/packages/core/src/Resizable/index.ts
@@ -9,7 +9,9 @@
* @position Package entry point for Resizable
*/
+export {percent} from './utils';
export {useResizable} from './useResizable';
+export type {ResizablePercentSize, ResizableSize} from './utils';
export type {
ResizableRegion,
ResizableRegionConfig,
diff --git a/packages/core/src/Resizable/shippedDirections.test.ts b/packages/core/src/Resizable/shippedDirections.test.ts
new file mode 100644
index 0000000000..890d6796f2
--- /dev/null
+++ b/packages/core/src/Resizable/shippedDirections.test.ts
@@ -0,0 +1,462 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Guards shipped useResizable/ResizeHandle axis pairings.
+ * @input Storybook, docsite, and CLI template source that composes Resizable
+ * @output Every statically paired hook and handle uses the same axis
+ * @position Static regression for shipped Resizable examples
+ */
+
+import {readdirSync, readFileSync} from 'node:fs';
+import {join, relative} from 'node:path';
+import ts from 'typescript';
+import {describe, expect, it} from 'vitest';
+
+const ROOT = join(__dirname, '../../../..');
+const SHIPPED_ROOTS = [
+ join(ROOT, 'apps/docsite/src'),
+ join(ROOT, 'apps/storybook/stories'),
+ join(ROOT, 'packages/cli/assets/templates'),
+];
+const EMBEDDED_DOC_ROOTS = [
+ join(ROOT, 'packages/core/src'),
+ join(ROOT, 'packages/cli/assets/docs'),
+ join(ROOT, 'packages/cli/assets/templates'),
+];
+
+type Direction = 'horizontal' | 'vertical';
+type Result<T> = {value: T} | {error: string};
+type Binding = {
+ path: string;
+ direction: Result<Direction>;
+ scope: ts.Node;
+};
+type Pairing = {
+ file: string;
+ line: number;
+ region: string | null;
+ hookDirection: Direction | null;
+ handleDirection: Direction | null;
+ error: string | null;
+};
+
+function filesUnder(
+ dir: string,
+ suffixes: string[],
+ files: string[] = [],
+): string[] {
+ for (const entry of readdirSync(dir, {withFileTypes: true})) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ filesUnder(path, suffixes, files);
+ } else if (suffixes.some(suffix => entry.name.endsWith(suffix))) {
+ files.push(path);
+ }
+ }
+ return files;
+}
+
+function enclosingFunction(node: ts.Node): ts.Node {
+ for (let parent = node.parent; parent != null; parent = parent.parent) {
+ if (ts.isFunctionLike(parent)) {
+ return parent;
+ }
+ }
+ return node.getSourceFile();
+}
+
+function contains(scope: ts.Node, node: ts.Node): boolean {
+ return scope.pos <= node.pos && scope.end >= node.end;
+}
+
+function unwrap(expression: ts.Expression): ts.Expression {
+ if (
+ ts.isAsExpression(expression) ||
+ ts.isTypeAssertionExpression(expression) ||
+ ts.isParenthesizedExpression(expression) ||
+ ts.isSatisfiesExpression(expression)
+ ) {
+ return unwrap(expression.expression);
+ }
+ return expression;
+}
+
+function variableInitializer(
+ sourceFile: ts.SourceFile,
+ name: string,
+ at: ts.Node,
+): ts.Expression | null {
+ const candidates: {initializer: ts.Expression; scope: ts.Node}[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isVariableDeclaration(node) &&
+ ts.isIdentifier(node.name) &&
+ node.name.text === name &&
+ node.initializer != null &&
+ node.pos < at.pos
+ ) {
+ const scope = enclosingFunction(node);
+ if (contains(scope, at)) {
+ candidates.push({initializer: node.initializer, scope});
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sourceFile);
+ candidates.sort(
+ (left, right) =>
+ left.scope.end - left.scope.pos - (right.scope.end - right.scope.pos),
+ );
+ return candidates[0]?.initializer ?? null;
+}
+
+function resolveExpression(
+ expression: ts.Expression,
+ sourceFile: ts.SourceFile,
+ at: ts.Node,
+ seen = new Set<string>(),
+): ts.Expression | null {
+ const value = unwrap(expression);
+ if (!ts.isIdentifier(value)) {
+ return value;
+ }
+ if (seen.has(value.text)) {
+ return null;
+ }
+ const initializer = variableInitializer(sourceFile, value.text, at);
+ if (initializer == null) {
+ return null;
+ }
+ return resolveExpression(
+ initializer,
+ sourceFile,
+ at,
+ new Set([...seen, value.text]),
+ );
+}
+
+function propertyName(node: ts.ObjectLiteralElementLike): string | null {
+ if (!('name' in node) || node.name == null) {
+ return null;
+ }
+ return ts.isIdentifier(node.name) || ts.isStringLiteralLike(node.name)
+ ? node.name.text
+ : null;
+}
+
+type ObjectDirection = {value: Direction | undefined} | {error: string};
+
+function directionFromObject(
+ expression: ts.Expression,
+ sourceFile: ts.SourceFile,
+ at: ts.Node,
+): ObjectDirection {
+ const resolved = resolveExpression(expression, sourceFile, at);
+ if (resolved == null || !ts.isObjectLiteralExpression(resolved)) {
+ return {error: 'useResizable config is not statically resolvable'};
+ }
+ let direction: ObjectDirection = {value: undefined};
+ for (const property of resolved.properties) {
+ if (ts.isSpreadAssignment(property)) {
+ const spreadDirection = directionFromObject(
+ property.expression,
+ sourceFile,
+ at,
+ );
+ if ('error' in spreadDirection || spreadDirection.value !== undefined) {
+ direction = spreadDirection;
+ }
+ continue;
+ }
+ if (propertyName(property) === 'direction') {
+ const initializer = ts.isPropertyAssignment(property)
+ ? property.initializer
+ : ts.isShorthandPropertyAssignment(property)
+ ? property.name
+ : null;
+ if (initializer == null) {
+ direction = {error: 'hook direction is not statically resolvable'};
+ continue;
+ }
+ const value = resolveExpression(initializer, sourceFile, at);
+ direction =
+ value != null &&
+ ts.isStringLiteralLike(value) &&
+ (value.text === 'horizontal' || value.text === 'vertical')
+ ? {value: value.text}
+ : {error: 'hook direction is not statically resolvable'};
+ }
+ }
+ return direction;
+}
+
+function pathOf(expression: ts.Expression): string | null {
+ const value = unwrap(expression);
+ if (ts.isIdentifier(value)) {
+ return value.text;
+ }
+ if (ts.isPropertyAccessExpression(value)) {
+ const parent = pathOf(value.expression);
+ return parent == null ? null : `${parent}.${value.name.text}`;
+ }
+ return null;
+}
+
+function hookBindings(sourceFile: ts.SourceFile): Binding[] {
+ const bindings: Binding[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isVariableDeclaration(node) &&
+ node.initializer != null &&
+ ts.isCallExpression(node.initializer) &&
+ ts.isIdentifier(node.initializer.expression) &&
+ node.initializer.expression.text === 'useResizable'
+ ) {
+ const config = node.initializer.arguments[0];
+ const objectDirection =
+ config == null
+ ? {value: undefined as Direction | undefined}
+ : directionFromObject(config, sourceFile, node);
+ const direction: Result<Direction> =
+ 'error' in objectDirection
+ ? objectDirection
+ : {value: objectDirection.value ?? 'horizontal'};
+ const scope = enclosingFunction(node);
+ if (ts.isIdentifier(node.name)) {
+ bindings.push({path: node.name.text, direction, scope});
+ } else if (ts.isObjectBindingPattern(node.name)) {
+ for (const element of node.name.elements) {
+ if (ts.isIdentifier(element.name)) {
+ const exported =
+ element.propertyName?.getText(sourceFile) ?? element.name.text;
+ if (exported === 'props') {
+ bindings.push({path: element.name.text, direction, scope});
+ }
+ }
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sourceFile);
+ return bindings;
+}
+
+function attribute(
+ node: ts.JsxAttributes,
+ name: string,
+): ts.JsxAttribute | undefined {
+ return node.properties.find(
+ property => ts.isJsxAttribute(property) && property.name.getText() === name,
+ ) as ts.JsxAttribute | undefined;
+}
+
+function directionFromAttribute(
+ node: ts.JsxAttribute | undefined,
+ sourceFile: ts.SourceFile,
+ at: ts.Node,
+): Result<Direction> {
+ if (node?.initializer == null) {
+ return {value: 'horizontal'};
+ }
+ const value = ts.isStringLiteral(node.initializer)
+ ? node.initializer
+ : ts.isJsxExpression(node.initializer) &&
+ node.initializer.expression != null
+ ? resolveExpression(node.initializer.expression, sourceFile, at)
+ : null;
+ return value != null &&
+ ts.isStringLiteralLike(value) &&
+ (value.text === 'horizontal' || value.text === 'vertical')
+ ? {value: value.text}
+ : {error: 'handle direction is not statically resolvable'};
+}
+
+function resizablePath(node: ts.JsxAttribute | undefined): string | null {
+ if (
+ node?.initializer == null ||
+ !ts.isJsxExpression(node.initializer) ||
+ node.initializer.expression == null
+ ) {
+ return null;
+ }
+ const path = pathOf(node.initializer.expression);
+ return path?.endsWith('.props') ? path.slice(0, -'.props'.length) : path;
+}
+
+function inspectSource(source: string, file: string): Pairing[] {
+ if (!source.includes('ResizeHandle') || !source.includes('useResizable')) {
+ return [];
+ }
+ const sourceFile = ts.createSourceFile(
+ file,
+ source,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const bindings = hookBindings(sourceFile);
+ const pairings: Pairing[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) &&
+ node.tagName.getText(sourceFile) === 'ResizeHandle'
+ ) {
+ const region = resizablePath(attribute(node.attributes, 'resizable'));
+ const matches = bindings
+ .filter(
+ binding =>
+ (binding.path === region ||
+ region?.startsWith(`${binding.path}.`)) &&
+ contains(binding.scope, node),
+ )
+ .sort(
+ (left, right) =>
+ left.scope.end -
+ left.scope.pos -
+ (right.scope.end - right.scope.pos),
+ );
+ const hook = matches[0];
+ const handle = directionFromAttribute(
+ attribute(node.attributes, 'direction'),
+ sourceFile,
+ node,
+ );
+ const {line} = sourceFile.getLineAndCharacterOfPosition(node.getStart());
+ pairings.push({
+ file,
+ line: line + 1,
+ region,
+ hookDirection:
+ hook != null && 'value' in hook.direction
+ ? hook.direction.value
+ : null,
+ handleDirection: 'value' in handle ? handle.value : null,
+ error:
+ region == null
+ ? 'resizable prop is not statically resolvable'
+ : hook == null
+ ? 'matching useResizable binding was not found'
+ : 'error' in hook.direction
+ ? hook.direction.error
+ : 'error' in handle
+ ? handle.error
+ : hook.direction.value === handle.value
+ ? null
+ : `hook is ${hook.direction.value}; handle is ${handle.value}`,
+ });
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sourceFile);
+ return pairings;
+}
+
+function embeddedExamples(source: string): string[] {
+ return [...source.matchAll(/`([\s\S]*?)`/g)]
+ .map(match => match[1])
+ .filter(
+ example =>
+ example.includes('useResizable') && example.includes('ResizeHandle'),
+ );
+}
+
+function sourcePairings(transform?: (source: string) => string): Pairing[] {
+ return SHIPPED_ROOTS.flatMap(root => filesUnder(root, ['.tsx'])).flatMap(
+ file => {
+ const source = readFileSync(file, 'utf8');
+ return inspectSource(transform?.(source) ?? source, relative(ROOT, file));
+ },
+ );
+}
+
+function documentedPairings(): Pairing[] {
+ return EMBEDDED_DOC_ROOTS.flatMap(root =>
+ filesUnder(root, ['.doc.mjs', '.doc.dense.mjs']),
+ ).flatMap(file =>
+ embeddedExamples(readFileSync(file, 'utf8')).flatMap((source, index) =>
+ inspectSource(source, `${relative(ROOT, file)}#example-${index + 1}`),
+ ),
+ );
+}
+
+describe('shipped Resizable examples', () => {
+ it('pairs every directly composed hook and handle on the same axis', () => {
+ const sources = sourcePairings();
+ const documented = documentedPairings();
+ const pairings = [...sources, ...documented];
+
+ expect(sources.length).toBeGreaterThanOrEqual(30);
+ expect(
+ sources.filter(pairing => pairing.handleDirection === 'vertical').length,
+ ).toBeGreaterThanOrEqual(6);
+ expect(documented.length).toBeGreaterThanOrEqual(1);
+ expect(pairings.filter(pairing => pairing.error != null)).toEqual([]);
+ });
+
+ it('detects all six shipped vertical mismatches against the unfixed source shape', () => {
+ const pairings = sourcePairings(source =>
+ source.replace(/^\s*direction: 'vertical',\n/gm, ''),
+ );
+ const mismatches = pairings.filter(
+ pairing => pairing.handleDirection === 'vertical',
+ );
+
+ expect(mismatches).toHaveLength(6);
+ expect(mismatches.every(pairing => pairing.error != null)).toBe(true);
+ });
+
+ it('detects either mismatch direction and unverifiable expressions', () => {
+ const inspect = (hookDirection: string, handleDirection: string) =>
+ inspectSource(
+ `function Example() {
+ const direction = 'vertical';
+ const base = {direction};
+ const region = useResizable(${hookDirection});
+ return <ResizeHandle ${handleDirection} resizable={region.props} />;
+ }`,
+ 'fixture.tsx',
+ )[0];
+
+ expect(inspect('{}', 'direction="vertical"')?.error).toBe(
+ 'hook is horizontal; handle is vertical',
+ );
+ expect(inspect("{direction: 'vertical'}", '')?.error).toBe(
+ 'hook is vertical; handle is horizontal',
+ );
+ expect(inspect('{...base}', 'direction={direction}')?.error).toBeNull();
+ expect(
+ inspect(
+ "{direction: 'vertical', ...{defaultSize: 10}}",
+ 'direction="vertical"',
+ )?.error,
+ ).toBeNull();
+ expect(
+ inspectSource(
+ `function Example() {
+ const {props} = useResizable({direction: 'vertical'});
+ return <ResizeHandle direction="vertical" resizable={props} />;
+ }`,
+ 'fixture.tsx',
+ )[0]?.error,
+ ).toBeNull();
+ expect(
+ inspectSource(
+ `function Example() {
+ const regions = useResizable({direction: 'vertical', regions: {top: {defaultSize: 100}}});
+ return <ResizeHandle direction="vertical" resizable={regions.top.props} />;
+ }`,
+ 'fixture.tsx',
+ )[0]?.error,
+ ).toBeNull();
+ expect(
+ inspect("{direction: 'vertical'}", 'direction="horizontal"')?.error,
+ ).toBe('hook is vertical; handle is horizontal');
+ expect(
+ inspect("{direction: 'vertical'}", 'direction={getDirection()}')?.error,
+ ).toBe('handle direction is not statically resolvable');
+ expect(
+ inspect('{direction: getDirection()}', 'direction={direction}')?.error,
+ ).toBe('hook direction is not statically resolvable');
+ });
+});
diff --git a/packages/core/src/Resizable/useResizable.doc.mjs b/packages/core/src/Resizable/useResizable.doc.mjs
index 90803dd53d..7918477444 100644
--- a/packages/core/src/Resizable/useResizable.doc.mjs
+++ b/packages/core/src/Resizable/useResizable.doc.mjs
@@ -5,29 +5,68 @@ export const docs = {
name: 'useResizable',
displayName: 'useResizable',
group: 'Resizable',
- keywords: ['resize', 'resizable', 'drag', 'split', 'panel', 'sidebar', 'divider', 'splitter'],
+ keywords: [
+ 'resize',
+ 'resizable',
+ 'drag',
+ 'split',
+ 'panel',
+ 'sidebar',
+ 'divider',
+ 'splitter',
+ ],
params: [
{
name: 'defaultSize',
- type: "number | string",
- description: 'Initial size in pixels or percentage string (e.g. "20%").',
+ type: 'SizeValue | ResizableSize',
+ description:
+ 'Initial size. Numbers, exact "Npx", and pixel(value) are pixels. Exact "N%" has no additional pixel bound. percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) adds one pixel floor or ceiling. A percentage resolves ONCE into pixels — against containerRef when supplied, against the viewport otherwise — and does not track its basis afterwards. The released broad number | string type remains compatible; runtime validation is authoritative.',
+ default: '250',
+ },
+ {
+ name: 'minSize',
+ type: 'ResizableSize',
+ description:
+ 'Minimum size. Numbers, exact "Npx", and pixel(value) remain pixels; exact "N%" has no additional pixel bound; percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) adds exactly one. Percentage minimums re-resolve when their basis changes and clamp the current pixel selection.',
+ default: '50',
+ },
+ {
+ name: 'maxSize',
+ type: 'ResizableSize',
+ description:
+ 'Maximum size. Numbers, exact "Npx", and pixel(value) remain pixels; exact "N%" has no additional pixel bound; percent(value, {min: pixel(value)}) or percent(value, {max: pixel(value)}) adds exactly one. Percentage maximums re-resolve when their basis changes and clamp the current pixel selection.',
+ default: 'Infinity',
+ },
+ {
+ name: 'containerRef',
+ type: 'RefObject<HTMLElement | null>',
+ description:
+ 'The element a percentage is a share of. Caller-owned: the hook never infers one. Omitted, percentages use the viewport, which is the released behaviour. The ref may point at a different element over time — the basis follows it. Until that element is actually laid out (not yet mounted, display:none, detached) percentages use a temporary 1200px basis rather than its zero measurement, and nothing is persisted from it.',
+ },
+ {
+ name: 'direction',
+ type: "'horizontal' | 'vertical'",
+ description:
+ "Which axis this region resizes along. Selects the container's inline or block content-box size as the percentage basis, and must match the direction given to ResizeHandle.",
+ default: "'horizontal'",
},
{
name: 'minSizePx',
type: 'number',
- description: 'Minimum size in pixels.',
- default: '50',
+ description:
+ 'Deprecated. Use minSize, which also accepts a percentage. Supplying both is a type error; if untyped code supplies both, minSize wins.',
},
{
name: 'maxSizePx',
type: 'number',
- description: 'Maximum size in pixels.',
- default: 'Infinity',
+ description:
+ 'Deprecated. Use maxSize, which also accepts a percentage. Explicit Infinity remains valid.',
},
{
name: 'collapsible',
type: 'boolean',
- description: 'Whether dragging below the collapsed threshold collapses the region to zero.',
+ description:
+ 'Whether dragging below the collapsed threshold collapses the region to zero.',
default: 'false',
},
{
@@ -38,23 +77,27 @@ export const docs = {
{
name: 'autoSaveId',
type: 'string',
- description: 'Key for localStorage persistence of size and collapse state across sessions.',
+ description:
+ 'Key for localStorage persistence of size and collapse state across sessions.',
},
{
name: 'defaultIsCollapsed',
type: 'boolean',
- description: 'Initial collapse state (uncontrolled). A persisted entry wins over it.',
+ description:
+ 'Initial collapse state (uncontrolled). A persisted entry wins over it.',
default: 'false',
},
{
name: 'isCollapsed',
type: 'boolean',
- description: 'Controlled collapse state. collapse(), expand() and a drag past the threshold then report through onCollapseChange instead of changing state internally.',
+ description:
+ 'Controlled collapse state. collapse(), expand() and a drag past the threshold then report through onCollapseChange instead of changing state internally.',
},
{
name: 'onCollapseChange',
type: '(isCollapsed: boolean) => void',
- description: 'Called once per collapse state change, via drag or programmatically.',
+ description:
+ 'Called once per collapse state change, via drag or programmatically.',
},
],
returns: [
@@ -86,15 +129,44 @@ export const docs = {
{
name: 'props',
type: 'ResizableProps',
- description: 'Props to spread on the resizable component or pass to ResizeHandle.',
+ description:
+ 'Props to spread on the resizable component or pass to ResizeHandle.',
},
],
usage: {
- description: 'Hook for adding drag-to-resize behavior to layout regions. Supports single-region and multi-region configurations with snap points, collapsible panels, localStorage persistence, and cascade resize ordering.',
+ description:
+ 'Hook for adding drag-to-resize behavior to layout regions. Supports single-region and multi-region configurations with snap points, collapsible panels, localStorage persistence, and cascade resize ordering.',
bestPractices: [
- {guidance: true, description: 'Use with Layout or AppShell sidebar for resizable navigation panels.'},
- {guidance: true, description: 'Set autoSaveId to persist user-chosen sizes across page reloads.'},
- {guidance: false, description: 'Set minSizePx too small; content becomes unreadable. Prefer collapsible for panels that can hide entirely.'},
+ {
+ guidance: true,
+ description:
+ 'Use percent(40, {min: pixel(333)}) for a 40% size with a 333px floor, or percent(10, {max: pixel(400)}) for a 10% size with a 400px ceiling. The options argument is required and carries a floor XOR a ceiling.',
+ },
+ {
+ guidance: true,
+ description:
+ 'A structured default is an initial choice only; a structured minSize or maxSize remains live. State, persistence, callbacks, resize(), paint, and ARIA all use resolved pixel numbers.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Import percent and Table’s same pixel binding from @astryxdesign/core/Resizable/utils when constructing configuration in a Server Component; the root package exposes one pixel symbol and one percent symbol without collision.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use with Layout or AppShell sidebar for resizable navigation panels.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set autoSaveId to persist user-chosen sizes across page reloads.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Set minSize too small; content becomes unreadable. Prefer collapsible for panels that can hide entirely.',
+ },
],
},
relatedComponents: ['Resizable', 'AppShell', 'Layout', 'SideNav'],
@@ -105,16 +177,26 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
- description: 'Adds drag-to-resize behavior to layout regions. Supports single-/multi-region configs w/ snap points, collapsible panels, localStorage persistence, cascade resize ordering.',
+ description:
+ 'Adds drag-to-resize behavior to layout regions. Supports single-/multi-region configs w/ snap points, collapsible panels, localStorage persistence, cascade resize ordering.',
paramDescriptions: {
- defaultSize: 'initial size in px / percentage string (e.g. "20%").',
- minSizePx: 'min size in px.',
- maxSizePx: 'max size in px.',
- collapsible: 'whether dragging below collapsed threshold collapses region to zero.',
+ defaultSize:
+ 'initial pixels, exact N%, or percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)}); resolves once.',
+ minSize:
+ 'live minimum: pixels, exact N%, or percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)}).',
+ maxSize:
+ 'live maximum: pixels, exact N%, or percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)}).',
+ containerRef: 'the element a percentage is a share of.',
+ direction: 'which axis to resize along.',
+ collapsible:
+ 'whether dragging below collapsed threshold collapses region to zero.',
snaps: 'px values to snap to during drag.',
- autoSaveId: 'key for localStorage persistence of size + collapse state across sessions.',
- defaultIsCollapsed: 'initial collapse state (uncontrolled); persisted entry wins.',
- isCollapsed: 'controlled collapse state; collapse()/expand()/drag report instead of mutating.',
+ autoSaveId:
+ 'key for localStorage persistence of size + collapse state across sessions.',
+ defaultIsCollapsed:
+ 'initial collapse state (uncontrolled); persisted entry wins.',
+ isCollapsed:
+ 'controlled collapse state; collapse()/expand()/drag report instead of mutating.',
onCollapseChange: 'called once per collapse state change.',
},
returnDescriptions: {
@@ -126,11 +208,24 @@ export const docsDense = {
props: 'props to spread on resizable component / pass to ResizeHandle.',
},
usage: {
- description: 'Adds drag-to-resize behavior to layout regions. Supports single-/multi-region configs w/ snap points, collapsible panels, localStorage persistence, cascade resize ordering.',
+ description:
+ 'Adds drag-to-resize behavior to layout regions. Supports single-/multi-region configs w/ snap points, collapsible panels, localStorage persistence, cascade resize ordering.',
bestPractices: [
- {guidance: true, description: 'Use w/ Layout / AppShell sidebar for resizable navigation panels.'},
- {guidance: true, description: 'Set autoSaveId to persist user-chosen sizes across page reloads.'},
- {guidance: false, description: 'Set minSizePx too small; content becomes unreadable. Prefer collapsible for panels that can hide entirely.'},
+ {
+ guidance: true,
+ description:
+ 'Use w/ Layout / AppShell sidebar for resizable navigation panels.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set autoSaveId to persist user-chosen sizes across page reloads.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Set minSize too small; content becomes unreadable. Prefer collapsible for panels that can hide entirely.',
+ },
],
},
};
diff --git a/packages/core/src/Resizable/useResizable.test.ts b/packages/core/src/Resizable/useResizable.test.ts
index d24e9e7c6f..28a2c16791 100644
--- a/packages/core/src/Resizable/useResizable.test.ts
+++ b/packages/core/src/Resizable/useResizable.test.ts
@@ -11,10 +11,16 @@
* SYNC: When useResizable changes, update tests to match new behavior
*/
-import {useLayoutEffect} from 'react';
-import {describe, it, expect, beforeEach, vi} from 'vitest';
-import {renderHook, act} from '@testing-library/react';
+import {createElement, useLayoutEffect, useRef} 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 {percent, pixel} from './utils';
+import type {ResizableSize} from './utils';
const AUTO_SAVE_ID = 'test-panel';
const KEY = `astryx-resizable:${AUTO_SAVE_ID}`;
@@ -36,6 +42,10 @@ beforeEach(() => {
localStorage.clear();
});
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
describe('useResizable persistence', () => {
it('restores a persisted width (legacy plain-number format)', () => {
localStorage.setItem(KEY, '320');
@@ -418,4 +428,1268 @@ describe('useResizable identity', () => {
expect(result.current.resize).toBe(first.resize);
expect(result.current.props._snaps).toBe(first.snaps);
});
+
+ it('settles a pixel-only mount without a ref in one render pass', () => {
+ let passes = 0;
+ const {result} = renderHook(() => {
+ passes += 1;
+ return useResizable({defaultSize: 200, minSizePx: 100, maxSizePx: 400});
+ });
+
+ expect(passes).toBe(1);
+ expect(result.current.size).toBe(200);
+ });
+
+ it.each([1, 10, 50])(
+ 'settles %i numeric-only mounts with containerRef in one pass each',
+ count => {
+ const resizeObserver = vi.fn();
+ vi.stubGlobal('ResizeObserver', resizeObserver);
+ const element = document.createElement('div');
+ let passes = 0;
+ let refReads = 0;
+ const containerRef = {
+ get current() {
+ refReads += 1;
+ return element;
+ },
+ };
+
+ function Probe() {
+ passes += 1;
+ useResizable({
+ defaultSize: 200,
+ minSizePx: 100,
+ maxSizePx: 400,
+ containerRef,
+ });
+ return null;
+ }
+
+ const view = render(
+ createElement(
+ 'div',
+ null,
+ Array.from({length: count}, (_, index) =>
+ createElement(Probe, {key: index}),
+ ),
+ ),
+ );
+
+ expect(passes).toBe(count);
+ expect(refReads).toBe(0);
+ expect(resizeObserver).not.toHaveBeenCalled();
+ view.unmount();
+ },
+ );
+});
+
+describe('useResizable percentage configuration (AST-010)', () => {
+ // jsdom lays nothing out and ships no ResizeObserver, so the container has
+ // to be stubbed for any of this to be observable. These pin the contract;
+ // the geometry proof is Chromium, in the PR.
+ 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() {
+ for (const o of StubResizeObserver.instances) {
+ o.callback(
+ o.targets.map(
+ target =>
+ ({
+ target,
+ contentBoxSize: [
+ {inlineSize: content, blockSize: contentBlock},
+ ],
+ }) as unknown as ResizeObserverEntry,
+ ),
+ o,
+ );
+ }
+ }
+ }
+
+ let content = 400;
+ let contentBlock = 300;
+
+ /** A container whose content box is `content` wide and `contentBlock` tall. */
+ const makeContainer = () => {
+ const node = document.createElement('div');
+ document.body.appendChild(node);
+ Object.defineProperty(node, 'clientWidth', {get: () => content});
+ Object.defineProperty(node, 'clientHeight', {get: () => contentBlock});
+ return {current: node};
+ };
+
+ beforeEach(() => {
+ content = 400;
+ contentBlock = 300;
+ StubResizeObserver.instances = [];
+ vi.stubGlobal('ResizeObserver', StubResizeObserver);
+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({
+ paddingTop: '0px',
+ paddingBottom: '0px',
+ paddingLeft: '0px',
+ paddingRight: '0px',
+ } as unknown as CSSStyleDeclaration);
+ });
+
+ describe('FR1 — the basis a percentage is a share of', () => {
+ it('keeps the released viewport basis when no container is given', () => {
+ // The compatibility path: this is what shipped, and it must not change.
+ window.innerWidth = 1000;
+ const {result} = renderHook(() => useResizable({defaultSize: '50%'}));
+ expect(result.current.size).toBe(500);
+ });
+
+ it('uses the container content box when one is given', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: '50%', containerRef}),
+ );
+ expect(result.current.size).toBe(200);
+ expect(result.current.size).not.toBe(window.innerWidth / 2);
+ });
+
+ it('resolves the default once — a later basis change does not move it', () => {
+ // The line between "configures a size" and "is a responsive mode".
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: '50%', containerRef}),
+ );
+ expect(result.current.size).toBe(200);
+ act(() => {
+ content = 800;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(200);
+ });
+ });
+
+ describe('FR2 — direction selects the axis', () => {
+ it('keeps the atomic percentage on the block axis', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: '50%',
+ containerRef,
+ direction: 'vertical',
+ }),
+ );
+ expect(result.current.size).toBe(150);
+ });
+
+ it('measures a structured percentage on the block axis', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: percent(50, {min: pixel(1)}),
+ containerRef,
+ direction: 'vertical',
+ }),
+ );
+ // 50% of the 300px block size, not of the 400px inline size.
+ expect(result.current.size).toBe(150);
+ });
+ });
+
+ describe('FR4/FR6 — bounds re-resolve and clamp, they never scale', () => {
+ it('clamps to a percentage maximum', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 100, maxSize: '50%', containerRef}),
+ );
+ act(() => {
+ result.current.resize(9999);
+ });
+ expect(result.current.size).toBe(200);
+ });
+
+ it('re-clamps the existing pixel size when the basis shrinks', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 100, maxSize: '50%', containerRef}),
+ );
+ act(() => {
+ result.current.resize(9999);
+ });
+ expect(result.current.size).toBe(200);
+ act(() => {
+ content = 200;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(100);
+ });
+
+ it('does not scale a selection back up when the basis grows', () => {
+ // Clamping is not a ratio. A size that fits its new maximum stays put.
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 100, maxSize: '50%', containerRef}),
+ );
+ act(() => {
+ result.current.resize(150);
+ });
+ act(() => {
+ content = 1000;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(150);
+ });
+
+ it('a clamp is permanent — growing the basis does not revive the old size', () => {
+ // Deriving the clamp for paint alone left the stored choice intact, so a
+ // container that shrank and grew again brought the pre-clamp size back.
+ // Measured in Chromium at 320px reviving to 560px before the fix.
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 100, maxSize: '50%', containerRef}),
+ );
+ act(() => {
+ result.current.resize(9999);
+ });
+ expect(result.current.size).toBe(200);
+ act(() => {
+ content = 200;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(100);
+ act(() => {
+ content = 4000;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(100);
+ });
+
+ it('does not revive a default clamped at initialization', () => {
+ // A default is a pixel selection once its first basis resolves. Keeping
+ // it as a nullable "still using the default" sentinel let the raw 321px
+ // value come back when a 400px container (200px max) grew to 800px.
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 321, maxSize: '50%', containerRef}),
+ );
+ expect(result.current.size).toBe(200);
+ act(() => {
+ content = 800;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(200);
+ });
+
+ it('mixes units across the default and the bounds', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: '50%',
+ minSize: 120,
+ maxSize: '80px',
+ containerRef,
+ }),
+ );
+ // Inverted on purpose: the maximum wins, as the released clamp order has
+ // always done.
+ expect(result.current.size).toBe(80);
+ });
+ });
+
+ describe('structured percent sizes', () => {
+ const observedTargets = () =>
+ StubResizeObserver.instances.flatMap(observer => observer.targets);
+
+ it('accepts Table pixel as a structured static value', () => {
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: pixel(333),
+ minSize: pixel(100),
+ maxSize: pixel(500),
+ }),
+ );
+ expect(result.current.size).toBe(333);
+ expect(result.current.props._minSizePx).toBe(100);
+ expect(result.current.props._maxSizePx).toBe(500);
+ });
+
+ it('applies the canonical percentage floor', () => {
+ content = 500;
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 0,
+ minSize: percent(40, {min: pixel(333)}),
+ containerRef,
+ }),
+ );
+
+ expect(result.current.props._minSizePx).toBe(333);
+ expect(result.current.size).toBe(333);
+ act(() => {
+ content = 1000;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.props._minSizePx).toBe(400);
+ expect(result.current.size).toBe(400);
+ });
+
+ it('applies the canonical percentage ceiling', () => {
+ content = 1000;
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 500,
+ maxSize: percent(10, {max: pixel(400)}),
+ containerRef,
+ }),
+ );
+
+ expect(result.current.props._maxSizePx).toBe(100);
+ expect(result.current.size).toBe(100);
+ act(() => {
+ content = 500;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.props._maxSizePx).toBe(50);
+ expect(result.current.size).toBe(50);
+ });
+
+ it('resolves a structured default once, then keeps the selected pixels', () => {
+ content = 1000;
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef,
+ }),
+ );
+
+ expect(result.current.size).toBe(400);
+ expect(observedTargets()).not.toContain(containerRef.current);
+ act(() => {
+ content = 500;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(400);
+ });
+
+ it('uses the initial viewport for a structured default without subscribing', () => {
+ window.innerWidth = 1000;
+ const addEventListener = vi.spyOn(window, 'addEventListener');
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: percent(40, {min: pixel(333)})}),
+ );
+
+ expect(result.current.size).toBe(400);
+ expect(
+ addEventListener.mock.calls.some(([type]) => type === 'resize'),
+ ).toBe(false);
+ act(() => {
+ window.innerWidth = 500;
+ window.dispatchEvent(new Event('resize'));
+ });
+ expect(result.current.size).toBe(400);
+ });
+
+ it('uses the deterministic 1200px server basis', () => {
+ const originalWindow = globalThis.window;
+ vi.stubGlobal('window', undefined);
+ try {
+ const html = renderToString(
+ createElement(() => {
+ const region = useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ });
+ return createElement('output', null, String(region.size));
+ }),
+ );
+ expect(html).toContain('480');
+ } finally {
+ vi.stubGlobal('window', originalWindow);
+ }
+ });
+
+ it('hydrates a container default without persisting the temporary basis', async () => {
+ content = 500;
+ const clientWidth = vi
+ .spyOn(HTMLElement.prototype, 'clientWidth', 'get')
+ .mockImplementation(() => content);
+ const clientHeight = vi
+ .spyOn(HTMLElement.prototype, 'clientHeight', 'get')
+ .mockImplementation(() => contentBlock);
+ const setItem = vi.spyOn(Storage.prototype, 'setItem');
+ const onSizeChange = vi.fn();
+
+ function Probe() {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const region = useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef,
+ autoSaveId: 'structured-hydration',
+ onSizeChange,
+ });
+ return createElement(
+ 'div',
+ {ref: containerRef},
+ createElement('output', {'data-size': region.size}, region.size),
+ );
+ }
+
+ const serverHTML = renderToString(createElement(Probe));
+ expect(serverHTML).toContain('data-size="480"');
+ 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>;
+
+ await act(async () => {
+ root = hydrateRoot(container, createElement(Probe), {
+ onRecoverableError: error => recoverableErrors.push(error),
+ });
+ });
+ await waitFor(() =>
+ expect(container.querySelector('output')).toHaveAttribute(
+ 'data-size',
+ '333',
+ ),
+ );
+
+ expect(recoverableErrors).toEqual([]);
+ expect(
+ consoleError.mock.calls.filter(call =>
+ String(call[0] ?? '')
+ .toLowerCase()
+ .includes('hydrat'),
+ ),
+ ).toEqual([]);
+ expect(onSizeChange).not.toHaveBeenCalled();
+ expect(
+ setItem.mock.calls.some(([, value]) => value.includes('"size":480')),
+ ).toBe(false);
+ expect(
+ localStorage.getItem('astryx-resizable:structured-hydration'),
+ ).toBe(JSON.stringify({size: 333, isCollapsed: false}));
+
+ await act(async () => root.unmount());
+ consoleError.mockRestore();
+ setItem.mockRestore();
+ clientWidth.mockRestore();
+ clientHeight.mockRestore();
+ container.remove();
+ });
+
+ it('waits for a positive basis and then removes a default-only observer', () => {
+ content = 0;
+ const containerRef = makeContainer();
+ const onSizeChange = vi.fn();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef,
+ autoSaveId: 'structured-zero',
+ onSizeChange,
+ }),
+ );
+
+ expect(result.current.size).toBe(480);
+ expect(
+ localStorage.getItem('astryx-resizable:structured-zero'),
+ ).toBeNull();
+ expect(observedTargets()).toContain(containerRef.current);
+ act(() => {
+ content = 500;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(333);
+ expect(localStorage.getItem('astryx-resizable:structured-zero')).toBe(
+ JSON.stringify({size: 333, isCollapsed: false}),
+ );
+ expect(onSizeChange).not.toHaveBeenCalled();
+ expect(observedTargets()).not.toContain(containerRef.current);
+ });
+
+ it('removes the default observer when resize selects pixels before layout', () => {
+ content = 0;
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef,
+ }),
+ );
+
+ expect(observedTargets()).toContain(containerRef.current);
+ act(() => result.current.resize(275));
+ act(() => {
+ content = 500;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(275);
+ expect(observedTargets()).not.toContain(containerRef.current);
+ });
+
+ it('lets a persisted pixel choice win without measuring the unused default', () => {
+ localStorage.setItem(
+ 'astryx-resizable:structured-persisted',
+ JSON.stringify({size: 321, isCollapsed: false}),
+ );
+ content = 1000;
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef,
+ autoSaveId: 'structured-persisted',
+ }),
+ );
+
+ expect(result.current.size).toBe(321);
+ expect(observedTargets()).not.toContain(containerRef.current);
+ });
+
+ it('measures the current basis before a newly added bound can clamp', () => {
+ content = 500;
+ const containerRef = makeContainer();
+ const initialProps: {maxSize?: ResizableSize} = {};
+ const {result, rerender} = renderHook(
+ ({maxSize}: {maxSize?: ResizableSize}) =>
+ useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ maxSize,
+ containerRef,
+ }),
+ {initialProps},
+ );
+
+ expect(result.current.size).toBe(333);
+ act(() => result.current.resize(450));
+ content = 1000;
+ rerender({maxSize: percent(50, {max: pixel(800)})});
+
+ expect(result.current.props._maxSizePx).toBe(500);
+ expect(result.current.size).toBe(450);
+ expect(observedTargets()).toContain(containerRef.current);
+ });
+
+ it('matches an atomic percentage default render count and drops both observers', () => {
+ content = 1000;
+ const atomicRef = makeContainer();
+ let atomicPasses = 0;
+ const atomic = renderHook(() => {
+ atomicPasses += 1;
+ return useResizable({defaultSize: '40%', containerRef: atomicRef});
+ });
+ expect(atomic.result.current.size).toBe(400);
+ expect(observedTargets()).not.toContain(atomicRef.current);
+ atomic.unmount();
+
+ const structuredRef = makeContainer();
+ let structuredPasses = 0;
+ const structured = renderHook(() => {
+ structuredPasses += 1;
+ return useResizable({
+ defaultSize: percent(40, {min: pixel(333)}),
+ containerRef: structuredRef,
+ });
+ });
+ expect(structured.result.current.size).toBe(400);
+ expect(structuredPasses).toBe(atomicPasses);
+ expect(observedTargets()).not.toContain(structuredRef.current);
+ });
+
+ it('treats an explicitly undefined opposite bound as absent', () => {
+ content = 500;
+ const containerRef = makeContainer();
+ const floor = percent(40, {min: pixel(333), max: undefined});
+ const ceiling = percent(80, {min: undefined, max: pixel(350)});
+
+ const minimum = renderHook(() =>
+ useResizable({defaultSize: floor, containerRef}),
+ );
+ expect(minimum.result.current.size).toBe(333);
+ minimum.unmount();
+
+ const maximum = renderHook(() =>
+ useResizable({defaultSize: ceiling, containerRef}),
+ );
+ expect(maximum.result.current.size).toBe(350);
+ maximum.unmount();
+ });
+
+ it.each([
+ ['negative', pixel(-1)],
+ ['NaN', pixel(Number.NaN)],
+ ['Infinity', pixel(Infinity)],
+ ])('rejects an invalid direct PixelWidth: %s', (_label, invalid) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: invalid as never}),
+ );
+ expect(result.current.size).toBe(250);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Falling back to 250'),
+ );
+ if (_label === 'Infinity') {
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('{"type":"pixel","value":Infinity}'),
+ );
+ }
+ warn.mockRestore();
+ });
+
+ it('rejects the removed CSS-like grammar', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 10,
+ minSize: 'max(40%, 333px)' as never,
+ maxSize: 'min(400px, 10%)' as never,
+ } as never),
+ );
+
+ expect(result.current.size).toBe(50);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('minSize: "max(40%, 333px)"'),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('maxSize: "min(400px, 10%)"'),
+ );
+ warn.mockRestore();
+ });
+
+ it('applies role-specific fallbacks to invalid structured bounds', () => {
+ const invalid = {
+ type: 'percent',
+ value: 40,
+ min: pixel(100),
+ max: pixel(500),
+ };
+ const minimum = renderHook(() =>
+ useResizable({defaultSize: 10, minSize: invalid as never}),
+ );
+ expect(minimum.result.current.size).toBe(50);
+ minimum.unmount();
+
+ const maximum = renderHook(() =>
+ useResizable({defaultSize: 10_000, maxSize: invalid as never}),
+ );
+ expect(maximum.result.current.size).toBe(10_000);
+ maximum.unmount();
+ });
+
+ it.each([
+ [
+ 'wrong discriminator',
+ {type: 'proportional', value: 40, min: pixel(100)},
+ ],
+ ['missing bound', {type: 'percent', value: 40}],
+ [
+ 'both bounds',
+ {type: 'percent', value: 40, min: pixel(100), max: pixel(500)},
+ ],
+ ['negative percentage', {type: 'percent', value: -1, min: pixel(100)}],
+ ['high percentage', {type: 'percent', value: 101, min: pixel(100)}],
+ [
+ 'non-finite percentage',
+ {type: 'percent', value: Infinity, min: pixel(100)},
+ ],
+ [
+ 'negative pixel helper',
+ {type: 'percent', value: 40, min: {type: 'pixel', value: -1}},
+ ],
+ [
+ 'non-finite pixel helper',
+ {type: 'percent', value: 40, max: {type: 'pixel', value: Infinity}},
+ ],
+ ['raw numeric bound', {type: 'percent', value: 40, min: 100}],
+ ])('rejects an invalid structured value: %s', (_label, invalid) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: invalid as never}),
+ );
+ expect(result.current.size).toBe(250);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Falling back to 250'),
+ );
+ if (_label === 'non-finite pixel helper') {
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('"max":{"type":"pixel","value":Infinity}'),
+ );
+ }
+ warn.mockRestore();
+ });
+ });
+
+ describe('FR5 — state, ARIA and paint describe one geometry', () => {
+ it('publishes the clamped size and the resolved bounds', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 100, maxSize: '50%', containerRef}),
+ );
+ act(() => {
+ result.current.resize(9999);
+ });
+ expect(result.current.props._size).toBe(200);
+ expect(result.current.props._maxSizePx).toBe(200);
+ expect(result.current.props._size).toBeLessThanOrEqual(
+ result.current.props._maxSizePx,
+ );
+ });
+ });
+
+ describe('FR10 — a basis change is not a user interaction', () => {
+ it('does not fire onSizeChange when a bound re-clamps the size', () => {
+ const containerRef = makeContainer();
+ const onSizeChange = vi.fn();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 100,
+ maxSize: '50%',
+ containerRef,
+ onSizeChange,
+ }),
+ );
+ act(() => {
+ result.current.resize(9999);
+ });
+ onSizeChange.mockClear();
+ act(() => {
+ content = 200;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.size).toBe(100);
+ expect(onSizeChange).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('FR12/API3 — exact parsing, role-specific fallbacks', () => {
+ it.each([
+ ['50 px', 'a space'],
+ ['50rem', 'another unit'],
+ ['120%', 'above 100%'],
+ ['-10px', 'negative'],
+ ['abc', 'not a size'],
+ [-1, 'a negative number'],
+ [Number.NaN, 'NaN'],
+ ])('falls back to 250px for defaultSize %s (%s)', (invalid, _why) => {
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: invalid as never}),
+ );
+ expect(result.current.size).toBe(250);
+ });
+
+ it('falls back to 50px for an invalid minimum', () => {
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 10, minSize: 'nope' as never}),
+ );
+ expect(result.current.size).toBe(50);
+ });
+
+ it('falls back to unbounded for an invalid maximum', () => {
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 10_000, maxSize: 'nope' as never}),
+ );
+ expect(result.current.size).toBe(10_000);
+ });
+
+ it('accepts an exact px string', () => {
+ const {result} = renderHook(() => useResizable({defaultSize: '180px'}));
+ expect(result.current.size).toBe(180);
+ });
+
+ it('keeps explicit maxSize: Infinity valid without warning', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 900, maxSize: Infinity}),
+ );
+ expect(result.current.size).toBe(900);
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('names a non-finite invalid input in its warning', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: Number.NaN}),
+ );
+ expect(result.current.size).toBe(250);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('defaultSize: NaN is not a size'),
+ );
+ warn.mockRestore();
+ });
+
+ it('keeps explicit maxSizePx: Infinity valid', () => {
+ // A shipped template uses this spelling.
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 900, maxSizePx: Infinity}),
+ );
+ expect(result.current.size).toBe(900);
+ });
+ });
+
+ describe('API4 — the unified bound beats its deprecated alias', () => {
+ it('prefers minSize over minSizePx when untyped input supplies both', () => {
+ // Typed callers cannot do this; a spread or an `any` can, and the
+ // explicit migration target must not lose to a stale alias.
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 10,
+ ...({minSize: 300, minSizePx: 60} as object),
+ } as never),
+ );
+ expect(result.current.size).toBe(300);
+ });
+
+ it('warns for both ignored aliases when untyped input supplies both pairs', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 250,
+ ...({
+ minSize: 100,
+ minSizePx: 60,
+ maxSize: 500,
+ maxSizePx: 800,
+ } as object),
+ } as never),
+ );
+
+ expect(result.current.size).toBe(250);
+ expect(warn).toHaveBeenCalledTimes(2);
+ expect(warn).toHaveBeenCalledWith(
+ 'useResizable: both `minSize` and `minSizePx` were supplied. ' +
+ '`minSize` wins; the deprecated `minSizePx` is ignored.',
+ );
+ expect(warn).toHaveBeenCalledWith(
+ 'useResizable: both `maxSize` and `maxSizePx` were supplied. ' +
+ '`maxSize` wins; the deprecated `maxSizePx` is ignored.',
+ );
+ warn.mockRestore();
+ });
+
+ it('preserves exact atomic strings from untyped legacy aliases', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: 1000,
+ containerRef,
+ ...({minSizePx: '180px', maxSizePx: '50%'} as object),
+ } as never),
+ );
+
+ expect(result.current.props._minSizePx).toBe(180);
+ expect(result.current.props._maxSizePx).toBe(200);
+ expect(result.current.size).toBe(200);
+ });
+
+ it('leaves an old-only caller exactly as it was', () => {
+ const {result} = renderHook(() =>
+ useResizable({defaultSize: 260, minSizePx: 180, maxSizePx: 480}),
+ );
+ expect(result.current.size).toBe(260);
+ act(() => {
+ result.current.resize(9999);
+ });
+ expect(result.current.size).toBe(480);
+ });
+ });
+
+ describe('API6 — resize stays pixels and keeps the last legal size', () => {
+ it.each([Number.NaN, Infinity, -5])('ignores resize(%s)', bad => {
+ const {result} = renderHook(() => useResizable({defaultSize: 200}));
+ act(() => {
+ result.current.resize(bad);
+ });
+ expect(result.current.size).toBe(200);
+ expect(Number.isFinite(result.current.size)).toBe(true);
+ });
+ });
+
+ describe('FR11 — multi-region shares one container and axis', () => {
+ it('keeps atomic percentage regions independent', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ containerRef,
+ regions: {
+ left: {defaultSize: '25%'},
+ right: {defaultSize: '50%'},
+ },
+ }),
+ );
+ expect(result.current.left.size).toBe(100);
+ expect(result.current.right.size).toBe(200);
+ act(() => result.current.left.resize(160));
+ expect(result.current.left.size).toBe(160);
+ expect(result.current.right.size).toBe(200);
+ });
+
+ it('gives every structured region the same basis without coupling sizes', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ containerRef,
+ regions: {
+ left: {defaultSize: percent(25, {min: pixel(80)})},
+ right: {defaultSize: percent(50, {max: pixel(300)})},
+ },
+ }),
+ );
+ expect(result.current.left.size).toBe(100);
+ expect(result.current.right.size).toBe(200);
+ act(() => {
+ result.current.left.resize(160);
+ });
+ // Independent: moving one leaves the other alone.
+ expect(result.current.left.size).toBe(160);
+ expect(result.current.right.size).toBe(200);
+ });
+ });
+
+ describe('FR9 — persistence stays pixel-only', () => {
+ it('restores a persisted pixel size over a percentage default', () => {
+ localStorage.setItem(
+ 'astryx-resizable:pct-persist',
+ JSON.stringify({size: 321, isCollapsed: false}),
+ );
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: '50%',
+ containerRef,
+ autoSaveId: 'pct-persist',
+ }),
+ );
+ expect(result.current.size).toBe(321);
+ localStorage.clear();
+ });
+
+ it('never writes a percentage to storage', () => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({
+ defaultSize: '50%',
+ containerRef,
+ autoSaveId: 'pct-write',
+ }),
+ );
+ act(() => {
+ result.current.resize(175);
+ });
+ const raw = localStorage.getItem('astryx-resizable:pct-write');
+ expect(raw).toBe(JSON.stringify({size: 175, isCollapsed: false}));
+ localStorage.clear();
+ });
+ });
+
+ describe('API1 — the basis follows the element the ref points at', () => {
+ /** A container of a fixed content width, independent of `content`. */
+ const makeSized = (width: number) => {
+ const node = document.createElement('div');
+ document.body.appendChild(node);
+ Object.defineProperty(node, 'clientWidth', {get: () => width});
+ Object.defineProperty(node, 'clientHeight', {get: () => 300});
+ return node;
+ };
+
+ it('reconciles a live ref replacement before flushSync returns', () => {
+ const first = makeSized(400);
+ const second = makeSized(800);
+ const containerRef: {current: HTMLElement | null} = {current: first};
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+
+ function Probe() {
+ const region = useResizable({
+ containerRef,
+ defaultSize: 100,
+ minSize: '50%',
+ });
+ return createElement('output', {'data-size': region.size});
+ }
+
+ try {
+ act(() => {
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- test the DOM at the commit boundary before passive effects
+ flushSync(() => root.render(createElement(Probe)));
+ expect(host.querySelector('output')).toHaveAttribute(
+ 'data-size',
+ '200',
+ );
+ });
+
+ containerRef.current = second;
+ act(() => {
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- test the DOM at the commit boundary before passive effects
+ flushSync(() => root.render(createElement(Probe)));
+ expect(host.querySelector('output')).toHaveAttribute(
+ 'data-size',
+ '400',
+ );
+ });
+ } finally {
+ act(() => {
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- finish this low-level root without leaving async cleanup
+ flushSync(() => root.unmount());
+ });
+ host.remove();
+ }
+ });
+
+ it('starts following the current ref when a pixel-only config gains a percentage bound', () => {
+ const first = makeSized(400);
+ const replacement = makeSized(800);
+ const containerRef: {current: HTMLElement | null} = {current: first};
+ const initialProps: {maxSize?: ResizableSize} = {};
+ const {result, rerender} = renderHook(
+ ({maxSize}: {maxSize?: ResizableSize}) =>
+ useResizable({containerRef, defaultSize: 350, maxSize}),
+ {initialProps},
+ );
+ const observed = () =>
+ StubResizeObserver.instances.flatMap(observer => observer.targets);
+
+ expect(result.current.size).toBe(350);
+ expect(observed()).not.toContain(first);
+
+ act(() => {
+ containerRef.current = replacement;
+ });
+ rerender({maxSize: percent(50, {max: pixel(600)})});
+
+ expect(result.current.props._maxSizePx).toBe(400);
+ expect(result.current.size).toBe(350);
+ expect(observed()).not.toContain(first);
+ expect(observed()).toContain(replacement);
+ });
+
+ it('does not clamp against an old element when a percentage bound returns', () => {
+ const first = makeSized(400);
+ const replacement = makeSized(800);
+ const containerRef: {current: HTMLElement | null} = {current: first};
+ const initialProps: {maxSize?: ResizableSize} = {maxSize: '50%'};
+ const {result, rerender} = renderHook(
+ ({maxSize}: {maxSize?: ResizableSize}) =>
+ useResizable({containerRef, defaultSize: 100, maxSize}),
+ {initialProps},
+ );
+ const observed = () =>
+ StubResizeObserver.instances.flatMap(observer => observer.targets);
+
+ expect(result.current.props._maxSizePx).toBe(200);
+ rerender({maxSize: undefined});
+ act(() => result.current.resize(350));
+ expect(result.current.size).toBe(350);
+ expect(observed()).not.toContain(first);
+
+ act(() => {
+ containerRef.current = replacement;
+ });
+ rerender({maxSize: percent(50, {max: pixel(600)})});
+
+ expect(result.current.props._maxSizePx).toBe(400);
+ expect(result.current.size).toBe(350);
+ expect(observed()).not.toContain(first);
+ expect(observed()).toContain(replacement);
+ });
+
+ it('re-resolves against the replacement when the ref changes element', () => {
+ // A ref object is stable across an element swap, so nothing about the
+ // hook's inputs changes: the subscription has to follow the ref itself.
+ const first = makeSized(398);
+ const second = makeSized(798);
+ const containerRef: {current: HTMLElement | null} = {current: first};
+ const {result, rerender} = renderHook(() =>
+ useResizable({containerRef, defaultSize: 150, maxSize: '50%'}),
+ );
+ 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);
+ const containerRef: {current: HTMLElement | null} = {current: first};
+ const {rerender} = renderHook(() =>
+ useResizable({containerRef, defaultSize: 150, maxSize: '50%'}),
+ );
+ const observed = () =>
+ StubResizeObserver.instances.flatMap(o => o.targets);
+ expect(observed()).toContain(first);
+
+ act(() => {
+ containerRef.current = second;
+ });
+ rerender();
+ // The old node is detached by now; leaving it observed is what reported
+ // a content box of 0 and zeroed the bounds.
+ expect(observed()).not.toContain(first);
+ expect(observed()).toContain(second);
+ });
+
+ it('treats an unlaid-out container as unmeasured, not as zero', () => {
+ // display:none, detached, or not yet laid out: all report 0. Resolving a
+ // percentage against 0 makes every bound 0.
+ const hidden = makeSized(0);
+ const {result} = renderHook(() =>
+ useResizable({
+ containerRef: {current: hidden},
+ defaultSize: 200,
+ maxSize: '50%',
+ }),
+ );
+ // The documented temporary 1200px basis, not 0.
+ expect(result.current.props._maxSizePx).toBe(600);
+ expect(result.current.size).toBe(200);
+ });
+
+ it('does not overwrite a saved size from an unmeasured basis', () => {
+ localStorage.setItem(
+ 'astryx-resizable:hidden-mount',
+ JSON.stringify({size: 321, isCollapsed: false}),
+ );
+ const hidden = makeSized(0);
+ renderHook(() =>
+ useResizable({
+ containerRef: {current: hidden},
+ defaultSize: 200,
+ maxSize: '50%',
+ autoSaveId: 'hidden-mount',
+ }),
+ );
+ expect(localStorage.getItem('astryx-resizable:hidden-mount')).toBe(
+ JSON.stringify({size: 321, 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.
+ const containerRef = {current: makeSized(400)};
+ const {result} = renderHook(() =>
+ useResizable({containerRef, defaultSize: 200, autoSaveId: 'px-only'}),
+ );
+ act(() => {
+ result.current.resize(240);
+ });
+ expect(localStorage.getItem('astryx-resizable:px-only')).toBe(
+ JSON.stringify({size: 240, isCollapsed: false}),
+ );
+ localStorage.clear();
+ });
+ });
+
+ describe('FR7 — every terminal gesture releases the frozen basis', () => {
+ it.each([
+ ['_onResizeEnd', (p: ResizableProps) => p._onResizeEnd()],
+ ['_onResizeCancel', (p: ResizableProps) => p._onResizeCancel?.()],
+ ])('%s lets the bounds re-resolve', (_name, finish) => {
+ const containerRef = makeContainer();
+ const {result} = renderHook(() =>
+ useResizable({containerRef, defaultSize: 200, maxSize: '50%'}),
+ );
+ expect(result.current.props._maxSizePx).toBe(200);
+
+ act(() => {
+ result.current.props._onResizeStart();
+ });
+ // The container shrinks mid-gesture: the bound must hold until the
+ // gesture is over, so the handle does not move away from the pointer.
+ act(() => {
+ content = 200;
+ StubResizeObserver.resizeAll();
+ });
+ expect(result.current.props._maxSizePx).toBe(200);
+
+ act(() => {
+ finish(result.current.props);
+ });
+ expect(result.current.props._maxSizePx).toBe(100);
+ expect(result.current.size).toBe(100);
+ });
+ });
+});
+
+describe('Resizable size source compatibility (AST-010 API3/API4)', () => {
+ it('keeps the released broad default type and adds structured values', () => {
+ const computed: string = 'runtime-validated-string';
+ const configs = [
+ {defaultSize: computed},
+ {defaultSize: 333},
+ {defaultSize: '333px'},
+ {defaultSize: '40%'},
+ {defaultSize: pixel(333)},
+ {defaultSize: percent(40, {min: pixel(333)})},
+ {defaultSize: 0, minSize: percent(40, {min: pixel(333)})},
+ {defaultSize: 500, maxSize: percent(10, {max: pixel(400)})},
+ {defaultSize: 260, minSizePx: 180, maxSizePx: 480},
+ ] satisfies UseResizableSingleConfig[];
+ expect(configs).toHaveLength(9);
+ });
+
+ it('rejects unsupported bound strings and alias conflicts', () => {
+ // @ts-expect-error bound strings are exact px/% only
+ const rem: UseResizableSingleConfig = {minSize: '10rem'};
+ const cssMath: UseResizableSingleConfig = {
+ // @ts-expect-error CSS functions are not part of ResizableSize
+ minSize: 'max(40%, 333px)',
+ };
+ // @ts-expect-error unified minimum and legacy alias are mutually exclusive
+ const duplicateMin: UseResizableSingleConfig = {
+ minSize: '40%',
+ minSizePx: 100,
+ };
+ // @ts-expect-error unified maximum and legacy alias are mutually exclusive
+ const duplicateMax: UseResizableSingleConfig = {
+ maxSize: percent(10, {max: pixel(400)}),
+ maxSizePx: 500,
+ };
+ expect([rem, cssMath, duplicateMin, duplicateMax]).toHaveLength(4);
+ });
+});
+
+describe('ResizableProps source compatibility (AST-010 API5)', () => {
+ it('accepts an object literal written before _direction existed', () => {
+ // The type is exported. Every field added to it since has to be optional,
+ // or a hand-built object that satisfied the released type stops compiling.
+ const prePr: ResizableProps = {
+ _size: 200,
+ _isCollapsed: false,
+ _onResizeStart: () => {},
+ _onResizeMove: () => {},
+ _onResizeEnd: () => {},
+ _minSizePx: 100,
+ _maxSizePx: 400,
+ _snaps: [],
+ _collapsedSize: 40,
+ _collapsible: false,
+ _isResizableProps: true,
+ };
+ expect(prePr._direction).toBeUndefined();
+ expect(prePr._onResizeCancel).toBeUndefined();
+ });
});
diff --git a/packages/core/src/Resizable/useResizable.ts b/packages/core/src/Resizable/useResizable.ts
index 56809dfd97..44fbed1326 100644
--- a/packages/core/src/Resizable/useResizable.ts
+++ b/packages/core/src/Resizable/useResizable.ts
@@ -4,25 +4,61 @@
/**
* @file useResizable.ts
- * @input Resize configuration (defaultSize, minSizePx, maxSizePx, snaps) and
- * collapse configuration (collapsible, defaultIsCollapsed, isCollapsed)
+ * @input Resize configuration (defaultSize, minSize, maxSize, legacy pixel
+ * aliases, snaps) and collapse configuration (collapsible,
+ * defaultIsCollapsed, isCollapsed)
* @output Hook return: size, isCollapsed, collapse/expand/resize methods, props for handle
* @position Public hook; consumed by layout components via `resizable` prop
*/
-import {useCallback, useEffect, useRef, useState} from 'react';
+import {
+ useCallback,
+ useEffect,
+ 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';
// =============================================================================
// Types
// =============================================================================
-export interface ResizableRegionConfig {
- /** Default size in pixels, or percentage string (e.g. '20%'). */
- defaultSize?: number | string;
- /** Minimum size in pixels. @default 50 */
- minSizePx?: number;
- /** Maximum size in pixels. @default Infinity */
- maxSizePx?: number;
+/**
+ * The minimum, in one of two spellings. Exactly one may be supplied: the union
+ * makes passing both a type error, so a migration cannot leave a stale
+ * deprecated value shadowing the new one (AST-010 API4).
+ */
+export type ResizableMinConfig =
+ | {minSize?: ResizableSize; minSizePx?: never}
+ | {minSize?: never; minSizePx?: number};
+
+/** The maximum, in one of two spellings. See {@link ResizableMinConfig}. */
+export type ResizableMaxConfig =
+ | {maxSize?: ResizableSize; maxSizePx?: never}
+ | {maxSize?: never; maxSizePx?: number};
+
+export type ResizableDirection = 'horizontal' | 'vertical';
+
+export interface ResizableRegionSizing {
+ /**
+ * Initial size. A number is pixels, exact `Npx` is pixels, exact `N%` is a
+ * share of the basis, and the structured percent form in
+ * {@link ResizableSize} adds exactly one pixel floor or ceiling to that percentage. The public type retains the released
+ * {@link SizeValue} (`number | string`) for compatibility, so runtime
+ * validation remains authoritative for strings.
+ *
+ * A basis-dependent value resolves ONCE into a pixel size — against the
+ * container when `containerRef` is supplied, against the viewport otherwise.
+ * It configures the initial selection; it does not make the region track its
+ * basis afterwards.
+ */
+ defaultSize?: ResizableSize | SizeValue;
/** Whether this region can collapse to 0. @default false */
collapsible?: boolean;
/** Size in px at which dragging triggers collapse. @default 40 */
@@ -33,6 +69,10 @@ export interface ResizableRegionConfig {
shrinkOrder?: number;
}
+export type ResizableRegionConfig = ResizableRegionSizing &
+ ResizableMinConfig &
+ ResizableMaxConfig;
+
/**
* Shared config shape for any component that integrates built-in resize
* (e.g. SideNav `resizable` prop). Provides a simplified API surface
@@ -57,7 +97,23 @@ export interface ResizableConfig {
onCollapseChange?: (isCollapsed: boolean) => void;
}
-export interface UseResizableSingleConfig extends ResizableRegionConfig {
+export interface UseResizableSingleOptions {
+ /**
+ * The element a percentage is a share of. Caller-owned: only the caller
+ * knows which element is the intended layout container, so the hook never
+ * infers one from the panel or the handle.
+ *
+ * Omitted, percentages keep the released viewport basis. Supplied, they use
+ * this element's content-box size on the active axis. It changes the basis
+ * only — it does not make a selected size responsive.
+ */
+ containerRef?: RefObject<HTMLElement | null>;
+ /**
+ * Which axis this region resizes along. Selects the container's inline or
+ * block content-box size as the percentage basis, and must match the
+ * `direction` given to `ResizeHandle`. @default 'horizontal'
+ */
+ direction?: ResizableDirection;
/** Unique key for localStorage persistence. */
autoSaveId?: string;
/**
@@ -78,9 +134,18 @@ export interface UseResizableSingleConfig extends ResizableRegionConfig {
onCollapseChange?: (isCollapsed: boolean) => void;
}
+export type UseResizableSingleConfig = ResizableRegionConfig &
+ UseResizableSingleOptions;
+
export interface UseResizableMultiConfig {
- /** Layout direction. @default 'horizontal' */
- direction?: 'horizontal' | 'vertical';
+ /** Layout direction, shared by every region. @default 'horizontal' */
+ direction?: ResizableDirection;
+ /**
+ * One container for every region's percentage basis. Regions stay
+ * independently pixel-selected; sharing a basis adds no ratio or
+ * total-100% invariant between them.
+ */
+ containerRef?: RefObject<HTMLElement | null>;
/** Named region configurations. */
regions: Record<string, ResizableRegionConfig>;
/** Unique key for localStorage persistence. */
@@ -109,6 +174,16 @@ export interface ResizableProps {
_onResizeStart: () => void;
_onResizeMove: (delta: number) => void;
_onResizeEnd: () => void;
+ /**
+ * The gesture ended without completing — pointercancel, a lost pointer
+ * capture, or a handle unmounted mid-drag. Separate from `_onResizeEnd`
+ * because a cancelled drag deliberately does not signal a resize end (#5297),
+ * but it must still release everything the gesture was holding.
+ *
+ * Optional: `ResizableProps` is exported, so a hand-built object from before
+ * this existed has to keep compiling.
+ */
+ _onResizeCancel?: () => void;
_minSizePx: number;
_maxSizePx: number;
_snaps: number[];
@@ -116,6 +191,14 @@ export interface ResizableProps {
/** Whether the region supports collapsing. */
// eslint-disable-next-line @astryx/boolean-prop-naming
_collapsible: boolean;
+ /**
+ * The hook's axis, so a handle can flag a direction mismatch.
+ *
+ * Optional for the same reason as `_onResizeCancel`: this type is exported,
+ * and requiring a new field would break every object literal that already
+ * satisfies it. Absent means "no axis to check", not "horizontal".
+ */
+ _direction?: ResizableDirection;
_isResizableProps: true;
}
@@ -225,21 +308,263 @@ function persistState(key: string, state: PersistedResizableState): void {
}
}
-function resolveDefaultSize(defaultSize: number | string | undefined): number {
- if (defaultSize == null) {
- return 250;
+/** The released compatibility basis when there is no window to measure. */
+const SERVER_BASIS = 1200;
+const DEFAULT_SIZE_FALLBACK = 250;
+const RESIZABLE_SIZE_GUIDANCE =
+ 'Use a non-negative number of pixels, an exact "Npx" string, an exact ' +
+ '"N%" string from 0% to 100%, pixel(value), or ' +
+ 'percent(value, {min: pixel(value)}) / percent(value, {max: pixel(value)}).';
+const LEGACY_PIXEL_GUIDANCE = 'Use a non-negative number of pixels.';
+const LEGACY_MAX_PIXEL_GUIDANCE =
+ 'Use a non-negative number of pixels or explicit Infinity.';
+
+/** Parsed, validated input. */
+type ParsedSize =
+ | {kind: 'px'; value: number}
+ | {kind: 'percent'; value: number; min?: number; max?: number};
+
+const PX_PATTERN = /^(\d+(?:\.\d+)?)px$/;
+const PERCENT_PATTERN = /^(\d+(?:\.\d+)?)%$/;
+
+function parseSizeString(value: string): ParsedSize | null {
+ // Preserve the released atomic fast path exactly.
+ const px = PX_PATTERN.exec(value);
+ if (px) {
+ const parsed = Number(px[1]);
+ return Number.isFinite(parsed) ? {kind: 'px', value: parsed} : null;
+ }
+ const percentValue = PERCENT_PATTERN.exec(value);
+ if (percentValue) {
+ const parsed = Number(percentValue[1]);
+ return Number.isFinite(parsed) && parsed <= 100
+ ? {kind: 'percent', value: parsed}
+ : null;
+ }
+ return null;
+}
+
+function parsePixelSize(value: unknown): number | null {
+ if (typeof value !== 'object' || value == null || Array.isArray(value)) {
+ return null;
+ }
+ const candidate = value as {type?: unknown; value?: unknown};
+ return candidate.type === 'pixel' &&
+ typeof candidate.value === 'number' &&
+ Number.isFinite(candidate.value) &&
+ candidate.value >= 0
+ ? candidate.value
+ : null;
+}
+
+function parsePercentSize(value: object): ParsedSize | null {
+ if (Array.isArray(value)) {
+ return null;
+ }
+ const candidate = value as {
+ type?: unknown;
+ value?: unknown;
+ min?: unknown;
+ max?: unknown;
+ };
+ if (
+ candidate.type !== 'percent' ||
+ typeof candidate.value !== 'number' ||
+ !Number.isFinite(candidate.value) ||
+ candidate.value < 0 ||
+ candidate.value > 100
+ ) {
+ return null;
+ }
+
+ const hasMin = candidate.min !== undefined;
+ const hasMax = candidate.max !== undefined;
+ // Exactly one bound is required. The helper's public type enforces this for
+ // typed callers; this branch preserves it for JavaScript and `any`.
+ if (hasMin === hasMax) {
+ return null;
+ }
+ if (hasMin) {
+ const min = parsePixelSize(candidate.min);
+ return min == null ? null : {kind: 'percent', value: candidate.value, min};
+ }
+ const max = parsePixelSize(candidate.max);
+ return max == null ? null : {kind: 'percent', value: candidate.value, max};
+}
+
+function parseSize(value: unknown): ParsedSize | null {
+ if (typeof value === 'number') {
+ return Number.isFinite(value) && value >= 0 ? {kind: 'px', value} : null;
+ }
+ if (typeof value === 'string') {
+ return parseSizeString(value);
+ }
+ if (typeof value === 'object' && value != null) {
+ const pixelValue = parsePixelSize(value);
+ return pixelValue == null
+ ? parsePercentSize(value)
+ : {kind: 'px', value: pixelValue};
+ }
+ return null;
+}
+
+function parseLegacyPixel(
+ value: unknown,
+ allowInfinity: boolean,
+): ParsedSize | null {
+ if (allowInfinity && value === Infinity) {
+ return {kind: 'px', value};
+ }
+ if (typeof value === 'number') {
+ return Number.isFinite(value) && value >= 0 ? {kind: 'px', value} : null;
+ }
+ // Preserve the released runtime compatibility for untyped callers. The
+ // public aliases remain number-only, but exact atomic strings worked before
+ // they were deprecated and continue to resolve through the same fast path.
+ return typeof value === 'string' ? parseSizeString(value) : null;
+}
+
+/** Whether this parsed value must be recomputed when its basis changes. */
+function dependsOnBasis(parsed: ParsedSize | null): boolean {
+ return parsed?.kind === 'percent';
+}
+
+/** Resolve a parsed size against its basis, then apply its one pixel bound. */
+function toPixels(parsed: ParsedSize, basis: number | null): number | null {
+ if (parsed.kind === 'px') {
+ return parsed.value;
+ }
+ if (basis == null) {
+ return null;
+ }
+ const percentagePx = Math.round((parsed.value / 100) * basis);
+ if (parsed.min !== undefined) {
+ return Math.max(percentagePx, parsed.min);
+ }
+ if (parsed.max !== undefined) {
+ return Math.min(percentagePx, parsed.max);
+ }
+ return percentagePx;
+}
+
+function describeUnknown(value: unknown): string {
+ if (typeof value === 'number' && !Number.isFinite(value)) {
+ return String(value);
+ }
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+}
+
+function describePixelCandidate(value: unknown): string {
+ if (typeof value !== 'object' || value == null || Array.isArray(value)) {
+ return describeUnknown(value);
+ }
+ const candidate = value as {type?: unknown; value?: unknown};
+ return candidate.type === 'pixel'
+ ? `{"type":"pixel","value":${describeUnknown(candidate.value)}}`
+ : describeUnknown(value);
+}
+
+function describeSize(value: unknown): string {
+ if (typeof value === 'object' && value != null && !Array.isArray(value)) {
+ const candidate = value as {
+ type?: unknown;
+ value?: unknown;
+ min?: unknown;
+ max?: unknown;
+ };
+ if (candidate.type === 'pixel') {
+ return describePixelCandidate(value);
+ }
+ if (candidate.type === 'percent') {
+ const fields = [
+ '"type":"percent"',
+ `"value":${describeUnknown(candidate.value)}`,
+ ];
+ if (candidate.min !== undefined) {
+ fields.push(`"min":${describePixelCandidate(candidate.min)}`);
+ }
+ if (candidate.max !== undefined) {
+ fields.push(`"max":${describePixelCandidate(candidate.max)}`);
+ }
+ return `{${fields.join(',')}}`;
+ }
+ }
+ return describeUnknown(value);
+}
+
+/**
+ * Resolves one configured value, applying its role's fallback when the input is
+ * not accepted. The warning remains development-only through `devWarn`; every
+ * build takes the same deterministic fallback.
+ */
+function resolveBound(
+ raw: unknown,
+ parsed: ParsedSize | null,
+ basis: number | null,
+ fallback: number,
+ label: string,
+ accepted: string,
+ didWarnRef: {current: boolean},
+): number {
+ if (raw === undefined) {
+ return fallback;
}
- if (typeof defaultSize === 'number') {
- return defaultSize;
+ // Preserve the released explicit unbounded maximum on both the unified and
+ // deprecated spellings. Other roles still reject non-finite numbers.
+ if (raw === Infinity && fallback === Infinity) {
+ return Infinity;
}
- if (defaultSize.endsWith('%')) {
- const pct = parseFloat(defaultSize);
- if (!isNaN(pct)) {
- const approx = typeof window !== 'undefined' ? window.innerWidth : 1200;
- return Math.round((pct / 100) * approx);
+ if (parsed == null) {
+ if (!didWarnRef.current) {
+ didWarnRef.current = true;
+ devWarn(
+ 'useResizable',
+ `${label}: ${describeSize(raw)} is not a size. ${accepted} ` +
+ `Falling back to ${fallback}.`,
+ );
}
+ return fallback;
}
- return 250;
+ return toPixels(parsed, basis) ?? fallback;
+}
+
+/**
+ * The container's content-box size on the active axis.
+ *
+ * Content box, not border box: a bordered or padded container would otherwise
+ * report a basis a few pixels larger than the space a percentage is actually a
+ * share of, and that error lands in `aria-valuemax`. The observer entry
+ * carries `contentBoxSize` natively, which is already writing-mode aware;
+ * measuring the element is the fallback for the synthetic entry
+ * `observeResize` fires on registration.
+ */
+function measureContentBox(
+ element: HTMLElement,
+ direction: ResizableDirection,
+ entry?: ResizeObserverEntry,
+): number | null {
+ const box = entry?.contentBoxSize?.[0];
+ if (box) {
+ return direction === 'vertical' ? box.blockSize : box.inlineSize;
+ }
+ const style =
+ typeof window === 'undefined' ? null : window.getComputedStyle(element);
+ if (style == null) {
+ return null;
+ }
+ const size =
+ direction === 'vertical'
+ ? element.clientHeight -
+ parseFloat(style.paddingTop) -
+ parseFloat(style.paddingBottom)
+ : element.clientWidth -
+ parseFloat(style.paddingLeft) -
+ parseFloat(style.paddingRight);
+ return Number.isFinite(size) ? size : null;
}
// =============================================================================
@@ -249,8 +574,12 @@ function resolveDefaultSize(defaultSize: number | string | undefined): number {
function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
const {
defaultSize,
- minSizePx = DEFAULT_MIN,
- maxSizePx = Infinity,
+ minSize,
+ maxSize,
+ minSizePx,
+ maxSizePx,
+ containerRef,
+ direction = 'horizontal',
collapsible = false,
collapsedSize = DEFAULT_COLLAPSED_SIZE,
snaps: configuredSnaps,
@@ -263,15 +592,316 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
const emptySnapsRef = useRef<number[]>([]);
const snaps = configuredSnaps ?? emptySnapsRef.current;
- const resolvedDefault = resolveDefaultSize(defaultSize);
+ // The unified prop wins over its deprecated alias. The types make supplying
+ // both an error, so reaching here means untyped JavaScript, an `any`, or a
+ // spread — exactly the case where a stale alias hidden in an object would
+ // otherwise silently beat the explicit migration target.
+ const hasUnifiedMin = minSize !== undefined;
+ const hasUnifiedMax = maxSize !== undefined;
+ const minConflict = hasUnifiedMin && minSizePx !== undefined;
+ const maxConflict = hasUnifiedMax && maxSizePx !== undefined;
+ const rawMin = hasUnifiedMin ? minSize : minSizePx;
+ const rawMax = hasUnifiedMax ? maxSize : maxSizePx;
+
+ const parsedDefault = parseSize(defaultSize);
+ const parsedMin = hasUnifiedMin
+ ? parseSize(minSize)
+ : parseLegacyPixel(minSizePx, false);
+ const parsedMax = hasUnifiedMax
+ ? parseSize(maxSize)
+ : parseLegacyPixel(maxSizePx, true);
+ const hasContainer = containerRef != null;
const persisted = autoSaveId ? loadPersistedState(autoSaveId) : null;
- const initial = persisted?.size ?? resolvedDefault;
+ const initialDefaultRef = useRef<{px: number; isFinal: boolean} | null>(null);
+ const [, setDefaultBasisCleanupTick] = useState(0);
- // `size` is always the *expanded* size: collapse hides it behind the
- // isCollapsed gate below rather than zeroing it, so the width the user had
- // survives a collapse, a persist round-trip, and an expand.
- const [size, setSize] = useState(() =>
- clampSize(initial, minSizePx, maxSizePx, snaps),
+ 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,
+ () => (typeof window === 'undefined' ? SERVER_BASIS : window.innerWidth),
+ () => SERVER_BASIS,
+ );
+
+ // 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 releases the frozen basis when a gesture ends.
+ const [gestureTick, setGestureTick] = useState(0);
+ void gestureTick;
+ const basis = gestureBasisRef.current ?? liveBasis;
+
+ const didWarnMinRef = useRef(false);
+ const didWarnMaxRef = useRef(false);
+ const didWarnDefaultRef = useRef(false);
+ const didWarnInvertedRef = useRef(false);
+ const didWarnMinAliasRef = useRef(false);
+ const didWarnMaxAliasRef = 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,
+ hasUnifiedMin ? 'minSize' : 'minSizePx',
+ hasUnifiedMin ? RESIZABLE_SIZE_GUIDANCE : LEGACY_PIXEL_GUIDANCE,
+ didWarnMinRef,
+ );
+ const resolvedMax = resolveBound(
+ rawMax,
+ parsedMax,
+ basis,
+ Infinity,
+ hasUnifiedMax ? 'maxSize' : 'maxSizePx',
+ hasUnifiedMax ? RESIZABLE_SIZE_GUIDANCE : LEGACY_MAX_PIXEL_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,
@@ -303,11 +933,47 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
[isControlled],
);
+ // Configuration warnings live in an effect, not in render: render runs twice
+ // under StrictMode and must stay free of side effects.
+ useEffect(() => {
+ if (minConflict && !didWarnMinAliasRef.current) {
+ didWarnMinAliasRef.current = true;
+ devWarn(
+ 'useResizable',
+ 'both `minSize` and `minSizePx` were supplied. `minSize` wins; the ' +
+ 'deprecated `minSizePx` is ignored.',
+ );
+ }
+ if (maxConflict && !didWarnMaxAliasRef.current) {
+ didWarnMaxAliasRef.current = true;
+ devWarn(
+ 'useResizable',
+ 'both `maxSize` and `maxSizePx` were supplied. `maxSize` wins; the ' +
+ 'deprecated `maxSizePx` is ignored.',
+ );
+ }
+ }, [minConflict, maxConflict]);
+
+ 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]);
+
useEffect(() => {
- if (autoSaveId) {
+ // Nothing is written while the basis is still the temporary stand-in. The
+ // size on such a render is a placeholder, and persisting it overwrites the
+ // real saved size with a value derived from a basis that was never real
+ // (AST-010 Platform support, FR9).
+ if (autoSaveId && isBasisMeasured) {
persistState(autoSaveId, {size, isCollapsed});
}
- }, [size, isCollapsed, autoSaveId]);
+ }, [size, isCollapsed, autoSaveId, isBasisMeasured]);
const collapse = useCallback(() => {
// The already-collapsed guard keeps a repeated call from re-notifying a
@@ -331,9 +997,21 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
const resize = useCallback(
(newSize: number) => {
- const clamped = clampSize(newSize, minSizePx, maxSizePx, snaps);
+ // 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;
- setSize(clamped);
+ 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.
@@ -342,12 +1020,22 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
}
onSizeChange?.(clamped);
},
- [minSizePx, maxSizePx, snaps, setCollapsed, onCollapseChange, onSizeChange],
+ [
+ resolvedMin,
+ resolvedMax,
+ snaps,
+ setCollapsed,
+ onCollapseChange,
+ onSizeChange,
+ ],
);
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]);
+ }, [size, liveBasis]);
const onResizeMove = useCallback(
(delta: number) => {
@@ -364,37 +1052,56 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
setCollapsed(false);
onCollapseChange?.(false);
}
- const clamped = clampSize(raw, minSizePx, maxSizePx, snaps);
- setSize(clamped);
+ const clamped = clampSize(raw, resolvedMin, resolvedMax, snaps);
+ setChosenSize(clamped);
onSizeChange?.(clamped);
},
[
collapsible,
collapsedSize,
setCollapsed,
- minSizePx,
- maxSizePx,
+ resolvedMin,
+ resolvedMax,
snaps,
onSizeChange,
onCollapseChange,
],
);
- const onResizeEnd = useCallback(() => {
- // Sizes already committed during move
+ // Releasing the frozen basis needs a render to apply whatever the basis
+ // became during the gesture.
+ const releaseGestureBasis = useCallback(() => {
+ if (gestureBasisRef.current != null) {
+ gestureBasisRef.current = null;
+ setGestureTick(tick => tick + 1);
+ }
}, []);
+ const onResizeEnd = useCallback(() => {
+ // Sizes are already committed during move; only the basis is held.
+ 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.
+ const onResizeCancel = releaseGestureBasis;
+
const props: ResizableProps = {
_size: isCollapsed ? 0 : size,
_isCollapsed: isCollapsed,
_onResizeStart: onResizeStart,
_onResizeMove: onResizeMove,
_onResizeEnd: onResizeEnd,
- _minSizePx: minSizePx,
- _maxSizePx: maxSizePx,
+ _onResizeCancel: onResizeCancel,
+ _minSizePx: resolvedMin,
+ _maxSizePx: resolvedMax,
_snaps: snaps,
_collapsedSize: collapsedSize,
_collapsible: collapsible,
+ _direction: direction,
_isResizableProps: true,
};
@@ -421,7 +1128,7 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
function useMultiResizable(
config: UseResizableMultiConfig,
): Record<string, ResizableRegion> {
- const {regions, autoSaveId} = config;
+ const {regions, autoSaveId, containerRef, direction} = config;
// Stable key order — callers must not change region keys between renders.
// Using Object.keys is safe here because the regions object shape is static.
@@ -433,6 +1140,11 @@ function useMultiResizable(
// eslint-disable-next-line @eslint-react/rules-of-hooks -- region count is stable (documented contract)
useSingleResizable({
...regionConfig,
+ // One container and one axis for every region (AST-010 FR11). Regions
+ // stay independently pixel-selected; sharing a basis introduces no ratio
+ // between them and no 100% total.
+ containerRef,
+ direction,
autoSaveId: autoSaveId ? `${autoSaveId}:${key}` : undefined,
}),
);
diff --git a/packages/core/src/Resizable/utils.test.ts b/packages/core/src/Resizable/utils.test.ts
new file mode 100644
index 0000000000..53b3415d0e
--- /dev/null
+++ b/packages/core/src/Resizable/utils.test.ts
@@ -0,0 +1,74 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {readFileSync} from 'node:fs';
+import {join} from 'node:path';
+import {describe, expect, it} from 'vitest';
+import {pixel as tablePixel} from '../Table/utils';
+import {percent as barrelPercent} from './index';
+import {percent, pixel} from './utils';
+import type {ResizablePercentSize, ResizableSize} from './utils';
+
+describe('Resizable structured sizing helpers', () => {
+ it('creates a percentage with a pixel floor', () => {
+ expect(percent(40, {min: pixel(333)})).toEqual({
+ type: 'percent',
+ value: 40,
+ min: {type: 'pixel', value: 333},
+ });
+ });
+
+ it('creates a percentage with a pixel ceiling', () => {
+ expect(percent(10, {max: pixel(400)})).toEqual({
+ type: 'percent',
+ value: 10,
+ max: {type: 'pixel', value: 400},
+ });
+ });
+
+ it('keeps compatible atomic values and structured helpers in the union', () => {
+ const values = [
+ 333,
+ '333px',
+ '40%',
+ pixel(333),
+ percent(40, {min: pixel(333)}),
+ percent(10, {max: pixel(400)}),
+ ] satisfies ResizableSize[];
+ expect(values).toHaveLength(6);
+ });
+
+ it('re-exports Table pixel and percent without a root collision', async () => {
+ const [module, root] = await Promise.all([
+ import('@astryxdesign/core/Resizable/utils'),
+ import('@astryxdesign/core'),
+ ]);
+ const source = readFileSync(
+ join(process.cwd(), 'packages/core/src/Resizable/utils.ts'),
+ 'utf8',
+ );
+
+ expect(pixel).toBe(tablePixel);
+ expect(module.pixel).toBe(tablePixel);
+ expect(module.percent).toBe(percent);
+ expect(root.pixel).toBe(tablePixel);
+ expect(root.percent).toBe(percent);
+ expect(barrelPercent).toBe(percent);
+ expect(source).not.toContain("'use client'");
+ expect(source).toContain("export {pixel} from '../Table/utils'");
+ });
+
+ it('requires exactly one pixel helper bound at compile time', () => {
+ // @ts-expect-error an unbounded percentage already uses the canonical 'N%' spelling
+ const missing: ResizablePercentSize = {type: 'percent', value: 40};
+ // @ts-expect-error a descriptor carries a floor XOR a ceiling, never both
+ const both: ResizablePercentSize = {
+ type: 'percent',
+ value: 40,
+ min: pixel(100),
+ max: pixel(500),
+ };
+ // @ts-expect-error the options argument is required
+ const duplicate = percent(40);
+ expect([missing, both, duplicate]).toHaveLength(3);
+ });
+});
diff --git a/packages/core/src/Resizable/utils.ts b/packages/core/src/Resizable/utils.ts
new file mode 100644
index 0000000000..44ffd81df6
--- /dev/null
+++ b/packages/core/src/Resizable/utils.ts
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file utils.ts
+ * @output Server-safe Resizable sizing helpers and public types
+ * @position Subpath entry point: `@astryxdesign/core/Resizable/utils`
+ */
+
+import type {PixelWidth} from '../Table/utils';
+
+export {pixel} from '../Table/utils';
+export type {PixelWidth} from '../Table/utils';
+
+/** A percentage with exactly one pixel floor or ceiling. */
+export type ResizablePercentSize = {
+ type: 'percent';
+ value: number;
+} & ({min: PixelWidth; max?: never} | {min?: never; max: PixelWidth});
+
+/** A Resizable size: compatible atomic values or a structured size. */
+export type ResizableSize =
+ number | `${number}px` | `${number}%` | PixelWidth | ResizablePercentSize;
+
+/**
+ * Create a literal percentage with one pixel floor or ceiling.
+ *
+ * The options argument is required because an unbounded percentage already has
+ * the canonical `'N%'` spelling. Use Table's `pixel()` helper for the bound.
+ */
+export function percent(
+ value: number,
+ options: {min: PixelWidth; max?: never} | {min?: never; max: PixelWidth},
+): ResizablePercentSize {
+ return {type: 'percent', value, ...options};
+}
diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js
index 64ef048a49..e5d6c3ba40 100644
--- a/scripts/sync-exports.js
+++ b/scripts/sync-exports.js
@@ -111,6 +111,7 @@ const UTIL_SUBPATH_DIRS = [
'Calendar',
'Markdown',
'PowerSearch',
+ 'Resizable',
'Selector',
'Table',
'Typeahead',