Skip to content

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

TypeScript

feat(Resizable): a resizable LayoutPanel slides closed and open under every pointer (#9989)

Christopher Chedeau46d18133760e
diff --git a/.changeset/layout-panel-slides-on-collapse.md b/.changeset/layout-panel-slides-on-collapse.md
new file mode 100644
index 0000000000..33cb88601f
--- /dev/null
+++ b/.changeset/layout-panel-slides-on-collapse.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] A `LayoutPanel` that takes a `useResizable` region in its `resizable` prop slides closed and open from the edge facing its `ResizeHandle` when the region collapses or opens, under every pointer, with the content beside it moving on the same motion: through `collapse()`, `expand()`, Enter, a double-click, the grow arrow, a controlled `isCollapsed`, or a drag past the collapse threshold. A drag that reopens the panel follows the pointer, and Reduce Motion is honored. A hand-built `ResizableProps` object does not slide. No prop or option is added.
+
+@vjeux
diff --git a/apps/storybook/stories/Resizable.stories.tsx b/apps/storybook/stories/Resizable.stories.tsx
index 55d39bce23..a907a2b5a5 100644
--- a/apps/storybook/stories/Resizable.stories.tsx
+++ b/apps/storybook/stories/Resizable.stories.tsx
@@ -840,3 +840,207 @@ export const CollapsingScrollPanelFixture: Story = {
tags: ['!autodocs', 'no-visual'],
render: () => <CollapsingScrollPanel />,
};
+
+/**
+ * A LayoutPanel that takes a `useResizable` region slides closed and open
+ * from the edge facing its ResizeHandle. The content beside it moves on
+ * the same motion. "Close panel" collapses it from inside, so focus moves to
+ * the handle and the collapsed panel is inert. Enter on the handle, a
+ * double-click or "Open panel" opens it again.
+ */
+function SlidingPanelSplit({
+ side,
+ lineCount = 0,
+}: {
+ side: 'start' | 'end';
+ lineCount?: number;
+}) {
+ const resizable = useResizable({
+ defaultSize: 200,
+ minSize: 120,
+ maxSize: 320,
+ collapsible: true,
+ });
+ const pane = (
+ <LayoutPanel resizable={resizable} data-testid="sliding-panel">
+ <Stack gap={2}>
+ <Heading level={4}>Panel</Heading>
+ <Button label="Close panel" onClick={resizable.collapse} />
+ {Array.from({length: lineCount}, (_, index) => (
+ <Text key={index}>Line {index + 1}</Text>
+ ))}
+ </Stack>
+ </LayoutPanel>
+ );
+ const handle = (
+ <ResizeHandle
+ resizable={resizable}
+ isReversed={side === 'end'}
+ hasDivider
+ label="Resize panel"
+ />
+ );
+ return (
+ <div {...stylex.props(ps.shell)}>
+ <Layout
+ height="fill"
+ start={
+ side === 'start' ? (
+ <>
+ {pane}
+ {handle}
+ </>
+ ) : undefined
+ }
+ content={
+ <LayoutContent data-testid="sliding-content">
+ <Stack gap={2}>
+ <Text>The content glides with the panel's edge.</Text>
+ <Button label="Open panel" onClick={resizable.expand} />
+ <Button
+ label="Toggle panel"
+ onClick={
+ resizable.isCollapsed ? resizable.expand : resizable.collapse
+ }
+ />
+ </Stack>
+ </LayoutContent>
+ }
+ end={
+ side === 'end' ? (
+ <>
+ {handle}
+ {pane}
+ </>
+ ) : undefined
+ }
+ />
+ </div>
+ );
+}
+
+export const SlidingStartPanel: Story = {
+ render: () => <SlidingPanelSplit side="start" />,
+};
+
+export const SlidingEndPanel: Story = {
+ render: () => <SlidingPanelSplit side="end" />,
+};
+
+/** A sliding start panel with more lines than fit, for a scrolled slide. */
+export const SlidingScrolledPanelFixture: Story = {
+ tags: ['!autodocs', 'no-visual'],
+ render: () => <SlidingPanelSplit side="start" lineCount={40} />,
+};
+
+/**
+ * A start LayoutPanel whose collapse state its parent owns: `isCollapsed`
+ * with `onCollapseChange`, and a toggle that flips the parent's state. The
+ * panel slides on each controlled change too.
+ */
+function ControlledSlidingPanel() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+ const resizable = useResizable({
+ defaultSize: 200,
+ minSize: 120,
+ maxSize: 320,
+ collapsible: true,
+ isCollapsed,
+ onCollapseChange: setIsCollapsed,
+ });
+ return (
+ <div {...stylex.props(ps.shell)}>
+ <Layout
+ height="fill"
+ start={
+ <>
+ <LayoutPanel resizable={resizable} data-testid="sliding-panel">
+ <Stack gap={2}>
+ <Heading level={4}>Panel</Heading>
+ <Button label="Close panel" onClick={resizable.collapse} />
+ </Stack>
+ </LayoutPanel>
+ <ResizeHandle
+ resizable={resizable}
+ hasDivider
+ label="Resize panel"
+ />
+ </>
+ }
+ content={
+ <LayoutContent data-testid="sliding-content">
+ <Stack gap={2}>
+ <Text>The parent owns whether the panel is collapsed.</Text>
+ <Button
+ label="Toggle panel"
+ onClick={() => {
+ setIsCollapsed(!isCollapsed);
+ }}
+ />
+ </Stack>
+ </LayoutContent>
+ }
+ />
+ </div>
+ );
+}
+
+export const SlidingControlledPanel: Story = {
+ render: () => <ControlledSlidingPanel />,
+};
+
+/**
+ * Browser fixtures for two start panels. One takes the hook's own `props`
+ * and slides. The other takes a hand-built `ResizableProps` object, with the same
+ * fields in an object the hook did not return, and collapses without a slide.
+ * Both move focus inside them to the handle and go inert while collapsed.
+ */
+function PropsPanelSplit({isHandBuilt}: {isHandBuilt: boolean}) {
+ const resizable = useResizable({
+ defaultSize: 200,
+ minSize: 120,
+ maxSize: 320,
+ collapsible: true,
+ });
+ const panelValue = isHandBuilt ? {...resizable.props} : resizable.props;
+ return (
+ <div {...stylex.props(ps.shell)}>
+ <Layout
+ height="fill"
+ start={
+ <>
+ <LayoutPanel resizable={panelValue} data-testid="sliding-panel">
+ <Stack gap={2}>
+ <Heading level={4}>Panel</Heading>
+ <Button label="Close panel" onClick={resizable.collapse} />
+ </Stack>
+ </LayoutPanel>
+ <ResizeHandle
+ resizable={resizable}
+ hasDivider
+ label="Resize panel"
+ />
+ </>
+ }
+ content={
+ <LayoutContent data-testid="sliding-content">
+ <Stack gap={2}>
+ <Text>The content glides with the panel's edge.</Text>
+ <Button label="Open panel" onClick={resizable.expand} />
+ </Stack>
+ </LayoutContent>
+ }
+ />
+ </div>
+ );
+}
+
+export const SlidingPanelWithHookProps: Story = {
+ tags: ['!autodocs', 'no-visual'],
+ render: () => <PropsPanelSplit isHandBuilt={false} />,
+};
+
+export const PanelWithHandBuiltProps: Story = {
+ tags: ['!autodocs', 'no-visual'],
+ render: () => <PropsPanelSplit isHandBuilt />,
+};
diff --git a/docs/specs/components/Layout/LayoutPanel.spec.md b/docs/specs/components/Layout/LayoutPanel.spec.md
index 6116b2af4a..d07f16df98 100644
--- a/docs/specs/components/Layout/LayoutPanel.spec.md
+++ b/docs/specs/components/Layout/LayoutPanel.spec.md
@@ -86,8 +86,6 @@ Consumer migration instructions belong in consumer docs and release notes.
`hasDivider` beside a ResizeHandle that draws the same line paints the
boundary twice; nothing prevents it, so callers keep `hasDivider={false}`
when the ResizeHandle owns the line (`family:layout-regions` FR5).
-- **A collapsing panel jumps (FR7).** A resizable panel closes and opens at
- once, where `spec:AST-105` FR9 slides it.
## Ownership boundary
@@ -125,7 +123,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR4 | `hasDivider` draws a 1px solid `--color-border` line on the content-facing edge; LayoutPanel does not read a Layout divider default. Without a divider and with the automatic inset, the panel overlaps the content area by the inner inset so the two share one gap. One boundary has one divider owner (`family:layout-regions` FR5). Implementation gap: nothing prevents a panel divider and an adjacent ResizeHandle line from both painting (Current-state impact). | Current source and docs; `family:layout-regions` FR5, FR6 |
| FR5 | `role` and `label` set the root's `role` and `aria-label`; LayoutPanel adds a role and a name of its own only while it scrolls (AR3). | Current source and tests; `family:layout-regions` FR8 |
| FR6 | `ref` reaches the root. Supported DOM, data, ARIA, and event props reach the root after the component's own attributes; `xstyle`, `className`, and `style` compose after component styles. | Current source and tests; `architecture:public-component-api` INV5–INV8 |
-| FR7 | A LayoutPanel whose size comes from a resize controller lends its element to the controller of the ResizeHandle on its content-facing edge through an internal channel, so the panel slides closed and open by `spec:AST-105` FR9's edge reveal when its region collapses or opens: its content-facing edge (FR2) moves, and the content on that edge's side moves on the same motion (`component:Resizable` FR8). A panel given the configuration-object form, a hand-built `ResizableProps` object that `useResizable` did not return passed through `resizable`, and a panel with no resize controller, never slide; `useResizable`'s own `props` passed through `resizable` do slide. LayoutPanel adds no prop. Implementation gap: no panel slides yet (Current-state impact). | `spec:AST-105` FR9; `component:Resizable` FR8 |
+| FR7 | A LayoutPanel whose size comes from a resize controller lends its element to the controller of the ResizeHandle on its content-facing edge through an internal channel, so the panel slides closed and open by `spec:AST-105` FR9's edge reveal when its region collapses or opens: its content-facing edge (FR2) moves, and the content on that edge's side moves on the same motion (`component:Resizable` FR8). A panel given the configuration-object form, a hand-built `ResizableProps` object that `useResizable` did not return passed through `resizable`, and a panel with no resize controller, never slide; `useResizable`'s own `props` passed through `resizable` do slide. LayoutPanel adds no prop. A panel at the region's size beside that handle does not slide. | `spec:AST-105` FR9; `component:Resizable` FR8 |
| FR8 | `resizable` takes useResizable's output directly; the region's `props` is still accepted (owner decision, 2026-11-04). The panel takes the hook's value through that slot prop (owner decision, 2026-11-04). | `component:Resizable` FR9; `architecture:public-component-api` INV21 |
### Allowed variation
@@ -211,7 +209,7 @@ of its own, so no anatomy-theming block is declared here.
| FR4 | Source review | `hasDivider`; no divider | Gap: no test covers the divider line, the shared gap, or a panel divider beside a ResizeHandle. | `audit:LayoutPanel/layout` |
| FR5, AR1 | `LayoutSlots.test.tsx` landmark test; `Layout.a11y.test.tsx` and `Layout.a11y.chromium.spec.ts` `start-end-navigation-rtl` and `nested-panel-region` states | Caller `navigation` and `region` roles and labels | A lost role or name fails, including at the accessibility tree. Gap: no test asserts that a panel without `role` exposes none. | `audit:LayoutPanel/accessibility` |
| FR6 | `LayoutSlots.test.tsx` ref and className tests | Ref; caller class | A ref on another element or a dropped class fails. Gap: no test covers `style`, DOM, data, or event props, or the `xstyle` merge order. | `audit:LayoutPanel/api` |
-| FR7, AR2 | Real-browser frame capture of a start and an end panel collapsing and opening, with focus inside, with the hook's `props` and with a hand-built object (pending) | Start and end; toggle, Enter and a drag past the threshold; configuration-object form; Reduce Motion | A jump instead of a slide, a gap beside the moving edge, a slide under the configuration-object form, focus left in a collapsed panel, a collapsed panel reachable by Tab or exposed to assistive technology, or a new prop fails. | `audit:LayoutPanel/behavior` |
+| FR7, AR2 | `paneSlide.interaction.browser.spec.ts`: a start and an end panel collapsing and opening, with focus inside, with the hook's own value and with a hand-built one | Start and end; toggle, Enter and a drag past the threshold; configuration-object form; Reduce Motion | A jump instead of a slide, a gap beside the moving edge, a slide under the configuration-object form, focus left in a collapsed panel, a collapsed panel reachable by Tab or exposed to assistive technology, or a new prop fails. | `audit:LayoutPanel/behavior` |
| AR3 | `useScrollRegionProps.test.tsx` LayoutPanel tests; `scrollRegionName.a11y.chromium.spec.ts` `panel-scrolls`; `collapsedPanel.interaction.browser.spec.ts` | Scrolling panel; caller `navigation` role and label; a scrolling panel collapsed to width 0 | A group role or name missing while the panel overflows fails, at Chromium's accessibility tree too; a caller's role or label lost fails. A group role kept at width 0 fails. | `audit:LayoutPanel/accessibility` |
| PR1 | Source review | Every state | Gap: no automated check fails if LayoutPanel adds a listener, timer, or measurement. | `audit:LayoutPanel/behavior` |
| RTL relation | RTL audit curated D2 target (`apps/storybook/rtl-audit/targets.json`) on the `Content width with start panel` story | Start panel beside the content; LTR and RTL | A start panel that is not at the inline start of the content in both directions fails D2. | `audit:LayoutPanel/i18n-rtl` |
diff --git a/docs/specs/components/Resizable/Resizable.spec.md b/docs/specs/components/Resizable/Resizable.spec.md
index 083b69a181..45b81c6feb 100644
--- a/docs/specs/components/Resizable/Resizable.spec.md
+++ b/docs/specs/components/Resizable/Resizable.spec.md
@@ -99,8 +99,6 @@ Consumer migration instructions belong in consumer docs and release notes.
`onDoubleClick`, so passing any of them stops the Handle's focus-visible
pill and its double-click collapse, where
`architecture:public-component-api` INV7 has handlers compose.
-- **Collapse and open do not slide yet (FR8).** A LayoutPanel's pane jumps
- closed and open, where `spec:AST-105` FR9 slides it.
- **No `collapsedLabel` yet (AR1).** `createResizable` and the options form
of `useResizable` are not built, so a caller without a provider cannot
replace the English "Collapsed" announcement, where
@@ -150,7 +148,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR5 | A `percent(value, {min: pixel(value)})` or `percent(value, {max: pixel(value)})` resolves against one basis — the supplied container, or the viewport when no `containerRef` is given (`spec:AST-010` FR1, FR2); as a default it selects pixels once, and as a bound it stays live and clamps the selected pixels. A descriptor with both or neither bound is invalid. Selected state, persistence, callbacks, paint, and ARIA are pixels. | `spec:AST-010`; current source and tests |
| FR6 | `minSize` and `maxSize` are the bound props; numeric values are pixels. When resolved bounds conflict, the maximum wins. | `spec:AST-010`; current source and tests |
| FR7 | `ref`, DOM, data, ARIA, and event props reach the Handle, and a caller's explicit `role`, ARIA attribute, or `tabIndex` reaches it as given; a caller `onKeyDown` runs before the Handle's own key handling; caller `onFocus`, `onBlur`, and `onDoubleClick` compose with the Handle's own focus tracking and double-click collapse (`architecture:public-component-api` INV5, INV7); `xstyle` and `className` compose after component styles, and `style` is not accepted. Implementation gap: caller `onFocus`, `onBlur`, and `onDoubleClick` replace the Handle's own handlers (Current-state impact). | Current source; `architecture:public-component-api` INV5–INV8 |
-| FR8 | When a region collapses or opens, its pane slides by `spec:AST-105` FR9's edge reveal when a LayoutPanel renders it (`component:LayoutPanel` FR7): the resize controller measures the pane's box before and after the collapse state commits, before its subscribers hear of it, and the pane's edge facing its ResizeHandle, read from the region's direction and reversal, moves with the content on that edge's side on one motion. Every collapse and open plays it: `collapse()`, `expand()`, a resize out of collapse, Enter, a double-click, the grow arrow, a controlled `isCollapsed` change, and a drag that crosses `collapsedSize` to collapse. A drag that reopens a collapsed pane plays nothing, because the pointer drives the edge; a resize that neither collapses nor opens, and the first render, play nothing. A pane the caller renders at the hook's size alone, and a LayoutPanel given the configuration-object form, a hand-built `ResizableProps` object that `useResizable` did not return passed through its `resizable`, show no slide; the hook's own `props` passed through `resizable` do slide. No prop, option or return member is added; size, `isCollapsed`, callbacks, persistence and the Handle's ARIA values are unchanged. Focus inside a collapsing pane follows `component:LayoutPanel` AR2. Implementation gap: no collapse or open slides yet (Current-state impact). | `spec:AST-105` FR9; `component:LayoutPanel` FR7, AR2 |
+| FR8 | When a region collapses or opens, its pane slides by `spec:AST-105` FR9's edge reveal when a LayoutPanel renders it (`component:LayoutPanel` FR7): the resize controller measures the pane's box before and after the collapse state commits, before its subscribers hear of it, and the pane's edge facing its ResizeHandle, read from the region's direction and reversal, moves with the content on that edge's side on one motion. Every collapse and open plays it: `collapse()`, `expand()`, a resize out of collapse, Enter, a double-click, the grow arrow, a controlled `isCollapsed` change, and a drag that crosses `collapsedSize` to collapse. A drag that reopens a collapsed pane plays nothing, because the pointer drives the edge; a resize that neither collapses nor opens, and the first render, play nothing. A pane the caller renders at the hook's size alone, and a LayoutPanel given the configuration-object form, a hand-built `ResizableProps` object that `useResizable` did not return passed through its `resizable`, show no slide; the hook's own `props` passed through `resizable` do slide. No prop, option or return member is added; size, `isCollapsed`, callbacks, persistence and the Handle's ARIA values are unchanged. Focus inside a collapsing pane follows `component:LayoutPanel` AR2. A ResizeHandle given the props holds a panel at the hook's size collapsed. | `spec:AST-105` FR9; `component:LayoutPanel` FR7, AR2 |
| FR9 | `resizable` takes useResizable's output directly; the region's `props` is still accepted (owner decision, 2026-11-04). Components take the hook's value through the `resizable` slot prop (owner decision, 2026-11-04): LayoutPanel (`component:LayoutPanel` FR8), ResizeHandle, and SideNav (`component:SideNav` FR7). Any other element can use the hook's `size`. | `architecture:public-component-api` INV21, INV22 |
### Allowed variation
@@ -276,7 +274,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| FR5, ORD1–ORD3 | `useResizable.test.ts`, `utils.test.ts`, typecheck | Floor, ceiling, default; invalid shapes; basis changes; numeric container parity | Wrong resolution, a rescaled default, a stale clamp, an observer leak, or state, paint, storage, and ARIA that disagree fails. | `audit:Resizable/behavior` |
| FR6 | `useResizable.test.ts`; typecheck | Numeric bounds; conflicting bounds | A removed alias that type-checks, a numeric bound that is not pixels, or a minimum that wins a conflict fails. | `audit:Resizable/behavior` |
| FR7 | `ResizeHandle.test.tsx` consumer `onKeyDown` test; source review | Caller props and `onKeyDown` | A consumer `onKeyDown` that stops keyboard resizing, or keyboard resizing that skips the consumer handler, fails. Gap: no test covers other caller props, the styling merge, caller `onFocus`, `onBlur`, or `onDoubleClick`, or a caller `role` or ARIA attribute. | `audit:Resizable/api` |
-| FR8 | Real-browser frame capture of a start and an end LayoutPanel collapsing and opening by each listed path, a drag reopening a pane, a hook-only pane, and a hand-built `ResizableProps` pane (pending) | Start and end panes; `collapse()`, `expand()`, Enter, double-click, the grow arrow, a controlled `isCollapsed` change, a drag across `collapsedSize`; a reopening drag; the hook's `props` and a hand-built object through `resizable`; Reduce Motion | A jump instead of a slide, a slide from the wrong edge, a slide during a reopening drag or on first render, a slide for a hook-only pane or a hand-built object, no slide for the hook's `props`, or a new prop, option or return member fails. | `audit:Resizable/behavior` |
+| FR8 | `paneSlide.interaction.browser.spec.ts`: a start and an end LayoutPanel collapsed from inside and opened with Enter, a toggle, a controlled `isCollapsed`, a double-click, the grow arrow, a drag past the threshold, a reopening drag, a hand-built `ResizableProps` pane, and Reduce Motion; `paneReveal.test.tsx` for `expand()`, `resize()` out of collapse, and a hook-only pane | Start and end panes; `collapse()`, `expand()`, Enter, double-click, the grow arrow, a controlled `isCollapsed` change, a drag across `collapsedSize`; a reopening drag; the hook's `props` and a hand-built object through `resizable`; Reduce Motion | A jump instead of a slide, a slide from the wrong edge, a slide during a reopening drag or on first render, a slide for a hook-only pane or a hand-built object, no slide for the hook's `props`, or a new prop, option or return member fails. | `audit:Resizable/behavior` |
| AR1 | `ResizeHandle.test.tsx` ("makes the separator focusable", "exposes the region size and bounds via ARIA", "grows the panel by a step on ArrowRight", "shrinks the panel by a step on ArrowLeft", "uses the large step when Shift is held", "jumps to the minimum on Home", "jumps to the maximum on End", "collapses on Enter when the region is collapsible", "inverts the pointer delta under RTL so dragging resizes intuitively", "restores the previous size, not the minimum, when Enter reopens a collapsed pane", "reopens on Enter even when the minimum size sits below the collapse threshold", "reports the window basis as aria-valuemax when no maximum is configured; End leaves an unbounded region alone", "reports the container basis as aria-valuemax while a percentage bound already observes it", "never reports aria-valuemax below aria-valuemin while collapsed in a small window", "reports no aria-valuemax for an unbounded pixel-only region in a container, which stays unobserved", "a grow arrow opens a collapsed pane one step above its minimum; the shrink arrow leaves it collapsed", "a grow arrow opens a collapsed pane at its collapsedSize when the minimum sits below it", "a grow arrow opens a collapsed pane in the reversed layout and under RTL too", "in a reversed layout, ArrowLeft opens a collapsed pane and ArrowRight leaves it collapsed", "under RTL, ArrowLeft opens a collapsed pane and ArrowRight leaves it collapsed", "a grow arrow opens a hand-built collapsed region one step above its minimum", "with snap points, an arrow moves to the adjacent point in its direction and Shift moves two, clamped to the ends", "with snap points past the bounds, a point beyond maxSize or minSize counts as that bound", "with snap points, the arrows follow the reversed layout and the reading direction", "with snap points in a reversed layout, ArrowLeft moves to the next point and ArrowRight to the previous", "with snap points, the grow arrow opens a collapsed pane at the snap point nearest one step above its minimum") and `shippedDirections.test.ts`; `SideNav.test.tsx` ("names the nav it resizes with aria-controls (APG window splitter)"); RTL keyboard mirroring, and the disabled state under the Window Splitter accessibility contract (`internal/a11y-spec`, pending); `ResizeHandle.a11y.test.tsx` and `ResizeHandle.a11y.chromium.spec.ts` | Inline and block axes; LTR and RTL; collapsed; disabled | The Handle loses its role, name, orientation, or value properties; an arrow, Home, End, or Enter stops moving the divider or moves it against the reading direction. | `audit:Resizable/accessibility` |
| PR1 | `useResizable.test.ts` observer tests | Pixel, percentage default, percentage bound | An observer on a pixel-only path, or one that outlives a final default, fails. | `audit:Resizable/behavior` |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and two targets | Missing, extra, or stale mappings fail repository validation. | `audit:Resizable/theming` |
diff --git a/packages/core/src/Layout/LayoutPanel.doc.mjs b/packages/core/src/Layout/LayoutPanel.doc.mjs
index 8496c0b0a3..2ef82b18d7 100644
--- a/packages/core/src/Layout/LayoutPanel.doc.mjs
+++ b/packages/core/src/Layout/LayoutPanel.doc.mjs
@@ -71,7 +71,7 @@ export const docs = {
name: 'resizable',
type: 'ResizableRegion | ResizableProps',
description:
- "The output of useResizable(), or its props. 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. Focus inside the panel moves to its ResizeHandle as it collapses, and the panel is inert while collapsed.",
+ "The output of useResizable(), or its props. 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. With the hook's own value, the panel slides closed and open from the edge facing its ResizeHandle; a hand-built object does not slide. Either way, focus inside the panel moves to its ResizeHandle as it collapses, and the panel is inert while collapsed.",
},
],
};
@@ -125,7 +125,7 @@ export const docsZh = {
name: 'resizable',
type: 'ResizableRegion | ResizableProps',
description:
- "useResizable() 的返回值或其 props。提供时面板宽度由 hook 驱动,应在面板旁放置 ResizeHandle。其中携带区域的轴向('horizontal' | 'vertical'),必须与相邻 ResizeHandle 的 direction 一致。折叠时面板内的焦点会移到其 ResizeHandle 上,折叠期间面板为 inert。",
+ "useResizable() 的返回值或其 props。提供时面板宽度由 hook 驱动,应在面板旁放置 ResizeHandle。其中携带区域的轴向('horizontal' | 'vertical'),必须与相邻 ResizeHandle 的 direction 一致。使用 hook 自身返回的值时,面板从朝向其 ResizeHandle 的边缘滑动关闭和打开;手动构造的对象不会滑动。两种情况下,折叠时面板内的焦点都会移到其 ResizeHandle 上,折叠期间面板为 inert。",
},
],
};
@@ -147,6 +147,6 @@ export const docsDense = {
width:
'Panel width. Numbers = pixels, strings as-is. Ignored when resizable provided; hook controls width. width={region.size} beside a ResizeHandle given the region props: inert while collapsed; focus inside moves to the handle on collapse.',
resizable:
- 'useResizable() output or its props. Hook drives panel width; place ResizeHandle adjacent. Focus inside moves to the handle on collapse; inert while collapsed.',
+ 'useResizable() output or its props. Hook drives panel width; place ResizeHandle adjacent. Hook values slide; hand-built ones do not. Focus inside moves to the handle on collapse; inert while collapsed.',
},
};
diff --git a/packages/core/src/Layout/LayoutPanel.tsx b/packages/core/src/Layout/LayoutPanel.tsx
index a2d02c5727..3ff85d91ee 100644
--- a/packages/core/src/Layout/LayoutPanel.tsx
+++ b/packages/core/src/Layout/LayoutPanel.tsx
@@ -7,8 +7,8 @@
* @input Uses React StyleX, LayoutAreaContext, LayoutSlotsContext,
* useScrollRegionProps, resizablePane.ts
* @output Exports LayoutPanel component and LayoutPanelProps
- * @position Sidebar panel for Layout start/end slots. Use for navigation panels,
- * settings sidebars, detail panels, or any fixed-width side content.
+ * @position Sidebar panel for Layout start/end slots; its resize controller slides it.
+ * Use for navigation panels, settings sidebars, detail panels, or any fixed-width side content.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/Layout/Layout.doc.mjs
@@ -34,6 +34,7 @@ import {
} from '../Resizable/useResizable';
import {
createResizablePaneLink,
+ regionOfProps,
resizeHandleBeside,
} from '../Resizable/resizablePane';
import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';
@@ -252,30 +253,57 @@ export function LayoutPanel({
// When resizable props are provided, use the hook-driven size
const effectiveWidth = resizable ? resizable._size : width;
+ // A collapsed region sizes its panel to 0.
+ const isZeroWidth = effectiveWidth === 0;
+ const elementRef = useRef<HTMLDivElement>(null);
- // With no `resizable`, a ResizeHandle beside the panel that has a region's
- // props finds the panel and holds it collapsed with the region. The panel
- // lends its element in its callback ref for that.
+ // A panel sized by a resize controller lends it its element. The
+ // controller slides it on collapse and open. Given the hook's own `props`,
+ // the panel hands itself to that region. With no `resizable`, a
+ // ResizeHandle beside it that has the region's props finds it and holds it
+ // collapsed. A hand-built `resizable` object has no region: it lends
+ // nothing and never slides.
const [paneLink] = useState(createResizablePaneLink);
const isHeldCollapsed = useSyncExternalStore(
paneLink.subscribe,
paneLink.isCollapsed,
returnFalse,
);
- const isLentBeside = resizable == null;
- const lendRef = useCallback(
- (element: HTMLDivElement | null) => {
- paneLink.attach(isLentBeside ? element : null);
- },
- [paneLink, isLentBeside],
- );
+ const isFoundBeside = resizable == null;
+ const paneRegion = resizable == null ? undefined : regionOfProps(resizable);
+ // Syncs the panel's element with its resize controller. It lends here, not
+ // in the callback ref. The scroll region's ref changes at width 0, so React
+ // runs every merged ref again. A lend taken back mid-collapse would land the
+ // slide.
+ useIsomorphicLayoutEffect(() => {
+ const isLent = isFoundBeside || paneRegion != null;
+ const lend = (element: HTMLDivElement | null) => {
+ const pane = paneLink.attach(isLent ? element : null, isFoundBeside);
+ paneRegion?.attach(pane);
+ };
+ lend(elementRef.current);
+ return () => {
+ lend(null);
+ };
+ }, [paneLink, isFoundBeside, paneRegion]);
+ const contentFacingEdge = area === 'end' ? 'inline-start' : 'inline-end';
+ // A collapse or open reaches the controller before the DOM changes, in the
+ // commit that renders it. That holds for the controller's own change and
+ // for a controlled `isCollapsed` it hears of after this commit.
+ const tellBeforeChange = useCallback(() => {
+ paneLink.beforeChange(isZeroWidth);
+ }, [paneLink, isZeroWidth]);
+ // Syncs the resize controller's pane link with the width and edge this
+ // commit rendered.
+ useIsomorphicLayoutEffect(() => {
+ paneLink.committed(effectiveWidth, contentFacingEdge);
+ });
// A collapsing panel moves focus inside it to its ResizeHandle, through the
// focus-leaving sequence that disclosures share. It goes inert and hidden
// from assistive technology a commit later, so inert never drops that focus
// to the page. Opening drops both at once. The ResizeHandle beside it holds
// the region's collapse state, or else the `resizable` props hold it.
- const elementRef = useRef<HTMLDivElement>(null);
const isRegionCollapsed =
resizable == null ? isHeldCollapsed : resizable._isCollapsed;
const noteFocusBeforeCollapse = useFocusLeavingChange(
@@ -313,8 +341,6 @@ export function LayoutPanel({
const isEndPanel = area === 'end';
const isZeroPadding = padding === 0;
- // A collapsed region sizes its panel to 0.
- const isZeroWidth = effectiveWidth === 0;
// When no divider, collapse spacing for seamless visual flow
const shouldCollapseSpacing =
@@ -325,7 +351,7 @@ export function LayoutPanel({
role,
label,
});
- const mergedRef = useMergedRefs(ref, region.ref, elementRef, lendRef);
+ const mergedRef = useMergedRefs(ref, region.ref, elementRef);
// Select divider style based on position
const dividerStyle = isStartPanel
@@ -375,6 +401,10 @@ export function LayoutPanel({
)}
{...props}
{...(isConcealed ? {inert: true, 'aria-hidden': true} : {})}>
+ <LayoutChangeSnapshot
+ value={isZeroWidth}
+ onBeforeChange={tellBeforeChange}
+ />
<LayoutChangeSnapshot
value={isRegionCollapsed}
onBeforeChange={noteFocusBeforeCollapse}
diff --git a/packages/core/src/Resizable/ResizeHandle.tsx b/packages/core/src/Resizable/ResizeHandle.tsx
index ebd3705e01..817d346292 100644
--- a/packages/core/src/Resizable/ResizeHandle.tsx
+++ b/packages/core/src/Resizable/ResizeHandle.tsx
@@ -39,6 +39,7 @@ import {
} from './resizeGesture';
import {
handOverPane,
+ regionOfProps,
registerResizeHandle,
resizablePaneFor,
watchResizablePanes,
@@ -79,6 +80,10 @@ function resolveEffectiveSide(
const styles = stylex.create({
handle: {
position: 'relative',
+ // The grab zone and the pill stay above the content beside the handle. A
+ // glide's translate makes the handle a stacking context, which traps
+ // their own z-index inside it.
+ zIndex: 2,
flexShrink: 0,
display: 'flex',
alignItems: 'center',
@@ -491,7 +496,15 @@ export function ResizeHandle({
isDisabled:
configRef.current.isDisabled || resizableRef.current == null,
}),
- setIsDragging,
+ dragging => {
+ setIsDragging(dragging);
+ // The hook's region lets a pointer drag reopen its pane without a
+ // slide; a hand-built object has none.
+ const region = resizableRef.current;
+ if (region != null) {
+ regionOfProps(region)?.setPointerDragging(dragging);
+ }
+ },
);
});
@@ -564,6 +577,7 @@ export function ResizeHandle({
heldPaneRef.current = handOverPane(
heldPaneRef.current,
null,
+ null,
false,
null,
);
@@ -586,6 +600,7 @@ export function ResizeHandle({
heldPaneRef.current = handOverPane(
heldPaneRef.current,
pane,
+ null,
isRegionCollapsed,
element,
);
diff --git a/packages/core/src/Resizable/__tests__/paneSlide.interaction.browser.spec.ts b/packages/core/src/Resizable/__tests__/paneSlide.interaction.browser.spec.ts
new file mode 100644
index 0000000000..77a9873b2d
--- /dev/null
+++ b/packages/core/src/Resizable/__tests__/paneSlide.interaction.browser.spec.ts
@@ -0,0 +1,798 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file paneSlide.interaction.browser.spec.ts
+ * @input The a11y-spec Playwright entry and the interaction harness:
+ * Resizable's sliding-panel stories and their props fixtures
+ * @output Proves the pane slides closed and open from the edge facing its
+ * handle, by every path, and nothing inside it moves, a scrolled pane
+ * included. Focus leaves a collapsing pane, which goes inert. It runs in
+ * Chromium and WebKit, with and without Reduce Motion
+ * @position Interaction proof for createResizable.ts, resizablePane.ts and
+ * LayoutPanel.tsx
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+type Side = 'start' | 'end';
+
+const STORY = {
+ start: 'core-resizable--sliding-start-panel',
+ end: 'core-resizable--sliding-end-panel',
+ hookProps: 'core-resizable--sliding-panel-with-hook-props',
+ handBuilt: 'core-resizable--panel-with-hand-built-props',
+ controlled: 'core-resizable--sliding-controlled-panel',
+ scrolled: 'core-resizable--sliding-scrolled-panel-fixture',
+} as const;
+
+/** How many evenly spaced moments of a motion are captured. */
+const MOMENTS = 24;
+
+/** One moment's geometry: the pane's shown edge facing the handle, and the handle's. */
+interface Frame {
+ /** The pane's edge that faces the handle, where its clip shows it end. */
+ shownEdge: number;
+ /** The handle's edge that faces the pane. */
+ handleEdge: number;
+ paneWidth: number;
+ /** Where the pane's first child starts, along the row. */
+ inside: number;
+ /** How far the pane is scrolled down. */
+ scrollTop: number;
+ /** Whether a press on the handle where it shows lands on the handle. */
+ pressTaken: boolean;
+}
+
+/** What a collapse or open did, captured at evenly spaced moments. */
+interface Motion {
+ /** The rest before the input, then each moment, then the end. */
+ frames: Frame[];
+ /** Whether the pane got a clip animation and the handle a glide. */
+ clips: boolean;
+ glides: boolean;
+ durationMs: number;
+}
+
+/**
+ * Installs, in the page, the reader of one moment of the pane and its handle.
+ * The pane moves by no transform: its box is its layout, and its clip says
+ * where it shows. The handle shows at its layout place plus its glide at the
+ * glide's own time. The pane's margin box ends at that layout place in the
+ * row. The handle's own rect is not read. WebKit reports a compositor-run
+ * translate ahead of the frame time, in the rect and in the computed style
+ * alike. In Chromium the two readings agree.
+ */
+interface ReaderWindow {
+ __readPaneFrame: (side: Side) => Frame;
+}
+
+function installFrameReader(): void {
+ (window as unknown as ReaderWindow).__readPaneFrame = (side: Side): Frame => {
+ const pane = document.querySelector<HTMLElement>(
+ '[data-testid="sliding-panel"]',
+ );
+ const handle = document.querySelector<HTMLElement>('[role="separator"]');
+ if (pane == null || handle == null) {
+ throw new Error('the sliding panel story did not render');
+ }
+ const pixels = (value: unknown) =>
+ [...String(value).matchAll(/(-?[\d.e+-]+)px/g)].map(match =>
+ Number(match[1]),
+ );
+ const glide = handle
+ .getAnimations()
+ .find(
+ animation =>
+ animation.effect instanceof KeyframeEffect &&
+ animation.effect.getKeyframes().some(k => k.translate != null),
+ );
+ let glideX = 0;
+ const effect = glide?.effect;
+ if (glide != null && effect instanceof KeyframeEffect) {
+ const keyframes = effect.getKeyframes();
+ if (keyframes.length === 1) {
+ glideX = pixels(keyframes[0].translate)[0] ?? 0;
+ } else if (keyframes.length > 1) {
+ const duration = Number(effect.getTiming().duration);
+ const at = Math.min(
+ 1,
+ Math.max(0, Number(glide.currentTime ?? 0) / duration),
+ );
+ let index = 0;
+ while (
+ index < keyframes.length - 2 &&
+ keyframes[index + 1].computedOffset < at
+ ) {
+ index++;
+ }
+ const [x0 = 0] = pixels(keyframes[index].translate);
+ const [x1 = 0] = pixels(keyframes[index + 1].translate);
+ const span =
+ keyframes[index + 1].computedOffset - keyframes[index].computedOffset;
+ const progress =
+ span > 0 ? (at - keyframes[index].computedOffset) / span : 1;
+ glideX = x0 + (x1 - x0) * progress;
+ }
+ }
+ const paneRect = pane.getBoundingClientRect();
+ const paneStyle = getComputedStyle(pane);
+ // inset(top right bottom left): the clip on the edge facing the handle.
+ const insets = (paneStyle.clipPath.match(/-?[\d.]+(px|%)?/g) ?? []).map(
+ value =>
+ value.endsWith('%')
+ ? (parseFloat(value) / 100) * paneRect.width
+ : parseFloat(value),
+ );
+ const inside = pane.firstElementChild?.getBoundingClientRect().left ?? 0;
+ const handleEdge =
+ side === 'start'
+ ? paneRect.right + (parseFloat(paneStyle.marginInlineEnd) || 0) + glideX
+ : paneRect.left -
+ (parseFloat(paneStyle.marginInlineStart) || 0) +
+ glideX;
+ // The middle of the handle where it shows, which a finger aims at.
+ const handleRect = handle.getBoundingClientRect();
+ const pressAt = document.elementFromPoint(
+ handleEdge + ((side === 'start' ? 1 : -1) * handle.offsetWidth) / 2,
+ handleRect.top + handleRect.height / 2,
+ );
+ return {
+ shownEdge:
+ side === 'start'
+ ? paneRect.right - (insets[1] ?? 0)
+ : paneRect.left + (insets[3] ?? 0),
+ handleEdge,
+ paneWidth: paneRect.width,
+ inside,
+ scrollTop: pane.scrollTop,
+ pressTaken: pressAt != null && handle.contains(pressAt),
+ };
+ };
+}
+
+/** Reads one moment now. */
+async function readNow(page: Page, side: Side): Promise<Frame> {
+ return page.evaluate(
+ sideArg => (window as unknown as ReaderWindow).__readPaneFrame(sideArg),
+ side,
+ );
+}
+
+/** Opens a fixture with the frame reader installed. */
+async function openFixture(page: Page, storyId: string): Promise<void> {
+ await page.addInitScript(installFrameReader);
+ await openStory(page, storybook(), storyId);
+}
+
+interface CaptureWindow extends ReaderWindow {
+ __paneAnimations: Animation[];
+ __paneAnimate?: Element['animate'];
+ __collapsedTextBefore?: string | null;
+}
+
+/**
+ * Captures the collapse or open the input `trigger` starts at evenly spaced
+ * moments. Every animation the change starts is paused as it is created and
+ * held there. The module starts each one by setting its start time to the
+ * timeline's current time, which would set it running. So none advances
+ * while the test waits for a starved page. Then, in one task,
+ * each is set to the same moment before the geometry is read, and they
+ * finish. Neither a renderer that skips frames nor a page that answers late
+ * can hide a slide or fake one.
+ */
+async function captureMotion(
+ page: Page,
+ side: Side,
+ trigger: () => Promise<void>,
+): Promise<Motion> {
+ const rest = await readNow(page, side);
+ await page.evaluate(() => {
+ const capture = window as unknown as CaptureWindow;
+ const animations: Animation[] = [];
+ capture.__paneAnimations = animations;
+ capture.__collapsedTextBefore = document
+ .querySelector('[role="separator"]')
+ ?.getAttribute('aria-valuetext');
+ const animate = Element.prototype.animate;
+ capture.__paneAnimate = animate;
+ Element.prototype.animate = function (
+ this: Element,
+ ...args: Parameters<Element['animate']>
+ ) {
+ const animation = animate.apply(this, args);
+ animation.pause();
+ Object.defineProperty(animation, 'startTime', {
+ configurable: true,
+ get: () => null,
+ set: () => {},
+ });
+ animations.push(animation);
+ return animation;
+ };
+ });
+ await trigger();
+ const motion = await page.evaluate(
+ async ({sideArg, moments}) => {
+ const capture = window as unknown as CaptureWindow;
+ const animations = capture.__paneAnimations;
+ // Wait until the change commits: an animation starts, or the handle
+ // says the collapse state changed. Two more frames let a later commit
+ // start its motion. Frames, not time, so a starved page only takes
+ // longer. Nothing it starts can run meanwhile.
+ const nextFrame = async () =>
+ new Promise(resolve => requestAnimationFrame(resolve));
+ const collapsedText = () =>
+ document
+ .querySelector('[role="separator"]')
+ ?.getAttribute('aria-valuetext');
+ while (
+ animations.length === 0 &&
+ collapsedText() === capture.__collapsedTextBefore
+ ) {
+ await nextFrame();
+ }
+ for (let frame = 0; frame < 2 && animations.length === 0; frame++) {
+ await nextFrame();
+ }
+ if (capture.__paneAnimate != null) {
+ Element.prototype.animate = capture.__paneAnimate;
+ capture.__paneAnimate = undefined;
+ }
+ for (const animation of animations) {
+ Reflect.deleteProperty(animation, 'startTime');
+ }
+ const pane = document.querySelector('[data-testid="sliding-panel"]');
+ const handle = document.querySelector('[role="separator"]');
+ const keyframesOf = (animation: Animation) =>
+ animation.effect instanceof KeyframeEffect
+ ? animation.effect.getKeyframes()
+ : [];
+ const targetOf = (animation: Animation) =>
+ animation.effect instanceof KeyframeEffect
+ ? animation.effect.target
+ : null;
+ const clips = animations.some(
+ a =>
+ targetOf(a) === pane && keyframesOf(a).some(k => k.clipPath != null),
+ );
+ const glides = animations.some(
+ a =>
+ targetOf(a) === handle &&
+ keyframesOf(a).some(k => k.translate != null),
+ );
+ const durationMs =
+ animations.length === 0
+ ? 0
+ : Math.max(
+ ...animations.map(a =>
+ Number(a.effect?.getComputedTiming().endTime),
+ ),
+ );
+ const frames: Frame[] = [];
+ // One task: no frame passes between setting a moment and reading it.
+ // Moments up to, not at, the end: a motion's effects stop applying at
+ // their end, before its finish drops what it holds.
+ for (let moment = 0; durationMs > 0 && moment < moments; moment++) {
+ for (const animation of animations) {
+ animation.currentTime = (durationMs * moment) / moments;
+ }
+ frames.push(capture.__readPaneFrame(sideArg));
+ }
+ for (const animation of animations) {
+ animation.finish();
+ }
+ // What a finished motion leaves behind, once its holds are dropped.
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ frames.push(capture.__readPaneFrame(sideArg));
+ return {frames, clips, glides, durationMs};
+ },
+ {sideArg: side, moments: MOMENTS},
+ );
+ return {...motion, frames: [rest, ...motion.frames]};
+}
+
+/**
+ * Starts the motion the input `trigger` starts, paused at `atMs` into it, the
+ * way `captureMotion` pauses it. It holds there until `releaseMotion`.
+ */
+async function holdMotionAt(
+ page: Page,
+ atMs: number,
+ trigger: () => Promise<void>,
+): Promise<void> {
+ await page.evaluate(() => {
+ const capture = window as unknown as CaptureWindow;
+ const animations: Animation[] = [];
+ capture.__paneAnimations = animations;
+ capture.__collapsedTextBefore = document
+ .querySelector('[role="separator"]')
+ ?.getAttribute('aria-valuetext');
+ const animate = Element.prototype.animate;
+ capture.__paneAnimate = animate;
+ Element.prototype.animate = function (
+ this: Element,
+ ...args: Parameters<Element['animate']>
+ ) {
+ const animation = animate.apply(this, args);
+ animation.pause();
+ Object.defineProperty(animation, 'startTime', {
+ configurable: true,
+ get: () => null,
+ set: () => {},
+ });
+ animations.push(animation);
+ return animation;
+ };
+ });
+ await trigger();
+ const held = await page.evaluate(async at => {
+ const capture = window as unknown as CaptureWindow;
+ const animations = capture.__paneAnimations;
+ // As in `captureMotion`: frames until the change commits, then two more.
+ const nextFrame = async () =>
+ new Promise(resolve => requestAnimationFrame(resolve));
+ const collapsedText = () =>
+ document
+ .querySelector('[role="separator"]')
+ ?.getAttribute('aria-valuetext');
+ while (
+ animations.length === 0 &&
+ collapsedText() === capture.__collapsedTextBefore
+ ) {
+ await nextFrame();
+ }
+ for (let frame = 0; frame < 2 && animations.length === 0; frame++) {
+ await nextFrame();
+ }
+ if (capture.__paneAnimate != null) {
+ Element.prototype.animate = capture.__paneAnimate;
+ capture.__paneAnimate = undefined;
+ }
+ for (const animation of animations) {
+ Reflect.deleteProperty(animation, 'startTime');
+ animation.currentTime = at;
+ }
+ return animations.length;
+ }, atMs);
+ expect(held).toBeGreaterThan(0);
+}
+
+/** Lets a held motion finish. */
+async function releaseMotion(page: Page): Promise<void> {
+ await page.evaluate(async () => {
+ for (const animation of (window as unknown as CaptureWindow)
+ .__paneAnimations) {
+ animation.finish();
+ }
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ });
+}
+
+/**
+ * Every captured moment keeps the pane's shown edge where it sits beside the
+ * handle once the motion ends. No gap opens, and the edge never runs ahead.
+ * A panel without a divider overlaps its handle by its collapse spacing only
+ * while open. That overlap lies under the content's own spacing, and it
+ * changes in the first moment.
+ */
+function expectEdgeOnHandle(frames: Frame[]): void {
+ const end = frames[frames.length - 1];
+ const settled = end.shownEdge - end.handleEdge;
+ frames.forEach((frame, index) => {
+ // The first frame is the rest before the input.
+ if (index > 0 && frame.paneWidth > 0) {
+ expect(
+ Math.abs(frame.shownEdge - frame.handleEdge - settled),
+ `moment ${index} of ${frames.length}: ${JSON.stringify(frame)}, at the end ${settled}`,
+ ).toBeLessThanOrEqual(1.5);
+ }
+ });
+}
+
+/**
+ * Nothing inside the pane moves while it shows. Its first child stays where
+ * it is in `still`: the rest a pane conceals from, or the end it reveals to.
+ */
+function expectInsideStill(frames: Frame[], still: Frame): void {
+ frames.forEach((frame, index) => {
+ if (frame.paneWidth > 0) {
+ expect(
+ Math.abs(frame.inside - still.inside),
+ `moment ${index} of ${frames.length}: ${JSON.stringify(frame)}`,
+ ).toBeLessThanOrEqual(1.5);
+ }
+ });
+}
+
+/**
+ * How many captured moments show the handle strictly between where it
+ * started and where it ended, moving one way.
+ */
+function travelling(frames: Frame[]): number {
+ const from = frames[0].handleEdge;
+ const to = frames[frames.length - 1].handleEdge;
+ const low = Math.min(from, to) + 1;
+ const high = Math.max(from, to) - 1;
+ return frames.filter(f => f.handleEdge > low && f.handleEdge < high).length;
+}
+
+/**
+ * The pane's width once collapsed: its region's size is 0, and a border-box
+ * LayoutPanel keeps only its inline padding and borders.
+ */
+async function collapsedWidthOf(page: Page): Promise<number> {
+ return page.getByTestId('sliding-panel').evaluate(element => {
+ const style = getComputedStyle(element);
+ return [
+ style.paddingInlineStart,
+ style.paddingInlineEnd,
+ style.borderInlineStartWidth,
+ style.borderInlineEndWidth,
+ ].reduce((sum, value) => sum + (parseFloat(value) || 0), 0);
+ });
+}
+
+/** The pane, its handle and the content are present and painted. */
+async function expectPresent(page: Page): Promise<void> {
+ for (const element of [
+ page.getByTestId('sliding-panel'),
+ page.getByRole('separator', {name: 'Resize panel'}),
+ page.getByTestId('sliding-content'),
+ ]) {
+ await expect(element).toHaveCount(1);
+ const box = await element.boundingBox();
+ expect(box?.width ?? 0).toBeGreaterThan(0);
+ expect(box?.height ?? 0).toBeGreaterThan(0);
+ }
+ expect(
+ (await page.getByTestId('sliding-panel').boundingBox())?.width,
+ ).toBeCloseTo(200, 0);
+}
+
+/**
+ * Proves one pane's slide. A button inside the pane collapses it: focus moves
+ * to the handle, and the pane ends inert. Then the handle opens it, and no
+ * focus moves. The shown edge stays on the handle at every captured moment of
+ * both.
+ */
+async function expectSlide(
+ page: Page,
+ side: Side,
+ storyId: string,
+): Promise<void> {
+ await openFixture(page, storyId);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+
+ await page.getByRole('button', {name: 'Close panel'}).focus();
+ const closing = await captureMotion(page, side, async () => {
+ await page.keyboard.press('Enter');
+ });
+ // A slide, not a jump: the pane clips and the handle glides. The handle is
+ // on its way at many captured moments, though not all: a spring settles its
+ // last pixel late ...
+ expect(closing.clips).toBe(true);
+ expect(closing.glides).toBe(true);
+ expect(travelling(closing.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ // ... and the pane's shown edge stays on it throughout, with nothing inside
+ // the pane moving.
+ expectEdgeOnHandle(closing.frames);
+ expectInsideStill(closing.frames, closing.frames[0]);
+ // It ends where the collapsed layout puts it, with nothing held.
+ expect((await pane.boundingBox())?.width).toBeCloseTo(
+ await collapsedWidthOf(page),
+ 0,
+ );
+ await expect(handle).toBeFocused();
+ await expect(pane).toHaveAttribute('inert', '');
+ await expect(pane).toHaveAttribute('aria-hidden', 'true');
+
+ // Open from the handle: no focus moves.
+ const opening = await captureMotion(page, side, async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(opening.glides).toBe(true);
+ expect(travelling(opening.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ expectEdgeOnHandle(opening.frames);
+ expectInsideStill(opening.frames, opening.frames[opening.frames.length - 1]);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(200, 0);
+ await expect(handle).toBeFocused();
+ await expect(pane).not.toHaveAttribute('inert', '');
+ await expect(pane).not.toHaveAttribute('aria-hidden', 'true');
+}
+
+for (const side of ['start', 'end'] as const) {
+ test(`a ${side} panel slides closed and open from the edge facing its handle, and focus inside it moves to the handle`, async ({
+ page,
+ }) => {
+ await expectSlide(page, side, STORY[side]);
+ });
+}
+
+test("a panel that takes the hook's own props slides the same way", async ({
+ page,
+}) => {
+ await expectSlide(page, 'start', STORY.hookProps);
+});
+
+test('a panel that takes a hand-built ResizableProps object collapses and opens without a slide, and focus still leaves it', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.handBuilt);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+ await page.getByRole('button', {name: 'Close panel'}).focus();
+ const closing = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(closing.clips).toBe(false);
+ expect(closing.glides).toBe(false);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(
+ await collapsedWidthOf(page),
+ 0,
+ );
+ await expect(handle).toBeFocused();
+ await expect(pane).toHaveAttribute('inert', '');
+ await expect(pane).toHaveAttribute('aria-hidden', 'true');
+ const opening = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(opening.clips).toBe(false);
+ expect(opening.glides).toBe(false);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(200, 0);
+ await expect(handle).toBeFocused();
+ await expect(pane).not.toHaveAttribute('inert', '');
+});
+
+test('a scrolled panel keeps its scroll offset while it slides closed', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.scrolled);
+ const pane = page.getByTestId('sliding-panel');
+ await pane.evaluate(element => {
+ element.scrollTop = 120;
+ });
+ const closing = await captureMotion(page, 'start', async () => {
+ await page.getByRole('button', {name: 'Toggle panel'}).click();
+ });
+ expect(closing.clips).toBe(true);
+ closing.frames.forEach((frame, index) => {
+ if (frame.paneWidth > 0) {
+ expect(
+ frame.scrollTop,
+ `moment ${index} of ${closing.frames.length}`,
+ ).toBe(120);
+ }
+ });
+ expectInsideStill(closing.frames, closing.frames[0]);
+});
+
+/** A slide: the pane clips and the handle glides, with the edge on the handle. */
+function expectSlid(motion: Motion): void {
+ expect(motion.clips).toBe(true);
+ expect(motion.glides).toBe(true);
+ expect(travelling(motion.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ expectEdgeOnHandle(motion.frames);
+}
+
+test('a toggle outside the panel slides it closed and open, and keeps its focus', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.start);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const toggle = page.getByRole('button', {name: 'Toggle panel'});
+ await toggle.focus();
+ expectSlid(
+ await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ }),
+ );
+ await expect(toggle).toBeFocused();
+ await expect(pane).toHaveAttribute('inert', '');
+ const opening = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(opening.glides).toBe(true);
+ expect(travelling(opening.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ expectEdgeOnHandle(opening.frames);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(200, 0);
+ await expect(toggle).toBeFocused();
+});
+
+test('a controlled isCollapsed change slides the panel closed and open', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.controlled);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const toggle = page.getByRole('button', {name: 'Toggle panel'});
+ await toggle.focus();
+ expectSlid(
+ await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ }),
+ );
+ expect((await pane.boundingBox())?.width).toBeCloseTo(
+ await collapsedWidthOf(page),
+ 0,
+ );
+ await expect(pane).toHaveAttribute('inert', '');
+ const opening = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(opening.glides).toBe(true);
+ expect(travelling(opening.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ expectEdgeOnHandle(opening.frames);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(200, 0);
+ await expect(pane).not.toHaveAttribute('inert', '');
+});
+
+test('a double-click on the handle slides the panel closed and open', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.start);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+ expectSlid(
+ await captureMotion(page, 'start', async () => {
+ await handle.dblclick();
+ }),
+ );
+ expect((await pane.boundingBox())?.width).toBeCloseTo(
+ await collapsedWidthOf(page),
+ 0,
+ );
+ const opening = await captureMotion(page, 'start', async () => {
+ await handle.dblclick();
+ });
+ expect(opening.glides).toBe(true);
+ expectEdgeOnHandle(opening.frames);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(200, 0);
+});
+
+test('the grow arrow opens a collapsed panel with a slide', async ({page}) => {
+ await openFixture(page, STORY.start);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+ await handle.focus();
+ await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect((await pane.boundingBox())?.width).toBeCloseTo(
+ await collapsedWidthOf(page),
+ 0,
+ );
+ const opening = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('ArrowRight');
+ });
+ expect(opening.glides).toBe(true);
+ expect(travelling(opening.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ expectEdgeOnHandle(opening.frames);
+ expect((await pane.boundingBox())?.width ?? 0).toBeGreaterThan(100);
+});
+
+test('a drag past the threshold slides the panel closed, and a drag that reopens it follows the pointer with no slide', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.start);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+ const start = await handle.boundingBox();
+ if (start == null) {
+ throw new Error('the handle is not laid out');
+ }
+ const y = start.y + start.height / 2;
+ await page.mouse.move(start.x + start.width / 2, y);
+ await page.mouse.down();
+ expectSlid(
+ await captureMotion(page, 'start', async () => {
+ await page.mouse.move(start.x + start.width / 2 - 190, y, {steps: 4});
+ }),
+ );
+ await page.mouse.up();
+ expect((await pane.boundingBox())?.width).toBeCloseTo(
+ await collapsedWidthOf(page),
+ 0,
+ );
+
+ const collapsed = await handle.boundingBox();
+ if (collapsed == null) {
+ throw new Error('the handle is not laid out');
+ }
+ await page.mouse.move(collapsed.x + collapsed.width / 2, y);
+ await page.mouse.down();
+ const reopening = await captureMotion(page, 'start', async () => {
+ await page.mouse.move(collapsed.x + collapsed.width / 2 + 160, y, {
+ steps: 4,
+ });
+ });
+ await page.mouse.up();
+ // The pointer drives the edge: no clip and no glide play.
+ expect(reopening.clips).toBe(false);
+ expect(reopening.glides).toBe(false);
+ expect((await pane.boundingBox())?.width ?? 0).toBeGreaterThan(100);
+ await expect(pane).not.toHaveAttribute('inert', '');
+});
+
+test('a press where the handle shows lands on it at every moment of a slide, on both sides', async ({
+ page,
+}) => {
+ for (const side of ['start', 'end'] as const) {
+ await openFixture(page, STORY[side]);
+ await expectPresent(page);
+ await page.getByRole('button', {name: 'Toggle panel'}).focus();
+ const closing = await captureMotion(page, side, async () => {
+ await page.keyboard.press('Enter');
+ });
+ const opening = await captureMotion(page, side, async () => {
+ await page.keyboard.press('Enter');
+ });
+ for (const motion of [closing, opening]) {
+ expect(travelling(motion.frames)).toBeGreaterThanOrEqual(MOMENTS / 3);
+ expect(motion.frames.map(frame => frame.pressTaken).indexOf(false)).toBe(
+ -1,
+ );
+ }
+ }
+});
+
+test('a drag that starts on the handle 40 ms into a slide takes the handle and reopens the pane', async ({
+ page,
+}) => {
+ await openFixture(page, STORY.start);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+ await holdMotionAt(page, 40, async () => {
+ await page.getByRole('button', {name: 'Toggle panel'}).click();
+ });
+ const box = await handle.boundingBox();
+ if (box == null) {
+ throw new Error('the handle is not laid out');
+ }
+ const frame = await readNow(page, 'start');
+ const x = frame.handleEdge + 0.5;
+ const y = box.y + box.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await expect(handle).toHaveAttribute('data-resizing', 'true');
+ await page.mouse.move(x + 160, y, {steps: 4});
+ await page.mouse.up();
+ await releaseMotion(page);
+ expect((await pane.boundingBox())?.width ?? 0).toBeGreaterThan(100);
+ await expect(pane).not.toHaveAttribute('inert', '');
+});
+
+test('under Reduce Motion the pane does not travel, and focus still leaves it', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await openFixture(page, STORY.start);
+ await expectPresent(page);
+ const pane = page.getByTestId('sliding-panel');
+ const handle = page.getByRole('separator', {name: 'Resize panel'});
+ await page.getByRole('button', {name: 'Close panel'}).focus();
+ const closing = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(closing.glides).toBe(false);
+ expect(travelling(closing.frames)).toBe(0);
+ await expect(handle).toBeFocused();
+ await expect(pane).toHaveAttribute('inert', '');
+ const opening = await captureMotion(page, 'start', async () => {
+ await page.keyboard.press('Enter');
+ });
+ expect(opening.glides).toBe(false);
+ expect(travelling(opening.frames)).toBe(0);
+ expect((await pane.boundingBox())?.width).toBeCloseTo(200, 0);
+});
diff --git a/packages/core/src/Resizable/createResizable.ts b/packages/core/src/Resizable/createResizable.ts
index f6fa411644..3b95cb85be 100644
--- a/packages/core/src/Resizable/createResizable.ts
+++ b/packages/core/src/Resizable/createResizable.ts
@@ -2,8 +2,8 @@
/**
* @file createResizable.ts
- * @input A handle element, or null for a region with no handle yet, and the
- * region's options
+ * @input A handle element, or null for a region with no handle yet, the
+ * region's options, and the pane a LayoutPanel lends (resizablePane.ts)
* @output createResizable; readInitialResizableState for the hook's first
* render; createResizableAs and the internal channel for the hooks
* @position The Resizable family's factory, internal to the package. Its
@@ -39,6 +39,13 @@ import {
type ResizeGestureModel,
type ResizeGestureState,
} from './resizeGesture';
+import {
+ createPaneReveal,
+ handOverPane,
+ type PaneListener,
+ type RegionPaneSlot,
+ type ResizablePane,
+} from './resizablePane';
import {separatorAttributes} from './separatorAttributes';
import type {ResizableSize} from './utils';
@@ -300,6 +307,12 @@ interface ResizableInternals {
* keys of a ResizeHandle given the configuration object's props.
*/
model: ResizeGestureModel;
+ /**
+ * The hook's region: the pane its LayoutPanel hands over,
+ * and whether its ResizeHandle's pointer drags. Returns the function that
+ * stops following it.
+ */
+ followRegion(slot: RegionPaneSlot): () => void;
}
const internals = new WeakMap<ResizableController, ResizableInternals>();
@@ -444,6 +457,21 @@ export function createResizableAs(
let snapshot: ResizableSnapshot | null = null;
const snapshotListeners = new Set<() => void>();
+ // The pane is the LayoutPanel the hook's region hands over. The factory
+ // measures its edge reveal before the DOM changes. It plays the reveal once
+ // the pane renders its new size.
+ let pane: ResizablePane | null = null;
+ let regionSlot: RegionPaneSlot | null = null;
+ const paneReveal = createPaneReveal(
+ () => pane?.element.parentElement ?? null,
+ );
+ // `pendingFlip` is a flip this factory made that the pane has not rendered
+ // yet. `expectedFlip` is a controlled flip that the pane rendered and
+ // measured first.
+ let pendingFlip: {toCollapsed: boolean; isPlayable: boolean} | null = null;
+ let expectedFlip: boolean | null = null;
+ let isPointerReopening = false;
+
const direction = (): ResizableDirection => opts.direction ?? 'horizontal';
const collapsible = (): boolean => opts.collapsible ?? false;
const isControlled = (): boolean => opts.isCollapsed !== undefined;
@@ -649,6 +677,28 @@ export function createResizableAs(
size: derived.isCollapsed ? 0 : derived.size,
isCollapsed: derived.isCollapsed,
};
+ if (notified != null) {
+ if (notified.isCollapsed !== reported.isCollapsed) {
+ if (expectedFlip === reported.isCollapsed) {
+ // The pane rendered this change first and has measured it.
+ expectedFlip = null;
+ pendingFlip = null;
+ } else {
+ pendingFlip = {
+ toCollapsed: reported.isCollapsed,
+ isPlayable: !isPointerReopening,
+ };
+ if (isPointerReopening) {
+ // The pointer drives the edge: a running conceal lands at once.
+ paneReveal.land();
+ }
+ }
+ } else if (notified.size !== reported.size) {
+ // A resize that neither collapses nor opens lands a running motion.
+ paneReveal.land();
+ }
+ }
+ pane?.setCollapsed(reported.isCollapsed, handle);
const next: ResizableSnapshot = {
size: reported.size,
isCollapsed: reported.isCollapsed,
@@ -685,6 +735,51 @@ export function createResizableAs(
}
}
+ // --- The pane a LayoutPanel lends ---
+
+ const paneListener: PaneListener = {
+ beforeChange(toCollapsed) {
+ const current = pane;
+ if (current == null) {
+ return;
+ }
+ if (pendingFlip?.toCollapsed === toCollapsed) {
+ const {isPlayable} = pendingFlip;
+ pendingFlip = null;
+ if (isPlayable) {
+ paneReveal.measure(current, current.contentFacingEdge());
+ } else {
+ paneReveal.land();
+ }
+ return;
+ }
+ // The pane renders a collapse or open this factory has not made yet,
+ // ahead of the size it reports. A controlled isCollapsed does that: it
+ // reaches the factory after this commit. It plays too.
+ const reportedSize = derived.isCollapsed ? 0 : derived.size;
+ const isAhead = toCollapsed ? reportedSize !== 0 : reportedSize === 0;
+ if (collapsible() && isAhead && derived.isCollapsed !== toCollapsed) {
+ expectedFlip = toCollapsed;
+ paneReveal.measure(current, current.contentFacingEdge());
+ }
+ },
+ committed() {
+ if (pane != null) {
+ paneReveal.committed(pane);
+ }
+ },
+ };
+
+ function setPane(next: ResizablePane | null): void {
+ if (next === pane) {
+ return;
+ }
+ paneReveal.land();
+ pendingFlip = null;
+ expectedFlip = null;
+ pane = handOverPane(pane, next, paneListener, derived.isCollapsed, handle);
+ }
+
/** Nothing is written while the basis stands in, nor while a gesture runs. */
function persist(): void {
const key = opts.autoSaveId;
@@ -853,7 +948,10 @@ export function createResizableAs(
}
const clamped = clampSize(raw, derived.min, derived.max, snaps());
chosenSize = clamped;
+ // Only a pointer reopens without a reveal; a key's step plays one.
+ isPointerReopening = reopens && regionSlot?.isPointerDragging() === true;
commit();
+ isPointerReopening = false;
if (reopens) {
opts.onCollapseChange?.(false);
}
@@ -957,6 +1055,8 @@ export function createResizableAs(
}
bindHandle();
+ let stopFollowingRegion: (() => void) | null = null;
+
commit();
const controller: ResizableController = {
@@ -997,6 +1097,10 @@ export function createResizableAs(
// than the factory's own, ends the same way.
endGesture();
isDestroyed = true;
+ stopFollowingRegion?.();
+ stopFollowingRegion = null;
+ paneReveal.land();
+ pane = handOverPane(pane, null, paneListener, false, null);
if (!isSuspended) {
letGoOfPage();
}
@@ -1020,6 +1124,8 @@ export function createResizableAs(
gesture.interrupt();
endGesture();
isSuspended = true;
+ // A suspended region plays no reveal, so a running one lands now.
+ paneReveal.land();
letGoOfPage();
},
resume() {
@@ -1041,6 +1147,25 @@ export function createResizableAs(
commit();
}
},
+ followRegion(slot) {
+ stopFollowingRegion?.();
+ regionSlot = slot;
+ const stop = slot.follow(next => {
+ if (!isDestroyed) {
+ setPane(next);
+ }
+ });
+ stopFollowingRegion = () => {
+ stop();
+ if (regionSlot === slot) {
+ regionSlot = null;
+ }
+ };
+ return () => {
+ stopFollowingRegion?.();
+ stopFollowingRegion = null;
+ };
+ },
});
return controller;
}
diff --git a/packages/core/src/Resizable/paneReveal.test.tsx b/packages/core/src/Resizable/paneReveal.test.tsx
new file mode 100644
index 0000000000..9ea40aba4c
--- /dev/null
+++ b/packages/core/src/Resizable/paneReveal.test.tsx
@@ -0,0 +1,518 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file paneReveal.test.tsx
+ * @input vitest (jsdom), Testing Library, Layout with a LayoutPanel beside a
+ * ResizeHandle, the useResizable hook's region, and a recording
+ * stand-in for the animated-layout module's edge reveal
+ * @output Checks when a LayoutPanel's pane slides on collapse and open, from
+ * which edge and around which commit
+ * @position Integration tests for createResizable.ts, resizablePane.ts,
+ * LayoutPanel.tsx and ResizeHandle.tsx
+ */
+
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {useLayoutEffect, useState} from 'react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {__resetInteractionModalityForTest} from '../utils/interactionModality';
+import type * as AnimatedLayoutModule from '../motion/animatedLayout';
+import {Layout} from '../Layout/Layout';
+import {LayoutContent} from '../Layout/LayoutContent';
+import {LayoutPanel} from '../Layout/LayoutPanel';
+import {ResizeHandle} from './ResizeHandle';
+import {
+ useResizable,
+ type ResizableRegion,
+ type UseResizableSingleConfig,
+} from './useResizable';
+
+interface RecordedReveal {
+ edge: string;
+ target: () => Element | null;
+ /** The pane's inline style when each call ran. */
+ measuredStyle: string | null;
+ animatedStyle: string | null;
+ measureBefore: ReturnType<typeof vi.fn>;
+ animate: ReturnType<typeof vi.fn>;
+ cancel: ReturnType<typeof vi.fn>;
+}
+
+const reveals: RecordedReveal[] = [];
+
+vi.mock('../motion/animatedLayout', async importOriginal => {
+ const original = await importOriginal<typeof AnimatedLayoutModule>();
+ return {
+ ...original,
+ reportLayoutEdge: vi.fn(
+ (
+ _handle: unknown,
+ target: (() => Element | null) | {current: Element | null},
+ {edge}: {edge: string},
+ ) => {
+ const resolve = () =>
+ typeof target === 'function' ? target() : target.current;
+ const recorded: RecordedReveal = {
+ edge,
+ target: resolve,
+ measuredStyle: null,
+ animatedStyle: null,
+ measureBefore: vi.fn(() => {
+ recorded.measuredStyle = resolve()?.getAttribute('style') ?? null;
+ }),
+ animate: vi.fn(() => {
+ recorded.animatedStyle = resolve()?.getAttribute('style') ?? null;
+ }),
+ cancel: vi.fn(),
+ };
+ reveals.push(recorded);
+ return {
+ measureBefore: recorded.measureBefore,
+ animate: recorded.animate,
+ cancel: recorded.cancel,
+ };
+ },
+ ),
+ };
+});
+
+let propsRegion: ResizableRegion | undefined;
+
+const NO_CONFIG: UseResizableSingleConfig = {};
+
+/**
+ * A Layout whose start panel, or end panel when reversed, takes the
+ * hook's own `props`. Or it takes a hand-built copy: the
+ * same fields in an object `useResizable` did not return. Or, with
+ * `isWidthPanel`, it renders at the hook's size beside a handle given the
+ * props.
+ */
+function PropsSplit({
+ config = NO_CONFIG,
+ isReversed = false,
+ isHandBuilt = false,
+ isWidthPanel = false,
+ panelKey = 'panel',
+}: {
+ config?: UseResizableSingleConfig;
+ isReversed?: boolean;
+ isHandBuilt?: boolean;
+ isWidthPanel?: boolean;
+ panelKey?: string;
+}) {
+ const value = useResizable({defaultSize: 200, collapsible: true, ...config});
+ propsRegion = value;
+ const panelProps = isHandBuilt ? {...value.props} : value.props;
+ const panel = isWidthPanel ? (
+ <LayoutPanel key={panelKey} width={value.size} data-testid="pane">
+ <button type="button">Inside</button>
+ </LayoutPanel>
+ ) : (
+ <LayoutPanel key={panelKey} resizable={panelProps} data-testid="pane">
+ <button type="button">Inside</button>
+ </LayoutPanel>
+ );
+ const handle = (
+ <ResizeHandle
+ resizable={value.props}
+ isReversed={isReversed}
+ label="Resize pane"
+ />
+ );
+ return (
+ <>
+ <button type="button">Outside</button>
+ <Layout
+ start={
+ isReversed ? undefined : (
+ <>
+ {panel}
+ {handle}
+ </>
+ )
+ }
+ content={<LayoutContent>Main</LayoutContent>}
+ end={
+ isReversed ? (
+ <>
+ {handle}
+ {panel}
+ </>
+ ) : undefined
+ }
+ />
+ </>
+ );
+}
+
+interface ParentCommit {
+ parent: boolean;
+ hook: boolean;
+ /** Whether the pane rendered its open width (200px) in this commit. */
+ isOpenWidth: boolean;
+}
+let commits: ParentCommit[] = [];
+
+/** A parent that owns the collapse state through onCollapseChange. */
+function ControlledSplit() {
+ const [isCollapsed, setIsCollapsed] = useState(false);
+ const options = {
+ defaultSize: 200,
+ collapsible: true,
+ isCollapsed,
+ onCollapseChange: setIsCollapsed,
+ };
+ return <ControlledConfig isCollapsed={isCollapsed} options={options} />;
+}
+
+function useRecordParent(parent: boolean, hook: boolean) {
+ useLayoutEffect(() => {
+ commits.push({
+ parent,
+ hook,
+ isOpenWidth: (
+ screen.getByTestId('pane').getAttribute('style') ?? ''
+ ).includes('200px'),
+ });
+ });
+}
+
+function ControlledConfig({
+ isCollapsed,
+ options,
+}: {
+ isCollapsed: boolean;
+ options: UseResizableSingleConfig;
+}) {
+ const value = useResizable(options);
+ propsRegion = value;
+ useRecordParent(isCollapsed, value.isCollapsed);
+ return (
+ <Layout
+ start={
+ <>
+ <LayoutPanel resizable={value.props} data-testid="pane" />
+ <ResizeHandle resizable={value.props} label="Resize pane" />
+ </>
+ }
+ content={<LayoutContent>Main</LayoutContent>}
+ />
+ );
+}
+
+const pane = () => screen.getByTestId('pane');
+const separator = () => screen.getByRole('separator', {name: 'Resize pane'});
+/** The grab zone, which takes the pointer. */
+const grabZone = () => separator().firstElementChild as HTMLElement;
+
+beforeEach(() => {
+ __resetInteractionModalityForTest();
+ commits = [];
+ reveals.length = 0;
+ propsRegion = undefined;
+ localStorage.clear();
+});
+
+afterEach(() => {
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+});
+
+describe("a LayoutPanel's pane slides on collapse and open (component:Resizable FR8, component:LayoutPanel FR7)", () => {
+ it('measures a start pane before its collapse commits and plays from its inline-end edge after the pane renders its new width', () => {
+ render(<PropsSplit />);
+ expect(reveals).toHaveLength(0);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(reveals).toHaveLength(1);
+ const [reveal] = reveals;
+ expect(reveal.edge).toBe('inline-end');
+ expect(reveal.target()).toBe(pane());
+ expect(reveal.measureBefore).toHaveBeenCalledTimes(1);
+ expect(reveal.animate).toHaveBeenCalledTimes(1);
+ // Measured at the old width, played at the new one.
+ expect(reveal.measuredStyle).toContain('200px');
+ expect(reveal.animatedStyle).not.toContain('200px');
+ expect(reveal.measureBefore.mock.invocationCallOrder[0]).toBeLessThan(
+ reveal.animate.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('plays an end pane, beside a reversed handle, from its inline-start edge', () => {
+ render(<PropsSplit isReversed />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(reveals.map(r => r.edge)).toEqual(['inline-start']);
+ expect(reveals[0].target()).toBe(pane());
+ });
+
+ it('plays every collapse and open: collapse(), expand(), a resize out of collapse, Enter, a double-click and the grow arrow', () => {
+ render(<PropsSplit />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ act(() => {
+ propsRegion?.expand();
+ });
+ act(() => {
+ propsRegion?.collapse();
+ });
+ act(() => {
+ propsRegion?.resize(260);
+ });
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ fireEvent.doubleClick(separator());
+ fireEvent.keyDown(separator(), {key: 'ArrowRight'});
+ expect(reveals).toHaveLength(8);
+ for (const reveal of reveals) {
+ expect(reveal.edge).toBe('inline-end');
+ expect(reveal.measureBefore).toHaveBeenCalledTimes(1);
+ expect(reveal.animate).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it('plays a controlled isCollapsed change', () => {
+ const view = render(<PropsSplit config={{isCollapsed: false}} />);
+ view.rerender(<PropsSplit config={{isCollapsed: true}} />);
+ view.rerender(<PropsSplit config={{isCollapsed: false}} />);
+ expect(reveals).toHaveLength(2);
+ expect(reveals.every(r => r.animate.mock.calls.length === 1)).toBe(true);
+ });
+
+ it('plays a drag that crosses the collapse threshold, plays nothing for a drag that reopens, and lands a running conceal then', () => {
+ render(<PropsSplit />);
+ fireEvent.pointerDown(grabZone(), {pointerId: 1, clientX: 300});
+ fireEvent.pointerMove(grabZone(), {pointerId: 1, clientX: 110});
+ expect(propsRegion?.isCollapsed).toBe(true);
+ expect(reveals).toHaveLength(1);
+ expect(reveals[0].animate).toHaveBeenCalledTimes(1);
+ fireEvent.pointerMove(grabZone(), {pointerId: 1, clientX: 320});
+ expect(propsRegion?.isCollapsed).toBe(false);
+ expect(reveals).toHaveLength(1);
+ expect(reveals[0].cancel).toHaveBeenCalledTimes(1);
+ fireEvent.pointerUp(grabZone(), {pointerId: 1, clientX: 320});
+ });
+
+ it('plays nothing for the first render or a resize that neither collapses nor opens', () => {
+ render(<PropsSplit config={{defaultIsCollapsed: true}} />);
+ act(() => {
+ propsRegion?.expand();
+ });
+ expect(reveals).toHaveLength(1);
+ fireEvent.keyDown(separator(), {key: 'ArrowLeft'});
+ act(() => {
+ propsRegion?.resize(240);
+ });
+ expect(reveals).toHaveLength(1);
+ });
+
+ it('lands a running motion at once when the region goes away', () => {
+ const view = render(<PropsSplit />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ view.unmount();
+ expect(reveals[0].cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows no reveal for a pane the caller renders at the hook size alone', () => {
+ function HookOnly() {
+ const value = useResizable({defaultSize: 200, collapsible: true});
+ propsRegion = value;
+ return (
+ <div style={{display: 'flex'}}>
+ <div data-testid="pane" style={{width: value.size}}>
+ <button type="button">Inside</button>
+ </div>
+ <ResizeHandle resizable={value.props} label="Resize pane" />
+ </div>
+ );
+ }
+ render(<HookOnly />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(reveals).toHaveLength(0);
+ expect(pane()).not.toHaveAttribute('inert');
+ });
+
+ it("slides a pane that takes the hook's own props, from the edge facing its handle, measured before the collapse commits", () => {
+ for (const isReversed of [false, true]) {
+ reveals.length = 0;
+ const view = render(<PropsSplit isReversed={isReversed} />);
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ expect(separator()).toHaveAttribute('aria-valuetext', 'Collapsed');
+ expect(reveals).toHaveLength(1);
+ const [reveal] = reveals;
+ expect(reveal.edge).toBe(isReversed ? 'inline-start' : 'inline-end');
+ expect(reveal.target()).toBe(pane());
+ expect(reveal.measuredStyle).toContain('200px');
+ expect(reveal.animatedStyle).not.toContain('200px');
+ expect(reveal.animate).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ expect(reveals).toHaveLength(2);
+ expect(reveals[1].measuredStyle).not.toContain('200px');
+ expect(reveals[1].animatedStyle).toContain('200px');
+ view.unmount();
+ }
+ });
+
+ it("slides the pane of a region whose collapse() ran before the hook's first layout effect", () => {
+ /** A child's layout effect runs before its parent's. */
+ function EarlyCollapse({target}: {target: ResizableRegion}) {
+ const [initial] = useState(target);
+ useLayoutEffect(() => {
+ initial.collapse();
+ }, [initial]);
+ return null;
+ }
+ function EarlySplit() {
+ const value = useResizable({defaultSize: 200, collapsible: true});
+ propsRegion = value;
+ return (
+ <Layout
+ start={
+ <>
+ <LayoutPanel resizable={value.props} data-testid="pane">
+ <button type="button">Inside</button>
+ </LayoutPanel>
+ <ResizeHandle resizable={value.props} label="Resize pane" />
+ <EarlyCollapse target={value} />
+ </>
+ }
+ content={<LayoutContent>Main</LayoutContent>}
+ />
+ );
+ }
+ render(<EarlySplit />);
+ expect(separator()).toHaveAttribute('aria-valuetext', 'Collapsed');
+ reveals.length = 0;
+ act(() => {
+ propsRegion?.expand();
+ });
+ expect(reveals).toHaveLength(1);
+ expect(reveals[0].target()).toBe(pane());
+ });
+
+ it("plays every collapse and open for the hook's props, and nothing for a drag that reopens", () => {
+ render(<PropsSplit />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ act(() => {
+ propsRegion?.expand();
+ });
+ act(() => {
+ propsRegion?.collapse();
+ });
+ act(() => {
+ propsRegion?.resize(260);
+ });
+ fireEvent.doubleClick(separator());
+ fireEvent.keyDown(separator(), {key: 'ArrowRight'});
+ expect(reveals).toHaveLength(6);
+ for (const reveal of reveals) {
+ expect(reveal.edge).toBe('inline-end');
+ expect(reveal.measureBefore).toHaveBeenCalledTimes(1);
+ expect(reveal.animate).toHaveBeenCalledTimes(1);
+ }
+ fireEvent.pointerDown(grabZone(), {pointerId: 1, clientX: 300});
+ fireEvent.pointerMove(grabZone(), {pointerId: 1, clientX: 100});
+ expect(propsRegion?.isCollapsed).toBe(true);
+ expect(reveals).toHaveLength(7);
+ expect(reveals[6].animate).toHaveBeenCalledTimes(1);
+ fireEvent.pointerMove(grabZone(), {pointerId: 1, clientX: 340});
+ expect(propsRegion?.isCollapsed).toBe(false);
+ expect(reveals).toHaveLength(7);
+ expect(reveals[6].cancel).toHaveBeenCalled();
+ fireEvent.pointerUp(grabZone(), {pointerId: 1, clientX: 340});
+ });
+
+ it("plays a controlled isCollapsed change for the hook's props", () => {
+ const view = render(<PropsSplit config={{isCollapsed: false}} />);
+ view.rerender(<PropsSplit config={{isCollapsed: true}} />);
+ expect(pane().getAttribute('style') ?? '').not.toContain('200px');
+ view.rerender(<PropsSplit config={{isCollapsed: false}} />);
+ expect(reveals).toHaveLength(2);
+ expect(reveals.every(r => r.animate.mock.calls.length === 1)).toBe(true);
+ });
+
+ it('lands the motion of a pane that takes the hook props when the region goes away', () => {
+ const view = render(<PropsSplit />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ view.unmount();
+ expect(reveals[0].cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('shows no reveal for a hand-built ResizableProps object', () => {
+ render(<PropsSplit isHandBuilt />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(pane().getAttribute('style') ?? '').not.toContain('200px');
+ act(() => {
+ propsRegion?.expand();
+ });
+ expect(pane().getAttribute('style') ?? '').toContain('200px');
+ expect(reveals).toHaveLength(0);
+ });
+
+ it("measures a controlled change before the DOM changes and reports it in the commit of the parent's state", () => {
+ render(<ControlledSplit />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(reveals).toHaveLength(1);
+ expect(reveals[0].measuredStyle).toContain('200px');
+ expect(reveals[0].animatedStyle).not.toContain('200px');
+ expect(reveals[0].animate).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(separator(), {key: 'Enter'});
+ expect(reveals).toHaveLength(2);
+ expect(reveals[1].measuredStyle).not.toContain('200px');
+ expect(reveals[1].animatedStyle).toContain('200px');
+ for (const commit of commits) {
+ expect(commit.hook, JSON.stringify(commits)).toBe(commit.parent);
+ expect(commit.isOpenWidth, JSON.stringify(commits)).toBe(!commit.parent);
+ }
+ });
+
+ it('hands a LayoutPanel that replaces another to its region', () => {
+ const refView = render(<PropsSplit panelKey="first" />);
+ refView.rerender(<PropsSplit panelKey="second" />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(reveals).toHaveLength(1);
+ expect(reveals[0].target()).toBe(pane());
+ refView.unmount();
+
+ reveals.length = 0;
+ const propsView = render(<PropsSplit panelKey="first" />);
+ propsView.rerender(<PropsSplit panelKey="second" />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(reveals).toHaveLength(1);
+ expect(reveals[0].target()).toBe(pane());
+ });
+
+ it("shows no reveal for a LayoutPanel at the hook's size beside a handle given its props, which still holds it collapsed", () => {
+ for (const isReversed of [false, true]) {
+ reveals.length = 0;
+ const view = render(<PropsSplit isReversed={isReversed} isWidthPanel />);
+ act(() => {
+ propsRegion?.collapse();
+ });
+ expect(pane()).toHaveAttribute('inert');
+ act(() => {
+ propsRegion?.expand();
+ });
+ expect(reveals).toHaveLength(0);
+ view.unmount();
+ }
+ });
+});
diff --git a/packages/core/src/Resizable/resizablePane.ts b/packages/core/src/Resizable/resizablePane.ts
index b2591e36ae..3865c2433e 100644
--- a/packages/core/src/Resizable/resizablePane.ts
+++ b/packages/core/src/Resizable/resizablePane.ts
@@ -2,24 +2,53 @@
/**
* @file resizablePane.ts
- * @input A LayoutPanel's element, and the collapse state the ResizeHandle
- * beside it reports
- * @output The internal channel through which a LayoutPanel at a region's size
- * lends its element to the ResizeHandle beside it, and the ResizeHandle a
- * collapsing panel hands focus to
+ * @input A LayoutPanel's element, its commits and the width it renders; the
+ * collapse state its resize controller reports; motion/animatedLayout.ts
+ * @output The internal channel through which a LayoutPanel lends its element
+ * to the resize controller that sizes it. It also carries that controller's
+ * edge reveal and the ResizeHandle a collapsing panel hands focus to
* @position Internal to Resizable and Layout; no entry point exports it. No
* React, and no DOM work on import
*/
-/** What a LayoutPanel lends the ResizeHandle beside it. */
+import {
+ createAnimatedLayout,
+ reportLayoutEdge,
+ type LayoutEdge,
+} from '../motion/animatedLayout';
+import type {ResizableProps} from './useResizable';
+
+export type {LayoutEdge};
+
+/** The width a panel renders: pixels, a CSS length, or none. */
+export type RenderedPaneWidth = number | string | null | undefined;
+
+/** What the controller that sizes a pane hears from it. */
+export interface PaneListener {
+ /**
+ * In the commit that renders the pane at width 0, or away from it, before
+ * React changes the DOM.
+ */
+ beforeChange(toCollapsed: boolean): void;
+ /** After every commit of the pane. */
+ committed(): void;
+}
+
+/** What a LayoutPanel lends the resize controller that sizes it. */
export interface ResizablePane {
readonly element: HTMLElement;
+ /** The width the panel renders now. */
+ renderedWidth(): RenderedPaneWidth;
+ /** The panel's edge that faces its content, where its ResizeHandle sits. */
+ contentFacingEdge(): LayoutEdge;
/**
- * The handle says whether its region is collapsed, and which handle focus
- * inside the panel moves to as it collapses. The panel is then inert and
- * hidden from assistive technology while it is collapsed.
+ * The controller says whether its region is collapsed, and which handle
+ * focus inside the panel moves to as it collapses. The panel is then inert
+ * and hidden from assistive technology while it is collapsed.
*/
setCollapsed(isCollapsed: boolean, focusTarget: HTMLElement | null): void;
+ /** The controller that sizes the pane listens to it; null stops it. */
+ listen(listener: PaneListener | null): void;
}
const lent = new WeakMap<Element, ResizablePane>();
@@ -43,7 +72,7 @@ function notifyWatchers(): void {
/**
* Calls `listener` whenever a panel is lent beside a handle or taken back, so
- * a handle looks for its pane again. Returns the function that stops it.
+ * a factory looks for its pane again. Returns the function that stops it.
*/
export function watchResizablePanes(listener: () => void): () => void {
watchers.add(listener);
@@ -67,18 +96,26 @@ export function resizablePaneFor(
}
/**
- * Moves a handle's hold from `held` to `next`, and returns `next`. A pane the
- * handle no longer holds opens. The held pane takes the region's collapse
- * state, and focus inside it moves to `handle` as it collapses.
+ * Moves a region's hold from `held` to `next`, and returns `next`. A pane the
+ * region no longer sizes stops listening and opens. The held pane takes the
+ * region's collapse state, and focus inside it moves to `handle` as it
+ * collapses. A controller that sizes the pane passes its `listener`.
*/
export function handOverPane(
held: ResizablePane | null,
next: ResizablePane | null,
+ listener: PaneListener | null,
isCollapsed: boolean,
handle: HTMLElement | null,
): ResizablePane | null {
if (next !== held) {
+ if (listener != null) {
+ held?.listen(null);
+ }
held?.setCollapsed(false, null);
+ if (listener != null) {
+ next?.listen(listener);
+ }
}
next?.setCollapsed(isCollapsed, handle);
return next;
@@ -106,24 +143,103 @@ export function resizeHandleBeside(
return null;
}
+/**
+ * The hook's side of a region. The LayoutPanel that takes the hook's own
+ * props hands its pane here as it mounts. The factory the region has, now
+ * or later, follows it.
+ */
+export interface RegionPaneSlot {
+ /** From the LayoutPanel: its pane, or null as it goes. */
+ attach(pane: ResizablePane | null): void;
+ /** Calls `listener` with the pane now and whenever it changes. */
+ follow(listener: (pane: ResizablePane | null) => void): () => void;
+ /**
+ * From the ResizeHandle given the props: whether a pointer drags it, so a
+ * drag that reopens the pane plays nothing while a key step plays.
+ */
+ setPointerDragging(isDragging: boolean): void;
+ isPointerDragging(): boolean;
+}
+
+export function createRegionPaneSlot(): RegionPaneSlot {
+ let current: ResizablePane | null = null;
+ let isDragging = false;
+ const listeners = new Set<(pane: ResizablePane | null) => void>();
+ return {
+ setPointerDragging(next) {
+ isDragging = next;
+ },
+ isPointerDragging: () => isDragging,
+ attach(pane) {
+ if (pane === current) {
+ return;
+ }
+ current = pane;
+ for (const listener of [...listeners]) {
+ listener(pane);
+ }
+ },
+ follow(listener) {
+ listeners.add(listener);
+ listener(current);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ };
+}
+
+/**
+ * Kept off the exported `ResizableProps`, like the hook's collapse controls:
+ * a hand-built object has no region, so its panel never slides.
+ */
+const propsRegions = new WeakMap<ResizableProps, RegionPaneSlot>();
+
+/** The hook registers each `props` object it returns with its region. */
+export function registerPropsRegion(
+ props: ResizableProps,
+ slot: RegionPaneSlot,
+): void {
+ propsRegions.set(props, slot);
+}
+
+/** The region of the hook's own `props`, or undefined for a hand-built object. */
+export function regionOfProps(
+ props: ResizableProps,
+): RegionPaneSlot | undefined {
+ return propsRegions.get(props);
+}
+
/** LayoutPanel's side of the channel, one per panel. */
export interface ResizablePaneLink {
- /** For useSyncExternalStore: whether a handle holds the panel collapsed. */
+ /** For useSyncExternalStore: whether a controller holds the panel collapsed. */
readonly subscribe: (listener: () => void) => () => void;
readonly isCollapsed: () => boolean;
- /** The handle that named itself for focus to move to, if any. */
+ /** The handle the controller named for focus to move to, if any. */
focusTarget(): HTMLElement | null;
/**
- * From the panel's callback ref: its element, lent beside its handle for
- * the handle to find. Null takes it back.
+ * From the panel: its element, lent beside its handle for a factory to
+ * find (`isFoundBeside`). Or the element is handed to a region.
+ * Null takes it back. Returns the pane lent, if any.
*/
- attach(element: HTMLElement | null): void;
+ attach(
+ element: HTMLElement | null,
+ isFoundBeside: boolean,
+ ): ResizablePane | null;
+ /** Before the DOM changes in a commit that renders width 0, or away from it. */
+ beforeChange(toCollapsed: boolean): void;
+ /** After every commit of the panel, with the width it rendered and its content-facing edge. */
+ committed(width: RenderedPaneWidth, edge: LayoutEdge): void;
}
export function createResizablePaneLink(): ResizablePaneLink {
let isCollapsed = false;
let focusTarget: HTMLElement | null = null;
+ let width: RenderedPaneWidth = undefined;
+ let edge: LayoutEdge = 'inline-end';
let attached: ResizablePane | null = null;
+ let isAttachedBeside = false;
+ let listener: PaneListener | null = null;
const listeners = new Set<() => void>();
const setCollapsed = (next: boolean) => {
@@ -145,35 +261,117 @@ export function createResizablePaneLink(): ResizablePaneLink {
},
isCollapsed: () => isCollapsed,
focusTarget: () => focusTarget,
- attach(element) {
- if (attached?.element === element) {
- return;
+ attach(element, isFoundBeside) {
+ if (attached?.element === element && isAttachedBeside === isFoundBeside) {
+ return attached;
}
- const wasLent = attached != null;
+ const wasBeside = attached != null && isAttachedBeside;
if (attached != null && lent.get(attached.element) === attached) {
lent.delete(attached.element);
}
attached = null;
+ listener = null;
+ isAttachedBeside = isFoundBeside;
if (element == null) {
- // Taken back: no handle holds it collapsed any more.
+ // Taken back: no controller holds it collapsed any more.
focusTarget = null;
setCollapsed(false);
} else {
const pane: ResizablePane = {
element,
+ renderedWidth: () => width,
+ contentFacingEdge: () => edge,
setCollapsed(next, nextFocusTarget) {
if (attached === pane) {
focusTarget = nextFocusTarget;
setCollapsed(next);
}
},
+ listen(next) {
+ if (attached === pane) {
+ listener = next;
+ }
+ },
};
attached = pane;
- lent.set(element, pane);
+ if (isFoundBeside) {
+ lent.set(element, pane);
+ }
}
- if (wasLent || element != null) {
+ if (wasBeside || (element != null && isFoundBeside)) {
notifyWatchers();
}
+ return attached;
+ },
+ beforeChange(toCollapsed) {
+ listener?.beforeChange(toCollapsed);
+ },
+ committed(nextWidth, nextEdge) {
+ width = nextWidth;
+ edge = nextEdge;
+ listener?.committed();
+ },
+ };
+}
+
+/**
+ * The edge reveal a resize controller plays for its pane. It measures before
+ * the DOM changes and plays on the pane's first commit at a new size. It runs
+ * on the controller's own animated-layout handle over the pane's row, with no
+ * copy.
+ */
+export interface PaneReveal {
+ /** Before the DOM changes: measures `pane` for its reveal from `edge`. */
+ measure(pane: ResizablePane, edge: LayoutEdge): void;
+ /** After a commit of the pane: the one that renders its new size plays. */
+ committed(pane: ResizablePane): void;
+ /** Lands a measured or running reveal at once. */
+ land(): void;
+}
+
+type EdgeReport = ReturnType<typeof reportLayoutEdge>;
+
+export function createPaneReveal(getRow: () => Element | null): PaneReveal {
+ // Measured, waiting for the pane to render its new size; then played.
+ let pending: {
+ report: EdgeReport;
+ pane: ResizablePane;
+ widthBefore: RenderedPaneWidth;
+ } | null = null;
+ let played: EdgeReport | null = null;
+ const layout = createAnimatedLayout(getRow);
+
+ const land = () => {
+ pending?.report.cancel();
+ pending = null;
+ played?.cancel();
+ played = null;
+ };
+
+ return {
+ measure(pane, edge) {
+ // A measured change the pane never rendered is stale; a running one
+ // reverses from what it shows.
+ pending?.report.cancel();
+ pending = null;
+ const element = pane.element;
+ const report = reportLayoutEdge(layout, () => element, {edge});
+ report.measureBefore();
+ pending = {report, pane, widthBefore: pane.renderedWidth()};
+ },
+ committed(pane) {
+ if (
+ pending == null ||
+ pending.pane !== pane ||
+ pane.renderedWidth() === pending.widthBefore
+ ) {
+ return;
+ }
+ const {report} = pending;
+ pending = null;
+ played = report;
+ report.animate();
},
+ land,
};
}
diff --git a/packages/core/src/Resizable/useResizable.ts b/packages/core/src/Resizable/useResizable.ts
index ff41d69de9..76a9b91a54 100644
--- a/packages/core/src/Resizable/useResizable.ts
+++ b/packages/core/src/Resizable/useResizable.ts
@@ -31,6 +31,11 @@ import {
type ResizableController,
type ResizableSnapshot,
} from './createResizable';
+import {
+ createRegionPaneSlot,
+ registerPropsRegion,
+ type RegionPaneSlot,
+} from './resizablePane';
import {
DEFAULT_COLLAPSED_SIZE,
type ResizableDirection,
@@ -218,8 +223,10 @@ const EMPTY_SNAPS: number[] = [];
* factory's region through them.
*/
function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
+ // The region's pane: the LayoutPanel that takes these props hands it over.
+ const [regionSlot] = useState(createRegionPaneSlot);
const {getResizable, size, isCollapsed, snapshot, collapse, expand, resize} =
- useResizableController(config);
+ useResizableController(config, regionSlot);
// The region's side of the handle's gesture, read at each input, so a whole
// drag reaches the factory as it is now.
const model = useCallback(() => {
@@ -258,6 +265,9 @@ function useSingleResizable(config: UseResizableSingleConfig): ResizableRegion {
_isResizableProps: true,
};
collapseControls.set(props, {collapse, expand});
+ // The LayoutPanel that takes these props hands its pane to the region, and
+ // the ResizeHandle that takes them says when a pointer drags it.
+ registerPropsRegion(props, regionSlot);
// Without a configured maximum a measured extent stands in, only once it
// is a real measurement (an observed container, or the window).
if (snapshot.effectiveMaxPx != null) {
@@ -520,6 +530,7 @@ interface ResizableReading {
*/
function useResizableController(
options: CreateResizableOptions,
+ regionSlot?: RegionPaneSlot,
): ResizableReading {
const optionsRef = useRef(options);
optionsRef.current = options;
@@ -527,6 +538,19 @@ function useResizableController(
const [serverInitial] = useState(() =>
readInitialResizableState(options, 'server'),
);
+ // Every start of the factory, the commit's and an early call's, follows the
+ // region a LayoutPanel lends.
+ const start = useCallback(
+ (passed: CreateResizableOptions): ResizableController => {
+ const resizable = createResizableAs('useResizable', null, passed);
+ if (regionSlot != null) {
+ // destroy() stops following the region.
+ readResizableInternals(resizable)?.followRegion(regionSlot);
+ }
+ return resizable;
+ },
+ [regionSlot],
+ );
// The hook keeps one factory. After an unmount or an `<Activity>` hide, the
// same factory takes the page back (`resume`).
const follow = useCallback(() => {
@@ -536,9 +560,9 @@ function useResizableController(
return;
}
const passed = optionsRef.current;
- const resizable = createResizableAs('useResizable', null, passed);
+ const resizable = start(passed);
slot.set({resizable, passed});
- }, [slot]);
+ }, [slot, start]);
useIsomorphicLayoutEffect(() => {
follow();
});
@@ -613,11 +637,11 @@ function useResizableController(
return entry.resizable;
}
const passed = optionsRef.current;
- const resizable = createResizableAs('useResizable', null, passed);
+ const resizable = start(passed);
readResizableInternals(resizable)?.suspend();
slot.set({resizable, passed});
return resizable;
- }, [slot]);
+ }, [slot, start]);
const collapse = useCallback(() => {
ensureResizable().collapse();
}, [ensureResizable]);
diff --git a/packages/core/src/motion/animatedLayout.boundary.test.ts b/packages/core/src/motion/animatedLayout.boundary.test.ts
index 040c11428b..176b909778 100644
--- a/packages/core/src/motion/animatedLayout.boundary.test.ts
+++ b/packages/core/src/motion/animatedLayout.boundary.test.ts
@@ -4,12 +4,14 @@
* @file animatedLayout.boundary.test.ts
* @input The source of motion/animatedLayout.ts, the core entry points and
* every core source file that imports the module
- * @output The source boundary check `architecture:react-component-runtime`
- * INV12 asks for: the module animates no layout property, its walk reaches
+ * @output The source boundary check that
+ * `architecture:react-component-runtime` INV12 asks for. The module
+ * animates no layout property. Its walk reaches
* elements only through parentElement and the element siblings on either
- * side (and firstElementChild under `display: contents`), stopping at the
- * band around the visible part, the reporting functions are
- * not public, and only the hook and the adopting components use it
+ * side, and firstElementChild under `display: contents`. It stops at the
+ * band around the visible part. The reporting functions are not public.
+ * Only the hook, the adopting components and the resize controller's edge
+ * reveal use it
* @position Testing; the real-browser half of INV12's verification is in
* __tests__/animatedLayout.interaction.browser.spec.ts
*/
@@ -162,6 +164,7 @@ describe('architecture:react-component-runtime INV12 source boundary', () => {
'Collapsible/Collapsible.tsx',
'List/List.tsx',
'List/listLayoutUpdates.ts',
+ 'Resizable/resizablePane.ts',
'SideNav/railMotion.ts',
'Table/plugins/rowExpansion/useTableRowExpansion.tsx',
'TreeList/TreeList.tsx',
diff --git a/packages/core/src/motion/animatedLayout.edge.test.ts b/packages/core/src/motion/animatedLayout.edge.test.ts
index 4228f791da..0b3ac3c625 100644
--- a/packages/core/src/motion/animatedLayout.edge.test.ts
+++ b/packages/core/src/motion/animatedLayout.edge.test.ts
@@ -6,16 +6,17 @@
* Element.animate (its KeyframeEffect's `setKeyframes` and `updateTiming`
* included, and a current time read off a stubbed document timeline) and
* stubbed layout rectangles (jsdom lays nothing out)
- * @output Checks `spec:AST-105` FR9's edge reveal: the one-state reveal and
- * conceal from each edge, left to right and right to left; a reversal that
- * starts from what shows; the moving edge riding the glide of the content
- * after it, through a reversal too; and the two-state form, which holds the
- * old state as one copy while the edge rides a gliding element, the element
- * raised above the copy while it conceals, a reversal starting from the
- * extent it shows, and Reduce Motion by pointer; and a resized element's
- * reveal with no copy (a resize controller's pane): held at the extent it
- * was laid out at while it conceals, its edge's margin freeing the
- * difference, clipped to its new extent, riding the content beside it
+ * @output Checks `spec:AST-105` FR9's edge reveal. The one-state reveal and
+ * conceal play from each edge, left to right and right to left. A reversal
+ * starts from what shows. The moving edge rides the glide of the content
+ * after it, through a reversal too. The two-state form holds the old state
+ * as one copy while the edge rides a gliding element. That element stays
+ * above the copy while it conceals, a reversal starts from the extent it
+ * shows, and Reduce Motion goes by pointer. A resized element's reveal (a
+ * resize controller's pane) uses no copy. While it conceals, it holds the
+ * extent it was laid out at, and its edge's margin frees the difference.
+ * Its padding, overflow and scroll offset stay as laid out. It is clipped
+ * to its new extent and rides the content beside it
* @position Testing; the real geometry is proven in
* __tests__/animatedLayout.interaction.browser.spec.ts and, for the SideNav
* rail's two-state form, SideNav's rail-motion specs
@@ -643,11 +644,15 @@ function paneSetup({
handle,
pane: paneEl,
grip,
- /** Collapses or opens the pane, as the controller does, around the report. */
- resize(next: number, edge: LayoutEdge) {
+ /**
+ * Collapses or opens the pane, as the controller does, around the report.
+ * `commit` changes what else the new size changes in the same commit.
+ */
+ resize(next: number, edge: LayoutEdge, commit?: () => void) {
const report = reportLayoutEdge(handle, () => paneEl, {edge});
report.measureBefore();
width = next;
+ commit?.();
report.animate();
return report;
},
@@ -678,6 +683,48 @@ describe('the edge reveal of a resized element, with no copy (spec:AST-105 FR9)'
expect(pane.style.getPropertyValue('margin-inline-end')).toBe('');
});
+ it('keeps the padding and overflow it was laid out with while it conceals, and puts back its own once the motion ends', () => {
+ const {pane, resize} = paneSetup();
+ pane.style.setProperty('padding-inline-start', '16px');
+ pane.style.setProperty('padding-inline-end', '16px');
+ pane.style.setProperty('overflow-y', 'auto');
+ resize(0, 'inline-end', () => {
+ // A LayoutPanel at width 0 drops its padding and stops scrolling.
+ pane.style.setProperty('padding-inline-start', '0px');
+ pane.style.setProperty('padding-inline-end', '0px');
+ pane.style.setProperty('overflow-y', 'clip');
+ });
+ expect(pane.style.getPropertyValue('padding-inline-start')).toBe('16px');
+ expect(pane.style.getPropertyValue('padding-inline-end')).toBe('16px');
+ expect(pane.style.getPropertyValue('overflow-y')).toBe('auto');
+ clipsOf(pane)[0].finish?.();
+ expect(pane.style.getPropertyValue('padding-inline-start')).toBe('0px');
+ expect(pane.style.getPropertyValue('padding-inline-end')).toBe('0px');
+ expect(pane.style.getPropertyValue('overflow-y')).toBe('clip');
+ });
+
+ it('keeps the scroll offset it was laid out at while it conceals, and a reveal that reverses it scrolls back there', () => {
+ const {pane, resize} = paneSetup();
+ let scrollTop = 120;
+ Object.defineProperty(pane, 'scrollTop', {
+ configurable: true,
+ get: () => scrollTop,
+ set: (value: number) => {
+ scrollTop = value;
+ },
+ });
+ // A pane that stops scrolling in the commit loses its offset.
+ resize(48, 'inline-end', () => {
+ scrollTop = 0;
+ });
+ expect(scrollTop).toBe(120);
+ // Releasing the hold to reverse loses it again.
+ resize(260, 'inline-end', () => {
+ scrollTop = 0;
+ });
+ expect(scrollTop).toBe(120);
+ });
+
it('conceals entirely to a size of 0', () => {
const {pane, resize} = paneSetup();
resize(0, 'inline-end');
diff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.ts
index d402254e26..7f2d386324 100644
--- a/packages/core/src/motion/animatedLayout.ts
+++ b/packages/core/src/motion/animatedLayout.ts
@@ -3354,12 +3354,56 @@ const HOLD_PROPERTIES = {
],
} as const;
+/**
+ * The inside of an element as it was laid out: its padding along an axis, its
+ * overflow and its scroll offset. A size change can change them in the same
+ * commit, as a LayoutPanel at width 0 drops its padding and stops scrolling.
+ */
+interface LaidOutInside {
+ /** Its padding at the axis's start and end. */
+ readonly gutters: readonly [string, string];
+ /** Its overflow across and down. */
+ readonly overflow: readonly [string, string];
+ /** Its scroll offset across and down. */
+ readonly scroll: readonly [number, number];
+}
+
+function insideOf(
+ element: HTMLElement,
+ axis: 'inline' | 'block',
+): LaidOutInside {
+ const style = getComputedStyle(element);
+ return {
+ gutters: [
+ style.getPropertyValue(`padding-${axis}-start`),
+ style.getPropertyValue(`padding-${axis}-end`),
+ ],
+ overflow: [
+ style.getPropertyValue('overflow-x'),
+ style.getPropertyValue('overflow-y'),
+ ],
+ scroll: [element.scrollLeft, element.scrollTop],
+ };
+}
+
+function restoreScroll(element: HTMLElement, inside: LaidOutInside): void {
+ const [across, down] = inside.scroll;
+ if (element.scrollLeft !== across) {
+ element.scrollLeft = across;
+ }
+ if (element.scrollTop !== down) {
+ element.scrollTop = down;
+ }
+}
+
/**
* Holds `element` at `extent` own px along `edge`'s axis while it conceals to
* `keep`, freeing the difference by the margin on that edge's side, so what
- * lies beyond the edge stays where the new size puts it. Returns what puts
- * back every value it set, or null when no margin frees it (the content on
- * that side did not stay put), having set nothing.
+ * lies beyond the edge stays where the new size puts it. Its padding,
+ * overflow and scroll offset stay as `inside` measured them, so nothing in it
+ * moves while it is clipped. Returns what puts back every value it set.
+ * When no margin frees it, as the content on that side did not stay put, it
+ * sets nothing and returns null.
*/
function holdExtent(
element: HTMLElement,
@@ -3367,10 +3411,21 @@ function holdExtent(
edge: LayoutEdge,
extent: number,
keep: number,
+ inside: LaidOutInside,
): (() => void) | null {
const axis = edge.startsWith('inline') ? 'inline' : 'block';
const margin = `margin-${edge}`;
- const properties = [...HOLD_PROPERTIES[axis], margin];
+ const insideProperties = [
+ [`padding-${axis}-start`, inside.gutters[0]],
+ [`padding-${axis}-end`, inside.gutters[1]],
+ ['overflow-x', inside.overflow[0]],
+ ['overflow-y', inside.overflow[1]],
+ ] as const;
+ const properties = [
+ ...HOLD_PROPERTIES[axis],
+ margin,
+ ...insideProperties.map(([property]) => property),
+ ];
const prior = properties.map(
property =>
[
@@ -3401,6 +3456,11 @@ function holdExtent(
element.style.setProperty('flex-basis', 'auto', 'important');
element.style.setProperty('flex-grow', '0', 'important');
element.style.setProperty('flex-shrink', '0', 'important');
+ for (const [property, value] of insideProperties) {
+ if (value !== '') {
+ element.style.setProperty(property, value, 'important');
+ }
+ }
element.style.setProperty(margin, `${keep - extent}px`, 'important');
if (beyond != null && before != null) {
// One correction from the measured result (a gap, the element's own
@@ -3426,6 +3486,7 @@ function holdExtent(
return null;
}
}
+ restoreScroll(element, inside);
return restore;
}
@@ -3439,7 +3500,9 @@ function holdExtent(
* the extent the element showed. A smaller one conceals: the element is held
* at the extent it was laid out at, the difference freed by the margin on
* that edge's side so the content beyond it stays where the new size puts it,
- * and clipped down to its new extent; the hold goes when the motion ends. The
+ * and clipped down to its new extent; the hold goes when the motion ends.
+ * Its padding, overflow and scroll offset stay as laid out while it is held,
+ * so nothing inside it jumps when the new size changes them. The
* moving edge rides the glide of the content on that side, frame by frame,
* and a change made while it runs starts from the extent it shows. It slides:
* nothing fades. Under Reduce Motion with a coarse primary pointer a reveal
@@ -3456,7 +3519,13 @@ export function reportLayoutEdge(
* What the element showed, its laid-out extent and its box, before the
* change.
*/
- let measured: {shown: number; box: number; rect: DOMRect} | null = null;
+ let measured: {
+ shown: number;
+ box: number;
+ rect: DOMRect;
+ inside: LaidOutInside;
+ } | null = null;
+ const axis = edge.startsWith('inline') ? 'inline' : 'block';
const release = (element: HTMLElement | null) => {
if (element == null) {
return;
@@ -3472,12 +3541,15 @@ export function reportLayoutEdge(
const running = resizeReveals.get(element);
const elapsed = Number(running?.animation?.currentTime);
const rect = element.getBoundingClientRect();
+ // A running conceal holds the inside as it was laid out.
+ const inside = insideOf(element, axis);
measured =
running == null
? {
shown: extentOf(element, edge),
box: extentOf(element, edge),
rect,
+ inside,
}
: {
shown: running.shownAt(
@@ -3485,6 +3557,7 @@ export function reportLayoutEdge(
),
box: running.box,
rect,
+ inside,
};
running?.release();
}
@@ -3498,6 +3571,8 @@ export function reportLayoutEdge(
if (handle == null || element == null || before == null) {
return;
}
+ // A conceal released to reverse can drop the scroll offset.
+ restoreScroll(element, before.inside);
const area = areaOf(handle, element);
if (area == null) {
return;
@@ -3538,7 +3613,7 @@ export function reportLayoutEdge(
// the one it was laid out at, held while it runs.
const box = isConceal ? Math.max(before.box, before.shown) : after;
const restore = isConceal
- ? holdExtent(element, area, edge, box, after)
+ ? holdExtent(element, area, edge, box, after, before.inside)
: () => {};
if (restore == null) {
return;