From a2cf19a7d5b2802822d364fcb2402a76dacabbbd Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Sat, 24 Oct 2026 04:03:48 -0700 Subject: [PATCH 1/3] fix(core): an anchored layer ends above the software keyboard On iOS 26.2 a popover that would run under the software keyboard keeps its top on its source and shrinks so its far edge stays 10 pt above the keyboard; its content scrolls, and it grows back when the keyboard goes down. On main the keyboard covers the lower part of any anchored layer (a Popover, a menu, a Selector's list), and a button there cannot be reached until the keyboard is dismissed. The layer runtime now caps every open anchor-mode layer. useLayerKeyboardClearance, imported through the runtime's touch module LayerTouch.ts, reads the keyboard module's one height (getKeyboardHeight, and the layout guide for timing). It writes the room above the keyboard as a custom property on the layer's own element. The runtime's block-size cap (layerViewportInset.maxBlockSize) folds it in, so the layer box and every surface capped by that definition shrink together. A layer nested in a capped one sets its own value, so it is not clamped. - Timing: a rising keyboard covers the difference on its way up, so the cap comes when it has arrived: UIKit's notification duration after it started, or the end of Gboard's slide in Chrome. A falling one takes it off at once, and a keyboard that changes at once is followed at once. A change under a press inside the layer waits for its click, through the shared wait for the browser's click. - A layer opened with the keyboard up is capped in the frame before its first paint. Its box is read with settledBox, as the fallback order reads it: without the entrance transform. Only a layer whose committed element carries data-layer-anchored is capped. - A layer element the runtime swaps in while open is measured again from its own box before it paints: the runtime's layer ref callback hands it to the cap. The viewport is read in layout px. - The Selector, MultiSelector, Typeahead, Breadcrumbs and ContextMenu lists cap their 300 px at the layer's block-size cap. A panel with a search field is a flex column capped as a whole. - Left as they are: a layer clear of the keyboard, a layer whose bottom the fallback order holds (above its trigger), and a layer in custom or fixed positioning. - A menu's on-demand sheet keeps its keyboard code on demand: the cap imports the keyboard module's own files (lazy-sheet-bundle test). --- .changeset/layer-keyboard-clearance.md | 7 + apps/storybook/stories/Popover.stories.tsx | 74 ++ .../core/src/Breadcrumbs/BreadcrumbItem.tsx | 8 +- packages/core/src/ContextMenu/ContextMenu.tsx | 8 +- .../src/DropdownMenu/DropdownMenu.test.tsx | 10 +- .../DropdownMenu/DropdownMenuSubMenu.test.tsx | 2 +- packages/core/src/Layer/LayerTouch.ts | 17 + ...ardCappedLists.interaction.browser.spec.ts | 194 +++++ .../core/src/Layer/layerKeyboardClearance.ts | 55 ++ .../layerViewportInset.source-build.test.mjs | 6 +- .../src/Layer/layerViewportInset.stylex.ts | 21 +- .../core/src/Layer/layerViewportInset.test.ts | 15 +- packages/core/src/Layer/settledBox.ts | 138 ++++ packages/core/src/Layer/useLayer.tsx | 157 +--- .../Layer/useLayerKeyboardClearance.test.tsx | 766 ++++++++++++++++++ .../src/Layer/useLayerKeyboardClearance.ts | 366 +++++++++ .../core/src/MultiSelector/MultiSelector.tsx | 26 +- packages/core/src/Popover/Popover.tsx | 3 + ...opoverKeyboard.interaction.browser.spec.ts | 359 ++++++++ packages/core/src/Selector/Selector.tsx | 26 +- packages/core/src/Typeahead/BaseTypeahead.tsx | 9 +- .../core/src/theme/derivedVarRegistry.test.ts | 5 + scripts/lazy-sheet-bundle.test.mjs | 129 +++ 23 files changed, 2256 insertions(+), 145 deletions(-) create mode 100644 .changeset/layer-keyboard-clearance.md create mode 100644 packages/core/src/Layer/LayerTouch.ts create mode 100644 packages/core/src/Layer/__tests__/keyboardCappedLists.interaction.browser.spec.ts create mode 100644 packages/core/src/Layer/layerKeyboardClearance.ts create mode 100644 packages/core/src/Layer/settledBox.ts create mode 100644 packages/core/src/Layer/useLayerKeyboardClearance.test.tsx create mode 100644 packages/core/src/Layer/useLayerKeyboardClearance.ts create mode 100644 packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts create mode 100644 scripts/lazy-sheet-bundle.test.mjs diff --git a/.changeset/layer-keyboard-clearance.md b/.changeset/layer-keyboard-clearance.md new file mode 100644 index 0000000000000..27883a3195134 --- /dev/null +++ b/.changeset/layer-keyboard-clearance.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] An anchored layer (a Popover, a menu, a Selector's or MultiSelector's panel, a Typeahead's list) that would run under the software keyboard, in Safari on iOS, now keeps its top and shrinks to end 10 px above the keyboard, its content scrolling, and grows back when the keyboard goes down; before, the keyboard covered its lower part and a button there could not be reached. A layer clear of the keyboard, or placed above its trigger, does not change. + +@vjeux diff --git a/apps/storybook/stories/Popover.stories.tsx b/apps/storybook/stories/Popover.stories.tsx index b0f91b75752ac..98201b060ca7d 100644 --- a/apps/storybook/stories/Popover.stories.tsx +++ b/apps/storybook/stories/Popover.stories.tsx @@ -13,6 +13,7 @@ import {List, ListItem} from '@astryxdesign/core/List'; import {VStack, HStack} from '@astryxdesign/core/Layout'; import {Text, Heading} from '@astryxdesign/core/Text'; import {Switch} from '@astryxdesign/core/Switch'; +import {TextInput} from '@astryxdesign/core/TextInput'; import {CheckboxInput} from '@astryxdesign/core/CheckboxInput'; import {Divider} from '@astryxdesign/core/Divider'; import {Section} from '@astryxdesign/core/Section'; @@ -821,6 +822,79 @@ export const TriggerInteractionEvidence: Story = { }, }; +// ============================================================================= +// Keyboard Avoidance +// ============================================================================= + +const NOTE_TIPS = [ + 'Notes are shared with everyone on the project.', + 'Mention a teammate to send them the note.', + 'Pin a note to keep it at the top of the list.', + 'Notes older than a year are archived.', + 'Attach a file by dropping it on the note.', + 'Use a short title: it is what the list shows.', +]; + +function NoteContent() { + const [title, setTitle] = React.useState(''); + return ( + + + Add a note + + + + {NOTE_TIPS.map(tip => ( + {tip} + ))} + + + ); +} + +function SearchNotesField() { + const [query, setQuery] = React.useState(''); + return ( +
+ +
+ ); +} + +export const KeyboardAvoidance: Story = { + name: 'Keyboard Avoidance', + parameters: { + layout: 'fullscreen', + docs: { + story: {inline: false, height: '844px'}, + description: { + story: + 'A tall popover with a text field. On a phone, the field brings up the software keyboard; the popover keeps its top and stays clear of the keyboard, as a popover on iOS does. Search notes, below the trigger, brings the keyboard up before the popover opens: it then opens clear of the keyboard.', + }, + }, + }, + render: () => ( +
+ }> + + + +
+ ), +}; + export const KeepPopoverPresentation: Story = { name: 'Keep Popover Presentation', parameters: { diff --git a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx index ebd6dac4e00f4..a959058ba9dad 100644 --- a/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx +++ b/packages/core/src/Breadcrumbs/BreadcrumbItem.tsx @@ -58,6 +58,7 @@ import {menuTouchActionStyles} from '../DropdownMenu/menuTouchAction.stylex'; import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow'; import {useTypeahead} from '../hooks/useTypeahead'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; +import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems'; import { DropdownMenuContext, @@ -254,7 +255,12 @@ const menuStyles = stylex.create({ display: 'flex', flexDirection: 'column', gap: spacingVars['--spacing-0-5'], - maxHeight: '300px', + // 300 px, and no taller than its layer's block-size cap, which folds in + // the software keyboard's. + maxHeight: stylex.firstThatWorks( + `min(300px, ${layerViewportInset.maxBlockSize})`, + `min(300px, ${layerViewportInset.maxBlockSizeFallback})`, + ), overflowY: 'auto', '--_dropdown-menu-radius': radiusVars['--radius-container'], '--_dropdown-menu-padding': spacingVars['--spacing-1'], diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx index ffc0999b774fe..0219e56f8d325 100644 --- a/packages/core/src/ContextMenu/ContextMenu.tsx +++ b/packages/core/src/ContextMenu/ContextMenu.tsx @@ -80,6 +80,7 @@ import {useMenuPress} from '../hooks/useMenuPress'; import {useTypeahead} from '../hooks/useTypeahead'; import {useLongPress} from '../hooks/useLongPress'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; +import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import { colorVars, spacingVars, @@ -146,7 +147,12 @@ const styles = stylex.create({ display: 'flex', flexDirection: 'column', gap: spacingVars['--spacing-0-5'], - maxHeight: '300px', + // 300 px, and no taller than its layer's block-size cap, which folds in + // the software keyboard's. + maxHeight: stylex.firstThatWorks( + `min(300px, ${layerViewportInset.maxBlockSize})`, + `min(300px, ${layerViewportInset.maxBlockSizeFallback})`, + ), overflowY: 'auto', '--_dropdown-menu-radius': radiusVars['--radius-container'], '--_dropdown-menu-padding': spacingVars['--spacing-1'], diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx index c76e5622f0b7f..be919d3733252 100644 --- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx @@ -797,7 +797,7 @@ describe('DropdownMenu', () => { ); }); expect(menu).toHaveStyle( - 'max-height: min(300px,calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))))', + 'max-height: min(300px,min(calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))), var(--astryx-layer-keyboard-max-block-size, 100dvb)))', ); expect(menu).not.toHaveStyle({overflowY: 'auto'}); expect(menu).toHaveAttribute('tabindex', '-1'); @@ -3362,11 +3362,13 @@ describe('DropdownMenu menuMaxHeight', () => { const menu = screen.getByRole('menu', {hidden: true}); // The cap is lifted to the given height, still bounded by the viewport. expect(menu).toHaveStyle({maxHeight: 'var(--x-maxHeight)'}); - expect(menu.getAttribute('style')).toContain('min(528px, calc(100dvb'); + expect(menu.getAttribute('style')).toContain('min(528px, min(calc(100dvb'); expect(menu.getAttribute('style')).not.toContain('min(300px'); // The popover viewport that holds the menu lifts its cap with it. const popover = menu.closest('[popover]'); - expect(popover?.getAttribute('style')).toContain('min(528px, calc(100dvb'); + expect(popover?.getAttribute('style')).toContain( + 'min(528px, min(calc(100dvb', + ); }); it('keeps the viewport bound below the raised cap', () => { @@ -3381,7 +3383,7 @@ describe('DropdownMenu menuMaxHeight', () => { />, ); const menu = screen.getByRole('menu', {hidden: true}); - expect(menu.getAttribute('style')).toContain('min(720px, calc(100dvb'); + expect(menu.getAttribute('style')).toContain('min(720px, min(calc(100dvb'); }); }); diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx index e3b322bedfd99..90798dcb620dc 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx @@ -126,7 +126,7 @@ describe('DropdownMenuSubMenu', () => { expect(popover).toHaveStyle({minWidth: 'var(--x-minWidth)'}); expect(popover?.getAttribute('style')).toContain('min(640px, calc(100vw'); expect(flyout).toHaveStyle( - 'max-height: min(300px,calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))))', + 'max-height: min(300px,min(calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))), var(--astryx-layer-keyboard-max-block-size, 100dvb)))', ); expect(flyout).not.toHaveStyle({overflowY: 'auto'}); expect(flyout).toHaveAttribute('tabindex', '-1'); diff --git a/packages/core/src/Layer/LayerTouch.ts b/packages/core/src/Layer/LayerTouch.ts new file mode 100644 index 0000000000000..a5af59bb65487 --- /dev/null +++ b/packages/core/src/Layer/LayerTouch.ts @@ -0,0 +1,17 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file LayerTouch.ts + * @input useLayerKeyboardClearance.ts (the software keyboard's part of the + * viewport caps) + * @output The layer runtime's touch layer: useLayerKeyboardClearance + * @position The one module the layer runtime imports touch-only code through, + * and its only import site is useLayer.tsx. It is imported statically, as + * every touch module is. + * + * SYNC: When modified, keep every touch-only import of useLayer.tsx here. + */ + +export {useLayerKeyboardClearance} from './useLayerKeyboardClearance'; diff --git a/packages/core/src/Layer/__tests__/keyboardCappedLists.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/keyboardCappedLists.interaction.browser.spec.ts new file mode 100644 index 0000000000000..73f69d1e1d196 --- /dev/null +++ b/packages/core/src/Layer/__tests__/keyboardCappedLists.interaction.browser.spec.ts @@ -0,0 +1,194 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file keyboardCappedLists.interaction.browser.spec.ts + * @input The Selector, MultiSelector, Typeahead, Breadcrumbs and ContextMenu + * stories, and a stand-in + * software keyboard that drives `window.visualViewport` + * @output Proves each list or menu ends 10 px above the keyboard once the + * keyboard caps its layer. A list or menu that is its layer's only content + * folds the layer's block-size cap into its own height limit. A panel with + * a search field is capped as a whole, and its list takes what the field's + * row leaves. + * @position Layer runtime: browser proof of the keyboard cap inside the + * composing components; the cap itself is proven by the Popover keyboard + * spec + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + openStory, + waitForRest, + withStorybook, +} from '@astryxdesign/interaction-harness'; +import {LAYER_KEYBOARD_CLEARANCE_PX} from '../layerKeyboardClearance'; +import {timing} from '../../motion/uikit/timing'; + +const storybook = withStorybook(test); + +// How far above the open list's end the stand-in keyboard's top comes: each +// list runs under it, whatever its length. +const UNDER = 60; + +/** + * Replaces `window.visualViewport` before the page loads with one the test + * drives: `__keyboard(cover)` shrinks it from the bottom and fires one + * `resize`, as Mobile Safari does. The keyboard module measures it wherever + * a visual viewport exists (spec:AST-099 FR6). + */ +async function installKeyboard(page: Page) { + await page.addInitScript(() => { + const viewport = Object.assign(new EventTarget(), { + height: window.innerHeight, + width: window.innerWidth, + offsetTop: 0, + offsetLeft: 0, + pageTop: 0, + pageLeft: 0, + scale: 1, + }); + Object.defineProperty(window, 'visualViewport', { + configurable: true, + get: () => viewport, + }); + (window as unknown as {__keyboard: (cover: number) => void}).__keyboard = + cover => { + viewport.height = window.innerHeight - cover; + viewport.dispatchEvent(new Event('resize')); + }; + }); +} + +/** Raises the stand-in keyboard to `cover` and waits until it has arrived. */ +async function raiseKeyboard(page: Page, cover: number) { + await page.evaluate( + value => + (window as unknown as {__keyboard: (cover: number) => void}).__keyboard( + value, + ), + cover, + ); + await page.waitForTimeout(timing.keyboardNotificationMs + 100); +} + +/** + * Where the list's visible part ends: the bottom of the scroll container it + * scrolls in (itself, or the dropdown around it). + */ +const visibleEnd = async (list: Locator) => + list.evaluate(element => { + let node: Element | null = element; + while (node != null && node !== document.body) { + const overflow = getComputedStyle(node).overflowY; + if (overflow === 'auto' || overflow === 'scroll') { + return node.getBoundingClientRect().bottom; + } + node = node.parentElement; + } + return element.getBoundingClientRect().bottom; + }); + +/** The line the list must end above: the keyboard's top, less the clearance. */ +const limitOf = async (page: Page) => + page.evaluate( + clearance => + (window.visualViewport?.height ?? window.innerHeight) - clearance, + LAYER_KEYBOARD_CLEARANCE_PX, + ); + +const cases: { + name: string; + story: string; + open: (page: Page) => Promise; +}[] = [ + { + name: 'Selector', + story: 'core-selector--default', + open: async page => { + await page.locator('button[aria-haspopup="listbox"]').first().click(); + return page.getByRole('listbox'); + }, + }, + { + name: 'MultiSelector', + story: 'core-multiselector--default', + open: async page => { + await page.locator('button[aria-haspopup="listbox"]').first().click(); + return page.getByRole('listbox'); + }, + }, + { + name: 'A searchable Selector', + story: 'core-selector--searchable', + open: async page => { + await page.locator('button[aria-haspopup="listbox"]').first().click(); + // The keyboard is up for the search field, whose row stays above the list. + await page.getByRole('combobox', {name: 'Search options'}).focus(); + return page.getByRole('listbox'); + }, + }, + { + name: 'A searchable MultiSelector', + story: 'core-multiselector--searchable', + open: async page => { + await page.locator('button[aria-haspopup="listbox"]').first().click(); + await page.getByRole('combobox', {name: 'Search options'}).focus(); + return page.getByRole('listbox'); + }, + }, + { + name: "A Breadcrumb crumb's menu", + story: 'core-breadcrumbs--menu-crumb', + open: async page => { + await page.getByRole('button', {name: 'Teams'}).click(); + return page.getByRole('menu'); + }, + }, + { + name: 'A ContextMenu', + story: 'core-contextmenu--default', + open: async page => { + await page.getByText('Right-click this area').click({button: 'right'}); + return page.getByRole('menu'); + }, + }, + { + name: 'Typeahead', + story: 'core-typeahead--default', + open: async page => { + const input = page.getByRole('combobox'); + await input.click(); + await input.fill('e'); + return page.getByRole('listbox'); + }, + }, +]; + +for (const {name, story, open} of cases) { + test(`${name}: its list ends ${LAYER_KEYBOARD_CLEARANCE_PX} px above the keyboard once the keyboard caps its layer`, async ({ + page, + }) => { + await installKeyboard(page); + await openStory(page, storybook(), story); + const list = await open(page); + await expect(list).toBeVisible(); + const layer = page.locator('[popover]').filter({has: list}).first(); + await waitForRest(layer); + // A keyboard whose top comes UNDER px above the open list's end. + const before = await visibleEnd(list); + const innerHeight = await page.evaluate(() => window.innerHeight); + await raiseKeyboard( + page, + innerHeight - (Math.min(before, innerHeight) - UNDER), + ); + await waitForRest(layer); + expect(await visibleEnd(list)).toBeLessThanOrEqual( + (await limitOf(page)) + 1, + ); + }); +} diff --git a/packages/core/src/Layer/layerKeyboardClearance.ts b/packages/core/src/Layer/layerKeyboardClearance.ts new file mode 100644 index 0000000000000..c4446b19a6616 --- /dev/null +++ b/packages/core/src/Layer/layerKeyboardClearance.ts @@ -0,0 +1,55 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file layerKeyboardClearance.ts + * @input A layer's box, the layout viewport's height and the keyboard's + * cover + * @output Exports `LAYER_KEYBOARD_CLEARANCE_PX`, `LAYER_ANCHORED_ATTRIBUTE` and + * `keyboardClearanceCap` + * @position Layer runtime: the software keyboard cap's numbers, with no DOM + * and no React. A browser proof can import them on its own. + * useLayerKeyboardClearance.ts applies them. + * + * SYNC: When modified, update: + * - /packages/core/src/Layer/useLayerKeyboardClearance.ts + * - /packages/core/src/Layer/useLayerKeyboardClearance.test.tsx + */ + +/** + * How far above the software keyboard a capped layer ends, CSS px. It is the + * clearance UIKit keeps under a popover the keyboard would cover. + * @source measured: UIKit lab, iOS 26.2 simulator, iPhone 17 Pro. A + * 320 × 533 popover below a source at y 160 (top 204) shrank to 325 pt. + * Its bottom stopped at 529, with the keyboard's top at about 539. It + * shrank from UIKeyboardWillShow over the keyboard's 0.3833 s, and grew + * back the same way on the hide. A 320 × 240 popover clear of the keyboard + * did not move. + */ +export const LAYER_KEYBOARD_CLEARANCE_PX = 10; + +/** + * The attribute useLayer.tsx renders on a layer in anchor positioning. The + * cap reads it from the committed element at measurement, not from a value a + * render wrote. Only an anchored layer is capped. + */ +export const LAYER_ANCHORED_ATTRIBUTE = 'data-layer-anchored'; + +/** + * The block size that keeps a layer `LAYER_KEYBOARD_CLEARANCE_PX` above a + * keyboard covering `inset` px of the layout viewport's bottom. It is null + * when the layer, at its own size, is already clear of the keyboard. + */ +export function keyboardClearanceCap( + box: {top: number; bottom: number}, + viewportHeight: number, + inset: number, +): number | null { + if (inset <= 0) { + return null; + } + const limit = viewportHeight - inset - LAYER_KEYBOARD_CLEARANCE_PX; + if (box.bottom <= limit) { + return null; + } + return Math.max(0, limit - box.top); +} diff --git a/packages/core/src/Layer/layerViewportInset.source-build.test.mjs b/packages/core/src/Layer/layerViewportInset.source-build.test.mjs index 53048c89aaf4c..123e744bf856f 100644 --- a/packages/core/src/Layer/layerViewportInset.source-build.test.mjs +++ b/packages/core/src/Layer/layerViewportInset.source-build.test.mjs @@ -74,14 +74,16 @@ describe('layer viewport inset stylesheet (spec:AST-059)', () => { const inlineCaps = declarations(css, 'max-width'); expect(blockCaps).toContainEqual( - expect.stringMatching(/^calc\(calc\(100dvb - .*safe-area-inset-top/), + expect.stringMatching( + /^calc\(min\(calc\(100dvb - .*safe-area-inset-top.*var\(--astryx-layer-keyboard-max-block-size, 100dvb\)/, + ), ); expect(inlineCaps).toContainEqual( expect.stringMatching(/^calc\(calc\(100vi - .*safe-area-inset-left/), ); // The older-engine fallbacks still ship, ahead of the preferred value. expect(blockCaps).toContainEqual( - expect.stringMatching(/^calc\(calc\(100vh - /), + expect.stringMatching(/^calc\(min\(calc\(100vh - /), ); expect(inlineCaps).toContainEqual( expect.stringMatching(/^calc\(calc\(100vw - /), diff --git a/packages/core/src/Layer/layerViewportInset.stylex.ts b/packages/core/src/Layer/layerViewportInset.stylex.ts index defcbdc121307..704571144d0a3 100644 --- a/packages/core/src/Layer/layerViewportInset.stylex.ts +++ b/packages/core/src/Layer/layerViewportInset.stylex.ts @@ -2,8 +2,10 @@ /** * @file layerViewportInset.stylex.ts - * @input Uses the spacing token, the device safe-area insets, and the - * app-declared `--astryx-layer-inset-*` custom properties + * @input Uses the spacing token, the device safe-area insets, the + * app-declared `--astryx-layer-inset-*` custom properties, and the + * keyboard cap each layer's own style declares + * (`--astryx-layer-keyboard-max-block-size`) * @output Exports the one definition of an anchored layer's viewport gutter * and the size caps derived from it * @position Layer runtime geometry; read by useLayer and by consumers that @@ -27,6 +29,7 @@ * * SYNC: When modified, update these files to stay in sync: * - /packages/core/src/Layer/useLayer.tsx + * - /packages/core/src/Layer/useLayerKeyboardClearance.ts * - /packages/core/src/Layer/layerViewportInset.test.ts * - /docs/specs/AST-059-layer-viewport-inset/spec.md */ @@ -42,6 +45,10 @@ const INSET_BLOCK_START = 'var(--astryx-layer-inset-block-start, 0px)'; const INSET_BLOCK_END = 'var(--astryx-layer-inset-block-end, 0px)'; const INSET_INLINE_START = 'var(--astryx-layer-inset-inline-start, 0px)'; const INSET_INLINE_END = 'var(--astryx-layer-inset-inline-end, 0px)'; +// Each layer's own style declares the room the software keyboard leaves it +// (useLayer.tsx's `keyboardCap`, from useLayerKeyboardClearance.ts). An +// uncapped layer declares a limit out of reach. +const KEYBOARD_CAP_PROPERTY = '--astryx-layer-keyboard-max-block-size'; const GUTTER_BLOCK_START = `calc(max(${SPACING}, env(safe-area-inset-top, 0px)) + ${INSET_BLOCK_START})`; const GUTTER_BLOCK_END = `calc(max(${SPACING}, env(safe-area-inset-bottom, 0px)) + ${INSET_BLOCK_END})`; @@ -79,7 +86,11 @@ export const layerViewportInset = stylex.defineConsts({ /** The largest inline size a layer may take: the viewport minus both gutters. */ maxInlineSize: `calc(100vi - ${GUTTER_INLINE_LEFT} - ${GUTTER_INLINE_RIGHT})`, maxInlineSizeFallback: `calc(100vw - ${SPACING} - ${SPACING} - ${INSET_INLINE_START} - ${INSET_INLINE_END})`, - /** The largest block size a layer may take: the viewport minus both gutters. */ - maxBlockSize: `calc(100dvb - ${GUTTER_BLOCK_START} - ${GUTTER_BLOCK_END})`, - maxBlockSizeFallback: `calc(100vh - ${SPACING} - ${SPACING} - ${INSET_BLOCK_START} - ${INSET_BLOCK_END})`, + /** + * The largest block size a layer may take: the viewport minus both + * gutters. It is no more than the room the software keyboard leaves while + * it caps the layer. + */ + maxBlockSize: `min(calc(100dvb - ${GUTTER_BLOCK_START} - ${GUTTER_BLOCK_END}), var(${KEYBOARD_CAP_PROPERTY}, 100dvb))`, + maxBlockSizeFallback: `min(calc(100vh - ${SPACING} - ${SPACING} - ${INSET_BLOCK_START} - ${INSET_BLOCK_END}), var(${KEYBOARD_CAP_PROPERTY}, 100vh))`, }); diff --git a/packages/core/src/Layer/layerViewportInset.test.ts b/packages/core/src/Layer/layerViewportInset.test.ts index 7627ff8a45ade..2c70ff908a207 100644 --- a/packages/core/src/Layer/layerViewportInset.test.ts +++ b/packages/core/src/Layer/layerViewportInset.test.ts @@ -64,11 +64,22 @@ describe('layerViewportInset (spec:AST-059)', () => { } }); + it('caps the block axis to the room the software keyboard leaves while it caps the layer (FR9)', () => { + expect(layerViewportInset.maxBlockSize).toContain( + 'var(--astryx-layer-keyboard-max-block-size, 100dvb)', + ); + expect(layerViewportInset.maxBlockSizeFallback).toContain( + 'var(--astryx-layer-keyboard-max-block-size, 100vh)', + ); + }); + it('caps both axes to the viewport minus both gutters, with env()-less fallbacks (FR2, FR3)', () => { expect(layerViewportInset.maxInlineSize).toMatch(/^calc\(100vi - /); - expect(layerViewportInset.maxBlockSize).toMatch(/^calc\(100dvb - /); + expect(layerViewportInset.maxBlockSize).toMatch(/^min\(calc\(100dvb - /); expect(layerViewportInset.maxInlineSizeFallback).toMatch(/^calc\(100vw - /); - expect(layerViewportInset.maxBlockSizeFallback).toMatch(/^calc\(100vh - /); + expect(layerViewportInset.maxBlockSizeFallback).toMatch( + /^min\(calc\(100vh - /, + ); for (const value of [ layerViewportInset.maxInlineSizeFallback, layerViewportInset.maxBlockSizeFallback, diff --git a/packages/core/src/Layer/settledBox.ts b/packages/core/src/Layer/settledBox.ts new file mode 100644 index 0000000000000..92de387c6522a --- /dev/null +++ b/packages/core/src/Layer/settledBox.ts @@ -0,0 +1,138 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file settledBox.ts + * @input A layer element + * @output Exports `settledBox`: the layer's box where its position option put + * it, without the transform an entrance (or anything else) applies to it + * @position Layer runtime: the one box read the fallback order and the + * software keyboard's cap both measure with (useLayer.tsx, + * useLayerKeyboardClearance.ts) + * + * SYNC: When modified, update: + * - /packages/core/src/Layer/useLayer.tsx + * - /packages/core/src/Layer/useLayerKeyboardClearance.ts + */ + +const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate']; + +function hasTransform(style: CSSStyleDeclaration): boolean { + return TRANSFORM_PROPERTIES.some(name => { + const value = style.getPropertyValue(name); + return value !== '' && value !== 'none'; + }); +} + +/** + * `rect`, the box of an element whose computed style still carries a 2D + * transform, with that transform undone. The transformed box's centre is the + * image of the element's centre. So undoing the transform about its origin on + * that centre gives the untransformed box, at the element's layout size. A + * transform this cannot undo (3D, or a rotation in another unit) leaves `rect` + * as it is. + */ +function untransform( + rect: DOMRect, + layer: HTMLElement, + style: CSSStyleDeclaration, +): DOMRect { + const set = (value: string) => value !== '' && value !== 'none'; + if (typeof DOMMatrix === 'undefined' || layer.offsetWidth <= 0) { + return rect; + } + // The individual transform properties apply before `transform`, in this + // order (CSS Transforms 2). + let matrix = new DOMMatrix(); + if (set(style.translate)) { + const [x = '0', y = '0', z] = style.translate.split(' '); + if (z != null) { + return rect; + } + matrix = matrix.translate(parseFloat(x), parseFloat(y)); + } + if (set(style.rotate)) { + if (!/^-?[\d.]+deg$/.test(style.rotate)) { + return rect; + } + matrix = matrix.rotate(parseFloat(style.rotate)); + } + if (set(style.scale)) { + const [x = '1', y = x, z] = style.scale.split(' '); + if (z != null) { + return rect; + } + matrix = matrix.scale(parseFloat(x), parseFloat(y)); + } + if (set(style.transform)) { + matrix = matrix.multiply(new DOMMatrix(style.transform)); + } + if (!matrix.is2D) { + return rect; + } + const [originX = 0, originY = 0] = style.transformOrigin + .split(' ') + .map(value => parseFloat(value)); + const width = layer.offsetWidth; + const height = layer.offsetHeight; + const centre = matrix.transformPoint( + new DOMPoint(width / 2 - originX, height / 2 - originY), + ); + const left = rect.left + rect.width / 2 - centre.x - originX; + const top = rect.top + rect.height / 2 - centre.y - originY; + return new DOMRect(left, top, width, height); +} + +/** + * The layer's box where its position option put it, without the transform an + * entry animation (or anything else) applies to it. A Tooltip enters from a + * few pixels toward its trigger, scaled down. So the transformed box of a + * tooltip that fits beside its trigger can read as covering it while it + * enters. For this one read, the layer's transforms are overridden with + * `none !important`, which outranks an animation. They are restored in the + * same task, so no frame paints in between and the animation keeps running. + * Where the engine still applies an animated transform under that override + * (WebKit), the read box has that transform undone instead (`untransform`). A + * layer that transitions a transform property is not overridden, since + * restoring the value would start that transition. Its box has its transform + * undone. + */ +export function settledBox(layer: HTMLElement): DOMRect { + const view = layer.ownerDocument.defaultView; + const style = view?.getComputedStyle(layer); + if (style == null || !hasTransform(style)) { + return layer.getBoundingClientRect(); + } + const transitions = style.transitionProperty.split(',').map(p => p.trim()); + const durations = style.transitionDuration.split(',').map(parseFloat); + const transitioned = transitions.some( + (name, index) => + (name === 'all' || TRANSFORM_PROPERTIES.includes(name)) && + (durations[index % durations.length] ?? 0) > 0, + ); + if (transitioned) { + return untransform(layer.getBoundingClientRect(), layer, style); + } + const saved = TRANSFORM_PROPERTIES.map( + name => + [ + name, + layer.style.getPropertyValue(name), + layer.style.getPropertyPriority(name), + ] as const, + ); + for (const name of TRANSFORM_PROPERTIES) { + layer.style.setProperty(name, 'none', 'important'); + } + const box = layer.getBoundingClientRect(); + const under = view?.getComputedStyle(layer); + const settled = + under != null && hasTransform(under) ? untransform(box, layer, under) : box; + for (const [name, value, priority] of saved) { + if (value === '') { + layer.style.removeProperty(name); + } else { + layer.style.setProperty(name, value, priority); + } + } + return settled; +} diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index a1b531ff3d27f..3a90632beb700 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -36,6 +36,9 @@ import {resolveLayerPortalTarget} from './layerHost'; import {layerTextReset} from './layerTextReset.stylex'; import {layerStructureReset} from './layerStructureReset.stylex'; import {layerViewportInset} from './layerViewportInset.stylex'; +import {useLayerKeyboardClearance} from './LayerTouch'; +import {LAYER_ANCHORED_ATTRIBUTE} from './layerKeyboardClearance'; +import {settledBox} from './settledBox'; import {layerInsetProperties} from './layerInset'; import { LAYER_CLEARANCE_PROPERTY, @@ -60,6 +63,15 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {overlayPaddingReset} from '../Layout/overlayPaddingReset.stylex'; const styles = stylex.create({ + // The software keyboard's block-size cap, on the layer's own element. Every + // layer sets it, an uncapped one to a limit no viewport cap reaches. So a + // layer nested in a capped one does not inherit the outer cap. The surfaces + // inside a layer read it through `layerViewportInset.maxBlockSize`. + // SYNC: the property is LAYER_KEYBOARD_CAP_PROPERTY + // (useLayerKeyboardClearance.ts). + keyboardCap: (cap: string) => ({ + '--astryx-layer-keyboard-max-block-size': cap, + }), // Base reset for all layers base: { marginBlockStart: 0, @@ -479,128 +491,6 @@ function placeAfresh(layer: HTMLElement): void { }); } -const TRANSFORM_PROPERTIES = ['transform', 'translate', 'scale', 'rotate']; - -function hasTransform(style: CSSStyleDeclaration): boolean { - return TRANSFORM_PROPERTIES.some(name => { - const value = style.getPropertyValue(name); - return value !== '' && value !== 'none'; - }); -} - -/** - * `rect`, the box of an element whose computed style still carries a 2D - * transform, with that transform undone: the transformed box's centre is the - * image of the element's centre, so undoing the transform about its origin on - * that centre gives the untransformed box, at the element's layout size. A - * transform this cannot undo (3D, or a rotation in another unit) leaves `rect` - * as it is. - */ -function untransform( - rect: DOMRect, - layer: HTMLElement, - style: CSSStyleDeclaration, -): DOMRect { - const set = (value: string) => value !== '' && value !== 'none'; - if (typeof DOMMatrix === 'undefined' || layer.offsetWidth <= 0) { - return rect; - } - // The individual transform properties apply before `transform`, in this - // order (CSS Transforms 2). - let matrix = new DOMMatrix(); - if (set(style.translate)) { - const [x = '0', y = '0', z] = style.translate.split(' '); - if (z != null) { - return rect; - } - matrix = matrix.translate(parseFloat(x), parseFloat(y)); - } - if (set(style.rotate)) { - if (!/^-?[\d.]+deg$/.test(style.rotate)) { - return rect; - } - matrix = matrix.rotate(parseFloat(style.rotate)); - } - if (set(style.scale)) { - const [x = '1', y = x, z] = style.scale.split(' '); - if (z != null) { - return rect; - } - matrix = matrix.scale(parseFloat(x), parseFloat(y)); - } - if (set(style.transform)) { - matrix = matrix.multiply(new DOMMatrix(style.transform)); - } - if (!matrix.is2D) { - return rect; - } - const [originX = 0, originY = 0] = style.transformOrigin - .split(' ') - .map(value => parseFloat(value)); - const width = layer.offsetWidth; - const height = layer.offsetHeight; - const centre = matrix.transformPoint( - new DOMPoint(width / 2 - originX, height / 2 - originY), - ); - const left = rect.left + rect.width / 2 - centre.x - originX; - const top = rect.top + rect.height / 2 - centre.y - originY; - return new DOMRect(left, top, width, height); -} - -/** - * The layer's box where its position option put it, without the transform an - * entry animation (or anything else) applies to it: a Tooltip enters from a - * few pixels toward its trigger, scaled down, so the transformed box of a - * tooltip that fits beside its trigger can read as covering it while it - * enters. The layer's transforms are overridden with `none !important`, which - * outranks an animation, for this one read and then restored, in the same - * task: no frame paints in between and the animation keeps running. Where the - * engine still applies an animated transform under that override (WebKit), - * the read box has that transform undone instead (`untransform`). A layer - * that transitions a transform property is not overridden, since restoring the - * value would start that transition; its box has its transform undone. - */ -function settledBox(layer: HTMLElement): DOMRect { - const view = layer.ownerDocument.defaultView; - const style = view?.getComputedStyle(layer); - if (style == null || !hasTransform(style)) { - return layer.getBoundingClientRect(); - } - const transitions = style.transitionProperty.split(',').map(p => p.trim()); - const durations = style.transitionDuration.split(',').map(parseFloat); - const transitioned = transitions.some( - (name, index) => - (name === 'all' || TRANSFORM_PROPERTIES.includes(name)) && - (durations[index % durations.length] ?? 0) > 0, - ); - if (transitioned) { - return untransform(layer.getBoundingClientRect(), layer, style); - } - const saved = TRANSFORM_PROPERTIES.map( - name => - [ - name, - layer.style.getPropertyValue(name), - layer.style.getPropertyPriority(name), - ] as const, - ); - for (const name of TRANSFORM_PROPERTIES) { - layer.style.setProperty(name, 'none', 'important'); - } - const box = layer.getBoundingClientRect(); - const under = view?.getComputedStyle(layer); - const settled = - under != null && hasTransform(under) ? untransform(box, layer, under) : box; - for (const [name, value, priority] of saved) { - if (value === '') { - layer.style.removeProperty(name); - } else { - layer.style.setProperty(name, value, priority); - } - } - return settled; -} - /** * Whether the standard list has failed a layer that must keep its anchor * clear: its box covers the anchor or, while the anchor is in view, leaves the @@ -1647,6 +1537,13 @@ function useLayerImplementation( [handleBeforeToggle], ); + // An anchored layer that would run under the software keyboard keeps its + // block-start edge and ends clear of the keyboard. + const {cap: keyboardCap, followLayerElement} = useLayerKeyboardClearance( + isOpen && mode === 'context', + popoverRef, + ); + const popoverRefCallback = useCallback( (el: HTMLElement | null) => { popoverRef.current = el; @@ -1663,7 +1560,9 @@ function useLayerImplementation( // Changing a portal target remounts the popover. Preserve the logical // open state without firing onShow again for the replacement element. // A show the browser refused during one of its own hides replays once - // that hide has ended, for the element still mounted then. + // that hide has ended, for the element still mounted then. The + // keyboard cap follows the replacement element too. + followLayerElement(); if (showPopoverElement(el)) { if (keepsAnchorClear) { keepAnchorClear(el, triggerRef.current); @@ -1691,6 +1590,7 @@ function useLayerImplementation( showPopoverElement, isCurrentContextPopover, keepsAnchorClear, + followLayerElement, ], ); @@ -1882,6 +1782,7 @@ function useLayerImplementation( layerStructureReset.reset, styles.base, overlayPaddingReset.reset, + styles.keyboardCap(keyboardCap == null ? '100vh' : `${keyboardCap}px`), viewportStyles, offsetStyle, xstyle, @@ -1898,6 +1799,12 @@ function useLayerImplementation( void>(), + subscribe(listener: (transition: KeyboardTransition) => void) { + guide.listeners.add(listener); + return () => { + guide.listeners.delete(listener); + }; + }, + emit(transition: Partial) { + // A transition re-renders the layer with its cap. + act(() => guide.deliver(transition)); + }, + deliver(transition: Partial) { + for (const listener of guide.listeners) { + listener({ + kind: 'show', + from: 0, + to: 0, + start: performance.now(), + velocity: 0, + animated: true, + predicted: false, + curve: null, + ...transition, + }); + } + }, +}; + +// The cap imports the keyboard module's own files (not its index). +vi.mock('../keyboard/keyboardLayoutGuide', () => ({ + getKeyboardLayoutGuide: () => guide, +})); +vi.mock('../keyboard/keyboardHeight', async importOriginal => ({ + ...(await importOriginal()), + // The keyboard module's one height. + getKeyboardHeight: () => guide.inset, +})); + +// The browser's own click after a lift. A test calls the wait's handlers, as +// the shared wait does once a trusted click has run its handlers. +type ClickWait = {target: Element} & BrowserClickWaitHandlers; +const clickWaits = vi.hoisted(() => [] as ClickWait[]); +vi.mock('../utils/browserClickWait', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + awaitBrowserClick: ( + target: Element, + handlers: BrowserClickWaitHandlers, + ) => { + clickWaits.push({target, ...handlers}); + return actual.awaitBrowserClick(target, handlers); + }, + }; +}); + +/** The browser's click for the last lift, as the shared wait reports it. */ +const browserClick = () => { + act(() => clickWaits.at(-1)!.onClicked(false)); +}; + +// The layout viewport of an iPhone 17 Pro in Safari, and the cover the +// keyboard, its accessory bar and the toolbar report over it. +const VIEWPORT = 714; +const COVER = 337; +// A tall layer below its trigger: its box at rest. +const BOX = {top: 68, bottom: 509}; +const CAPPED = `${VIEWPORT - COVER - 10 - BOX.top}px`; + +function Harness({ + isOpen = true, + isAnchored = true, + box = BOX, + focusRow = false, + heldBottom = false, + layerKey = 'a', + entering, + shiftedTop, +}: { + isOpen?: boolean; + isAnchored?: boolean; + box?: {top: number; bottom: number}; + focusRow?: boolean; + heldBottom?: boolean; + /** A new key replaces the layer element while it stays open. */ + layerKey?: string; + /** + * Still entering: its entrance transform holds the layer this many px + * below where it settles. + */ + entering?: number; + /** + * At its full height the viewport fit places the layer here, higher than + * `box` and over its trigger; any shorter, it sits at `box`. + */ + shiftedTop?: number; +}) { + const layerRef = useRef(null); + const {cap, followLayerElement} = useLayerKeyboardClearance(isOpen, layerRef); + // The layer's box: its content height, no taller than the cap the hook + // returned. The runtime applies the cap as the layer's own style, which its + // block-size cap folds in; the harness applies it the same way. Below its + // trigger the top stays; above it the bottom does. + const height = (el: HTMLElement) => { + const cap = parseFloat( + el.style.getPropertyValue(LAYER_KEYBOARD_CAP_PROPERTY), + ); + const natural = box.bottom - box.top; + return Number.isNaN(cap) ? natural : Math.min(natural, cap); + }; + return ( +
{ + layerRef.current = el; + if (el != null) { + // As the runtime's layer ref callback does. + followLayerElement(); + Object.defineProperty(el, 'offsetHeight', { + configurable: true, + get: () => height(el), + }); + el.getBoundingClientRect = () => { + const h = height(el); + // The box an engine reports carries the entrance transform. + const shift = + entering != null && + el.style.getPropertyValue('transform') !== 'none' + ? entering + : 0; + const natural = box.bottom - box.top; + const start = + shiftedTop != null && h >= natural ? shiftedTop : box.top; + const top = (heldBottom ? box.bottom - h : start) + shift; + return { + top, + bottom: top + h, + left: 0, + right: 320, + width: 320, + height: h, + x: 0, + y: top, + toJSON: () => ({}), + }; + }; + } + }}> +
{ + if (el != null) { + Object.defineProperty(el, 'scrollHeight', { + configurable: true, + get: () => 441, + }); + Object.defineProperty(el, 'clientHeight', { + configurable: true, + get: () => height(layerRef.current ?? el), + }); + el.getBoundingClientRect = () => { + const h = height(layerRef.current ?? el); + return { + top: box.top, + bottom: box.top + h, + left: 0, + right: 320, + width: 320, + height: h, + x: 0, + y: box.top, + toJSON: () => ({}), + }; + }; + } + }}> + { + if (el != null && focusRow) { + el.getBoundingClientRect = () => ({ + top: 420, + bottom: 444, + left: 0, + right: 300, + width: 300, + height: 24, + x: 0, + y: 420, + toJSON: () => ({}), + }); + el.focus(); + } + }} + /> +
+
+ ); +} + +/** Runs the timers a keyboard change scheduled, inside act: they re-render. */ +const advance = (ms: number) => { + act(() => { + vi.advanceTimersByTime(ms); + }); +}; + +const capOf = (container: HTMLElement) => + container + .querySelector('[data-testid="layer"]')! + .style.getPropertyValue(LAYER_KEYBOARD_CAP_PROPERTY); + +describe('keyboardClearanceCap', () => { + it('keeps the far edge 10 pt above the keyboard, and leaves a layer clear of it', () => { + expect(LAYER_KEYBOARD_CLEARANCE_PX).toBe(10); + expect(keyboardClearanceCap(BOX, VIEWPORT, COVER)).toBe( + VIEWPORT - COVER - 10 - BOX.top, + ); + expect( + keyboardClearanceCap({top: 68, bottom: 300}, VIEWPORT, COVER), + ).toBeNull(); + expect(keyboardClearanceCap(BOX, VIEWPORT, 0)).toBeNull(); + expect(keyboardClearanceCap({top: 400, bottom: 600}, VIEWPORT, COVER)).toBe( + 0, + ); + }); +}); + +/** + * The cap a layer's own element declares: its own value of the cap property, + * through the StyleX variable its class reads. It is never one inherited from + * an ancestor layer. + */ +function ownCap(el: HTMLElement): string { + const declared = getComputedStyle(el) + .getPropertyValue(LAYER_KEYBOARD_CAP_PROPERTY) + .trim(); + const variable = /^var\((--[^),\s]+)/.exec(declared)?.[1]; + return variable == null + ? el.style.getPropertyValue(LAYER_KEYBOARD_CAP_PROPERTY).trim() + : el.style.getPropertyValue(variable).trim(); +} + +/** A layer from the runtime that holds a second layer from the runtime. */ +function NestedLayers() { + const outer = useLayer({mode: 'context'}); + const inner = useLayer({mode: 'context'}); + return ( + <> + + {outer.render( + <> + + {inner.render(Inner content, {className: 'inner'})} + , + {className: 'outer'}, + )} + + ); +} + +// A promise that never settles: a render that reads it suspends for good. +const never = new Promise(() => {}); + +function Suspends({when}: {when: boolean}) { + if (when) { + use(never); + } + return null; +} + +/** + * A layer from the runtime whose positioning a render can change; a render + * with `suspend` never commits. + */ +function Positioned({ + positioning, + suspend = false, +}: { + positioning: 'anchor' | 'custom'; + suspend?: boolean; +}) { + const layer = useLayer({mode: 'context'}); + return ( + <> + + {layer.render( + <> + + Content + , + {className: 'positioned', positioning}, + )} + + ); +} + +describe('useLayerKeyboardClearance', () => { + beforeEach(() => { + vi.useFakeTimers(); + guide.inset = 0; + guide.profile = null; + guide.listeners.clear(); + clickWaits.length = 0; + Object.defineProperty(window, 'innerHeight', { + configurable: true, + value: VIEWPORT, + }); + }); + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('caps a layer once a rising keyboard has arrived', () => { + const {container} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + // On its way up the keyboard covers the difference. + expect(capOf(container)).toBe(''); + advance(timing.keyboardNotificationMs + 1); + expect(capOf(container)).toBe(CAPPED); + }); + + it('caps a layer in Chrome when Gboard\u2019s slide ends, before UIKit\u2019s notification duration', () => { + guide.profile = 'chromium'; + const {container} = render(); + const slide: KeyboardCurve = {durationMs: 267, points: [0.1, 0, 0, 1]}; + guide.emit({kind: 'show', from: 0, to: COVER, curve: slide}); + advance(slide.durationMs - 1); + expect(capOf(container)).toBe(''); + advance(2); + expect(capOf(container)).toBe(CAPPED); + expect(slide.durationMs).toBeLessThan(timing.keyboardNotificationMs); + }); + + it('takes the cap off as soon as the keyboard starts down', () => { + const {container} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + guide.emit({kind: 'hide', from: COVER, to: 0}); + expect(capOf(container)).toBe(''); + }); + + it('follows a keyboard that changes at once, at once', () => { + const {container} = render(); + guide.emit({kind: 'change', from: 0, to: 300, animated: false}); + expect(capOf(container)).toBe(`${VIEWPORT - 300 - 10 - BOX.top}px`); + }); + + it('caps in layout px under a pinch zoom, where WebKit reports innerHeight zoomed (spec:AST-059 FR9)', () => { + // WebKit reports innerHeight and innerWidth in the zoomed visual + // viewport's px. Safari on iOS 26.2 reports 536 for a 714 px layout + // viewport at a 1.33 zoom. Boxes and the keyboard's height stay in layout + // px. A 1.5 zoom keeps the arithmetic exact. + const zoom = 1.5; + const saved = (['innerWidth', 'visualViewport'] as const).map( + key => [key, Object.getOwnPropertyDescriptor(window, key)] as const, + ); + Object.defineProperty(window, 'innerHeight', { + configurable: true, + value: VIEWPORT / zoom, + }); + Object.defineProperty(window, 'innerWidth', { + configurable: true, + value: 402 / zoom, + }); + Object.defineProperty(window, 'visualViewport', { + configurable: true, + value: {width: 402 / zoom, height: VIEWPORT / zoom, scale: zoom}, + }); + try { + const {container} = render(); + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + expect(capOf(container)).toBe(CAPPED); + } finally { + for (const [key, descriptor] of saved) { + if (descriptor == null) { + Reflect.deleteProperty(window, key); + } else { + Object.defineProperty(window, key, descriptor); + } + } + } + }); + + it('leaves a layer clear of the keyboard as it is', () => { + const {container} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + expect(capOf(container)).toBe(''); + }); + + it('caps a layer the viewport fit pushed up over its trigger from where it starts once it is shorter', () => { + const {container} = render(); + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + expect(capOf(container)).toBe(CAPPED); + }); + + it('reads a layer that is still entering without its entrance transform, in one read (spec:AST-059 FR8)', () => { + const {container} = render(); + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + expect(capOf(container)).toBe(CAPPED); + }); + + it('leaves a layer in another positioning as it is', () => { + const {container} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + expect(capOf(container)).toBe(''); + }); + + it('keeps the field being typed into in view in the layer\u2019s scroll container', () => { + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + callback(0); + return 0; + }); + const {container} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + const scroller = container.querySelector( + '[data-testid="scroller"]', + )!; + // The box ends at 714 - 337 - 10 = 367; the field's bottom is at 444. + expect(scroller.scrollTop).toBe(444 - 367); + }); + + it('caps a layer opened while a keyboard is up in the frame before it paints, and takes the cap off when it closes', () => { + guide.inset = COVER; + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + frames.push(callback); + return frames.length; + }); + const {container, rerender} = render(); + // The commit sees the layer unplaced; the next frame places it. + expect(capOf(container)).toBe(''); + act(() => { + for (const frame of frames.splice(0)) { + frame(0); + } + }); + expect(capOf(container)).toBe(CAPPED); + rerender(); + expect(capOf(container)).toBe(''); + expect(guide.listeners.size).toBe(0); + }); + + it('measures a layer element the runtime swaps in while open from its own box, before it paints (spec:AST-059 FR8)', () => { + const {container, rerender} = render(); + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + const before = container.querySelector( + '[data-testid="layer"]', + )!; + expect(capOf(container)).toBe(CAPPED); + guide.inset = COVER; + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + frames.push(callback); + return frames.length; + }); + // The new element sits lower than the old one: its own box decides. + const lower = {top: 100, bottom: 600}; + rerender(); + const after = container.querySelector( + '[data-testid="layer"]', + )!; + expect(after).not.toBe(before); + act(() => { + for (const frame of frames.splice(0)) { + frame(0); + } + }); + expect(capOf(container)).toBe(`${VIEWPORT - COVER - 10 - lower.top}px`); + // The keyboard going down takes the cap off the new element. + guide.emit({kind: 'hide', from: COVER, to: 0, animated: false}); + expect(capOf(container)).toBe(''); + }); + + it('measures a swapped-in layer element during a press in the layer at the press\u2019s click (spec:AST-059 FR10)', () => { + const {container, rerender} = render(); + guide.inset = COVER; + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + expect(capOf(container)).toBe(CAPPED); + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + frames.push(callback); + return frames.length; + }); + fireEvent.pointerDown( + container.querySelector('[data-testid="layer"]')!, + {pointerId: 5}, + ); + const lower = {top: 100, bottom: 600}; + rerender(); + act(() => { + for (const frame of frames.splice(0)) { + frame(0); + } + }); + // Held for the press's click: the layer does not move under the finger. + expect(capOf(container)).toBe(CAPPED); + fireEvent.pointerUp(window, {pointerId: 5}); + browserClick(); + expect(capOf(container)).toBe(`${VIEWPORT - COVER - 10 - lower.top}px`); + }); + + it('leaves a layer element swapped in under a rising keyboard to the keyboard\u2019s arrival (spec:AST-059 FR10)', () => { + const {container, rerender} = render(); + guide.inset = COVER; + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + frames.push(callback); + return frames.length; + }); + guide.emit({kind: 'show', from: 0, to: COVER}); + const lower = {top: 100, bottom: 600}; + rerender(); + act(() => { + for (const frame of frames.splice(0)) { + frame(0); + } + }); + // On its way up the keyboard covers the difference: no cap yet. + expect(capOf(container)).toBe(''); + advance(timing.keyboardNotificationMs + 1); + expect(capOf(container)).toBe(`${VIEWPORT - COVER - 10 - lower.top}px`); + }); + + it('follows a press in a replaced layer element to its click', () => { + const {container, rerender} = render(); + guide.inset = COVER; + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + rerender(); + const layer = container.querySelector( + '[data-testid="layer"]', + )!; + fireEvent.pointerDown(layer, {pointerId: 1}); + guide.emit({kind: 'hide', from: COVER, to: 0}); + // Held for the press's click. + expect(capOf(container)).toBe(CAPPED); + fireEvent.pointerUp(layer, {pointerId: 1}); + expect(clickWaits.at(-1)?.target).toBe(layer); + browserClick(); + expect(capOf(container)).toBe(''); + }); + + it('leaves a layer whose bottom the fallback order holds (above its trigger) as it is', () => { + const {container} = render( + , + ); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + // A shorter box would move its top down and still end under the keyboard. + expect(capOf(container)).toBe(''); + }); + + it('keeps the cap through a press inside the layer until its click', () => { + const {container, getByTestId} = render(); + const layer = getByTestId('layer'); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + expect(capOf(container)).toBe(CAPPED); + // A tap on a button in the layer blurs the field: the keyboard starts + // down while the finger is still on the button. + fireEvent.pointerDown(layer, {pointerId: 3}); + guide.emit({kind: 'hide', from: COVER, to: 0}); + expect(capOf(container)).toBe(CAPPED); + fireEvent.pointerUp(window, {pointerId: 3}); + expect(capOf(container)).toBe(CAPPED); + // The lift waits for the browser's click through the shared wait. + expect(clickWaits.map(wait => wait.target)).toEqual([layer]); + browserClick(); + expect(capOf(container)).toBe(''); + }); + + it('a press that makes no click lets the change go a moment after it lifts', () => { + const {container, getByTestId} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + advance(timing.keyboardNotificationMs + 1); + fireEvent.pointerDown(getByTestId('layer'), {pointerId: 4}); + guide.emit({kind: 'hide', from: COVER, to: 0}); + fireEvent.pointerUp(window, {pointerId: 4}); + advance(BROWSER_CLICK_WAIT_MS - 1); + expect(capOf(container)).toBe(CAPPED); + advance(1); + expect(capOf(container)).toBe(''); + }); + + it('a rising keyboard after the layer closed changes nothing', () => { + const {container, rerender} = render(); + guide.emit({kind: 'show', from: 0, to: COVER}); + rerender(); + advance(timing.keyboardNotificationMs + 1); + expect(capOf(container)).toBe(''); + }); + + it('follows a press to its click only while a press in the layer is live', () => { + const added: string[] = []; + const removed: string[] = []; + const add = window.addEventListener.bind(window); + const remove = window.removeEventListener.bind(window); + vi.spyOn(window, 'addEventListener').mockImplementation( + (type, listener, options) => { + added.push(type); + add(type, listener, options); + }, + ); + vi.spyOn(window, 'removeEventListener').mockImplementation( + (type, listener, options) => { + removed.push(type); + remove(type, listener, options); + }, + ); + const {getByTestId} = render(); + const press = (types: string[]) => + types.filter(type => + ['pointerup', 'pointercancel', 'click'].includes(type), + ); + // Open: nothing on the window yet. + expect(press(added)).toEqual([]); + const layer = getByTestId('layer'); + fireEvent.pointerDown(layer, {pointerId: 1}); + expect(press(added)).toEqual(['pointerup', 'pointercancel']); + fireEvent.pointerUp(layer, {pointerId: 1}); + // At the lift the shared wait listens for the browser's click. + expect(press(added)).toEqual(['pointerup', 'pointercancel', 'click']); + browserClick(); + expect(press(removed).sort()).toEqual([ + 'click', + 'pointercancel', + 'pointerup', + ]); + }); + + it('caps each layer on its own element, so a layer nested in a capped one is not clamped by it', () => { + const natural = BOX.bottom - BOX.top; + // The outer layer is tall and below its trigger; the inner one is short. + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation( + function (this: HTMLElement) { + if (!this.classList.contains('outer')) { + return DOMRect.fromRect({x: 0, y: 100, width: 100, height: 40}); + } + // Only a cap in px limits it; the uncapped limit is out of reach. + const cap = ownCap(this); + const height = cap.endsWith('px') + ? Math.min(natural, parseFloat(cap)) + : natural; + return DOMRect.fromRect({x: 0, y: BOX.top, width: 100, height}); + }, + ); + // A fixed layer is measured from its offset box. + vi.spyOn(HTMLElement.prototype, 'offsetTop', 'get').mockImplementation( + function (this: HTMLElement) { + return this.getBoundingClientRect().top; + }, + ); + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation( + function (this: HTMLElement) { + return this.getBoundingClientRect().height; + }, + ); + render(); + fireEvent.click(screen.getByText('Outer')); + fireEvent.click(screen.getByText('Inner')); + const outer = document.querySelector('.outer')!; + const inner = document.querySelector('.inner')!; + expect(outer.contains(inner)).toBe(true); + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + expect(ownCap(outer)).toBe(CAPPED); + // The inner layer declares its own, uncapped limit rather than + // inheriting the outer layer's cap. + expect(ownCap(inner)).toBe('100vh'); + guide.emit({kind: 'hide', from: COVER, to: 0, animated: false}); + expect(ownCap(outer)).toBe('100vh'); + }); + + it('decides from the positioning its last commit rendered, never from a render React threw away (react-component-runtime INV4)', () => { + const natural = BOX.bottom - BOX.top; + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation( + function (this: HTMLElement) { + if (!this.classList.contains('positioned')) { + return DOMRect.fromRect({x: 0, y: 30, width: 100, height: 30}); + } + const cap = ownCap(this); + const height = cap.endsWith('px') + ? Math.min(natural, parseFloat(cap)) + : natural; + return DOMRect.fromRect({x: 0, y: BOX.top, width: 100, height}); + }, + ); + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation( + function (this: HTMLElement) { + return this.getBoundingClientRect().height; + }, + ); + const {rerender} = render(); + fireEvent.click(screen.getByText('Open')); + const layer = document.querySelector('.positioned')!; + // A transition renders the layer in custom positioning and suspends: + // React throws that render away, and the anchored layer stays on screen. + act(() => { + startTransition(() => { + rerender(); + }); + }); + expect(document.querySelector('.positioned')).toBe(layer); + guide.emit({kind: 'change', from: 0, to: COVER, animated: false}); + expect(ownCap(layer)).toBe(CAPPED); + }); +}); diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.ts b/packages/core/src/Layer/useLayerKeyboardClearance.ts new file mode 100644 index 0000000000000..6b40bce2baba3 --- /dev/null +++ b/packages/core/src/Layer/useLayerKeyboardClearance.ts @@ -0,0 +1,366 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file useLayerKeyboardClearance.ts + * @input Whether an anchor-mode layer is open, its element, and the keyboard + * module: its one height, and its layout guide for timing. + * @output Exports `useLayerKeyboardClearance` and its result type, + * `keyboardClearanceCap`, `LAYER_ANCHORED_ATTRIBUTE`, + * `LAYER_KEYBOARD_CAP_PROPERTY` and `LAYER_KEYBOARD_CLEARANCE_PX` + * @position Layer runtime, through the layer's touch module: the software + * keyboard's part of the viewport caps + * + * SYNC: When modified, update: + * - /packages/core/src/Layer/layerKeyboardClearance.ts + * - /packages/core/src/Layer/settledBox.ts + * - /packages/core/src/Layer/useLayerKeyboardClearance.test.tsx + * - /packages/core/src/Layer/layerViewportInset.stylex.ts + * - /docs/specs/AST-059-layer-viewport-inset/spec.md + */ + +import {useCallback, useRef, useState, type RefObject} from 'react'; +import {flushSync} from 'react-dom'; +import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; +// The keyboard module's own files, not its index. The index also re-exports +// BottomSheet's keyboard hook. An import through it would put that hook's +// on-demand code in every layered component. +import {getKeyboardLayoutGuide} from '../keyboard/keyboardLayoutGuide'; +import {getKeyboardHeight} from '../keyboard/keyboardHeight'; +import {timing} from '../motion/uikit/timing'; +import { + keyboardClearanceCap, + LAYER_ANCHORED_ATTRIBUTE, + LAYER_KEYBOARD_CLEARANCE_PX, +} from './layerKeyboardClearance'; +import {settledBox} from './settledBox'; +import {awaitBrowserClick} from '../utils/browserClickWait'; +import {subscribeInput} from '../utils/inputStream'; +import {layoutViewportHeight} from '../utils/layoutViewport'; + +export { + keyboardClearanceCap, + LAYER_ANCHORED_ATTRIBUTE, + LAYER_KEYBOARD_CLEARANCE_PX, +} from './layerKeyboardClearance'; + +/** + * The custom property each layer's style sets (useLayer.tsx's `keyboardCap` + * style). It holds the largest block size that keeps the layer clear of the + * keyboard while it caps the layer. Otherwise it sets no limit. + */ +export const LAYER_KEYBOARD_CAP_PROPERTY = + '--astryx-layer-keyboard-max-block-size'; + +/** + * Scrolls the nearest scroll container between `target` and `layer` the + * least amount that shows `target` inside it. + */ +function keepInView(layer: HTMLElement, target: Element) { + const view = layer.ownerDocument.defaultView; + for ( + let box: HTMLElement | null = target.parentElement; + box != null; + box = box === layer ? null : box.parentElement + ) { + const overflowY = view?.getComputedStyle(box).overflowY; + if ( + box.scrollHeight > box.clientHeight + 1 && + (overflowY === 'auto' || overflowY === 'scroll') + ) { + const outer = box.getBoundingClientRect(); + const inner = target.getBoundingClientRect(); + if (inner.bottom > outer.bottom) { + box.scrollTop += inner.bottom - outer.bottom; + } else if (inner.top < outer.top) { + box.scrollTop -= outer.top - inner.top; + } + return; + } + } +} + +/** What `useLayerKeyboardClearance` gives the layer runtime. */ +export interface LayerKeyboardClearance { + /** The block size that keeps the layer clear of the keyboard, or null. */ + readonly cap: number | null; + /** + * Follows a layer element the runtime swaps in while the layer is open. + * The runtime calls it from its layer ref callback. + */ + readonly followLayerElement: () => void; +} + +/** + * Keeps an open anchor-mode layer clear of the software keyboard. While a + * software keyboard covers the bottom of the viewport, an anchored layer that + * would run under it keeps its block-start edge. Its block size is capped so + * that it ends `LAYER_KEYBOARD_CLEARANCE_PX` above the keyboard. The caller + * applies the cap to the layer's own element (useLayer.tsx's `keyboardCap`). + * Only a layer whose committed element carries `LAYER_ANCHORED_ATTRIBUTE` + * (anchor positioning) is capped; other positionings own their geometry. + */ +export function useLayerKeyboardClearance( + isOpen: boolean, + layerRef: RefObject, +): LayerKeyboardClearance { + const [cap, setCap] = useState(null); + // The cap the layer renders with, read by the measurement between commits. + const capRef = useRef(null); + // Set while the layer is open: follows the runtime when it replaces the + // layer element without closing it. + const resyncRef = useRef<(() => void) | null>(null); + + // Syncs the cap with the software keyboard's layout guide and with the + // open layer's element. + useIsomorphicLayoutEffect(() => { + const initial = layerRef.current; + const win = initial?.ownerDocument.defaultView; + if (!isOpen || initial == null || win == null) { + return; + } + // The window, for the hoisted press handlers below. + const view: Window = win; + let isDisposed = false; + const guide = getKeyboardLayoutGuide(win); + // The element the cap and the press tracking are on. The runtime can + // replace the layer element while it stays open; `sync` moves both to the + // element the ref holds now. + let layer: HTMLElement = initial; + const sync = (): boolean => { + const next = layerRef.current; + if (next == null || next === layer) { + return false; + } + layer.removeEventListener('pointerdown', handlePress, true); + layer = next; + layer.addEventListener('pointerdown', handlePress, true); + return true; + }; + // Renders the layer with `next` and returns once that commit has laid it + // out, so the measurement after it reads the new box. Runs outside + // React's own work: keyboard reports, timers, frames and native events. + const commitCap = (next: number | null) => { + if (isDisposed || capRef.current === next) { + return; + } + capRef.current = next; + // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the box is measured at its new size in the same task, before the frame paints + flushSync(() => setCap(next)); + sync(); + }; + // Measured at the layer's own size, as the fallback order places it: + // returns whether the layer is capped. + const capFor = (inset: number): boolean => { + commitCap(null); + if (inset <= 0) { + return false; + } + // In layout px, the box's and the keyboard's units: WebKit reports + // `innerHeight` in the pinch-zoomed visual viewport's px. + const viewport = layoutViewportHeight(win); + const box = settledBox(layer); + const height = keyboardClearanceCap(box, viewport, inset); + if (height == null) { + return false; + } + commitCap(height); + // A layer too tall for the room below its trigger can sit higher, over + // the trigger, where the viewport fit placed it. Shorter, it goes back + // below the trigger: cap it again from where it starts now. + const placed = settledBox(layer); + if (placed.top > box.top + 1) { + const again = keyboardClearanceCap(placed, viewport, inset); + if (again != null) { + commitCap(again); + } + } + // The cap holds the block-start edge: below its trigger the top stays + // and the bottom comes up. Placed above its trigger the layer holds its + // bottom instead, which a shorter box cannot lift: leave it as it is. + const limit = viewport - inset - LAYER_KEYBOARD_CLEARANCE_PX; + if (settledBox(layer).bottom > limit + 1) { + commitCap(null); + return false; + } + return true; + }; + + const avoid = (inset: number) => { + sync(); + if (!layer.hasAttribute(LAYER_ANCHORED_ATTRIBUTE)) { + commitCap(null); + return; + } + if (!capFor(inset)) { + return; + } + // The composing component makes its surface a scroll container once it + // overflows. That comes a frame later, as its observer reports the + // smaller box. Keep the field being typed into in view after that. + const focused = layer.ownerDocument.activeElement; + if (focused != null && focused !== layer && layer.contains(focused)) { + win.requestAnimationFrame(() => + win.requestAnimationFrame(() => { + if (!isDisposed) { + keepInView(layer, focused); + } + }), + ); + } + }; + + let pending: number | null = null; + const cancelPending = () => { + if (pending != null) { + win.clearTimeout(pending); + pending = null; + } + }; + // A tap in the capped layer can blur the field it leaves (a button takes + // focus on Android and in Chromium). The keyboard then starts down. The + // full height must not come back between the tap's press and its click. + // Otherwise the click lands on whatever moved under the finger. Such a + // change waits for the browser's click after the lift (`awaitBrowserClick`). + // The window's release subscriptions are held only while a press in the + // layer is live. + const pressed = new Set(); + let deferred: (() => void) | null = null; + let stopWaiting: (() => void) | null = null; + let stopFollowing: (() => void) | null = null; + const follow = () => { + const stops = [ + subscribeInput(view, 'pointerup', handleRelease), + subscribeInput(view, 'pointercancel', handleRelease), + ]; + stopFollowing = () => { + for (const stop of stops) { + stop(); + } + }; + }; + const unfollow = () => { + stopFollowing?.(); + stopFollowing = null; + }; + const runDeferred = () => { + stopWaiting?.(); + stopWaiting = null; + pressed.clear(); + unfollow(); + const run = deferred; + deferred = null; + run?.(); + }; + function handlePress(event: PointerEvent) { + if (pressed.size === 0) { + follow(); + } + pressed.add(event.pointerId); + } + function handleRelease(event: PointerEvent) { + if (!pressed.has(event.pointerId)) { + return; + } + if (event.type === 'pointercancel') { + runDeferred(); + return; + } + stopWaiting ??= awaitBrowserClick(layer, { + onClicked: runDeferred, + onNoClick: runDeferred, + }); + } + layer.addEventListener('pointerdown', handlePress, true); + const unsubscribe = guide.subscribe(transition => { + cancelPending(); + if (transition.animated && transition.to > transition.from) { + // Rising: the keyboard covers the difference on its way up. A box's + // height cannot change on the compositor, so the cap changes once, + // when the keyboard arrives. Chrome draws Gboard's slide; Safari's + // keyboard takes UIKit's notification duration. + const arrival = + transition.start + + (guide.profile === 'chromium' && transition.curve != null + ? transition.curve.durationMs + : timing.keyboardNotificationMs); + pending = win.setTimeout( + () => { + pending = null; + avoid(transition.to); + }, + Math.max(0, arrival - win.performance.now()), + ); + return; + } + // Falling (it uncovers the full height as it goes) or at once; after + // the click of a press in progress inside the layer. + if (pressed.size > 0) { + deferred = () => avoid(transition.to); + return; + } + avoid(transition.to); + }); + // Opened while a keyboard is up: capped in the frame that first paints + // the layer, before its paint. A read in this commit would see the layer + // unplaced: Chromium places a just-shown anchored layer in that frame. + // With no keyboard up nothing is scheduled. + const opening = + getKeyboardHeight(win) > 0 + ? win.requestAnimationFrame(() => { + if (!isDisposed) { + avoid(getKeyboardHeight(win)); + } + }) + : null; + // A layer element the runtime swaps in while the layer is open. The press + // tracking moves to it in the commit that brings it. Its own box is read + // before it paints. Like the read at the open, the read waits for the + // frame that places the element. Like a keyboard change, it waits for a + // press in the layer to make its click. A rising keyboard's arrival reads + // it instead. + let swapped: number | null = null; + resyncRef.current = () => { + if (!sync() || swapped != null || getKeyboardHeight(win) <= 0) { + return; + } + swapped = win.requestAnimationFrame(() => { + swapped = null; + if (isDisposed || pending != null) { + return; + } + if (pressed.size > 0) { + deferred = () => avoid(getKeyboardHeight(win)); + return; + } + avoid(getKeyboardHeight(win)); + }); + }; + return () => { + isDisposed = true; + resyncRef.current = null; + if (opening != null) { + win.cancelAnimationFrame(opening); + } + if (swapped != null) { + win.cancelAnimationFrame(swapped); + } + unsubscribe(); + cancelPending(); + stopWaiting?.(); + layer.removeEventListener('pointerdown', handlePress, true); + unfollow(); + // A closed layer reopens at its own size. + if (capRef.current != null) { + capRef.current = null; + setCap(null); + } + }; + }, [isOpen, layerRef]); + + const followLayerElement = useCallback(() => { + resyncRef.current?.(); + }, []); + return {cap: isOpen ? cap : null, followLayerElement}; +} diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx index 90bb2bc035070..32c788dd73ee8 100644 --- a/packages/core/src/MultiSelector/MultiSelector.tsx +++ b/packages/core/src/MultiSelector/MultiSelector.tsx @@ -42,6 +42,7 @@ import { inputWrapperStyles, } from '../Field'; import {useKeepLayerOpenProps} from '../Layer/useLayer'; +import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import {InternalInputClearButton} from '../Field/InputClearButton'; import {Divider} from '../Divider'; import {Spinner} from '../Spinner'; @@ -318,10 +319,31 @@ const styles = stylex.create({ borderRadius: radiusVars['--radius-element'], }, + // A panel with a search field, capped as a whole. + searchPanel: { + display: 'flex', + flexDirection: 'column', + // No taller than its layer's block-size cap, which folds in the software + // keyboard's. The search field's row keeps its height, and the list takes + // what is left. + maxHeight: stylex.firstThatWorks( + `calc(${layerViewportInset.maxBlockSize})`, + `calc(${layerViewportInset.maxBlockSizeFallback})`, + ), + }, + // Dropdown container dropdown: { boxSizing: 'border-box', - maxHeight: '300px', + // In a search panel, the list shrinks below its content to fit the cap. + minHeight: 0, + // 300 px, and no taller than its layer's block-size cap, which folds in + // the software keyboard's: the list ends above the keyboard with the + // layer. + maxHeight: stylex.firstThatWorks( + `min(300px, ${layerViewportInset.maxBlockSize})`, + `min(300px, ${layerViewportInset.maxBlockSizeFallback})`, + ), overflowY: 'auto', padding: spacingVars['--spacing-1'], }, @@ -2404,7 +2426,7 @@ export function MultiSelector({ surface.activePresentation === 'bottom-sheet' || hasExternalTrigger; const panelContent = hasSearch ? ( -
+
{renderSearch()}
diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx index 5f02abb63d829..777b4c2fa3fa6 100644 --- a/packages/core/src/Popover/Popover.tsx +++ b/packages/core/src/Popover/Popover.tsx @@ -8,6 +8,9 @@ * @output Exports Popover with conditional overflow and content-first focus above the layer runtime's viewport fit * @position Layer component; declarative wrapper around usePopover hook * + * Like every anchored layer, a popover that would run under the software + * keyboard shrinks to stay above it (the layer runtime). + * * For hover-triggered overlays, use HoverCard instead. * * `presentation` chooses the surface, with the vocabulary DropdownMenu and diff --git a/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts new file mode 100644 index 0000000000000..ab7a64ec8b50e --- /dev/null +++ b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts @@ -0,0 +1,359 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file PopoverKeyboard.interaction.browser.spec.ts + * @input The built Keyboard Avoidance and Default Popover stories, a + * stand-in visual viewport that reports a software keyboard, real touch + * input and the interaction harness + * @output Proofs for the layer runtime's keyboard clearance, through + * Popover. A tall popover takes its shorter height once the rising + * keyboard has arrived. It ends 10 px above the keyboard, with its content + * scrollable and its last control reachable. It takes its full height back + * as the keyboard starts down. One opened while the keyboard is already up + * opens clear of it. A popover clear of the keyboard is left alone. A + * storyboard shows both states. + * @position Browser proofs for Layer/useLayerKeyboardClearance.ts. + * Headless browsers have no software keyboard. So the page's + * `visualViewport` is replaced by one the test shrinks the way Mobile + * Safari does (one `resize`, final height). Mobile Safari itself is proven + * on the iOS simulator. + */ + +import { + expect, + test, + type Locator, + type Page, +} from '@astryxdesign/a11y-spec/playwright'; +import { + openStory, + touchDriver, + waitForRest, + withStorybook, + writeEvidence, +} from '@astryxdesign/interaction-harness'; +import {LAYER_KEYBOARD_CLEARANCE_PX} from '../../Layer/layerKeyboardClearance'; +import {timing} from '../../motion/uikit/timing'; + +const storybook = withStorybook(test); + +// The cover Mobile Safari reports on an iPhone 17 Pro (keyboard, accessory +// bar and the floating address bar over a 714 px layout viewport). +const COVER = 337; + +/** + * Replaces `window.visualViewport` before the page loads with one the test + * drives: `__keyboard(cover)` shrinks it from the bottom and fires one + * `resize`, as Mobile Safari does. The keyboard module measures the visual + * viewport wherever one exists, Chrome's `navigator.virtualKeyboard` + * included (spec:AST-099 FR6, DEC-4). By default the page has no + * `navigator.virtualKeyboard`, as in Mobile Safari; `chrome` keeps it. + */ +async function installKeyboard(page: Page, {chrome = false} = {}) { + await page.addInitScript(keepVirtualKeyboard => { + if (!keepVirtualKeyboard) { + Reflect.deleteProperty(Navigator.prototype, 'virtualKeyboard'); + } + const viewport = Object.assign(new EventTarget(), { + height: window.innerHeight, + width: window.innerWidth, + offsetTop: 0, + offsetLeft: 0, + pageTop: 0, + pageLeft: 0, + scale: 1, + }); + Object.defineProperty(window, 'visualViewport', { + configurable: true, + get: () => viewport, + }); + (window as unknown as {__keyboard: (cover: number) => void}).__keyboard = + cover => { + viewport.height = window.innerHeight - cover; + viewport.dispatchEvent(new Event('resize')); + }; + }, chrome); +} + +const keyboard = async (page: Page, cover: number) => + page.evaluate( + value => + (window as unknown as {__keyboard: (cover: number) => void}).__keyboard( + value, + ), + cover, + ); + +interface Opened { + surface: Locator; + trigger: Locator; +} + +async function openPopover( + page: Page, + story: string, + name: string, + options: {chrome?: boolean} = {}, +): Promise { + await installKeyboard(page, options); + await openStory(page, storybook(), story); + const driver = await touchDriver(page); + const trigger = page.getByRole('button', {name}); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error(`no trigger named ${name}`); + } + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); + await expect(trigger).toHaveAttribute('aria-expanded', 'true'); + const layer = page.locator('[popover]:has([role="dialog"])').first(); + await waitForRest(layer); + return {surface: layer.locator('[role="dialog"]'), trigger}; +} + +/** + * A screenshot of the page with the stand-in keyboard drawn over its cover + * (headless browsers draw no keyboard): a grey block, for the evidence only. + */ +async function shotWithKeyboard(page: Page, cover: number) { + await page.evaluate(value => { + // A manual popover of its own, so it paints over the popover under test + // in the top layer, as the keyboard paints over the page. + const block = document.createElement('div'); + block.id = 'stand-in-keyboard'; + block.setAttribute('popover', 'manual'); + Object.assign(block.style, { + position: 'fixed', + inset: 'auto 0 0 0', + margin: '0', + border: '0', + padding: '0', + width: '100%', + height: `${value}px`, + background: 'rgb(209, 211, 217)', + pointerEvents: 'none', + }); + document.body.append(block); + block.showPopover(); + }, cover); + const viewport = page.viewportSize() ?? {width: 402, height: 714}; + const shot = await page.screenshot({ + clip: {x: 0, y: 0, width: viewport.width, height: viewport.height}, + }); + await page.evaluate(() => + document.getElementById('stand-in-keyboard')?.remove(), + ); + return shot; +} + +const boxOf = async (locator: Locator) => + locator.evaluate(element => { + const rect = element.getBoundingClientRect(); + const el = element as HTMLElement; + const layer = el.closest('[popover]'); + // The cap the layer's own style declares while the keyboard caps it, in + // px; an uncapped layer declares a limit out of reach instead. + const declared = + layer == null + ? '' + : getComputedStyle(layer) + .getPropertyValue('--astryx-layer-keyboard-max-block-size') + .trim(); + return { + top: rect.top, + bottom: rect.bottom, + clientHeight: el.clientHeight, + scrollHeight: el.scrollHeight, + keyboardCap: declared.endsWith('px') ? declared : '', + innerHeight: window.innerHeight, + }; + }); + +test('a tall popover shrinks to stay 10 px above the keyboard once it has arrived, and grows back as it goes down', async ({ + page, +}, testInfo) => { + const {surface} = await openPopover( + page, + 'core-popover--keyboard-avoidance', + 'Add note', + ); + const field = page.getByRole('textbox', {name: 'Title'}); + await field.focus(); + const before = await boxOf(surface); + const keyboardTop = before.innerHeight - COVER; + // The story's popover runs under the keyboard's resting top. + expect(before.bottom).toBeGreaterThan(keyboardTop); + + await keyboard(page, COVER); + // On its way up the keyboard covers the difference: nothing changes yet. + await page.waitForTimeout(timing.keyboardNotificationMs / 2); + expect((await boxOf(surface)).keyboardCap).toBe(''); + const covered = await shotWithKeyboard(page, COVER); + await page.waitForTimeout(timing.keyboardNotificationMs); + const avoiding = await boxOf(surface); + expect(avoiding.top).toBeCloseTo(before.top, 0); + expect( + Math.abs(avoiding.bottom - (keyboardTop - LAYER_KEYBOARD_CLEARANCE_PX)), + ).toBeLessThanOrEqual(1); + // Its content scrolls, and the last control can be reached above the + // keyboard. + expect(avoiding.scrollHeight).toBeGreaterThan(avoiding.clientHeight); + await expect(field).toBeFocused(); + await surface.evaluate(element => { + element.scrollTop = element.scrollHeight; + }); + const save = await page + .getByRole('button', {name: 'Save note'}) + .evaluate(element => element.getBoundingClientRect().bottom); + expect(save).toBeLessThanOrEqual(keyboardTop - LAYER_KEYBOARD_CLEARANCE_PX); + await surface.evaluate(element => { + element.scrollTop = 0; + }); + const clear = await shotWithKeyboard(page, COVER); + await writeEvidence( + 'keyboard/popover-avoidance', + { + [`${testInfo.project.name}.json`]: JSON.stringify( + {cover: COVER, keyboardTop, before, avoiding, save}, + null, + 1, + ), + [`${testInfo.project.name}-keyboard-rising.png`]: covered, + [`${testInfo.project.name}-keyboard-up.png`]: clear, + }, + testInfo, + ); + + // Going down: the full height comes back at once, behind the keyboard. + await keyboard(page, 0); + const restored = await boxOf(surface); + expect(restored.keyboardCap).toBe(''); + expect(restored.bottom).toBeCloseTo(before.bottom, 0); +}); + +test("where Chrome's navigator.virtualKeyboard exists, the visual viewport still sets the cap", async ({ + page, + browserName, +}) => { + test.skip( + browserName !== 'chromium', + "navigator.virtualKeyboard is Chrome's", + ); + const {surface} = await openPopover( + page, + 'core-popover--keyboard-avoidance', + 'Add note', + {chrome: true}, + ); + expect(await page.evaluate(() => 'virtualKeyboard' in navigator)).toBe(true); + await page.getByRole('textbox', {name: 'Title'}).focus(); + const before = await boxOf(surface); + const keyboardTop = before.innerHeight - COVER; + expect(before.bottom).toBeGreaterThan(keyboardTop); + await keyboard(page, COVER); + await page.waitForTimeout(timing.keyboardNotificationMs * 1.5); + const avoiding = await boxOf(surface); + expect(avoiding.top).toBeCloseTo(before.top, 0); + expect( + Math.abs(avoiding.bottom - (keyboardTop - LAYER_KEYBOARD_CLEARANCE_PX)), + ).toBeLessThanOrEqual(1); +}); + +test('with the keyboard up, a tap on the scrolled-in Save note clicks it', async ({ + page, +}) => { + const {surface} = await openPopover( + page, + 'core-popover--keyboard-avoidance', + 'Add note', + ); + const field = page.getByRole('textbox', {name: 'Title'}); + await field.focus(); + await keyboard(page, COVER); + await page.waitForTimeout(timing.keyboardNotificationMs * 1.5); + expect((await boxOf(surface)).keyboardCap).not.toBe(''); + await surface.evaluate(element => { + element.scrollTop = element.scrollHeight; + }); + const save = page.getByRole('button', {name: 'Save note'}); + await save.evaluate(element => { + const counter = window as unknown as {__saveClicks: number}; + counter.__saveClicks = 0; + element.addEventListener('click', () => { + counter.__saveClicks += 1; + }); + }); + const box = await save.boundingBox(); + if (box == null) { + throw new Error('no Save note'); + } + // The tap moves focus off the field, and the keyboard starts down: the + // popover keeps its height until the tap's click has landed on Save. + const driver = await touchDriver(page); + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); + await expect + .poll(async () => + page.evaluate( + () => (window as unknown as {__saveClicks: number}).__saveClicks, + ), + ) + .toBe(1); +}); + +test('opened while the keyboard is already up, it opens clear of the keyboard', async ({ + page, + browserName, +}) => { + await installKeyboard(page); + await openStory(page, storybook(), 'core-popover--keyboard-avoidance'); + const driver = await touchDriver(page); + // A field on the page brings the keyboard up first. + const search = page.getByRole('textbox', {name: 'Search notes'}); + await search.focus(); + await keyboard(page, COVER); + await page.waitForTimeout(timing.keyboardNotificationMs + 100); + const trigger = page.getByRole('button', {name: 'Add note'}); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger named Add note'); + } + // The layer's entrance is slowed through Chromium's DevTools protocol. So + // the popover is measured mid-flight, under its entrance transform, as on a + // phone. WebKit measures it as it comes. + const cdp = + browserName === 'chromium' + ? await page.context().newCDPSession(page) + : null; + await cdp?.send('Animation.enable'); + await cdp?.send('Animation.setPlaybackRate', {playbackRate: 0.1}); + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); + await expect(trigger).toHaveAttribute('aria-expanded', 'true'); + await page.waitForTimeout(200); + await cdp?.send('Animation.setPlaybackRate', {playbackRate: 1}); + const layer = page.locator('[popover]:has([role="dialog"])').first(); + await waitForRest(layer); + const surface = layer.locator('[role="dialog"]'); + const opened = await boxOf(surface); + const keyboardTop = opened.innerHeight - COVER; + expect(opened.keyboardCap).not.toBe(''); + expect( + Math.abs(opened.bottom - (keyboardTop - LAYER_KEYBOARD_CLEARANCE_PX)), + ).toBeLessThanOrEqual(1); + expect(opened.scrollHeight).toBeGreaterThan(opened.clientHeight); +}); + +test('a popover clear of the keyboard is left as it is', async ({page}) => { + const {surface} = await openPopover( + page, + 'core-popover--default', + 'Settings', + ); + const before = await boxOf(surface); + expect(before.bottom).toBeLessThan( + before.innerHeight - COVER - LAYER_KEYBOARD_CLEARANCE_PX, + ); + await keyboard(page, COVER); + await page.waitForTimeout(timing.keyboardNotificationMs + 200); + const after = await boxOf(surface); + expect(after.keyboardCap).toBe(''); + expect(after.bottom).toBeCloseTo(before.bottom, 0); +}); diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx index ee50746dadefa..e33acd439d455 100644 --- a/packages/core/src/Selector/Selector.tsx +++ b/packages/core/src/Selector/Selector.tsx @@ -50,6 +50,7 @@ import {Divider} from '../Divider'; import {layerAnimations} from '../Layer/layerAnimations.stylex'; import {reducedMotionFadeConsts} from '../motion/reducedMotion.stylex'; import {useKeepLayerOpenProps, type LayerPlacement} from '../Layer/useLayer'; +import {layerViewportInset} from '../Layer/layerViewportInset.stylex'; import {InternalInputClearButton} from '../Field/InputClearButton'; import {Spinner} from '../Spinner'; import {PanelSearchInput} from '../Field/PanelSearchInput'; @@ -348,10 +349,31 @@ const styles = stylex.create({ borderRadius: radiusVars['--radius-element'], }, + // A panel with a search field, capped as a whole. + searchPanel: { + display: 'flex', + flexDirection: 'column', + // No taller than its layer's block-size cap, which folds in the software + // keyboard's. The search field's row keeps its height, and the list takes + // what is left. + maxHeight: stylex.firstThatWorks( + `calc(${layerViewportInset.maxBlockSize})`, + `calc(${layerViewportInset.maxBlockSizeFallback})`, + ), + }, + // Dropdown container dropdown: { boxSizing: 'border-box', - maxHeight: '300px', + // In a search panel, the list shrinks below its content to fit the cap. + minHeight: 0, + // 300 px, and no taller than its layer's block-size cap, which folds in + // the software keyboard's: the list ends above the keyboard with the + // layer. + maxHeight: stylex.firstThatWorks( + `min(300px, ${layerViewportInset.maxBlockSize})`, + `min(300px, ${layerViewportInset.maxBlockSizeFallback})`, + ), overflowY: 'auto', outline: 'none', paddingBlock: spacingVars['--spacing-1'], @@ -1901,7 +1923,7 @@ export function Selector( ); const panelContent = hasSearch ? ( -
+
{renderSearch()}
{ + fs.rmSync(scratch, {recursive: true, force: true}); +}); + +/** + * The bytes each source module puts in what an import of `name` from + * `entry` loads at once. That is the entry chunk and every chunk it imports + * statically. It also counts the bytes in the chunks the import loads only + * through import(). It builds as the size report builds a component import. + */ +function importOf(entry, name) { + const entryFile = path.join(scratch, `${name}.mjs`); + fs.writeFileSync( + entryFile, + `export {${name}} from ${JSON.stringify(path.join(REPO, entry))};`, + ); + const result = esbuild.buildSync({ + absWorkingDir: REPO, + entryPoints: [entryFile], + outdir: path.join(scratch, `out-${name}`), + bundle: true, + splitting: true, + minify: true, + format: 'esm', + platform: 'browser', + define: {'process.env.NODE_ENV': '"production"'}, + loader: {'.css': 'empty'}, + external: [ + 'react', + 'react/*', + 'react-dom', + 'react-dom/*', + '@stylexjs/stylex', + ], + metafile: true, + write: false, + logLevel: 'silent', + }); + const outputs = result.metafile.outputs; + const entryOutput = Object.keys(outputs).find( + key => outputs[key].entryPoint != null, + ); + const eager = new Set(); + const pending = [entryOutput]; + while (pending.length > 0) { + const key = pending.pop(); + if (eager.has(key)) { + continue; + } + eager.add(key); + for (const {path: imported, kind} of outputs[key].imports) { + if (kind === 'import-statement' && outputs[imported] != null) { + pending.push(imported); + } + } + } + const bytesIn = keys => { + const bytes = {}; + for (const key of keys) { + for (const [input, {bytesInOutput}] of Object.entries( + outputs[key].inputs, + )) { + bytes[input] = (bytes[input] ?? 0) + bytesInOutput; + } + } + return bytes; + }; + const onDemand = Object.keys(outputs).filter( + key => !eager.has(key) && !key.endsWith('.map'), + ); + return {eager: bytesIn(eager), onDemand: bytesIn(onDemand)}; +} + +/** The inputs matching `pattern` that put bytes in `bytes`. */ +function rideIn(bytes) { + return Object.entries(bytes) + .filter(([input, size]) => SHEET_RIDE_INPUT.test(input) && size > 0) + .map(([input]) => input) + .sort(); +} + +describe('a menu with an on-demand bottom sheet', () => { + it.each([ + ['DropdownMenu', 'packages/core/src/DropdownMenu/index.ts'], + ['ContextMenu', 'packages/core/src/ContextMenu/index.ts'], + ['Selector', 'packages/core/src/Selector/index.ts'], + ['MultiSelector', 'packages/core/src/MultiSelector/index.ts'], + ])( + "%s loads the sheet's keyboard ride only with the sheet", + (name, entry) => { + const {eager, onDemand} = importOf(entry, name); + // The sheet still rides the keyboard, on demand. + expect(rideIn(onDemand)).toEqual([ + 'packages/core/src/keyboard/rideKeyboard.ts', + 'packages/core/src/motion/animator.ts', + ]); + expect(rideIn(eager)).toEqual([]); + }, + ); +}); From 4ce27c63afac41402a4389a6c24a89eac23172bf Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 01:05:05 -0800 Subject: [PATCH 2/3] fix(core): a popover opened over the keyboard clips from its first frame A popover opened while a software keyboard was up took its cap in a frame callback the open scheduled. Its surface became a scroll container only once its own overflow measure ran, a frame or more after the cap. Between the two, its content painted past its shorter box, down to the keyboard. The cap now commits in a microtask right after the open's commit, in the task that opens the layer. The runtime has shown the layer by then, and a read places it, as the fallback order's read does. Each layer also writes the overflow its surface takes beside the cap: `auto` while capped, `visible` otherwise. The surface reads it, so it scrolls from the commit that caps it. --- packages/core/src/Layer/useLayer.tsx | 19 ++-- .../Layer/useLayerKeyboardClearance.test.tsx | 12 +-- .../src/Layer/useLayerKeyboardClearance.ts | 43 ++++---- packages/core/src/Popover/Popover.tsx | 6 ++ ...opoverKeyboard.interaction.browser.spec.ts | 101 +++++++++++++++++- .../core/src/theme/derivedVarRegistry.test.ts | 3 + 6 files changed, 151 insertions(+), 33 deletions(-) diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index 9b761c616dea3..35a1b484fb0a6 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -66,11 +66,15 @@ const styles = stylex.create({ // The software keyboard's block-size cap, on the layer's own element. Every // layer sets it, an uncapped one to a limit no viewport cap reaches. So a // layer nested in a capped one does not inherit the outer cap. The surfaces - // inside a layer read it through `layerViewportInset.maxBlockSize`. - // SYNC: the property is LAYER_KEYBOARD_CAP_PROPERTY - // (useLayerKeyboardClearance.ts). - keyboardCap: (cap: string) => ({ + // inside a layer read it through `layerViewportInset.maxBlockSize`. The + // content of a capped layer overflows. So the cap also turns its surface + // into a scroll container, in the same commit, through the overflow + // property. The content never paints past the shorter box. + // SYNC: the properties are LAYER_KEYBOARD_CAP_PROPERTY and + // LAYER_KEYBOARD_OVERFLOW_PROPERTY (useLayerKeyboardClearance.ts). + keyboardCap: (cap: string, overflow: 'auto' | 'visible') => ({ '--astryx-layer-keyboard-max-block-size': cap, + '--astryx-layer-keyboard-overflow': overflow, }), // Base reset for all layers base: { @@ -1855,7 +1859,10 @@ function useLayerImplementation( layerStructureReset.reset, styles.base, overlayPaddingReset.reset, - styles.keyboardCap(keyboardCap == null ? '100vh' : `${keyboardCap}px`), + styles.keyboardCap( + keyboardCap == null ? '100vh' : `${keyboardCap}px`, + keyboardCap == null ? 'visible' : 'auto', + ), viewportStyles, offsetStyle, xstyle, @@ -1946,7 +1953,7 @@ function useLayerImplementation( overlayPaddingReset.reset, // A fixed layer is never capped; it still sets its own limit so it is // not clamped by a capped layer it sits in. - styles.keyboardCap('100vh'), + styles.keyboardCap('100vh', 'visible'), styles.fixed, xstyle, ); diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx index dc6fae8dbde8b..0252115db99ab 100644 --- a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx +++ b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx @@ -480,7 +480,7 @@ describe('useLayerKeyboardClearance', () => { expect(scroller.scrollTop).toBe(444 - 367); }); - it('caps a layer opened while a keyboard is up in the frame before it paints, and takes the cap off when it closes', () => { + it('caps a layer opened while a keyboard is up in the task that opens it, before any frame, and takes the cap off when it closes', async () => { guide.inset = COVER; const frames: FrameRequestCallback[] = []; vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { @@ -488,13 +488,11 @@ describe('useLayerKeyboardClearance', () => { return frames.length; }); const {container, rerender} = render(); - // The commit sees the layer unplaced; the next frame places it. - expect(capOf(container)).toBe(''); - act(() => { - for (const frame of frames.splice(0)) { - frame(0); - } + // The microtask right after the open's commit caps it. No frame runs. + await act(async () => { + await Promise.resolve(); }); + expect(frames).toHaveLength(0); expect(capOf(container)).toBe(CAPPED); rerender(); expect(capOf(container)).toBe(''); diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.ts b/packages/core/src/Layer/useLayerKeyboardClearance.ts index 6b40bce2baba3..57017574f8377 100644 --- a/packages/core/src/Layer/useLayerKeyboardClearance.ts +++ b/packages/core/src/Layer/useLayerKeyboardClearance.ts @@ -8,7 +8,8 @@ * module: its one height, and its layout guide for timing. * @output Exports `useLayerKeyboardClearance` and its result type, * `keyboardClearanceCap`, `LAYER_ANCHORED_ATTRIBUTE`, - * `LAYER_KEYBOARD_CAP_PROPERTY` and `LAYER_KEYBOARD_CLEARANCE_PX` + * `LAYER_KEYBOARD_CAP_PROPERTY`, `LAYER_KEYBOARD_OVERFLOW_PROPERTY` and + * `LAYER_KEYBOARD_CLEARANCE_PX` * @position Layer runtime, through the layer's touch module: the software * keyboard's part of the viewport caps * @@ -53,6 +54,15 @@ export { export const LAYER_KEYBOARD_CAP_PROPERTY = '--astryx-layer-keyboard-max-block-size'; +/** + * The custom property each layer's style sets beside the cap. It holds `auto` + * while the keyboard caps the layer, and `visible` otherwise. A surface whose + * own overflow measure makes it a scroll container reads it as its overflow. + * So it scrolls from the commit that caps it. + */ +export const LAYER_KEYBOARD_OVERFLOW_PROPERTY = + '--astryx-layer-keyboard-overflow'; + /** * Scrolls the nearest scroll container between `target` and `layer` the * least amount that shows `target` inside it. @@ -302,22 +312,22 @@ export function useLayerKeyboardClearance( } avoid(transition.to); }); - // Opened while a keyboard is up: capped in the frame that first paints - // the layer, before its paint. A read in this commit would see the layer - // unplaced: Chromium places a just-shown anchored layer in that frame. - // With no keyboard up nothing is scheduled. - const opening = - getKeyboardHeight(win) > 0 - ? win.requestAnimationFrame(() => { - if (!isDisposed) { - avoid(getKeyboardHeight(win)); - } - }) - : null; + // Opened while a keyboard is up: capped in the task that opens it. So no + // frame callback reads the layer uncapped, and no frame paints it so. The + // runtime has shown the layer before this commit. A read here places it, + // as the fallback order's read in the same task does. `flushSync` cannot + // run inside a commit, so the cap runs in a microtask right after it. + if (getKeyboardHeight(win) > 0) { + win.queueMicrotask(() => { + if (!isDisposed) { + avoid(getKeyboardHeight(win)); + } + }); + } // A layer element the runtime swaps in while the layer is open. The press // tracking moves to it in the commit that brings it. Its own box is read - // before it paints. Like the read at the open, the read waits for the - // frame that places the element. Like a keyboard change, it waits for a + // in the next frame, before that frame paints: the runtime shows the new + // element only after this call. Like a keyboard change, it waits for a // press in the layer to make its click. A rising keyboard's arrival reads // it instead. let swapped: number | null = null; @@ -340,9 +350,6 @@ export function useLayerKeyboardClearance( return () => { isDisposed = true; resyncRef.current = null; - if (opening != null) { - win.cancelAnimationFrame(opening); - } if (swapped != null) { win.cancelAnimationFrame(swapped); } diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx index 777b4c2fa3fa6..d56586e4499df 100644 --- a/packages/core/src/Popover/Popover.tsx +++ b/packages/core/src/Popover/Popover.tsx @@ -433,6 +433,12 @@ const styles = stylex.create({ `calc(${layerViewportInset.maxBlockSize})`, `calc(${layerViewportInset.maxBlockSizeFallback})`, ), + // A scroll container from the commit in which the software keyboard caps + // the layer, a frame before the overflow measure sees the shorter box. + // Otherwise `visible`. The type names the two values the property takes. + // SYNC: LAYER_KEYBOARD_OVERFLOW_PROPERTY (Layer/useLayerKeyboardClearance.ts). + overflow: 'var(--astryx-layer-keyboard-overflow, visible)' as + 'auto' | 'visible', }, surfaceScrollable: { overflow: 'auto', diff --git a/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts index ab7a64ec8b50e..6cef0d8b0ae62 100644 --- a/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts +++ b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts @@ -10,8 +10,8 @@ * keyboard has arrived. It ends 10 px above the keyboard, with its content * scrollable and its last control reachable. It takes its full height back * as the keyboard starts down. One opened while the keyboard is already up - * opens clear of it. A popover clear of the keyboard is left alone. A - * storyboard shows both states. + * is clear of it from the first frame that shows it. A popover clear of the + * keyboard is left alone. A storyboard shows both states. * @position Browser proofs for Layer/useLayerKeyboardClearance.ts. * Headless browsers have no software keyboard. So the page's * `visualViewport` is replaced by one the test shrinks the way Mobile @@ -341,6 +341,103 @@ test('opened while the keyboard is already up, it opens clear of the keyboard', expect(opened.scrollHeight).toBeGreaterThan(opened.clientHeight); }); +/** What the page read of the first frame that shows the layer. */ +interface FirstFrame { + /** As the frame begins: the layer's layout bottom, without its entrance. */ + bottom: number; + /** As the frame begins: the cap the layer declares. */ + cap: string; + /** After the frame's layout, before it paints: the content overflows. */ + overflows: boolean; + /** After the frame's layout, before it paints: the surface's overflow. */ + overflowY: string; +} + +/** + * Raises the stand-in keyboard from a field on the page, then taps Add note + * and reads the first frame that shows the popover. + */ +async function firstFrameOpenedWithKeyboardUp(page: Page): Promise { + await installKeyboard(page); + await openStory(page, storybook(), 'core-popover--keyboard-avoidance'); + const driver = await touchDriver(page); + await page.getByRole('textbox', {name: 'Search notes'}).focus(); + await keyboard(page, COVER); + await page.waitForTimeout(timing.keyboardNotificationMs + 100); + // The page's own frame loop, started before the tap. Its callback runs + // ahead of any frame callback the open schedules, so it reads each frame + // as the frame begins. In the first frame that shows the layer, a + // ResizeObserver started then reads the surface after that frame's layout. + await page.evaluate(() => { + const win = window as unknown as {__firstFrame?: FirstFrame}; + const read = () => { + const layer = document.querySelector( + '[popover]:has([role="dialog"])', + ); + const surface = layer?.querySelector('[role="dialog"]'); + if (layer?.matches(':popover-open') !== true || surface == null) { + requestAnimationFrame(read); + return; + } + const bottom = layer.offsetTop + layer.offsetHeight; + const cap = getComputedStyle(layer) + .getPropertyValue('--astryx-layer-keyboard-max-block-size') + .trim(); + const observer = new ResizeObserver(() => { + observer.disconnect(); + win.__firstFrame = { + bottom, + cap, + overflows: surface.scrollHeight > surface.clientHeight + 1, + overflowY: getComputedStyle(surface).overflowY, + }; + }); + observer.observe(surface); + }; + requestAnimationFrame(read); + }); + const trigger = page.getByRole('button', {name: 'Add note'}); + const box = await trigger.boundingBox(); + if (box == null) { + throw new Error('no trigger named Add note'); + } + await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2}); + await expect(trigger).toHaveAttribute('aria-expanded', 'true'); + const firstFrame = async () => + page.evaluate( + () => + (window as unknown as {__firstFrame?: FirstFrame}).__firstFrame ?? null, + ); + await expect.poll(firstFrame).not.toBeNull(); + const first = await firstFrame(); + if (first == null) { + throw new Error('no frame showed the popover'); + } + return first; +} + +test('opened while the keyboard is already up, it is clear of the keyboard in the first frame that shows it', async ({ + page, +}) => { + const first = await firstFrameOpenedWithKeyboardUp(page); + const innerHeight = await page.evaluate(() => window.innerHeight); + const keyboardTop = innerHeight - COVER; + expect(first.bottom).toBeLessThanOrEqual( + keyboardTop - LAYER_KEYBOARD_CLEARANCE_PX + 1, + ); + expect(first.cap).toMatch(/px$/); +}); + +test('opened while the keyboard is already up, its content stays inside its box in the first frame that paints it', async ({ + page, +}) => { + const first = await firstFrameOpenedWithKeyboardUp(page); + // The capped box is shorter than its content. + expect(first.overflows).toBe(true); + // So the surface already clips and scrolls its content in that frame. + expect(first.overflowY).not.toBe('visible'); +}); + test('a popover clear of the keyboard is left as it is', async ({page}) => { const {surface} = await openPopover( page, diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts index 54d02521a35d7..aca4b40fe2a77 100644 --- a/packages/core/src/theme/derivedVarRegistry.test.ts +++ b/packages/core/src/theme/derivedVarRegistry.test.ts @@ -130,6 +130,9 @@ const STRUCTURAL_VARS = new Set([ // (Layer/useLayerKeyboardClearance.ts). Runtime geometry, never authored by // a theme. '--astryx-layer-keyboard-max-block-size', + // Written beside it: `auto` while the keyboard caps the layer, so the + // surface scrolls from that commit. Runtime state, never authored by a theme. + '--astryx-layer-keyboard-overflow', ]); /** From 8b6d26a5c6883b35a6a7132a583301ae4a0d1372 Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Thu, 5 Nov 2026 06:24:32 -0800 Subject: [PATCH 3/3] fix(core): the keyboard cap's custom properties are private The layer runtime writes the software keyboard's cap, and the overflow a capped surface takes, as custom properties on each layer's element. Their public names made them rows of Core's stylesheet API, though no app or theme sets them. They are runtime state, so they take private names: --_layer-keyboard-max-block-size and --_layer-keyboard-overflow. No behavior changes. Two comment notes: the cap's comment names the one surface that reads the overflow, and Popover's file header drops a line that repeated the layer runtime's. --- packages/core/src/DropdownMenu/DropdownMenu.test.tsx | 2 +- .../src/DropdownMenu/DropdownMenuSubMenu.test.tsx | 2 +- .../Layer/layerViewportInset.source-build.test.mjs | 2 +- packages/core/src/Layer/layerViewportInset.stylex.ts | 4 ++-- packages/core/src/Layer/layerViewportInset.test.ts | 4 ++-- packages/core/src/Layer/useLayer.tsx | 12 ++++++------ packages/core/src/Layer/useLayerKeyboardClearance.ts | 6 ++---- packages/core/src/Popover/Popover.tsx | 6 +----- .../PopoverKeyboard.interaction.browser.spec.ts | 4 ++-- packages/core/src/theme/derivedVarRegistry.test.ts | 4 ++-- 10 files changed, 20 insertions(+), 26 deletions(-) diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx index 88c8951b29a74..81ee1d9da8020 100644 --- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx @@ -801,7 +801,7 @@ describe('DropdownMenu', () => { ); }); expect(menu).toHaveStyle( - 'max-height: min(300px,min(calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))), var(--astryx-layer-keyboard-max-block-size, 100dvb)))', + 'max-height: min(300px,min(calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))), var(--_layer-keyboard-max-block-size, 100dvb)))', ); expect(menu).not.toHaveStyle({overflowY: 'auto'}); expect(menu).toHaveAttribute('tabindex', '-1'); diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx index 90798dcb620dc..ab6f0be0ffb5f 100644 --- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx +++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx @@ -126,7 +126,7 @@ describe('DropdownMenuSubMenu', () => { expect(popover).toHaveStyle({minWidth: 'var(--x-minWidth)'}); expect(popover?.getAttribute('style')).toContain('min(640px, calc(100vw'); expect(flyout).toHaveStyle( - 'max-height: min(300px,min(calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))), var(--astryx-layer-keyboard-max-block-size, 100dvb)))', + 'max-height: min(300px,min(calc(100dvb - calc(max(var(--spacing-4), env(safe-area-inset-top, 0px)) + var(--astryx-layer-inset-block-start, 0px)) - calc(max(var(--spacing-4), env(safe-area-inset-bottom, 0px)) + var(--astryx-layer-inset-block-end, 0px))), var(--_layer-keyboard-max-block-size, 100dvb)))', ); expect(flyout).not.toHaveStyle({overflowY: 'auto'}); expect(flyout).toHaveAttribute('tabindex', '-1'); diff --git a/packages/core/src/Layer/layerViewportInset.source-build.test.mjs b/packages/core/src/Layer/layerViewportInset.source-build.test.mjs index 123e744bf856f..0ebdae4ed5926 100644 --- a/packages/core/src/Layer/layerViewportInset.source-build.test.mjs +++ b/packages/core/src/Layer/layerViewportInset.source-build.test.mjs @@ -75,7 +75,7 @@ describe('layer viewport inset stylesheet (spec:AST-059)', () => { expect(blockCaps).toContainEqual( expect.stringMatching( - /^calc\(min\(calc\(100dvb - .*safe-area-inset-top.*var\(--astryx-layer-keyboard-max-block-size, 100dvb\)/, + /^calc\(min\(calc\(100dvb - .*safe-area-inset-top.*var\(--_layer-keyboard-max-block-size, 100dvb\)/, ), ); expect(inlineCaps).toContainEqual( diff --git a/packages/core/src/Layer/layerViewportInset.stylex.ts b/packages/core/src/Layer/layerViewportInset.stylex.ts index 704571144d0a3..714bc4c88dcb3 100644 --- a/packages/core/src/Layer/layerViewportInset.stylex.ts +++ b/packages/core/src/Layer/layerViewportInset.stylex.ts @@ -5,7 +5,7 @@ * @input Uses the spacing token, the device safe-area insets, the * app-declared `--astryx-layer-inset-*` custom properties, and the * keyboard cap each layer's own style declares - * (`--astryx-layer-keyboard-max-block-size`) + * (`--_layer-keyboard-max-block-size`) * @output Exports the one definition of an anchored layer's viewport gutter * and the size caps derived from it * @position Layer runtime geometry; read by useLayer and by consumers that @@ -48,7 +48,7 @@ const INSET_INLINE_END = 'var(--astryx-layer-inset-inline-end, 0px)'; // Each layer's own style declares the room the software keyboard leaves it // (useLayer.tsx's `keyboardCap`, from useLayerKeyboardClearance.ts). An // uncapped layer declares a limit out of reach. -const KEYBOARD_CAP_PROPERTY = '--astryx-layer-keyboard-max-block-size'; +const KEYBOARD_CAP_PROPERTY = '--_layer-keyboard-max-block-size'; const GUTTER_BLOCK_START = `calc(max(${SPACING}, env(safe-area-inset-top, 0px)) + ${INSET_BLOCK_START})`; const GUTTER_BLOCK_END = `calc(max(${SPACING}, env(safe-area-inset-bottom, 0px)) + ${INSET_BLOCK_END})`; diff --git a/packages/core/src/Layer/layerViewportInset.test.ts b/packages/core/src/Layer/layerViewportInset.test.ts index 2c70ff908a207..11cb1dbbd48aa 100644 --- a/packages/core/src/Layer/layerViewportInset.test.ts +++ b/packages/core/src/Layer/layerViewportInset.test.ts @@ -66,10 +66,10 @@ describe('layerViewportInset (spec:AST-059)', () => { it('caps the block axis to the room the software keyboard leaves while it caps the layer (FR9)', () => { expect(layerViewportInset.maxBlockSize).toContain( - 'var(--astryx-layer-keyboard-max-block-size, 100dvb)', + 'var(--_layer-keyboard-max-block-size, 100dvb)', ); expect(layerViewportInset.maxBlockSizeFallback).toContain( - 'var(--astryx-layer-keyboard-max-block-size, 100vh)', + 'var(--_layer-keyboard-max-block-size, 100vh)', ); }); diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx index 35a1b484fb0a6..f91c405900f5e 100644 --- a/packages/core/src/Layer/useLayer.tsx +++ b/packages/core/src/Layer/useLayer.tsx @@ -66,15 +66,15 @@ const styles = stylex.create({ // The software keyboard's block-size cap, on the layer's own element. Every // layer sets it, an uncapped one to a limit no viewport cap reaches. So a // layer nested in a capped one does not inherit the outer cap. The surfaces - // inside a layer read it through `layerViewportInset.maxBlockSize`. The - // content of a capped layer overflows. So the cap also turns its surface - // into a scroll container, in the same commit, through the overflow - // property. The content never paints past the shorter box. + // inside a layer read it through `layerViewportInset.maxBlockSize`. The cap + // also writes the overflow a capped surface takes. Popover's surface reads + // it, so it scrolls from the commit that caps it. Both are private runtime + // state, never set by an app or a theme. // SYNC: the properties are LAYER_KEYBOARD_CAP_PROPERTY and // LAYER_KEYBOARD_OVERFLOW_PROPERTY (useLayerKeyboardClearance.ts). keyboardCap: (cap: string, overflow: 'auto' | 'visible') => ({ - '--astryx-layer-keyboard-max-block-size': cap, - '--astryx-layer-keyboard-overflow': overflow, + '--_layer-keyboard-max-block-size': cap, + '--_layer-keyboard-overflow': overflow, }), // Base reset for all layers base: { diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.ts b/packages/core/src/Layer/useLayerKeyboardClearance.ts index 57017574f8377..d03aff52f713f 100644 --- a/packages/core/src/Layer/useLayerKeyboardClearance.ts +++ b/packages/core/src/Layer/useLayerKeyboardClearance.ts @@ -51,8 +51,7 @@ export { * style). It holds the largest block size that keeps the layer clear of the * keyboard while it caps the layer. Otherwise it sets no limit. */ -export const LAYER_KEYBOARD_CAP_PROPERTY = - '--astryx-layer-keyboard-max-block-size'; +export const LAYER_KEYBOARD_CAP_PROPERTY = '--_layer-keyboard-max-block-size'; /** * The custom property each layer's style sets beside the cap. It holds `auto` @@ -60,8 +59,7 @@ export const LAYER_KEYBOARD_CAP_PROPERTY = * own overflow measure makes it a scroll container reads it as its overflow. * So it scrolls from the commit that caps it. */ -export const LAYER_KEYBOARD_OVERFLOW_PROPERTY = - '--astryx-layer-keyboard-overflow'; +export const LAYER_KEYBOARD_OVERFLOW_PROPERTY = '--_layer-keyboard-overflow'; /** * Scrolls the nearest scroll container between `target` and `layer` the diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx index d56586e4499df..ac81626cd2fe6 100644 --- a/packages/core/src/Popover/Popover.tsx +++ b/packages/core/src/Popover/Popover.tsx @@ -8,9 +8,6 @@ * @output Exports Popover with conditional overflow and content-first focus above the layer runtime's viewport fit * @position Layer component; declarative wrapper around usePopover hook * - * Like every anchored layer, a popover that would run under the software - * keyboard shrinks to stay above it (the layer runtime). - * * For hover-triggered overlays, use HoverCard instead. * * `presentation` chooses the surface, with the vocabulary DropdownMenu and @@ -437,8 +434,7 @@ const styles = stylex.create({ // the layer, a frame before the overflow measure sees the shorter box. // Otherwise `visible`. The type names the two values the property takes. // SYNC: LAYER_KEYBOARD_OVERFLOW_PROPERTY (Layer/useLayerKeyboardClearance.ts). - overflow: 'var(--astryx-layer-keyboard-overflow, visible)' as - 'auto' | 'visible', + overflow: 'var(--_layer-keyboard-overflow, visible)' as 'auto' | 'visible', }, surfaceScrollable: { overflow: 'auto', diff --git a/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts index 6cef0d8b0ae62..2586e5c984e91 100644 --- a/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts +++ b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts @@ -156,7 +156,7 @@ const boxOf = async (locator: Locator) => layer == null ? '' : getComputedStyle(layer) - .getPropertyValue('--astryx-layer-keyboard-max-block-size') + .getPropertyValue('--_layer-keyboard-max-block-size') .trim(); return { top: rect.top, @@ -381,7 +381,7 @@ async function firstFrameOpenedWithKeyboardUp(page: Page): Promise { } const bottom = layer.offsetTop + layer.offsetHeight; const cap = getComputedStyle(layer) - .getPropertyValue('--astryx-layer-keyboard-max-block-size') + .getPropertyValue('--_layer-keyboard-max-block-size') .trim(); const observer = new ResizeObserver(() => { observer.disconnect(); diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts index 9b186b3cda0a2..a9aa276c22395 100644 --- a/packages/core/src/theme/derivedVarRegistry.test.ts +++ b/packages/core/src/theme/derivedVarRegistry.test.ts @@ -129,10 +129,10 @@ const STRUCTURAL_VARS = new Set([ // writes it on each open layer from the keyboard's measured height // (Layer/useLayerKeyboardClearance.ts). Runtime geometry, never authored by // a theme. - '--astryx-layer-keyboard-max-block-size', + '--_layer-keyboard-max-block-size', // Written beside it: `auto` while the keyboard caps the layer, so the // surface scrolls from that commit. Runtime state, never authored by a theme. - '--astryx-layer-keyboard-overflow', + '--_layer-keyboard-overflow', ]); /**