Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Layer): a capped layer over its trigger keeps its top (#10497)

Christopher Chedeau3890d68ef53f
diff --git a/.changeset/layer-keyboard-cap-keeps-top.md b/.changeset/layer-keyboard-cap-keeps-top.md
new file mode 100644
index 0000000000..45e5c0382a
--- /dev/null
+++ b/.changeset/layer-keyboard-cap-keeps-top.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A popover taller than the room on both sides of its trigger keeps its top when the keyboard shortens it. The field being typed into stays under the caret. It used to jump below the trigger as the keyboard arrived, and back as it went.
+
+@vjeux
diff --git a/packages/core/src/Layer/LayerTouch.ts b/packages/core/src/Layer/LayerTouch.ts
index a5af59bb65..0d696ab262 100644
--- a/packages/core/src/Layer/LayerTouch.ts
+++ b/packages/core/src/Layer/LayerTouch.ts
@@ -6,7 +6,8 @@
* @file LayerTouch.ts
* @input useLayerKeyboardClearance.ts (the software keyboard's part of the
* viewport caps)
- * @output The layer runtime's touch layer: useLayerKeyboardClearance
+ * @output The layer runtime's touch layer: useLayerKeyboardClearance and
+ * keyboardLiftStyle
* @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.
@@ -14,4 +15,7 @@
* SYNC: When modified, keep every touch-only import of useLayer.tsx here.
*/
-export {useLayerKeyboardClearance} from './useLayerKeyboardClearance';
+export {
+ keyboardLiftStyle,
+ useLayerKeyboardClearance,
+} from './useLayerKeyboardClearance';
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index 52d207f73c..596c2672f3 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -36,7 +36,7 @@ import {resolveLayerPortalTarget} from './layerHost';
import {layerTextReset} from './layerTextReset.stylex';
import {layerStructureReset} from './layerStructureReset.stylex';
import {layerViewportInset} from './layerViewportInset.stylex';
-import {useLayerKeyboardClearance} from './LayerTouch';
+import {keyboardLiftStyle, useLayerKeyboardClearance} from './LayerTouch';
import {LAYER_ANCHORED_ATTRIBUTE} from './layerKeyboardClearance';
import {settledBox} from './settledBox';
import {layerInsetProperties} from './layerInset';
@@ -1761,6 +1761,7 @@ function useLayerImplementation(
// block-start edge and ends clear of the keyboard.
const {
cap: keyboardCap,
+ lift: keyboardLift,
inset: keyboardInset,
followLayerElement,
} = useLayerKeyboardClearance(isOpen && mode === 'context', popoverRef);
@@ -2037,6 +2038,7 @@ function useLayerImplementation(
style={{
...stylexResult.style,
...anchorStyle,
+ ...keyboardLiftStyle(keyboardLift),
...clearanceProperty,
...clearFallbacksProperty,
...layerInsetProperties(declaredInset),
@@ -2068,6 +2070,7 @@ function useLayerImplementation(
keepsAnchorClear,
keyboardCap,
keyboardInset,
+ keyboardLift,
lightDismiss,
mountStore,
popoverRefCallback,
diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
index f87e52afca..23e28960ff 100644
--- a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
+++ b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
@@ -7,7 +7,9 @@
* @output Checks the software keyboard's part of the viewport caps. The cap
* sits 10 px above the keyboard. It is written once a rising keyboard has
* arrived, and taken off as a falling one starts down. A keyboard already
- * up at the open caps the layer before paint. The field stays in view,
+ * up at the open caps the layer before paint. A layer the viewport fit
+ * shifted over its trigger keeps that block-start edge through the cap.
+ * The field stays in view,
* unless a person touched the layer after the cap. A component's own
* scroll keeps the reveal, and so does the next keyboard change. A layer
* clear of the keyboard, a bottom-held layer and a layer in another
@@ -33,6 +35,7 @@ import type {BrowserClickWaitHandlers} from '../utils/browserClickWait';
import type * as KeyboardHeightModule from '../keyboard/keyboardHeight';
import {
keyboardClearanceCap,
+ keyboardLiftStyle,
LAYER_ANCHORED_ATTRIBUTE,
LAYER_KEYBOARD_CAP_PROPERTY,
LAYER_KEYBOARD_CLEARANCE_PX,
@@ -122,6 +125,7 @@ function Harness({
layerKey = 'a',
entering,
shiftedTop,
+ ignoresLift = false,
slidesAboveKeyboard = false,
}: {
isOpen?: boolean;
@@ -141,6 +145,8 @@ function Harness({
* `box` and over its trigger; any shorter, it sits at `box`.
*/
shiftedTop?: number;
+ /** Stays below its trigger whatever the lift's insets say. */
+ ignoresLift?: boolean;
/**
* Places itself by the keyboard inset, as Selector's overlay does: while an
* inset is out, the layer ends above it.
@@ -148,7 +154,7 @@ function Harness({
slidesAboveKeyboard?: boolean;
}) {
const layerRef = useRef<HTMLDivElement>(null);
- const {cap, inset, followLayerElement} = useLayerKeyboardClearance(
+ const {cap, lift, inset, followLayerElement} = useLayerKeyboardClearance(
isOpen,
layerRef,
);
@@ -173,6 +179,8 @@ function Harness({
? {}
: {[LAYER_KEYBOARD_INSET_PROPERTY]: `${inset}px`}),
...(entering == null ? {} : {transform: `translateY(${entering}px)`}),
+ // As the runtime applies it: the insets move the layer's anchor area.
+ ...keyboardLiftStyle(lift),
}}
data-testid="layer"
ref={el => {
@@ -202,7 +210,8 @@ function Harness({
slidesAboveKeyboard && !Number.isNaN(keyboardInset)
? Math.min(placed, VIEWPORT - keyboardInset - h)
: placed;
- const top = (heldBottom ? box.bottom - h : start) + shift;
+ const lifted = ignoresLift ? 0 : liftOf(el);
+ const top = (heldBottom ? box.bottom - h : start) - lifted + shift;
return {
top,
bottom: top + h,
@@ -292,6 +301,12 @@ const capOf = (container: HTMLElement) =>
.querySelector<HTMLElement>('[data-testid="layer"]')!
.style.getPropertyValue(LAYER_KEYBOARD_CAP_PROPERTY);
+/** The lift the runtime applies, read back from the layer's insets. */
+function liftOf(layer: HTMLElement): number {
+ const end = parseFloat(layer.style.insetBlockEnd);
+ return Number.isNaN(end) ? 0 : end;
+}
+
const insetOf = (container: HTMLElement) =>
container
.querySelector<HTMLElement>('[data-testid="layer"]')!
@@ -469,18 +484,19 @@ describe('useLayerKeyboardClearance', () => {
);
});
- it('takes the cap off a layer that does not read the inset at once as the keyboard goes down, even where that moves it (spec:AST-059 FR10)', () => {
+ it('takes the cap off a layer that does not read the inset at once as the keyboard goes down, and its block-start stays (spec:AST-059 FR9, FR10)', () => {
// At its full height the viewport fit places this layer over its
- // trigger; capped, it sits below the trigger.
+ // trigger. Shorter, it would fit below the trigger, at 300.
const {container} = render(
<Harness box={{top: 300, bottom: 700}} shiftedTop={120} />,
);
guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
- expect(capOf(container)).not.toBe('');
+ expect(capOf(container)).toBe(`${VIEWPORT - COVER - 10 - 120}px`);
const layer = screen.getByTestId('layer');
- expect(layer.getBoundingClientRect().top).toBe(300);
+ expect(layer.getBoundingClientRect().top).toBe(120);
guide.emit({kind: 'hide', from: COVER, to: 0});
expect(capOf(container)).toBe('');
+ expect(liftOf(layer)).toBe(0);
expect(layer.getBoundingClientRect().top).toBe(120);
});
@@ -537,10 +553,32 @@ describe('useLayerKeyboardClearance', () => {
expect(capOf(container)).toBe('');
});
- it('caps a layer the viewport fit pushed up over its trigger from where it starts once it is shorter', () => {
+ it('keeps the block-start edge of a layer the viewport fit pushed up over its trigger: shorter, it fits below the trigger, and the cap lifts it back (spec:AST-059 FR9)', () => {
+ const {container} = render(<Harness shiftedTop={40} />);
+ guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
+ const layer = screen.getByTestId('layer');
+ expect(capOf(container)).toBe(`${VIEWPORT - COVER - 10 - 40}px`);
+ expect(liftOf(layer)).toBe(BOX.top - 40);
+ expect(layer.getBoundingClientRect().top).toBe(40);
+ expect(layer.getBoundingClientRect().bottom).toBe(VIEWPORT - COVER - 10);
+ });
+
+ it('keeps that block-start edge at the next keyboard change', () => {
const {container} = render(<Harness shiftedTop={40} />);
guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
+ guide.emit({kind: 'change', from: COVER, to: COVER + 20, animated: false});
+ const layer = screen.getByTestId('layer');
+ expect(capOf(container)).toBe(`${VIEWPORT - COVER - 20 - 10 - 40}px`);
+ expect(layer.getBoundingClientRect().top).toBe(40);
+ });
+
+ it('caps a layer from below its trigger where the engine does not move it by the lift', () => {
+ const {container} = render(<Harness shiftedTop={40} ignoresLift />);
+ guide.emit({kind: 'change', from: 0, to: COVER, animated: false});
+ const layer = screen.getByTestId('layer');
expect(capOf(container)).toBe(CAPPED);
+ expect(liftOf(layer)).toBe(0);
+ expect(layer.getBoundingClientRect().top).toBe(BOX.top);
});
it('reads a layer that is still entering without its entrance transform, in one read (spec:AST-059 FR8)', () => {
@@ -771,6 +809,7 @@ describe('useLayerKeyboardClearance', () => {
advance(timing.keyboardNotificationMs + 1);
// A shorter box would move its top down and still end under the keyboard.
expect(capOf(container)).toBe('');
+ expect(liftOf(screen.getByTestId('layer'))).toBe(0);
});
it('keeps the cap through a press inside the layer until its click', () => {
diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.ts b/packages/core/src/Layer/useLayerKeyboardClearance.ts
index e79f81958f..884990908c 100644
--- a/packages/core/src/Layer/useLayerKeyboardClearance.ts
+++ b/packages/core/src/Layer/useLayerKeyboardClearance.ts
@@ -7,7 +7,7 @@
* @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`,
+ * `keyboardLiftStyle`, `keyboardClearanceCap`, `LAYER_ANCHORED_ATTRIBUTE`,
* `LAYER_KEYBOARD_CAP_PROPERTY`, `LAYER_KEYBOARD_OVERFLOW_PROPERTY`,
* `LAYER_KEYBOARD_INSET_PROPERTY` and `LAYER_KEYBOARD_CLEARANCE_PX`
* @position Layer runtime, through the layer's touch module: the software
@@ -22,7 +22,13 @@
* - /docs/specs/AST-059-layer-viewport-inset/spec.md
*/
-import {useCallback, useRef, useState, type RefObject} from 'react';
+import {
+ useCallback,
+ useRef,
+ useState,
+ type CSSProperties,
+ 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
@@ -101,10 +107,25 @@ function keepInView(layer: HTMLElement, target: Element) {
}
}
+/**
+ * The insets that move a capped layer's anchor area `lift` px toward the
+ * block-start, or null without a lift. They hold the layer's block-start edge
+ * where it was when the cap landed (`LayerKeyboardClearance.lift`).
+ */
+export function keyboardLiftStyle(lift: number | null): CSSProperties | null {
+ return lift == null ? null : {insetBlockStart: -lift, insetBlockEnd: lift};
+}
+
/** 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;
+ /**
+ * While the cap holds the layer, how far its block-start edge sits above
+ * the place the fallback order picks for the shorter box, in px. The
+ * runtime applies it with `keyboardLiftStyle`. Otherwise null.
+ */
+ readonly lift: number | null;
/**
* Once a software keyboard is up, the layout px between the layout
* viewport's bottom and the line an anchored layer ends above. It keeps its
@@ -132,9 +153,11 @@ export function useLayerKeyboardClearance(
layerRef: RefObject<HTMLElement | null>,
): LayerKeyboardClearance {
const [cap, setCap] = useState<number | null>(null);
+ const [lift, setLift] = useState<number | null>(null);
const [keyboardInset, setKeyboardInset] = useState<number | null>(null);
// The cap the layer renders with, read by the measurement between commits.
const capRef = useRef<number | null>(null);
+ const liftRef = useRef<number | null>(null);
const keyboardInsetRef = useRef<number | null>(null);
// Set while the layer is open: follows the runtime when it replaces the
// layer element without closing it.
@@ -188,19 +211,24 @@ export function useLayerKeyboardClearance(
const commitCap = (
next: number | null,
nextInset = keyboardInsetRef.current,
+ nextLift: number | null = null,
) => {
if (
isDisposed ||
- (capRef.current === next && keyboardInsetRef.current === nextInset)
+ (capRef.current === next &&
+ keyboardInsetRef.current === nextInset &&
+ liftRef.current === nextLift)
) {
return;
}
capRef.current = next;
keyboardInsetRef.current = nextInset;
+ liftRef.current = nextLift;
// 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);
setKeyboardInset(nextInset);
+ setLift(nextLift);
});
sync();
};
@@ -226,14 +254,27 @@ export function useLayerKeyboardClearance(
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.
+ // A layer too tall for the room on both sides of its trigger sits over
+ // the trigger, where the viewport fit shifted it. Shorter, it fits below
+ // the trigger, and the fallback order moves it down. Lift it back, so it
+ // keeps the block-start edge it had when the cap landed. A layer that
+ // holds its block-end edge (placed above its trigger) moves only its
+ // top, and is not lifted.
const placed = settledBox(layer);
- if (placed.top > box.top + 1) {
- const again = keyboardClearanceCap(placed, viewport, inset);
- if (again != null) {
- commitCap(again);
+ if (
+ placed.top > box.top + 1 &&
+ Math.abs(placed.bottom - box.bottom) > 1
+ ) {
+ commitCap(height, keyboardInsetRef.current, placed.top - box.top);
+ // An engine that does not move the layer by the lift leaves it below
+ // the trigger: cap it from where it starts there.
+ const lifted = settledBox(layer);
+ if (Math.abs(lifted.top - box.top) > 1) {
+ commitCap(height);
+ const again = keyboardClearanceCap(placed, viewport, inset);
+ if (again != null) {
+ commitCap(again);
+ }
}
}
// The cap holds the block-start edge: below its trigger the top stays
@@ -429,6 +470,10 @@ export function useLayerKeyboardClearance(
capRef.current = null;
setCap(null);
}
+ if (liftRef.current != null) {
+ liftRef.current = null;
+ setLift(null);
+ }
if (keyboardInsetRef.current != null) {
keyboardInsetRef.current = null;
setKeyboardInset(null);
@@ -441,6 +486,7 @@ export function useLayerKeyboardClearance(
}, []);
return {
cap: isOpen ? cap : null,
+ lift: isOpen ? lift : null,
inset: isOpen ? keyboardInset : null,
followLayerElement,
};
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 2149b8b9be..7ba3a31b10 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,10 @@
* 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
- * 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.
+ * is clear of it from the first frame that shows it. One taller than both
+ * sides of its trigger keeps its block-start edge, and its field, through
+ * the cap, as does a hardware keyboard's shortcut bar. 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
@@ -46,6 +48,12 @@ 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;
+// The cover an iPad on iOS 26.2 reports for a hardware keyboard's shortcut
+// bar: the visual viewport ends 71 px higher.
+const SHORTCUT_BAR = 71;
+// The story's popover with 700 px more content below its field: taller than
+// the room on both sides of its trigger.
+const TALLER = '[data-layer-anchored] button { margin-block-start: 700px; }';
/**
* Replaces `window.visualViewport` before the page loads with one the test
@@ -99,10 +107,13 @@ async function openPopover(
page: Page,
story: string,
name: string,
- options: {chrome?: boolean} = {},
+ options: {chrome?: boolean; style?: string} = {},
): Promise<Opened> {
await installKeyboard(page, options);
await openStory(page, storybook(), story);
+ if (options.style != null) {
+ await page.addStyleTag({content: options.style});
+ }
const driver = await touchDriver(page);
const trigger = page.getByRole('button', {name});
const box = await trigger.boundingBox();
@@ -548,6 +559,84 @@ test('opened while the keyboard is already up, its content stays inside its box
expect(first.overflowY).not.toBe('visible');
});
+for (const [what, cover] of [
+ ['the software keyboard', COVER],
+ ["a hardware keyboard's shortcut bar", SHORTCUT_BAR],
+] as const) {
+ test(`a popover taller than both sides of its trigger keeps its block-start edge and its field in place as ${what} caps it and goes`, async ({
+ page,
+ }) => {
+ const {surface, trigger} = await openPopover(
+ page,
+ 'core-popover--keyboard-avoidance',
+ 'Add note',
+ {style: TALLER},
+ );
+ const field = page.getByRole('textbox', {name: 'Title'});
+ await field.focus();
+ const layer = page.locator('[popover]:has([role="dialog"])').first();
+ const before = await boxOf(layer);
+ const fieldTop = await field.evaluate(
+ element => element.getBoundingClientRect().top,
+ );
+ // The viewport fit shifts the layer up over its trigger.
+ expect(before.top).toBeLessThan((await boxOf(trigger)).bottom);
+ // Every frame from here on: the layer's top and the field's.
+ await layer.evaluate(element => {
+ const input = element.querySelector('input');
+ if (input == null) {
+ throw new Error('no field in the popover');
+ }
+ const w = window as unknown as {__tops: number[][]; __track: boolean};
+ w.__tops = [];
+ w.__track = true;
+ const tick = () => {
+ if (w.__track) {
+ w.__tops.push([
+ element.getBoundingClientRect().top,
+ input.getBoundingClientRect().top,
+ ]);
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ });
+
+ await keyboard(page, cover);
+ await expect
+ .poll(async () => (await boxOf(surface)).keyboardCap)
+ .not.toBe('');
+ await frames(page, 6);
+ const capped = await boxOf(layer);
+ expect(Math.abs(capped.top - before.top)).toBeLessThanOrEqual(0.5);
+ expect(
+ Math.abs(
+ capped.bottom -
+ (before.innerHeight - cover - LAYER_KEYBOARD_CLEARANCE_PX),
+ ),
+ ).toBeLessThanOrEqual(1);
+ await expect(field).toBeFocused();
+
+ // Going down: the full height comes back, and the layer stays where it is.
+ await keyboard(page, 0);
+ await frames(page, 6);
+ const restored = await boxOf(layer);
+ expect((await boxOf(surface)).keyboardCap).toBe('');
+ expect(Math.abs(restored.top - before.top)).toBeLessThanOrEqual(0.5);
+
+ const tops = await page.evaluate(() => {
+ const w = window as unknown as {__tops: number[][]; __track: boolean};
+ w.__track = false;
+ return w.__tops;
+ });
+ expect(tops.length).toBeGreaterThan(12);
+ for (const [layerTop, inputTop] of tops) {
+ expect(Math.abs(layerTop - before.top)).toBeLessThanOrEqual(0.5);
+ expect(Math.abs(inputTop - fieldTop)).toBeLessThanOrEqual(0.5);
+ }
+ });
+}
+
test('a popover clear of the keyboard is left as it is', async ({page}) => {
const {surface} = await openPopover(
page,