An open source design system that's fully customizable and agent ready
TypeScript
refactor(Resizable): ResizeHandle's input moves into resizeGesture.ts (#9680)
Christopher Chedeau30bae0c89b08
diff --git a/.changeset/resize-handle-input-module.md b/.changeset/resize-handle-input-module.mdnew file mode 100644index 0000000000..06a957522b--- /dev/null+++ b/.changeset/resize-handle-input-module.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] `ResizeHandle`'s pointer drag, keys and double-click move into one internal module, with no behavior change.++@vjeuxdiff --git a/.changeset/resize-handle-resizable-removed-mid-drag.md b/.changeset/resize-handle-resizable-removed-mid-drag.mdnew file mode 100644index 0000000000..987f06b69f--- /dev/null+++ b/.changeset/resize-handle-resizable-removed-mid-drag.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A `ResizeHandle` whose `resizable` prop goes away in the middle of a drag now ends the drag as it does on unmount: it releases the page's resize cursor and text selection, and the region hears that its gesture is over.++@vjeuxdiff --git a/packages/core/src/Resizable/ResizeHandle.test.tsx b/packages/core/src/Resizable/ResizeHandle.test.tsxindex 3a9c52748c..a4b93f3396 100644--- a/packages/core/src/Resizable/ResizeHandle.test.tsx+++ b/packages/core/src/Resizable/ResizeHandle.test.tsx@@ -948,6 +948,18 @@ describe('ResizeHandle', () => {expect(document.body.style.userSelect).toBe('');});+ it('releases body styles and tells the region the gesture is over when its resizable prop goes away mid-drag', () => {+ const resizable = {...makeResizable(), _onResizeCancel: vi.fn()};+ const view = render(<ResizeHandle resizable={resizable} label="Resize" />);+ fireEvent.pointerDown(getHitArea(), {pointerId: 1, clientX: 0, clientY: 0});+ expect(document.body.style.cursor).not.toBe('');+ view.rerender(<ResizeHandle label="Resize" />);+ expect(document.body.style.cursor).toBe('');+ expect(document.body.style.userSelect).toBe('');+ expect(resizable._onResizeCancel).toHaveBeenCalledTimes(1);+ expect(resizable._onResizeEnd).not.toHaveBeenCalled();+ });+// --- Persistence ---it.each([diff --git a/packages/core/src/Resizable/ResizeHandle.tsx b/packages/core/src/Resizable/ResizeHandle.tsxindex fbd74f23b5..20e0be032e 100644--- a/packages/core/src/Resizable/ResizeHandle.tsx+++ b/packages/core/src/Resizable/ResizeHandle.tsx@@ -22,21 +22,17 @@* (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.+ * The handle's input (the pointer drag, the keys, the double-click) is+ * resizeGesture.ts. ResizeHandle forwards its React events to it, over the+ * region its `resizable` prop describes. A drag takes pointer capture on the grab zone.+ * The gesture's move, up and cancel events then go there, as in Slider, even+ * over an embedded frame.*/-import {useCallback, useEffect, useRef, useState} from 'react';+import {useEffect, useRef, useState} from 'react';import type {ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';-import {devWarn} from '../utils/devWarning';import {colorVars,durationVars,@@ -51,8 +47,14 @@ import {getEffectiveMaxPx,type ResizableProps,} from './useResizable';+import {+ createResizeGesture,+ type ResizeGesture,+ type ResizeGestureModel,+} from './resizeGesture';import {themeProps} from '../utils/themeProps';+import {useDevWarning} from '../hooks/useDevWarning';import {useMergedRefs} from '../hooks/useMergedRefs';import {registerEnglishFallback,@@ -61,8 +63,6 @@ import {import english from '../i18n/generated-english/Resizable/ResizeHandle.generated';registerEnglishFallback(english);-const KEYBOARD_STEP = 10;-const KEYBOARD_LARGE_STEP = 50;type PillPlacement = 'start' | 'end' | 'center' | 'auto';@@ -105,21 +105,6 @@ 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',@@ -370,60 +355,6 @@ export interface ResizeHandleProps extends Omit<children?: ReactNode;}-/**- * The snap point `count` points away from the region's current size in- * `direction` (+1 grows, -1 shrinks). A point beyond `minSize` or `maxSize`- * counts as that bound; the nearest end point serves when fewer remain, and- * the current size when it is already there.- */-function adjacentSnapPoint(- resizable: ResizableProps,- direction: 1 | -1,- count: number,-): number {- const points = [- ...new Set(- resizable._snaps.map(p =>- Math.min(resizable._maxSizePx, Math.max(resizable._minSizePx, p)),- ),- ),- ].sort((a, b) => a - b);- const size = resizable._size;- const ahead =- direction > 0- ? points.filter(p => p > size)- : points.filter(p => p < size).reverse();- if (ahead.length === 0) {- return size;- }- return ahead[Math.min(count, ahead.length) - 1];-}--/**- * Collapse an open pane, or restore a collapsed one to the size it had before- * it collapsed (APG window splitter: Enter "restores the splitter to its- * previous position"). The hook's own collapse/expand do exactly that; a- * hand-built `ResizableProps` (no registered controls) falls back to a resize- * gesture to the minimum, which also cannot reopen a pane whose minimum sits below its- * collapse threshold.- */-function toggleCollapse(resizable: ResizableProps): void {- const controls = getCollapseControls(resizable);- if (controls) {- if (resizable._isCollapsed) {- controls.expand();- } else {- controls.collapse();- }- return;- }- resizable._onResizeStart();- resizable._onResizeMove(- resizable._isCollapsed ? resizable._minSizePx : -resizable._size,- );- resizable._onResizeEnd();-}-/*** Draggable resize handle placed between resizable panels. Renders as a thin* divider line with a wider invisible hit area and optional pill grip indicator.@@ -459,271 +390,133 @@ export function ResizeHandle({const t = useComponentTranslator();const label = labelFromProps ?? t('@astryx.resizable.handle.label');const handleRef = useRef<HTMLDivElement>(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);const isHorizontal = direction === 'horizontal';const isOverlay = positionMode === 'overlay';- const sign = isReversed ? -1 : 1;++ // --- The region a `resizable` prop describes ---++ // The gesture reads the latest props at each input. A drag sees the region+ // as it is now, not as it was at the press.+ const resizableRef = useRef(resizable);+ resizableRef.current = resizable;+ // The region a drag in flight started on: told the gesture is over even+ // after the prop has gone.+ const dragRegionRef = useRef<ResizableProps | undefined>(undefined);+ const configRef = useRef({direction, isReversed, isDisabled});+ configRef.current = {direction, isReversed, isDisabled};+ const [isDragging, setIsDragging] = useState(false);+ const [regionGesture] = useState<ResizeGesture>(() => {+ const model: ResizeGestureModel = {+ state() {+ const region = resizableRef.current;+ return {+ size: region?._size ?? 0,+ isCollapsed: region?._isCollapsed ?? false,+ minPx: region?._minSizePx ?? 0,+ maxPx: region?._maxSizePx ?? Infinity,+ snaps: region?._snaps ?? [],+ collapsedSize: region?._collapsedSize ?? 0,+ collapsible: region?._collapsible ?? false,+ };+ },+ start: () => {+ dragRegionRef.current = resizableRef.current;+ resizableRef.current?._onResizeStart();+ },+ move: delta => resizableRef.current?._onResizeMove(delta),+ end: () => {+ const region = resizableRef.current ?? dragRegionRef.current;+ dragRegionRef.current = undefined;+ region?._onResizeEnd();+ },+ // Not a resize end, but the gesture is over. The region froze its state+ // for the drag, so it must hear that the drag ended.+ cancel: () => {+ const region = resizableRef.current ?? dragRegionRef.current;+ dragRegionRef.current = undefined;+ region?._onResizeCancel?.();+ },+ // The hook's own collapse and expand restore the size before the+ // collapse; a hand-built `ResizableProps` has none.+ get collapse() {+ const region = resizableRef.current;+ return region ? getCollapseControls(region)?.collapse : undefined;+ },+ get expand() {+ const region = resizableRef.current;+ return region ? getCollapseControls(region)?.expand : undefined;+ },+ };+ return createResizeGesture(+ () => handleRef.current,+ model,+ () => ({+ ...configRef.current,+ isDisabled:+ configRef.current.isDisabled || resizableRef.current == null,+ }),+ setIsDragging,+ );+ });++ const gesture = resizable != null ? regionGesture : null;+ const isCollapsed = resizable?._isCollapsed ?? false;const effectiveSide = resolveEffectiveSide(pillPlacement,isReversed,- resizable?._isCollapsed ?? false,+ isCollapsed,);// Physical offset direction shared by the pill and the grab zone (null =// centered / no bias). Keeps the two positioned identically in LTR and RTL.const hitBiasDir = hitAreaBiasDir(effectiveSide);-- const getRTLMultiplier = useCallback((): number => {- const el = handleRef.current;- if (!el) {- return 1;- }- return getComputedStyle(el).direction === 'rtl' ? -1 : 1;- }, []);-const isInteracting = isHovered || isFocused;- // A handle whose axis disagrees with its hook drags along one axis while the- // hook measures percentage bounds on the other. `ResizableProps` is exported,- // so `_direction` is optional for old hand-built objects; absent means there- // is no hook axis to compare, not that the hook is horizontal.- const didWarnAxisRef = useRef(false);- useEffect(() => {- const hookDirection = resizable?._direction;- if (- hookDirection != null &&- hookDirection !== direction &&- !didWarnAxisRef.current- ) {- didWarnAxisRef.current = true;- devWarn(- 'ResizeHandle',- `direction="${direction}" but its useResizable region is ` +- `"${hookDirection}". They must match: the hook measures one axis ` +- 'and the handle drags the other.',- );- }- }, [direction, resizable]);-- // --- Pointer drag ---- const clearDrag = useCallback(() => {- dragRef.current = null;- setIsDragging(false);- clearBodyDragStyles();- }, []);-- const handlePointerDown = useCallback(- (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();- applyBodyDragStyles(isHorizontal);- },- [isDisabled, resizable, isHorizontal, getRTLMultiplier],- );-- const handlePointerMove = useCallback(- (e: React.PointerEvent<HTMLDivElement>) => {- const drag = dragRef.current;- if (!drag || drag.pointerId !== e.pointerId || !resizable) {- return;- }- const currentPos = isHorizontal ? e.clientX : e.clientY;- resizable._onResizeMove((currentPos - drag.startPos) * drag.rtl * sign);- },- [resizable, isHorizontal, sign],- );-- const handlePointerUp = useCallback(- (e: React.PointerEvent<HTMLDivElement>) => {- if (dragRef.current?.pointerId !== e.pointerId) {- return;- }- clearDrag();- resizable?._onResizeEnd();- },- [clearDrag, resizable],+ // A handle whose axis disagrees with its region drags along one axis while+ // the region measures percentage bounds on the other. `ResizableProps` is+ // exported, so `_direction` is optional for old hand-built objects. Without+ // it there is no axis to compare.+ const regionDirection = resizable?._direction;+ useDevWarning(+ 'ResizeHandle',+ `direction="${direction}" but its useResizable region is ` ++ `"${regionDirection}". They must match: the hook measures one axis ` ++ 'and the handle drags the other.',+ regionDirection != null && regionDirection !== direction,);- // 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();- // Not a resize end, but still the end of the gesture: the region froze- // state for the duration of the drag and has to be told it is over.- resizable?._onResizeCancel?.();- },- [clearDrag, resizable],- );-- // --- Keyboard ---- const handleKeyDown = useCallback(- (e: React.KeyboardEvent) => {- if (isDisabled || !resizable) {- return;- }- const step = e.shiftKey ? KEYBOARD_LARGE_STEP : KEYBOARD_STEP;- const rtl = isHorizontal ? getRTLMultiplier() : 1;-- // The pane's grow direction on this key: ArrowRight/Down grow unless the- // layout is reversed or, on the inline axis, right-to-left.- const grows = (key: string) =>- (key === 'ArrowRight' || key === 'ArrowDown'- ? 1- : key === 'ArrowLeft' || key === 'ArrowUp'- ? -1- : 0) *- (isHorizontal ? rtl : 1) *- sign >- 0;-- switch (e.key) {- case 'ArrowRight':- case 'ArrowDown':- case 'ArrowLeft':- case 'ArrowUp': {- e.preventDefault();- if (resizable._isCollapsed) {- // A collapsed pane answers only the grow arrow: it opens one step- // above its minimum, the value the separator announces while- // collapsed, or at the collapse threshold when that is larger (APG- // window splitter: the arrow moves the separator from where it is;- // a bare step would stay below the threshold and leave it in- // place). The shrink arrow is a no-op.- if (grows(e.key)) {- resizable._onResizeStart();- // At least the collapse threshold, or the move would stay- // collapsed when the minimum sits below it.- resizable._onResizeMove(- Math.max(resizable._minSizePx + step, resizable._collapsedSize),- );- resizable._onResizeEnd();- }- break;- }- if (resizable._snaps.length > 0) {- // With snap points the region can rest only on a point, so a- // pixel step would snap straight back; the arrow moves to the- // adjacent point in its direction instead (Shift, two points),- // staying within the bounds.- resizable._onResizeStart();- resizable._onResizeMove(- adjacentSnapPoint(- resizable,- grows(e.key) ? 1 : -1,- e.shiftKey ? 2 : 1,- ) - resizable._size,- );- resizable._onResizeEnd();- break;- }- const direction =- e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1;- resizable._onResizeStart();- resizable._onResizeMove(- direction * step * (isHorizontal ? rtl : 1) * sign,- );- resizable._onResizeEnd();- break;- }- case 'Home': {- e.preventDefault();- resizable._onResizeStart();- resizable._onResizeMove(resizable._minSizePx - resizable._size);- resizable._onResizeEnd();- break;- }- case 'End': {- e.preventDefault();- // Only a configured maximum is the region's own limit; the reported- // stand-in for an unbounded region is where the pane *could* reach,- // not where End may safely move it (a recorded gap).- if (resizable._maxSizePx !== Infinity) {- resizable._onResizeStart();- resizable._onResizeMove(resizable._maxSizePx - resizable._size);- resizable._onResizeEnd();- }- break;- }- case 'Enter': {- e.preventDefault();- if (resizable._collapsible) {- toggleCollapse(resizable);- }- break;- }- }- },- [isDisabled, resizable, isHorizontal, getRTLMultiplier, sign],- );+ // --- Cleanup on unmount, or when the `resizable` prop goes ---- // --- Double-click collapse ---- const handleDoubleClick = useCallback(() => {- if (isDisabled || !resizable || !resizable._collapsible) {- return;- }- toggleCollapse(resizable);- }, [isDisabled, resizable]);-- // --- Cleanup on unmount ---- // 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 — and the region, which outlives this handle, still has to hear+ // Removing the grab zone releases its captured pointer and its listeners.+ // A `resizable` prop that goes away takes the grab zone's handlers too. The+ // body's cursor and user-select overrides are not on the element, so they+ // are released here. The region outlives this handle and still has to hear// that its gesture is over.- const cancelOnUnmountRef = useRef<(() => void) | undefined>(undefined);- cancelOnUnmountRef.current = resizable?._onResizeCancel;+ const hasRegion = resizable != null;useEffect(() => {+ if (!hasRegion) {+ return;+ }return () => {- if (dragRef.current) {- dragRef.current = null;- clearBodyDragStyles();- cancelOnUnmountRef.current?.();- }+ regionGesture.interrupt();};- }, []);+ }, [hasRegion, regionGesture]);// --- ARIA ---// When collapsed the panel's real size (0) sits below aria-valuemin, which// is invalid per WCAG 4.1.2. Clamp aria-valuenow to the minimum and announce// the true state via aria-valuetext instead; the valuetext is removed as// soon as the panel expands so the numeric value reads again.- const isCollapsed = resizable?._isCollapsed ?? false;- const ariaValueNow = resizable- ? isCollapsed- ? Math.max(resizable._size, resizable._minSizePx)- : resizable._size- : undefined;- const ariaValueMin = resizable ? resizable._minSizePx : undefined;+ const sizeNow = resizable?._size;+ const minNow = resizable?._minSizePx;+ const ariaValueNow =+ sizeNow == null || minNow == null+ ? undefined+ : isCollapsed+ ? Math.max(sizeNow, minNow)+ : sizeNow;+ const ariaValueMin = minNow;// A separator with a value needs a maximum (WAI-ARIA, APG window splitter).// Unbounded regions report the basis they can fill; a hand-built props// object without it reports only a configured maximum.@@ -736,7 +529,9 @@ export function ResizeHandle({? effectiveMax: undefined;const ariaValueText =- resizable && isCollapsed ? t('@astryx.resizable.collapsed') : undefined;+ resizable != null && isCollapsed+ ? t('@astryx.resizable.collapsed')+ : undefined;return (<div@@ -750,7 +545,11 @@ export function ResizeHandle({aria-label={label}aria-disabled={isDisabled || undefined}tabIndex={isDisabled ? -1 : 0}- onDoubleClick={handleDoubleClick}+ onDoubleClick={() => {+ if (!isDisabled) {+ gesture?.doubleClick();+ }+ }}onFocus={() => setIsFocused(true)}onBlur={() => setIsFocused(false)}data-resizing={isDragging || undefined}@@ -786,7 +585,9 @@ export function ResizeHandle({// this accessibility-critical handler can't be clobbered by a passed prop.onKeyDown={e => {props.onKeyDown?.(e);- handleKeyDown(e);+ if (!isDisabled) {+ gesture?.keyDown(e);+ }}}>{/* Wider invisible hit area for pointer interaction */}<div@@ -806,11 +607,15 @@ export function ResizeHandle({: dynamicStyles.hitAreaOffsetY(hitBiasDir),isDisabled && styles.disabled,)}- onPointerDown={handlePointerDown}- onPointerMove={handlePointerMove}- onPointerUp={handlePointerUp}- onPointerCancel={cancelDrag}- onLostPointerCapture={cancelDrag}+ onPointerDown={e => {+ if (!isDisabled) {+ gesture?.pointerDown(e);+ }+ }}+ onPointerMove={e => gesture?.pointerMove(e)}+ onPointerUp={e => gesture?.pointerUp(e)}+ onPointerCancel={e => gesture?.pointerCancel(e)}+ onLostPointerCapture={e => gesture?.pointerCancel(e)}onPointerEnter={() => setIsHovered(true)}onPointerLeave={() => {if (!isDragging) {diff --git a/packages/core/src/Resizable/resizeGesture.ts b/packages/core/src/Resizable/resizeGesture.tsnew file mode 100644index 0000000000..ce5f44819c--- /dev/null+++ b/packages/core/src/Resizable/resizeGesture.ts@@ -0,0 +1,368 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file resizeGesture.ts+ * @input A handle element, a resize model (its state, and a gesture's start,+ * move, end and cancel), and the handle's axis, reversal and disabled state+ * @output createResizeGesture: the window splitter's input in one place: a+ * pointer drag that holds its pointer, the arrow keys, Home, End and Enter,+ * and a double-click collapse; and the body's drag cursor+ * @position Internal to the Resizable family. ResizeHandle forwards its React+ * events to it. No React, and no DOM work on import+ */++import type {ResizableDirection} from './resizableModel';++/** Pixels an arrow key moves the separator; Shift moves it further. */+export const KEYBOARD_STEP = 10;+export const KEYBOARD_LARGE_STEP = 50;++/** What a gesture reads from its region when an input arrives. */+export interface ResizeGestureState {+ /** The region's size in px, 0 while collapsed. */+ readonly size: number;+ readonly isCollapsed: boolean;+ readonly minPx: number;+ /** The configured maximum, Infinity when the region has none. */+ readonly maxPx: number;+ readonly snaps: ReadonlyArray<number>;+ readonly collapsedSize: number;+ readonly collapsible: boolean;+}++/** The region a gesture resizes. */+export interface ResizeGestureModel {+ state(): ResizeGestureState;+ /** A gesture begins: the region holds its basis until it ends. */+ start(): void;+ /** The gesture has moved `delta` px from where it began. */+ move(delta: number): void;+ /** The gesture ends as completed. */+ end(): void;+ /** The gesture ends without completing. */+ cancel(): void;+ /**+ * The region's own collapse and expand. They restore the size it had before+ * it collapsed, as the APG window splitter's Enter does. Without them a+ * toggle is a resize gesture to the minimum.+ */+ collapse?: () => void;+ expand?: () => void;+}++/** The handle's configuration, read at each input. */+export interface ResizeGestureConfig {+ readonly direction: ResizableDirection;+ readonly isReversed: boolean;+ readonly isDisabled: boolean;+}++/** The fields of a pointer event the gesture reads (native or React). */+export interface ResizeGesturePointerEvent {+ readonly pointerId: number;+ readonly clientX: number;+ readonly clientY: number;+ readonly currentTarget: EventTarget | null;+ preventDefault(): void;+ stopPropagation(): void;+}++/** The fields of a key event the gesture reads (native or React). */+export interface ResizeGestureKeyEvent {+ readonly key: string;+ readonly shiftKey: boolean;+ preventDefault(): void;+}++export interface ResizeGesture {+ pointerDown(event: ResizeGesturePointerEvent): void;+ pointerMove(event: ResizeGesturePointerEvent): void;+ pointerUp(event: ResizeGesturePointerEvent): void;+ /** A `pointercancel` or a `lostpointercapture`. */+ pointerCancel(event: ResizeGesturePointerEvent): void;+ keyDown(event: ResizeGestureKeyEvent): void;+ doubleClick(): void;+ /** Whether a pointer drag is in flight. */+ readonly isDragging: boolean;+ /**+ * Ends a drag in flight as cancelled, for a handle that goes away mid-drag.+ * It releases the pointer and the body's drag cursor, and tells the region+ * that the gesture is over.+ */+ interrupt(): void;+}++/**+ * Drag feedback lives on the page's `<body>`, not on the handle. During a+ * drag the pointer moves over whatever the panels contain, and the resize+ * cursor must hold there.+ */+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 = '';+}++/**+ * The snap point `count` points away from the region's current size in+ * `direction` (+1 grows, -1 shrinks). A point beyond the minimum or the+ * maximum counts as that bound. When fewer points remain, the nearest end+ * point serves, or the current size when the region is already there.+ */+function adjacentSnapPoint(+ state: ResizeGestureState,+ direction: 1 | -1,+ count: number,+): number {+ const points = [+ ...new Set(+ state.snaps.map(p => Math.min(state.maxPx, Math.max(state.minPx, p))),+ ),+ ].sort((a, b) => a - b);+ const {size} = state;+ const ahead =+ direction > 0+ ? points.filter(p => p > size)+ : points.filter(p => p < size).reverse();+ if (ahead.length === 0) {+ return size;+ }+ return ahead[Math.min(count, ahead.length) - 1];+}++function step(model: ResizeGestureModel, delta: number): void {+ model.start();+ model.move(delta);+ model.end();+}++/**+ * Collapse an open pane, or restore a collapsed one to the size it had before+ * it collapsed, with the region's own collapse and expand. A region without+ * them falls back to a resize gesture to the minimum. That gesture cannot+ * reopen a pane whose minimum sits below its collapse threshold.+ */+function toggleCollapse(model: ResizeGestureModel): void {+ const state = model.state();+ if (model.collapse != null && model.expand != null) {+ if (state.isCollapsed) {+ model.expand();+ } else {+ model.collapse();+ }+ return;+ }+ step(model, state.isCollapsed ? state.minPx : -state.size);+}++/**+ * The window splitter's input for one handle. A drag takes pointer capture+ * on the element the press landed on. The rest of the gesture then goes to+ * that element. Without capture, the browser hit-tests each move, and an+ * embedded frame under the pointer takes the drag.+ */+export function createResizeGesture(+ getHandle: () => Element | null,+ model: ResizeGestureModel,+ getConfig: () => ResizeGestureConfig,+ onDraggingChange?: (isDragging: boolean) => void,+): ResizeGesture {+ let drag: {+ pointerId: number;+ startPos: number;+ rtl: number;+ target: Element | null;+ } | null = null;++ const rtlMultiplier = (): number => {+ const handle = getHandle();+ if (handle == null) {+ return 1;+ }+ const view = handle.ownerDocument.defaultView;+ return view?.getComputedStyle(handle).direction === 'rtl' ? -1 : 1;+ };++ const clearDrag = () => {+ const ending = drag;+ drag = null;+ const target = ending?.target;+ if (+ ending != null &&+ target != null &&+ target.hasPointerCapture?.(ending.pointerId) === true+ ) {+ target.releasePointerCapture(ending.pointerId);+ }+ if (ending != null) {+ clearBodyDragStyles();+ }+ onDraggingChange?.(false);+ };++ return {+ get isDragging() {+ return drag != null;+ },++ pointerDown(event) {+ const config = getConfig();+ if (config.isDisabled || drag != null) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();+ // An element from another document (an iframe, a popup) is not an+ // instance of this page's Element, so test for the capture API itself.+ const current = event.currentTarget as Element | null;+ const target =+ typeof current?.setPointerCapture === 'function' ? current : null;+ target?.setPointerCapture?.(event.pointerId);+ const isHorizontal = config.direction === 'horizontal';+ drag = {+ pointerId: event.pointerId,+ startPos: isHorizontal ? event.clientX : event.clientY,+ rtl: isHorizontal ? rtlMultiplier() : 1,+ target,+ };+ onDraggingChange?.(true);+ model.start();+ applyBodyDragStyles(isHorizontal);+ },++ pointerMove(event) {+ if (drag == null || drag.pointerId !== event.pointerId) {+ return;+ }+ const config = getConfig();+ const position =+ config.direction === 'horizontal' ? event.clientX : event.clientY;+ const sign = config.isReversed ? -1 : 1;+ model.move((position - drag.startPos) * drag.rtl * sign);+ },++ pointerUp(event) {+ if (drag?.pointerId !== event.pointerId) {+ return;+ }+ clearDrag();+ model.end();+ },++ // Serves pointercancel and lostpointercapture alike: an interrupted drag+ // ends without a resize end. The implicit release after every pointerup+ // or pointercancel also fires lostpointercapture. By then the drag is+ // already cleared, and this is a no-op.+ pointerCancel(event) {+ if (drag?.pointerId !== event.pointerId) {+ return;+ }+ clearDrag();+ model.cancel();+ },++ interrupt() {+ if (drag == null) {+ return;+ }+ clearDrag();+ model.cancel();+ },++ keyDown(event) {+ const config = getConfig();+ if (config.isDisabled) {+ return;+ }+ const state = model.state();+ const isHorizontal = config.direction === 'horizontal';+ const sign = config.isReversed ? -1 : 1;+ const keyStep = event.shiftKey ? KEYBOARD_LARGE_STEP : KEYBOARD_STEP;+ const rtl = isHorizontal ? rtlMultiplier() : 1;++ // The pane's grow direction on this key: ArrowRight/Down grow unless the+ // layout is reversed or, on the inline axis, right-to-left.+ const grows = (key: string) =>+ (key === 'ArrowRight' || key === 'ArrowDown'+ ? 1+ : key === 'ArrowLeft' || key === 'ArrowUp'+ ? -1+ : 0) *+ (isHorizontal ? rtl : 1) *+ sign >+ 0;++ switch (event.key) {+ case 'ArrowRight':+ case 'ArrowDown':+ case 'ArrowLeft':+ case 'ArrowUp': {+ event.preventDefault();+ if (state.isCollapsed) {+ // A collapsed pane answers only the grow arrow. It opens one step+ // above its minimum, the value the separator announces while+ // collapsed. If the collapse threshold is larger, it opens there.+ // A bare step would stay below the threshold and leave the pane+ // closed. The shrink arrow is a no-op.+ if (grows(event.key)) {+ step(model, Math.max(state.minPx + keyStep, state.collapsedSize));+ }+ break;+ }+ if (state.snaps.length > 0) {+ // With snap points the region rests only on a point, so a pixel+ // step would snap straight back. The arrow moves to the adjacent+ // point in its direction instead, two points with Shift, within+ // the bounds.+ step(+ model,+ adjacentSnapPoint(+ state,+ grows(event.key) ? 1 : -1,+ event.shiftKey ? 2 : 1,+ ) - state.size,+ );+ break;+ }+ const direction =+ event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1 : -1;+ step(model, direction * keyStep * (isHorizontal ? rtl : 1) * sign);+ break;+ }+ case 'Home': {+ event.preventDefault();+ step(model, state.minPx - state.size);+ break;+ }+ case 'End': {+ event.preventDefault();+ // Only a configured maximum is the region's own limit. The reported+ // stand-in for an unbounded region is where the pane could reach,+ // not where End may move it.+ if (state.maxPx !== Infinity) {+ step(model, state.maxPx - state.size);+ }+ break;+ }+ case 'Enter': {+ event.preventDefault();+ if (state.collapsible) {+ toggleCollapse(model);+ }+ break;+ }+ }+ },++ doubleClick() {+ if (getConfig().isDisabled || !model.state().collapsible) {+ return;+ }+ toggleCollapse(model);+ },+ };+}