Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/layer-keyboard-clearance.md
Original file line number Diff line number Diff line change
@@ -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
74 changes: 74 additions & 0 deletions apps/storybook/stories/Popover.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 (
<VStack gap={3}>
<Heading level={4} tabIndex={-1}>
Add a note
</Heading>
<TextInput
label="Title"
placeholder="Short title"
value={title}
onChange={setTitle}
/>
<Divider />
{NOTE_TIPS.map(tip => (
<Text key={tip}>{tip}</Text>
))}
<Button label="Save note" variant="primary">
Save note
</Button>
</VStack>
);
}

function SearchNotesField() {
const [query, setQuery] = React.useState('');
return (
<div style={{marginTop: 16, maxWidth: 320}}>
<TextInput
label="Search notes"
placeholder="Search"
value={query}
onChange={setQuery}
/>
</div>
);
}

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: () => (
<div style={{padding: 16}}>
<Popover label="Add a note" width={320} content={<NoteContent />}>
<Button label="Add note">Add note</Button>
</Popover>
<SearchNotesField />
</div>
),
};

export const KeepPopoverPresentation: Story = {
name: 'Keep Popover Presentation',
parameters: {
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/Breadcrumbs/BreadcrumbItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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'],
Expand Down
8 changes: 7 additions & 1 deletion packages/core/src/ContextMenu/ContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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'],
Expand Down
10 changes: 6 additions & 4 deletions packages/core/src/DropdownMenu/DropdownMenu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,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');
Expand Down Expand Up @@ -3486,11 +3486,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', () => {
Expand All @@ -3505,7 +3507,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');
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/Layer/LayerTouch.ts
Original file line number Diff line number Diff line change
@@ -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';
Original file line number Diff line number Diff line change
@@ -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<Locator>;
}[] = [
{
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,
);
});
}
Loading