An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a BottomSheet drag writes its transform per move, not per render (#7169)
Christopher Chedeaua83e568e3d7e
diff --git a/.changeset/bottom-sheet-drag-off-render.md b/.changeset/bottom-sheet-drag-off-render.mdnew file mode 100644index 0000000000..82cdf9c11c--- /dev/null+++ b/.changeset/bottom-sheet-drag-off-render.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A BottomSheet drag writes its transform straight to the sheet once per input sample and renders nothing in between (React state changes when the drag begins and ends, and when its layout split changes). Measured in Chromium: 4 commits for a 24-sample drag, down from 49. The release still animates from wherever the finger left the sheet.++@vjeuxdiff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 8f7cd21f2d..74f862c20c 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -516,6 +516,7 @@ export function BottomSheetPanel({dragOffset,settledOffset,isDragging,+ isTraveling,sheetHeight,scrollPreservationInset,settlingLayoutOffset,@@ -555,7 +556,7 @@ export function BottomSheetPanel({isEnabled: height === 'tall',isFullyExpanded: settledOffset === 0,isPageScrollLocked,- isSheetTraveling: isDragging && dragOffset !== settledOffset,+ isSheetTraveling: isTraveling,isOpen: isInteractive,isPresented,sheetRef: elementRef,@@ -673,9 +674,33 @@ export function BottomSheetPanel({.filter(Boolean).join(' '): gestureTransform;+ const sheetTransform = isInteractive+ ? gestureTransform+ : isRetained+ ? retainedTransform+ : undefined;+ const consumerTransform = style?.transform;+ // The transform is written to the element here, not rendered through the+ // style prop. A drag writes it straight to the element once per input+ // sample (useSheetGestures) and renders nothing in between, so React never+ // sees those writes; rendered through the prop, the resting value would be+ // skipped as "unchanged" when the drag ends and the sheet would stay where+ // the finger left it. Written after every commit instead, outside a drag,+ // the resting value lands in the same style update as the restored+ // transition, so a settle or a dismissal animates from the live position.+ useLayoutEffect(() => {+ if (isDragging || consumerTransform != null) {+ return;+ }+ const element = elementRef.current;+ if (element != null) {+ element.style.transform = sheetTransform ?? '';+ }+ });const gestureStyle = {- ...contentProps.style,- transform: gestureTransform,+ transition: contentProps.style.transition,+ touchAction: contentProps.style.touchAction,+ overscrollBehavior: contentProps.style.overscrollBehavior,height: resizedHeight,};return (@@ -700,11 +725,9 @@ export function BottomSheetPanel({['--_sheet-budget' as string]: budget,...(isInteractive? gestureStyle- : isRetained- ? {transform: retainedTransform, height: resizedHeight}- : isClosing- ? {height: resizedHeight}- : {}),+ : isRetained || isClosing+ ? {height: resizedHeight}+ : {}),...style,},)}>diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.tsnew file mode 100644index 0000000000..7158f29069--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetDrag.a11y.chromium.spec.ts@@ -0,0 +1,128 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BottomSheetDrag.a11y.chromium.spec.ts+ * @input Built BottomSheet stories and real Chromium touch input (CDP)+ * @output Browser evidence that a drag follows the finger without rendering,+ * and that the release animates from where the finger left the sheet+ * @position Chromium proof for useSheetGestures' live transform path+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++test.use({hasTouch: true, viewport: {width: 390, height: 844}});++// A React commit counter: DevTools' hook is called once per committed root.+const COMMIT_COUNTER = `(() => {+ const hook = {+ renderers: new Map(), supportsFiber: true, commits: 0,+ inject() { return 1; },+ onCommitFiberRoot() { hook.commits += 1; },+ onCommitFiberUnmount() {}, onPostCommitFiberRoot() {},+ };+ Object.defineProperty(window, '__REACT_DEVTOOLS_GLOBAL_HOOK__', {value: hook});+})()`;++async function openSheet(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-bottomsheet--snap-points&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Open nearby places'}).click();+ const dialog = page.getByRole('dialog', {name: 'Nearby places'});+ await expect(dialog).toBeVisible();+ // The sheet panel carries the component class and the transform.+ const sheet = dialog.locator('.astryx-bottom-sheet').first();+ await expect(sheet).toBeVisible();+ await page.waitForTimeout(600); // the entrance+ return {dialog, sheet};+}++function tyOf(transform: string): number {+ const match = /translateY\((-?[\d.]+)px\)/.exec(transform);+ return match ? Number(match[1]) : 0;+}++test('a drag writes the transform per move and renders nothing between', async ({+ page,+}) => {+ await page.addInitScript(COMMIT_COUNTER);+ const {sheet} = await openSheet(page);+ const box = await sheet.boundingBox();+ if (box == null) {+ throw new Error('no sheet box');+ }+ const x = box.x + box.width / 2;+ const handleY = box.y + 12;+ const commitsBefore = await page.evaluate(+ () =>+ (window as unknown as {__REACT_DEVTOOLS_GLOBAL_HOOK__: {commits: number}})+ .__REACT_DEVTOOLS_GLOBAL_HOOK__.commits,+ );+ const cdp = await page.context().newCDPSession(page);+ const steps = 24;+ const trail: number[] = [];+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints: [{x, y: handleY}],+ });+ for (let i = 1; i <= steps; i += 1) {+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{x, y: handleY + i * 5}],+ });+ trail.push(+ tyOf(await sheet.evaluate(el => (el as HTMLElement).style.transform)),+ );+ await page.waitForTimeout(16);+ }+ const commitsDuring = await page.evaluate(+ () =>+ (+ window as unknown as {+ __REACT_DEVTOOLS_GLOBAL_HOOK__: {commits: number};+ }+ ).__REACT_DEVTOOLS_GLOBAL_HOOK__.commits,+ );+ // The transform followed the finger (inline, written per move; the first+ // samples ease out of the magnet around the resting detent) ...+ expect(trail[trail.length - 1]).toBeGreaterThanOrEqual(100);+ expect(trail.filter((ty, i) => i === 0 || ty >= trail[i - 1]).length).toBe(+ trail.length,+ );+ // ... and the moves cost a handful of commits (the drag beginning, the+ // sheet traveling), not one per move.+ expect(commitsDuring - commitsBefore).toBeLessThanOrEqual(4);+ await cdp.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ });+ // The release animates back from where the finger left the sheet: the+ // computed transform is still off rest a frame later, and at rest after the+ // transition.+ await page.waitForTimeout(40);+ const midway = await sheet.evaluate(el => getComputedStyle(el).transform);+ const midwayTy = /matrix\(1, 0, 0, 1, 0, (-?[\d.]+)\)/.exec(midway);+ expect(midwayTy, midway).not.toBeNull();+ expect(Number(midwayTy?.[1])).toBeGreaterThan(5);+ await expect+ .poll(async () => sheet.evaluate(el => getComputedStyle(el).transform), {+ timeout: 2_000,+ })+ .toMatch(/^(none|matrix\(1, 0, 0, 1, 0, 0\))$/);+ await expect(page.getByRole('dialog', {name: 'Nearby places'})).toBeVisible();+});diff --git a/packages/core/src/BottomSheet/useSheetGestures.test.ts b/packages/core/src/BottomSheet/useSheetGestures.test.tsindex dcb3ca52b0..4c5cef8121 100644--- a/packages/core/src/BottomSheet/useSheetGestures.test.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.test.ts@@ -82,6 +82,11 @@ type Hook = {result: {current: ReturnType<typeof useSheetGestures>};};+// The live drag position: written per input sample, not rendered.+function liveOffset(hook: Hook): number {+ return hook.result.current.activeOffsetRef.current;+}+function down(hook: Hook, y: number, t: number, target: HTMLElement) {// Register the sheet element the way the component does on mount, so the// hook can measure its height (it no longer queries the DOM for it).@@ -396,7 +401,7 @@ describe('useSheetGestures', () => {const t = makeTarget();down(hook, 0, 0, t);move(hook, 90, 100, t); // raw offset 90, 10px from the 100 detent- const off = hook.result.current.dragOffset;+ const off = liveOffset(hook);expect(off).toBeGreaterThan(90); // pulled up toward 100expect(off).toBeLessThanOrEqual(100);});@@ -406,11 +411,51 @@ describe('useSheetGestures', () => {const t = makeTarget();down(hook, 0, 0, t);move(hook, 50, 100, t);- expect(hook.result.current.dragOffset).toBe(50);+ expect(liveOffset(hook)).toBe(50);expect(hook.result.current.isDragging).toBe(true);- expect(hook.result.current.contentProps.style.transform).toBe(- 'translateY(50px)',+ // Written to the element, not rendered: the move costs one style write+ // and no commit.+ expect(t.style.transform).toBe('translateY(50px)');+ });++ it('renders nothing for a move that keeps the layout split', () => {+ let renders = 0;+ const onDismiss = vi.fn();+ const hook = renderHook(+ (props: UseSheetGesturesOptions) => {+ renders += 1;+ return useSheetGestures(props);+ },+ {initialProps: {isOpen: true, onDismiss, snapHeights: () => [200]}},);+ const t = makeTarget();+ down(hook, 0, 0, t);+ const rendersAtDown = renders;+ move(hook, 30, 50, t);+ move(hook, 60, 100, t);+ move(hook, 90, 150, t);+ expect(t.style.transform).toBe('translateY(90px)');+ // One render announces that the sheet is traveling; the moves after it+ // render nothing.+ expect(renders - rendersAtDown).toBeLessThanOrEqual(1);+ });++ it('restores the full layout height when a drag crosses above its base', () => {+ const onSnap = vi.fn();+ const {hook} = setup({snapHeights: () => [200], onSnap});+ const t = makeTarget();+ // Rest at the 200px working detent: the sheet gives 200px up as layout.+ down(hook, 0, 0, t);+ move(hook, 200, 400, t);+ up(hook, 200, 800, t);+ expect(hook.result.current.settledLayoutOffset).toBe(200);+ // Drag back up above the base: the layout split changes, and that one+ // render carries the offset the host pairs with the new height.+ down(hook, 200, 1000, t);+ move(hook, 150, 1100, t);+ expect(liveOffset(hook)).toBe(150);+ expect(liveOffset(hook)).toBe(150);+ expect(t.style.transform).toBe('translateY(150px)');});it('returns to the settled detent when a context menu interrupts a drag', () => {@@ -476,7 +521,7 @@ describe('useSheetGestures', () => {move(hook, 20, 100, t); // drag up 80px past the top of a rested-at-top sheet// Overscroll is allowed but damped: a resisted fraction of the raw -80,// and negative (above the top), not the raw distance and not clamped to 0.- const off = hook.result.current.dragOffset;+ const off = liveOffset(hook);expect(off).toBeLessThan(0);expect(off).toBeGreaterThan(-80); // resisted, so smaller in magnitude});@@ -527,7 +572,7 @@ describe('useSheetGestures', () => {bodyDown(hook, 0, 0, body);bodyMove(hook, 40, 100, body); // pull down while at the topexpect(hook.result.current.isDragging).toBe(true);- expect(hook.result.current.dragOffset).toBe(40);+ expect(liveOffset(hook)).toBe(40);});/**@@ -652,7 +697,7 @@ describe('useSheetGestures', () => {expect(hook.result.current.isDragging).toBe(true);// The handoff is only worth taking if the sheet follows the finger:// 50px of pull expands 50px toward the tallest detent.- expect(hook.result.current.dragOffset).toBe(150);+ expect(liveOffset(hook)).toBe(150);});it('leaves a bottom pull-up with the scroller at the tallest detent', () => {@@ -991,7 +1036,7 @@ describe('useSheetGestures', () => {touch(el, 'touchmove', 400, 7);});// 100px of pull past the touchstart, from the 200px detent.- expect(hook.result.current.dragOffset).toBe(100);+ expect(liveOffset(hook)).toBe(100);});// `pointercancel` for that same finger arrives the moment WebKit claims@@ -1025,7 +1070,7 @@ describe('useSheetGestures', () => {expect(hook.result.current.isDragging).toBe(true);// Anchored where the content ran out, so only the 50px past it moves the// sheet. Anchoring at touchstart would have thrown it 350px instead.- expect(hook.result.current.dragOffset).toBe(150);+ expect(liveOffset(hook)).toBe(150);});it('does not preventDefault the mid-gesture handoff', () => {@@ -1059,7 +1104,7 @@ describe('useSheetGestures', () => {touch(el, 'touchmove', 200); // the content ended heretouch(el, 'touchmove', 150);});- expect(hook.result.current.dragOffset).toBe(150);+ expect(liveOffset(hook)).toBe(150);act(() => {touch(el, 'touchmove', 210); // back below the anchor@@ -1075,7 +1120,7 @@ describe('useSheetGestures', () => {touch(el, 'touchmove', 140);});expect(hook.result.current.isDragging).toBe(true);- expect(hook.result.current.dragOffset).toBe(150);+ expect(liveOffset(hook)).toBe(150);});it('does not hand off on reaching the end without travelling past it', () => {diff --git a/packages/core/src/BottomSheet/useSheetGestures.ts b/packages/core/src/BottomSheet/useSheetGestures.tsindex cf724dc786..097eb56dc5 100644--- a/packages/core/src/BottomSheet/useSheetGestures.ts+++ b/packages/core/src/BottomSheet/useSheetGestures.ts@@ -23,6 +23,14 @@* only a sliver of the sheet — keeps the full height and slides below the* viewport instead of reflowing to that sliver.*+ * A live drag writes that transform straight to the sheet element, once per+ * input sample, and renders nothing: React state changes when the drag begins+ * and ends, and in between only when the layout split changes (a drag that+ * crosses above its base detent restores the full height). The live offset+ * is readable through `activeOffsetRef`. The host owns the element's+ * transform outside a drag and writes the resting value after each commit,+ * so a settle animates from wherever the finger left the sheet.+ ** Those are pixels, and the stops behind them are relative to the viewport, so* a sheet at rest re-resolves its detent on `resize` / `orientationchange`,* and whenever the host swaps the snap points, and re-anchors to the new@@ -361,12 +369,25 @@ export interface UseSheetGesturesResult {* in a second callback ref.*/bodyElementRef: RefObject<HTMLElement | null>;- /** Current live drag translate in px (0 = fully expanded, larger = collapsed). */+ /**+ * The drag offset the host last had to render against, in px (0 = fully+ * expanded, larger = collapsed): seeded when a drag begins and refreshed+ * when its layout split changes. Not the live position; see+ * `activeOffsetRef`.+ */dragOffset: number;/** Translate of the resting detent in px (0 = tallest detent). */settledOffset: number;/** Whether a drag is currently in progress. */isDragging: boolean;+ /** Whether the drag in progress has moved the sheet off its base detent. */+ isTraveling: boolean;+ /**+ * The sheet's offset right now, in px: the settled detent at rest, the live+ * position during a drag. Written per input sample without a render; read+ * it where the live number is needed without subscribing to it.+ */+ activeOffsetRef: RefObject<number>;/** Measured height of the fully expanded sheet. */sheetHeight: number;/** End padding that preserves the scroll position across height changes. */@@ -428,6 +449,9 @@ export function useSheetGestures({const [dragOffset, setDragOffset] = useState(0);const [settledOffset, setSettledOffset] = useState(0);const [isDragging, setIsDragging] = useState(false);+ // Whether the drag in flight has moved the sheet off its base detent. One+ // state change per drag, for hosts that react to travel beginning.+ const [isTraveling, setIsTraveling] = useState(false);const [sheetHeight, setSheetHeight] = useState(0);const [scrollPreservationInset, setScrollPreservationInset] = useState(0);// How much of the settled travel is expressed as layout height. Equal to@@ -520,8 +544,13 @@ export function useSheetGestures({},[updateScrollPreservationInset],);+ // The sheet's offset right now: the settled detent at rest, the live drag+ // position while dragging (written by the move handler, not by a render, so+ // a render in the middle of a drag must not overwrite it).const activeOffsetRef = useRef(0);- activeOffsetRef.current = isDragging ? dragOffset : settledOffset;+ if (!isDragging) {+ activeOffsetRef.current = settledOffset;+ }const isOpenRef = useRef(isOpen);isOpenRef.current = isOpen;@@ -560,6 +589,7 @@ export function useSheetGestures({renderedOffset: number;layoutOffset: number;naturalEndGap: number;+ hasTraveled: boolean;} | null>(null);// Fully-open height, tracked by a ResizeObserver (see sheetRef) so detents@@ -637,6 +667,8 @@ export function useSheetGestures({// eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopensetIsDragging(false);// eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopen+ setIsTraveling(false);+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- resets gesture state on controlled reopensetIsScrollAreaReconciling(false);recordSettledLayoutOffset(0);settledDetentIndexRef.current = 0;@@ -808,6 +840,23 @@ export function useSheetGestures({reanchorToSettledDetent();}, [reanchorToSettledDetent, snapHeights]);+ // The one write a finger sample costs: the sheet's compositor transform,+ // on the element, with no render between the input and the paint. The+ // value matches what the host renders at rest (offset less the layout+ // split), so a settle that follows continues from it.+ const writeLiveTransform = useCallback(+ (offset: number, layoutOffset: number) => {+ const element = sheetElRef.current;+ if (element == null) {+ return;+ }+ const translation = offset - layoutOffset;+ element.style.transform =+ translation !== 0 ? `translateY(${translation}px)` : '';+ },+ [],+ );+const cancelDrag = useCallback((target?: HTMLElement) => {const state = dragStateRef.current;@@ -823,6 +872,7 @@ export function useSheetGestures({}setDragOffset(state.baseOffset);setIsDragging(false);+ setIsTraveling(false);prepareScrollAreaSettle(state.baseLayoutOffset,state.baseOffset,@@ -1024,6 +1074,7 @@ export function useSheetGestures({renderedOffset: settledOffset,layoutOffset: baseLayoutOffset,naturalEndGap,+ hasTraveled: false,};updateScrollPreservationInset(preservationInsetForOffset(@@ -1117,9 +1168,20 @@ export function useSheetGestures({// viewport; otherwise keep whatever layout the base detent settled with// (0 at a peek, so a peek drag stays transform-only).const layoutOffset = next < state.baseOffset ? 0 : state.baseLayoutOffset;+ const hasLayoutChanged = layoutOffset !== state.layoutOffset;state.renderedOffset = next;state.layoutOffset = layoutOffset;- setDragOffset(next);+ activeOffsetRef.current = next;+ writeLiveTransform(next, layoutOffset);+ if (hasLayoutChanged) {+ // The layout split moved: the host renders the new height, reading+ // the offset it has to pair with it from state.+ setDragOffset(next);+ }+ if (!state.hasTraveled && next !== state.baseOffset) {+ state.hasTraveled = true;+ setIsTraveling(true);+ }updateScrollPreservationInset(preservationInsetForOffset(state.baseLayoutOffset,@@ -1143,7 +1205,7 @@ export function useSheetGestures({scrimOpacityForOffset(next, offsets, dismissOffset, peekOffset),);},- [resolveDetents, updateScrollPreservationInset],+ [resolveDetents, updateScrollPreservationInset, writeLiveTransform],);const endDrag = useCallback(@@ -1167,6 +1229,7 @@ export function useSheetGestures({target.releasePointerCapture?.(event.pointerId);}setIsDragging(false);+ setIsTraveling(false);settleFromDrag(offset,state.velocity,@@ -1512,7 +1575,9 @@ export function useSheetGestures({[reconcileScrollPreservationInset],);- // While dragging, follow the finger; otherwise rest at the settled detent.+ // The resting transform; a drag in flight writes its own to the element+ // (writeLiveTransform) and a host that owns the element's transform must not+ // render this over it while `isDragging`.const activeOffset = isDragging ? dragOffset : settledOffset;const contentProps = useMemo<SheetContentProps>(@@ -1585,6 +1650,8 @@ export function useSheetGestures({dragOffset,settledOffset,isDragging,+ isTraveling,+ activeOffsetRef,sheetHeight,scrollPreservationInset,settlingLayoutOffset,