Skip to content

fix(BottomSheet): follow the viewport when it changes under a resting sheet - #5159

Merged
imdreamrunner merged 1 commit into
mainfrom
codex/bottom-sheet-viewport-resize
Aug 17, 2026
Merged

imdreamrunner merged 1 commit into
mainfrom
codex/bottom-sheet-viewport-resize

Conversation

@imdreamrunner

Copy link
Copy Markdown
Contributor

The bug

BottomSheet reads the viewport once, at gesture time, and stores the
result in absolute pixels.

  • defaultSnapHeights() samples the viewport and turns the snap fractions into
    px (BottomSheetPanel.tsx).
  • It is only ever called from detentOffsets(), and that is only called from
    drag paths — handlePointerMove, settleFromDrag, cancelDrag. There was no
    resize listener anywhere in the gesture path.
  • The resting detent then lives as a px offset (settledOffset /
    settledLayoutOffset) rendered as a px height, so a parked sheet is no
    longer dvh-driven at all.
  • recordSheetHeight() discards every ResizeObserver report while
    activeOffsetRef.current > 0 — i.e. exactly while parked at a detent.

useSheetGestures' own docs promised the opposite: detents "stay correct across
rotation / viewport changes", and the lazy resolution keeps values current
"after rotation or virtual-keyboard opening". True for the next drag, never
for the sheet already on screen.

What that does (measured in Chrome, Core/BottomSheet → Tall sheet, 500px wide)

1. A parked sheet keeps its old pixel height.

viewport visible sheet
dragged to the mid detent 900 450 50% ✓
resized, untouched 600 450 75%
resized, untouched 1200 450 37.5%

It only heals on a drag back to fully open, or a close and reopen.

2. Peek detent + shrink → the sheet leaves the screen. Peek keeps its full
height and slides down by an offset computed for the old viewport (702px),
which is taller than the whole new window:

parked at peek       vh= 900  visible= 126
viewport -> 1200     vh=1200  visible= 402   (should be 168)
viewport ->  600     vh= 600  visible=-150   top edge 150px BELOW the window

<dialog> is still open, still :modal, backdrop still painted, page behind
still unclickable — a dimmed, blocked page with no sheet on it. Escape is the
only way out.

3. The next drag measures against the stale fully-open height. After
shrinking 900→600 and dragging up from the mid detent, the sheet travels
110px above the top of the window and takes the grab handle with it.
OVERSCROLL_MAX doesn't catch it, because the drag is still "below" the stale
fully-open reference.

4. The two viewport units disagreed. The budget is 92dvh, which the
virtual keyboard does not shrink; the snap fractions were of
visualViewport.height, which it does. With a 300px keyboard at 500×900 the
same two drags settled at 552/300 instead of 450/126, and a spurious fourth
detent appeared just below fully open (0.92 × 600 = 552 < the 828px sheet).
This hit the advertised flow: useMobileKeyboard blurs the field when travel
starts, so the keyboard retracts during the gesture and the sheet settles onto
detents computed for a viewport that no longer exists.

The fix

Re-resolve the settled detent when the viewport changes, and re-anchor without
animating
— the viewport moved, not the user's finger, so there is no gesture
to continue and nothing to ease. A live drag or an in-flight settle is left
alone; so is a closed sheet.

Track the detent by index. The pixels stop meaning the same thing when the
viewport changes; the stop the user chose does not. The index is recorded
wherever the sheet settles and clamped to the new list, so the peek stays the
peek and the half-height stop stays half of whatever the window now is.

Measure the fully open height through the pin. The panel writes a px height
at a resizing detent, so measuring the element just reads that stale number
back. measureFullyOpenHeight() drops the inline height, measures, and restores
it in the same synchronous block — the browser cannot paint in between, so it is
invisible — and the natural CSS budget is what gets measured.

