An open source design system that's fully customizable and agent ready
TypeScript
fix(ResizeHandle): keep the drag when the cursor crosses an embedded frame (#5297)
Cindy Zhang560d7333c384
diff --git a/.changeset/resize-handle-pointer-capture.md b/.changeset/resize-handle-pointer-capture.mdnew file mode 100644index 0000000000..50521391ac--- /dev/null+++ b/.changeset/resize-handle-pointer-capture.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] ResizeHandle: a drag survives the cursor crossing an embedded frame. The handle listened for `pointermove`/`pointerup` on `window` without taking pointer capture, so the browser hit-tested every later event — and the moment the cursor entered an `<iframe>` inside the resizable region the events went to the guest document instead. Measured in Chromium, the host received 0 of 25 pointermoves once the cursor was over the frame, the panel stopped tracking, and the `pointerup` was never heard: the handle stayed armed with `data-resizing` set and the body cursor/`user-select` overrides stuck. The drag now takes pointer capture on the grab zone on `pointerdown`, so the whole gesture is delivered there whatever is underneath, and the move/up/cancel handlers sit on that element rather than on `window` (the same shape as Slider and BottomSheet).++@cixzhangdiff --git a/apps/storybook/stories/Resizable.stories.tsx b/apps/storybook/stories/Resizable.stories.tsxindex b62e6159b3..2953412f09 100644--- a/apps/storybook/stories/Resizable.stories.tsx+++ b/apps/storybook/stories/Resizable.stories.tsx@@ -157,9 +157,7 @@ export const Collapsible: Story = {<Text><span {...stylex.props(ps.sz)}>{sidebar.size}px</span></Text>- <Text>- Double-click handle or press Enter to collapse.- </Text>+ <Text>Double-click handle or press Enter to collapse.</Text></Stack></LayoutPanel>)}@@ -288,9 +286,7 @@ export const SnapPoints: Story = {<Text><span {...stylex.props(ps.sz)}>{sidebar.size}px</span></Text>- <Text>- Snaps to 56 \u00b7 160 \u00b7 260 \u00b7 400px.- </Text>+ <Text>Snaps to 56 \u00b7 160 \u00b7 260 \u00b7 400px.</Text></Stack>)}</LayoutPanel>@@ -504,8 +500,8 @@ export const WithAppShell: Story = {{nav.isCollapsed ? 'Collapsed' : 'Expanded'}</Text><Text>- SideNav width driven by useResizable. Double-click handle- to collapse.+ SideNav width driven by useResizable. Double-click handle to+ collapse.</Text></Stack></LayoutContent>@@ -515,3 +511,54 @@ export const WithAppShell: Story = {);},};++/**+ * Panel whose content is an embedded frame. The drag must survive the cursor+ * crossing the frame: pointer events over a frame are dispatched into the+ * guest document, so a drag that stays armed only while the host keeps+ * receiving them dies mid-gesture here.+ */+export const WithEmbeddedFrame: Story = {+ render: () => {+ const sidebar = useResizable({+ defaultSize: 200,+ minSizePx: 120,+ maxSizePx: 520,+ });+ return (+ <div {...stylex.props(ps.shell)}>+ <Layout+ height="fill"+ start={+ <>+ <LayoutPanel width={sidebar.size} hasDivider={false}>+ <Stack gap={2}>+ <Heading level={4}>Sidebar</Heading>+ <Text>+ <span {...stylex.props(ps.sz)}>{sidebar.size}px</span>+ </Text>+ <Text>Drag right, across the preview, and back.</Text>+ </Stack>+ </LayoutPanel>+ <ResizeHandle+ direction="horizontal"+ hasDivider+ resizable={sidebar.props}+ label="Resize sidebar"+ />+ </>+ }+ content={+ <LayoutContent padding={0}>+ <iframe+ title="Preview"+ srcDoc="<!doctype html><body style='margin:0;font:14px system-ui;display:grid;place-items:center;height:100vh;background:#eef'>Embedded preview</body>"+ style={{width: '100%', height: '100%', border: 0}}+ />+ </LayoutContent>+ }+ />+ </div>+ );+ },+};diff --git a/packages/core/src/Resizable/ResizeHandle.test.tsx b/packages/core/src/Resizable/ResizeHandle.test.tsxindex 938a446742..40424ed137 100644--- a/packages/core/src/Resizable/ResizeHandle.test.tsx+++ b/packages/core/src/Resizable/ResizeHandle.test.tsx@@ -44,6 +44,27 @@ function getSeparator(): HTMLElement {return screen.getByRole('separator');}+function getHitArea(): HTMLElement {+ return getSeparator().firstElementChild as HTMLElement;+}++/** Stub region props, so drag assertions read the calls directly. */+function makeResizable(): ResizableProps {+ return {+ _size: 200,+ _isCollapsed: false,+ _onResizeStart: vi.fn(),+ _onResizeMove: vi.fn(),+ _onResizeEnd: vi.fn(),+ _minSizePx: 100,+ _maxSizePx: 400,+ _snaps: [],+ _collapsedSize: 40,+ _collapsible: false,+ _isResizableProps: true,+ };+}+describe('ResizeHandle', () => {// --- ARIA wiring ---@@ -213,37 +234,86 @@ describe('ResizeHandle', () => {// --- Drag listener lifecycle ---- it('stops driving the region and releases window listeners when unmounted mid-drag', () => {- const resizable: ResizableProps = {- _size: 200,- _isCollapsed: false,- _onResizeStart: vi.fn(),- _onResizeMove: vi.fn(),- _onResizeEnd: vi.fn(),- _minSizePx: 100,- _maxSizePx: 400,- _snaps: [],- _collapsedSize: 40,- _collapsible: false,- _isResizableProps: true,- };+ it('takes pointer capture on the grab zone when a drag starts', () => {+ const resizable = makeResizable();+ render(<ResizeHandle resizable={resizable} label="Resize" />);+ const hitArea = getHitArea();+ const setPointerCapture = vi.fn();+ Object.defineProperty(hitArea, 'setPointerCapture', {+ value: setPointerCapture,+ configurable: true,+ });++ fireEvent.pointerDown(hitArea, {pointerId: 7, clientX: 0, clientY: 0});+ // Capture keeps the rest of the gesture on this element, so an embedded+ // frame under the cursor can't swallow the drag into its own document.+ expect(setPointerCapture).toHaveBeenCalledWith(7);+ });++ it('drives and ends the drag from events on the grab zone', () => {+ const resizable = makeResizable();+ render(<ResizeHandle resizable={resizable} label="Resize" />);+ const hitArea = getHitArea();++ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 30, clientY: 0});+ expect(resizable._onResizeMove).toHaveBeenLastCalledWith(30);+ fireEvent.pointerUp(hitArea, {pointerId: 1, clientX: 30, clientY: 0});+ expect(resizable._onResizeEnd).toHaveBeenCalledTimes(1);++ // The drag is over: a later move must not resize anything.+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 90, clientY: 0});+ expect(resizable._onResizeMove).toHaveBeenCalledTimes(1);+ expect(document.body.style.cursor).toBe('');+ expect(document.body.style.userSelect).toBe('');+ });++ it('ignores moves from a pointer that does not own the drag', () => {+ const resizable = makeResizable();+ render(<ResizeHandle resizable={resizable} label="Resize" />);+ const hitArea = getHitArea();++ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});+ fireEvent.pointerMove(hitArea, {pointerId: 2, clientX: 30, clientY: 0});+ expect(resizable._onResizeMove).not.toHaveBeenCalled();+ });++ it.each([+ ['pointercancel', fireEvent.pointerCancel],+ ['lostpointercapture', fireEvent.lostPointerCapture],+ ])('ends the drag on %s without signalling a resize end', (_name, fire) => {+ const resizable = makeResizable();+ render(<ResizeHandle resizable={resizable} label="Resize" />);+ const hitArea = getHitArea();++ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});+ fire(hitArea, {pointerId: 1});+ expect(resizable._onResizeEnd).not.toHaveBeenCalled();+ expect(document.body.style.cursor).toBe('');+ expect(document.body.style.userSelect).toBe('');++ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 30, clientY: 0});+ expect(resizable._onResizeMove).not.toHaveBeenCalled();+ });++ it('stops driving the region and releases body styles when unmounted mid-drag', () => {+ const resizable = makeResizable();const {unmount} = render(<ResizeHandle resizable={resizable} label="Resize" />,);- const separator = screen.getByRole('separator');- const hitArea = separator.firstElementChild as HTMLElement;+ const hitArea = getHitArea();// Start a drag and confirm moves reach the region.- fireEvent.pointerDown(hitArea, {clientX: 0, clientY: 0});+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});expect(resizable._onResizeStart).toHaveBeenCalledTimes(1);- fireEvent.pointerMove(window, {clientX: 10, clientY: 0});+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 10, clientY: 0});expect(resizable._onResizeMove).toHaveBeenCalledTimes(1);- // Unmount mid-drag: the window listeners must be torn down, so further- // pointer moves no longer resize the (still-mounted) region, and the- // body cursor/user-select overrides are released.+ // Unmounting removes the capturing element, which implicitly releases the+ // pointer and takes its listeners with it. The body cursor/user-select+ // overrides live outside the element, so they must be released here.unmount();- fireEvent.pointerMove(window, {clientX: 50, clientY: 0});+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 50, clientY: 0});expect(resizable._onResizeMove).toHaveBeenCalledTimes(1);expect(document.body.style.cursor).toBe('');expect(document.body.style.userSelect).toBe('');@@ -252,43 +322,18 @@ describe('ResizeHandle', () => {// --- RTL pointer-drag direction ---it('drives the region with the raw pointer delta under LTR', () => {- const resizable: ResizableProps = {- _size: 200,- _isCollapsed: false,- _onResizeStart: vi.fn(),- _onResizeMove: vi.fn(),- _onResizeEnd: vi.fn(),- _minSizePx: 100,- _maxSizePx: 400,- _snaps: [],- _collapsedSize: 40,- _collapsible: false,- _isResizableProps: true,- };+ const resizable = makeResizable();render(<ResizeHandle resizable={resizable} label="Resize" />);- const hitArea = screen.getByRole('separator')- .firstElementChild as HTMLElement;+ const hitArea = getHitArea();- fireEvent.pointerDown(hitArea, {clientX: 0, clientY: 0});+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});// Pointer moves +40px to the right → panel grows by +40 under LTR.- fireEvent.pointerMove(window, {clientX: 40, clientY: 0});+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 40, clientY: 0});expect(resizable._onResizeMove).toHaveBeenLastCalledWith(40);});it('inverts the pointer delta under RTL so dragging resizes intuitively', () => {- const resizable: ResizableProps = {- _size: 200,- _isCollapsed: false,- _onResizeStart: vi.fn(),- _onResizeMove: vi.fn(),- _onResizeEnd: vi.fn(),- _minSizePx: 100,- _maxSizePx: 400,- _snaps: [],- _collapsedSize: 40,- _collapsible: false,- _isResizableProps: true,- };+ const resizable = makeResizable();// Under RTL the start panel sits on the RIGHT, so a pointer move to the// right (+clientX) must SHRINK it — the delta is inverted. The handle reads// its own computed `direction` via getRTLMultiplier(); jsdom doesn't resolve@@ -308,9 +353,9 @@ describe('ResizeHandle', () => {return realGetComputedStyle(el, pseudo ?? undefined);});- fireEvent.pointerDown(hitArea, {clientX: 0, clientY: 0});+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 0, clientY: 0});// Same +40px physical move as LTR, but mirrored → −40 delta under RTL.- fireEvent.pointerMove(window, {clientX: 40, clientY: 0});+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 40, clientY: 0});expect(resizable._onResizeMove).toHaveBeenLastCalledWith(-40);gcsSpy.mockRestore();diff --git a/packages/core/src/Resizable/ResizeHandle.tsx b/packages/core/src/Resizable/ResizeHandle.tsxindex a161b65ef1..46e7cd9023 100644--- a/packages/core/src/Resizable/ResizeHandle.tsx+++ b/packages/core/src/Resizable/ResizeHandle.tsx@@ -21,6 +21,15 @@* While the panel is collapsed, aria-valuenow is clamped to aria-valuemin* (a value below the minimum is invalid per WCAG 4.1.2) and a localized* "Collapsed" aria-valuetext announces the real state.+ *+ * Dragging takes pointer capture on the grab zone, so the rest of the gesture+ * is delivered to that element instead of being hit-tested against whatever+ * the cursor happens to be over. A resizable region that contains an embedded+ * frame otherwise loses the drag the moment the cursor crosses the frame: the+ * events go to the guest document, and a listener on the host window never+ * hears them again. Captured events are delivered to the capturing element,+ * so the move/up/cancel handlers live on the grab zone (as in Slider), not on+ * window.*/import {useCallback, useEffect, useRef, useState} from 'react';@@ -85,6 +94,21 @@ function hitAreaBiasDir(return effectiveSide === 'start' ? -1 : 1;}+/**+ * Drag feedback lives on `<body>`, not on the handle: the pointer spends the+ * drag off the handle, over whatever the panels contain, and the resize cursor+ * has to hold there. Module scope so the writes stay outside the component.+ */+function applyBodyDragStyles(isHorizontal: boolean): void {+ document.body.style.cursor = isHorizontal ? 'col-resize' : 'row-resize';+ document.body.style.userSelect = 'none';+}++function clearBodyDragStyles(): void {+ document.body.style.cursor = '';+ document.body.style.userSelect = '';+}+const styles = stylex.create({handle: {position: 'relative',@@ -369,9 +393,14 @@ export function ResizeHandle({const t = useTranslator();const label = labelFromProps ?? t('@astryx.resizable.handle.label');const handleRef = useRef<HTMLDivElement>(null);- // Removes the in-flight drag's window listeners (and resets body styles).- // Held in a ref so unmount can tear down a drag that never got a pointerup.- const dragCleanupRef = useRef<(() => void) | null>(null);+ // The pointer that owns the in-flight drag, plus the values its deltas are+ // measured against. A ref so moves don't re-render, and so unmount can tell+ // a live drag from a finished one.+ const dragRef = useRef<{+ pointerId: number;+ startPos: number;+ rtl: number;+ } | null>(null);const [isDragging, setIsDragging] = useState(false);const [isHovered, setIsHovered] = useState(false);const [isFocused, setIsFocused] = useState(false);@@ -398,50 +427,70 @@ export function ResizeHandle({const isInteracting = isHovered || isFocused;// --- Pointer drag ---+ const clearDrag = useCallback(() => {+ dragRef.current = null;+ setIsDragging(false);+ clearBodyDragStyles();+ }, []);+const handlePointerDown = useCallback(- (e: React.PointerEvent) => {- if (isDisabled || !resizable) {+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (isDisabled || !resizable || dragRef.current) {return;}e.preventDefault();e.stopPropagation();+ // Take the pointer for the whole gesture. Without capture the browser+ // re-hit-tests every move, so a frame anywhere under the drag path+ // swallows the rest of it into the guest document.+ e.currentTarget.setPointerCapture?.(e.pointerId);+ dragRef.current = {+ pointerId: e.pointerId,+ startPos: isHorizontal ? e.clientX : e.clientY,+ rtl: isHorizontal ? getRTLMultiplier() : 1,+ };setIsDragging(true);resizable._onResizeStart();- const startPos = isHorizontal ? e.clientX : e.clientY;- const rtl = isHorizontal ? getRTLMultiplier() : 1;- document.body.style.cursor = isHorizontal ? 'col-resize' : 'row-resize';- document.body.style.userSelect = 'none';+ applyBodyDragStyles(isHorizontal);+ },+ [isDisabled, resizable, isHorizontal, getRTLMultiplier],+ );- const onMove = (ev: PointerEvent) => {- const currentPos = isHorizontal ? ev.clientX : ev.clientY;- const delta = (currentPos - startPos) * rtl * sign;- resizable._onResizeMove(delta);- };- const onUp = () => {- cleanup();- setIsDragging(false);- resizable._onResizeEnd();- document.body.style.cursor = '';- document.body.style.userSelect = '';- };- const onCancel = () => {- cleanup();- setIsDragging(false);- document.body.style.cursor = '';- document.body.style.userSelect = '';- };- function cleanup() {- window.removeEventListener('pointermove', onMove);- window.removeEventListener('pointerup', onUp);- window.removeEventListener('pointercancel', onCancel);- dragCleanupRef.current = null;+ const handlePointerMove = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ const drag = dragRef.current;+ if (!drag || drag.pointerId !== e.pointerId || !resizable) {+ return;}- window.addEventListener('pointermove', onMove);- window.addEventListener('pointerup', onUp);- window.addEventListener('pointercancel', onCancel);- dragCleanupRef.current = cleanup;+ const currentPos = isHorizontal ? e.clientX : e.clientY;+ resizable._onResizeMove((currentPos - drag.startPos) * drag.rtl * sign);},- [isDisabled, resizable, isHorizontal, getRTLMultiplier, sign],+ [resizable, isHorizontal, sign],+ );++ const handlePointerUp = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (dragRef.current?.pointerId !== e.pointerId) {+ return;+ }+ clearDrag();+ resizable?._onResizeEnd();+ },+ [clearDrag, resizable],+ );++ // Serves pointercancel and lostpointercapture alike: an interrupted drag+ // ends without signalling a resize end. lostpointercapture also fires on the+ // implicit release after every pointerup/pointercancel, by which point the+ // drag is already cleared and this is a no-op.+ const cancelDrag = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (dragRef.current?.pointerId !== e.pointerId) {+ return;+ }+ clearDrag();+ },+ [clearDrag],);// --- Keyboard ---@@ -515,16 +564,16 @@ export function ResizeHandle({}, [isDisabled, resizable]);// --- Cleanup on unmount ---- // A drag in flight when the handle unmounts never gets its pointerup, so- // tear down the window listeners here too — otherwise every pointermove- // keeps driving the (still-mounted) region's resize state after the handle- // is gone, and the body cursor/user-select overrides stick.+ // Removing the grab zone implicitly releases its captured pointer and takes+ // its listeners with it, so an in-flight drag stops driving the region on+ // its own. The body cursor/user-select overrides are not on the element,+ // though, so they have to be released here or they stick after the handle+ // is gone.useEffect(() => {return () => {- if (dragCleanupRef.current) {- dragCleanupRef.current();- document.body.style.cursor = '';- document.body.style.userSelect = '';+ if (dragRef.current) {+ dragRef.current = null;+ clearBodyDragStyles();}};}, []);@@ -617,6 +666,10 @@ export function ResizeHandle({isDisabled && styles.disabled,)}onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerUp}+ onPointerCancel={cancelDrag}+ onLostPointerCapture={cancelDrag}onPointerEnter={() => setIsHovered(true)}onPointerLeave={() => {if (!isDragging) {diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsxindex 409f3dd20d..00dc8600c0 100644--- a/packages/core/src/SideNav/SideNav.test.tsx+++ b/packages/core/src/SideNav/SideNav.test.tsx@@ -1019,9 +1019,9 @@ describe('SideNav resizable', () => {const hitArea = handle.firstElementChild as HTMLElement;act(() => {- fireEvent.pointerDown(hitArea, {clientX: 260});- fireEvent.pointerMove(document, {clientX: 310});- fireEvent.pointerUp(document, {clientX: 310});+ fireEvent.pointerDown(hitArea, {pointerId: 1, clientX: 260});+ fireEvent.pointerMove(hitArea, {pointerId: 1, clientX: 310});+ fireEvent.pointerUp(hitArea, {pointerId: 1, clientX: 310});});expect(handleWidthChange).toHaveBeenCalledTimes(1);