Read snap fractions from the layout viewport (window.innerHeight), the
same viewport dvh is written against. The keyboard now moves neither the
budget nor the detents, which is what useMobileKeyboard already assumes: it
holds the sheet still and scrolls the body.

scrollAreaSizing, the peek's transform-only slide, and the transition-free
reconciliation are all untouched — the resize path reuses
prepareScrollAreaSettle(..., shouldAnimate: false), the same machinery a
release on a detent already used.

After

viewport visible sheet
mid detent 900 450 50% ✓
resized 600 300 50% ✓
resized 1200 600 50% ✓
peek 900 → 1200 → 600 126 → 168 → 84 14% throughout ✓

The handle no longer leaves the screen on the drag after a resize (worst top
edge 45px, inside the rubber band, vs −110px before), and the keyboard case
settles at 450/126 with and without a 300px keyboard.

Tests

Five behavioral tests, all of which fail on main and pass here:

  • useSheetGestures — re-resolves the settled detent against the new viewport;
    keeps the peek on screen when the viewport shrinks; refreshes the fully open
    height the next drag measures against.
  • BottomSheet — re-resolves the settled detent when the window resizes (end to
    end, asserting the rendered height, transform, and that the re-anchor does not
    animate); keeps its detents when the keyboard shrinks the visual viewport.

Two more assert the non-regressions the fix must not break: a drag in progress
is left alone, and a closed sheet stops re-resolving.

The existing suite needed one mechanical change: mockVisualViewport(800) was
standing in for the whole viewport, so those tests now also set the layout
viewport with a new mockWindowHeight(800). The keyboard tests that mock a
500px visual viewport deliberately leave the layout viewport alone — that is
the case this PR is separating.

pnpm lint:strict clean, pnpm build clean, packages/core/src/BottomSheet
147/147. Full-suite failures are pre-existing and unrelated (two CLI
name-resolution tests fail identically on main; TransferList/Table.perf are
timing-flaky and vary run to run).

Notes for review

  • Detent identity is an index, so a viewport change that changes how
    computeDetentOffsets de-dupes could shift which stop the index names. With
    proportional fractions the list length is stable; a content-hugging sheet
    whose hug height crosses DETENT_DEDUP_PX relative to a snap point is the
    edge case, and it clamps rather than throwing.
  • The alternative to all of this is to stop holding detents in pixels at all —
    render the resting height as a dvh fraction and pin px only during a
    gesture, so the browser reflows on resize for free. That is a larger change to
    the layout/transform split, and worth discussing against
    [RFC] Define BottomSheet vertical drag behavior #5087, which is deciding these semantics.

… sheet

Detents are viewport fractions, but a settled sheet holds them as pixels:
an offset to translate by and a layout height to render. Both were read
once, at gesture time, and never revisited, so a viewport change left the
sheet frozen at geometry that no longer described the window.

Re-resolve the settled detent on resize / orientationchange and re-anchor
to the new geometry without animating. The detent is tracked by index —
the pixels stop meaning the same thing when the viewport changes, the stop
the user chose does not.

Measuring the fully open height while parked needed care: the panel pins a
pixel height at a resizing detent, so reading the element just returns the
stale pin. Drop the inline height for the measurement and restore it in the
same synchronous block, before the browser can paint.

Also read the snap fractions from the layout viewport rather than the
visual viewport. The height budgets are `dvh`, which the virtual keyboard
does not shrink, so the two disagreed by exactly the keyboard's height:
every detent moved while the sheet being measured did not. A keyboard is
useMobileKeyboard's business — it holds the sheet still and scrolls the
body — and it does not redefine the sheet's detents.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 17, 2026
@vercel

vercel Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview Aug 17, 2026 6:35pm

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

BottomSheet (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 3076 -
Complexity N/A Very High (243) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.8KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

github-actions Bot added a commit that referenced this pull request Aug 17, 2026
@imdreamrunner
imdreamrunner marked this pull request as ready for review August 17, 2026 22:34
@imdreamrunner
imdreamrunner merged commit 0a9618e into main Aug 17, 2026
18 checks passed
imdreamrunner added a commit that referenced this pull request Aug 18, 2026
Review caught that the earlier commit fixed one reader of
`offsetTop + height` and left three, so a single pan still latched the
sheet into the unprotected behavior — matching the device symptom that
accessory-bar Next works down a form until something pans once, and
from there every Next pans and it never recovers.

A fully expanded Tall sheet is pinned to the layout viewport bottom, so
bodyBottom == innerHeight. At full pan `offsetTop + height` also equals
innerHeight, so overlap computes as 0: the inset is dropped, and
hasKeyboardLayout goes false, which disarms the head start. Measured
with bodyBottom = innerHeight = 768 and a 500px keyboard: 316px -> 0px,
after which this branch behaves exactly like main.

The pan-invariant quantity is the one the recovery check already uses.
The keyboard covers the bottom of the LAYOUT viewport, so its top edge
sits at visualViewport.height in client coordinates and stays there
under a pan — a pan slides the window over the page without moving the
keyboard. getUnobstructedBounds() returns that band and every reader
takes it. Identical when offsetTop is 0, so nothing off the pan path
moves.

The previous test for this passed only because rect({bottom: 800})
against jsdom's innerHeight of 768 left a 32px cushion, and its
348px -> 80px expectation encoded the bug: 268px of scroll range
vanishing during a pure pan. Both keyboard geometry tests now pin the
body to innerHeight, the way the real sheet sits.

Also from the same review:

- The tap path was taking the head start it does not need — it already
  focused with preventScroll — turning a glide between two fields into a
  snap. pendingPointerFocusScroll identifies it.
- The multi-touch guard covered pointerdown but not pointerup, so a
  resting thumb that lifted first still disarmed the tap in progress.
- scrollBy 'auto' defers to the element's computed scroll-behavior;
  'instant' is what a scroll racing the browser means.

Real story on the simulator, sheet top edge decoded from the scrim
boundary: 376px at rest, 376px after four accessory-bar Nexts, 376px
after eight, 376px across an app switch. Rebased onto main, which lands
the same insight in useSheetGestures (#5159).
imdreamrunner added a commit that referenced this pull request Aug 18, 2026
Review caught that the earlier commit fixed one reader of
`offsetTop + height` and left three, so a single pan still latched the
sheet into the unprotected behavior — matching the device symptom that
accessory-bar Next works down a form until something pans once, and
from there every Next pans and it never recovers.

A fully expanded Tall sheet is pinned to the layout viewport bottom, so
bodyBottom == innerHeight. At full pan `offsetTop + height` also equals
innerHeight, so overlap computes as 0: the inset is dropped, and
hasKeyboardLayout goes false, which disarms the head start. Measured
with bodyBottom = innerHeight = 768 and a 500px keyboard: 316px -> 0px,
after which this branch behaves exactly like main.

The pan-invariant quantity is the one the recovery check already uses.
The keyboard covers the bottom of the LAYOUT viewport, so its top edge
sits at visualViewport.height in client coordinates and stays there
under a pan — a pan slides the window over the page without moving the
keyboard. getUnobstructedBounds() returns that band and every reader
takes it. Identical when offsetTop is 0, so nothing off the pan path
moves.

The previous test for this passed only because rect({bottom: 800})
against jsdom's innerHeight of 768 left a 32px cushion, and its
348px -> 80px expectation encoded the bug: 268px of scroll range
vanishing during a pure pan. Both keyboard geometry tests now pin the
body to innerHeight, the way the real sheet sits.

Also from the same review:

- The tap path was taking the head start it does not need — it already
  focused with preventScroll — turning a glide between two fields into a
  snap. pendingPointerFocusScroll identifies it.
- The multi-touch guard covered pointerdown but not pointerup, so a
  resting thumb that lifted first still disarmed the tap in progress.
- scrollBy 'auto' defers to the element's computed scroll-behavior;
  'instant' is what a scroll racing the browser means.

Real story on the simulator, sheet top edge decoded from the scrim
boundary: 376px at rest, 376px after four accessory-bar Nexts, 376px
after eight, 376px across an app switch. Rebased onto main, which lands
the same insight in useSheetGestures (#5159).
imdreamrunner added a commit that referenced this pull request Aug 18, 2026
…tom Sheet field (#5158)

* fix(core): keep the page still when the mobile keyboard reveals a Bottom Sheet field

Only a confirmed single-finger tap was ever protected from iOS's native
focus reveal. An accessory-bar Next, a Tab, or a programmatic focus fell
through to a scroll snapshot that cannot undo what actually moves: with
the sheet in a fixed dialog over a scroll-locked page, the reveal pans
the visual viewport, and offsetTop is read-only.

Refocusing the destination with preventScroll is what #5043 reverted for
duplicating the focus lifecycle (B1), so don't re-enter it. WebKit only
pans when the control is still obscured after it scrolls what it can
reach, so scroll the destination into the safe area during focusout,
before focus lands, and leave the reveal with nothing to do.

Two smaller holes alongside it:

- At maximum pan the visual viewport's bottom reaches the layout
  viewport bottom with the keyboard still up, and the hook read that as
  a dismissal, clearing the inset and the scroll range under the field.
  Compare heights, which a pan does not change.
- A second contact anywhere on the page overwrote the single pending-tap
  slot, disarming the finger already tapping a field.

* chore(changeset): reference the PR

* docs(core): say that shorter Bottom Sheet heights leave the native focus reveal in place

* fix(core): narrow the second-contact guard to non-primary pointers

The guard ignored any pointerdown whose id differed from the armed tap's.
That is broader than the bug and it can wedge: if the armed tap's
pointerup never reaches the document listener — it is registered in the
bubble phase, so a consumer can stop it — the stale arming then blocks
every later tap from arming, permanently.

Only a primary contact can arm in the first place, so the real defect is
narrower: a secondary contact fell through and nulled the arming. Ignore
non-primary pointers and nothing else. A fresh primary pointerdown always
re-arms, so a stranded arming cannot lock the mechanism out.

Also pin the two guards that no test reached: the unobstructed-viewport
case now places the destination outside the body's visible area, so it
fails if the head start stops being gated on a measured keyboard, and a
swallowed pointerup is covered directly. Every guard in the hook now
fails a test when removed.

* fix(core): put back the document scroll the browser makes to reveal a field

Reproduced on an iPhone 17 simulator: focus a field in a Tall sheet,
leave Safari, come back, and the whole page is shifted up — and stays
there.

The instrumented run showed the shift is not the visual-viewport pan
this PR assumed. window.scrollY goes to 337 and the sheet, being fixed,
travels with it; visualViewport.offsetTop tracks scrollY exactly. It is
a real document scroll. useScrollLock pins the body, which stops the
USER scrolling but not the browser: revealing a focused control scrolls
the document itself.

Being a real scroll, it can simply be put back. The document's own
scroll event is the earliest signal — a millisecond ahead of
visualViewport's — so restore there, synchronously, before the frame is
painted, then bring the control into view with the sheet's own scroller.
Measured on the simulator: it settles in one step with no oscillation.

This corrects the outcome instead of racing the cause, so it covers
every route in, including the resume case, where no focus or pointer
event fires at all and the head start has nothing to hook into.

Restoring window scroll is not new here — restoreFocusScroll already
does it; it just runs during the focus event, ~140ms before the browser
scrolls. The expected position is captured when the keyboard layout is
established, so a non-modal sheet's legitimately scrolled page is
restored to where the user left it rather than to zero.

Real story on the simulator, same tap sequence, screenshots before and
after an app switch: pre-fix 4.3% of pixels differ, with the fix 0.0%.

* fix(core): read the keyboard boundary pan-invariantly, everywhere

Review caught that the earlier commit fixed one reader of
`offsetTop + height` and left three, so a single pan still latched the
sheet into the unprotected behavior — matching the device symptom that
accessory-bar Next works down a form until something pans once, and
from there every Next pans and it never recovers.

A fully expanded Tall sheet is pinned to the layout viewport bottom, so
bodyBottom == innerHeight. At full pan `offsetTop + height` also equals
innerHeight, so overlap computes as 0: the inset is dropped, and
hasKeyboardLayout goes false, which disarms the head start. Measured
with bodyBottom = innerHeight = 768 and a 500px keyboard: 316px -> 0px,
after which this branch behaves exactly like main.

The pan-invariant quantity is the one the recovery check already uses.
The keyboard covers the bottom of the LAYOUT viewport, so its top edge
sits at visualViewport.height in client coordinates and stays there
under a pan — a pan slides the window over the page without moving the
keyboard. getUnobstructedBounds() returns that band and every reader
takes it. Identical when offsetTop is 0, so nothing off the pan path
moves.

The previous test for this passed only because rect({bottom: 800})
against jsdom's innerHeight of 768 left a 32px cushion, and its
348px -> 80px expectation encoded the bug: 268px of scroll range
vanishing during a pure pan. Both keyboard geometry tests now pin the
body to innerHeight, the way the real sheet sits.

Also from the same review:

- The tap path was taking the head start it does not need — it already
  focused with preventScroll — turning a glide between two fields into a
  snap. pendingPointerFocusScroll identifies it.
- The multi-touch guard covered pointerdown but not pointerup, so a
  resting thumb that lifted first still disarmed the tap in progress.
- scrollBy 'auto' defers to the element's computed scroll-behavior;
  'instant' is what a scroll racing the browser means.

Real story on the simulator, sheet top edge decoded from the scrim
boundary: 376px at rest, 376px after four accessory-bar Nexts, 376px
after eight, 376px across an app switch. Rebased onto main, which lands
the same insight in useSheetGestures (#5159).

* fix(core): drop the isPrimary check the early return subsumes

tsc caught it: the new guard narrows event.isPrimary to true, so the
later 'isPrimary !== false' compares two disjoint literal types. Only
the build runs tsc over this file — lint:strict and vitest both pass
it.

* fix(core): claim the focus transition instead of chasing the scroll

The browser reveals a newly focused field by scrolling the document, and
a fixed sheet rides along. Everything here so far tried to get in front
of that scroll or undo it afterwards, and both are races: the reveal
runs on the compositor, so the correction can land a frame late and read
as a pan followed by a snap back.

The reveal is attached to the focus operation, which is where it can be
refused. `blur` is dispatched in the capture phase ahead of the browser's
own focus step and names the destination in `relatedTarget`: focus it
there with preventScroll and the transition is settled before the
browser starts one. Its focus step finds the element already active,
dispatches nothing, and has nothing to reveal. A tap, the keyboard's
Next, Tab and a programmatic focus() all pass through that single
transition, so the special-cased tap path is gone with it.

Measured on an iPhone 17 simulator, counting real focus events with the
takeover on and off — tap-to-tap, accessory Previous/Next, and
programmatic a.focus()/b.focus() — every case is exactly one focus, one
focusin, one blur, one focusout per transition, identical either way.
That is PR #5043's B1 concern, which blocked this approach: it does not
reproduce in WebKit. It does reproduce in jsdom, whose focus() is not
re-entrancy-safe, so the handler ignores a blur raised by its own
delivery and a test pins that.

Also from the same pass:

- Revealing the field is left to the existing focusin/viewport-resize
  path rather than duplicated in the new handler.
- A blur to nowhere — the keyboard's Done button — parks focus on the
  sheet. Left on the body, the field is still activeElement on the next
  tap, so no transition fires and the browser reveals it its own way.
- `overscroll-behavior: contain` ships as a stylesheet in its own layer
  while the sheet is open. Current iOS latches this at touchstart, too
  late for a listener to set, and the sheet body's own rule does not
  cover a nested scroller in consumer content.

The document-scroll restoration stays: app resume raises no focus event
at all, so it is the only thing covering that case, and a test fails
without it.

Real story on the simulator, sheet top decoded from the scrim boundary:
376px focused, 376px after six accessory-bar Nexts, 376px across an app
switch. Net -53 lines in the hook.

* fix(core): scope the keyboard hook to what it can prove

Self-review of this PR, with each finding reproduced before it was
changed.

A regression this PR introduced: behind a NON-MODAL sheet the page stays
scrollable by design, and the document-scroll net was reverting the
user's own scrolling to wherever the keyboard opened. The net exists for
one case — app resume, which raises no focus event to claim — and that
case only arises when the page is locked, which is exactly when a
document scroll cannot be the user's. The host knows; it now says so
through `isPageScrollLocked`, and a test covers a non-modal page scroll.

Removed, as machinery for cases that cannot happen:

- The re-entrancy guard around the claim. Real WebKit dispatches nothing
  further once the destination is focused — measured — so the guard was
  defending a jsdom artifact, and it would have dropped a legitimate
  chained transition where a consumer's own focus handler moves focus
  on. Its test went with it.
- The global `overscroll-behavior: contain` stylesheet. It addresses
  scroll chaining, which is a different mechanism, and nothing here was
  shown to need it. Worth revisiting with a case that fails without it.
- A dead `isActiveRef`, orphaned when the tap path went; a `top: 0` that
  was always zero, so the obstruction is now the single number it always
  was; and two comments describing a head start that no longer exists.

Narrowed: parking focus on the sheet after a blur to nowhere is for
keeping the NEXT tap claimable, so it no longer fires while the sheet is
closing — the host is restoring focus to the opener there.

Every guard now fails a test when removed, including the claim itself.
Real story on the simulator, sheet top from the scrim boundary: 376px
focused, 376px after six accessory-bar Nexts, 376px across an app
switch. Rebased onto main (#5172).

* fix(core): refuse the reveal when the sheet autofocuses a field

Review found the claim has a blind spot: presenting a sheet that
autofocuses a field is not a transition. Nothing was focused, so no blur
names the destination, and `focusPanel` was delivering that focus
unprevented — leaving the browser to reveal the field by scrolling the
page, the exact bug this PR is about. Both of its focus calls now pass
preventScroll; the sheet was about to show the field anyway, and
useMobileKeyboard brings it into view within the sheet.

Also from the same review:

- Two tests asserted nothing. They fired pointerdown/pointerup and
  expected no focus, but the hook has had no pointer listeners since the
  claim replaced them, so both passed at every height and detent — the
  opposite of what they are named for. They now drive a blur-named
  transition, which is what the gate actually governs, and the shorter-
  detent one fails when that gate is removed. The last user of
  `fireTouchPointer` went with them, so the helper is gone.
- The `height` doc said which heights opt out but not that a Tall sheet
  opts out under the user's own drag and opts back in when dragged
  up. It says so now.

Caret placement was raised as an untested assumption, since claiming the
focus ahead of the click could cost the tap's caret position. Measured
in Mobile Safari, tapping into the middle of a populated field with a
prior field focused: caret offset 40 of 40 with the claim, and 40 of 40
without it. Identical, so the click's hit test still owns the caret. A
tap into a field that is already focused cannot be affected at all — the
claim no-ops when the destination is already active.
@github-actions
github-actions Bot deleted the codex/bottom-sheet-viewport-resize branch August 18, 2026 06:11

This branch was successfully deployed

1 active deployment
Preview — f34a3d32 Deployed Aug 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant