Skip to content

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

TypeScript

fix(Layer): a scroll started after the keyboard caps a layer is not undone (#10457)

Christopher Chedeau0d7498a702d2
diff --git a/.changeset/layer-keyboard-reveal-person-scroll.md b/.changeset/layer-keyboard-reveal-person-scroll.md
new file mode 100644
index 0000000000..803429f0be
--- /dev/null
+++ b/.changeset/layer-keyboard-reveal-person-scroll.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Once the keyboard caps a layer such as a popover, a scroll a person starts in it afterwards is no longer undone. On a busy page, the layer could scroll back to the focused field just after. A later keyboard change still brings the field being typed into back into view.
+
+@vjeux
diff --git a/docs/specs/AST-059-layer-viewport-inset/spec.md b/docs/specs/AST-059-layer-viewport-inset/spec.md
index 458833c472..feca8a29ef 100644
--- a/docs/specs/AST-059-layer-viewport-inset/spec.md
+++ b/docs/specs/AST-059-layer-viewport-inset/spec.md
@@ -330,7 +330,10 @@ the app reaches every layer instead of the components that happen to read it.
its block size so that edge sits 10 px above the keyboard, the clearance
UIKit keeps under a popover. Its content overflows inside the layer box,
where the composing component scrolls it, and the field being typed into
- stays in view. A layer the keyboard does not reach, and a layer whose
+ stays in view. When a person presses, touches or turns a wheel inside the
+ layer after the cap lands, the content stays where they put it. A later
+ keyboard change brings the field into view again.
+ A layer the keyboard does not reach, and a layer whose
block-end edge the fallback order holds (placed above its trigger), stay as
they are. The keyboard's height is the keyboard module's one height
(`architecture:react-component-runtime` INV11); no layer measures the
diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
index 66feeb16dd..f87e52afca 100644
--- a/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
+++ b/packages/core/src/Layer/useLayerKeyboardClearance.test.tsx
@@ -7,8 +7,10 @@
* @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. A
- * layer clear of the keyboard, a bottom-held layer and a layer in another
+ * up at the open caps the layer before paint. 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
* positioning are left as they are. The positioning is read from the last
* commit. An entering layer is read without its entrance transform. The
* cap is held through a press until its click. The window listeners are
@@ -263,11 +265,21 @@ function Harness({
}
}}
/>
+ <div data-testid="list" style={{overflowY: 'auto'}} />
</div>
</div>
);
}
+/** Runs the frame callbacks a test held, and the ones they ask for. */
+const runFrames = (frames: FrameRequestCallback[]) => {
+ act(() => {
+ while (frames.length > 0) {
+ frames.shift()?.(0);
+ }
+ });
+};
+
/** Runs the timers a keyboard change scheduled, inside act: they re-render. */
const advance = (ms: number) => {
act(() => {
@@ -559,6 +571,78 @@ describe('useLayerKeyboardClearance', () => {
expect(scroller.scrollTop).toBe(444 - 367);
});
+ it.each([
+ ['a press', (element: Element) => fireEvent.pointerDown(element)],
+ ['a touch', (element: Element) => fireEvent.touchStart(element)],
+ ['a wheel turn', (element: Element) => fireEvent.wheel(element)],
+ ])(
+ 'leaves the content where a person scrolled it after %s in the layer, before the field reveal runs',
+ (_, touch) => {
+ const frames: FrameRequestCallback[] = [];
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const {container} = render(<Harness focusRow />);
+ guide.emit({kind: 'show', from: 0, to: COVER});
+ advance(timing.keyboardNotificationMs + 1);
+ const scroller = container.querySelector<HTMLElement>(
+ '[data-testid="scroller"]',
+ )!;
+ // The person's pan, between the cap and the reveal's frames. The
+ // browser takes the pan from the press.
+ touch(scroller);
+ fireEvent.pointerCancel(scroller);
+ scroller.scrollTop = 30;
+ runFrames(frames);
+ expect(scroller.scrollTop).toBe(30);
+ },
+ );
+
+ it('reveals the field again at the next keyboard change after a person scrolled', () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const {container} = render(<Harness focusRow />);
+ guide.emit({kind: 'show', from: 0, to: COVER});
+ advance(timing.keyboardNotificationMs + 1);
+ const scroller = container.querySelector<HTMLElement>(
+ '[data-testid="scroller"]',
+ )!;
+ fireEvent.pointerDown(scroller);
+ fireEvent.pointerCancel(scroller);
+ scroller.scrollTop = 30;
+ runFrames(frames);
+ expect(scroller.scrollTop).toBe(30);
+ // The keyboard grows by 20 px: a new cap, and the field is revealed.
+ guide.emit({kind: 'change', from: COVER, to: COVER + 20, animated: false});
+ runFrames(frames);
+ // The box now ends at 714 - 357 - 10 = 347. The stand-in field stays at
+ // 420 to 444 whatever the scroll, so the reveal adds 444 - 347.
+ expect(scroller.scrollTop).toBe(30 + 444 - 347);
+ });
+
+ it('still reveals the field after a component scrolls its own list in the layer', () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ frames.push(callback);
+ return frames.length;
+ });
+ const {container} = render(<Harness focusRow />);
+ guide.emit({kind: 'show', from: 0, to: COVER});
+ advance(timing.keyboardNotificationMs + 1);
+ const list = container.querySelector<HTMLElement>('[data-testid="list"]')!;
+ list.scrollTop = 50;
+ fireEvent.scroll(list);
+ runFrames(frames);
+ const scroller = container.querySelector<HTMLElement>(
+ '[data-testid="scroller"]',
+ )!;
+ expect(scroller.scrollTop).toBe(444 - 367);
+ });
+
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[] = [];
diff --git a/packages/core/src/Layer/useLayerKeyboardClearance.ts b/packages/core/src/Layer/useLayerKeyboardClearance.ts
index 20c0db252e..e79f81958f 100644
--- a/packages/core/src/Layer/useLayerKeyboardClearance.ts
+++ b/packages/core/src/Layer/useLayerKeyboardClearance.ts
@@ -156,14 +156,30 @@ export function useLayerKeyboardClearance(
// replace the layer element while it stays open; `sync` moves both to the
// element the ref holds now.
let layer: HTMLElement = initial;
+ // The field reveal after a cap stands down if a person's input reached
+ // the layer since the cap.
+ let personInputs = 0;
+ const notePersonInput = () => {
+ personInputs += 1;
+ };
const sync = (): boolean => {
const next = layerRef.current;
if (next == null || next === layer) {
return false;
}
layer.removeEventListener('pointerdown', handlePress, true);
+ layer.removeEventListener('touchstart', notePersonInput, {capture: true});
+ layer.removeEventListener('wheel', notePersonInput, {capture: true});
layer = next;
layer.addEventListener('pointerdown', handlePress, true);
+ layer.addEventListener('touchstart', notePersonInput, {
+ capture: true,
+ passive: true,
+ });
+ layer.addEventListener('wheel', notePersonInput, {
+ capture: true,
+ passive: true,
+ });
return true;
};
// Renders the layer with `next` and returns once that commit has laid it
@@ -242,12 +258,17 @@ export function useLayerKeyboardClearance(
}
// 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.
+ // smaller box. Keep the field being typed into in view after that. A
+ // person who presses, touches or turns a wheel in the layer by then has
+ // placed its content, so the reveal stands down. A component's own
+ // scroll, such as a list keeping its active option in view, does not
+ // stop it. The next cap reveals the field again.
const focused = layer.ownerDocument.activeElement;
if (focused != null && focused !== layer && layer.contains(focused)) {
+ const inputsAtCap = personInputs;
win.requestAnimationFrame(() =>
win.requestAnimationFrame(() => {
- if (!isDisposed) {
+ if (!isDisposed && personInputs === inputsAtCap) {
keepInView(layer, focused);
}
}),
@@ -298,6 +319,7 @@ export function useLayerKeyboardClearance(
run?.();
};
function handlePress(event: PointerEvent) {
+ notePersonInput();
if (pressed.size === 0) {
follow();
}
@@ -317,6 +339,14 @@ export function useLayerKeyboardClearance(
});
}
layer.addEventListener('pointerdown', handlePress, true);
+ layer.addEventListener('touchstart', notePersonInput, {
+ capture: true,
+ passive: true,
+ });
+ layer.addEventListener('wheel', notePersonInput, {
+ capture: true,
+ passive: true,
+ });
const unsubscribe = guide.subscribe(transition => {
cancelPending();
if (transition.animated && transition.to > transition.from) {
@@ -391,6 +421,8 @@ export function useLayerKeyboardClearance(
cancelPending();
stopWaiting?.();
layer.removeEventListener('pointerdown', handlePress, true);
+ layer.removeEventListener('touchstart', notePersonInput, {capture: true});
+ layer.removeEventListener('wheel', notePersonInput, {capture: true});
unfollow();
// A closed layer reopens at its own size.
if (capRef.current != null) {
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 de10b5725c..028263dbfe 100644
--- a/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts
+++ b/packages/core/src/Popover/__tests__/PopoverKeyboard.interaction.browser.spec.ts
@@ -26,7 +26,13 @@ import {
type Page,
} from '@astryxdesign/a11y-spec/playwright';
import {
+ drag,
+ frames,
+ freezePageWhen,
+ installPageFreeze,
+ installTimerGate,
openStory,
+ thawPage,
touchDriver,
waitForRest,
withStorybook,
@@ -350,6 +356,59 @@ test('with the keyboard up, a tap on the scrolled-in Save note clicks it', async
.toBe(1);
});
+test('a person who scrolls the capped popover before its field reveal keeps the content where they put it', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ "WebKit's injected touches do not scroll (README: engine limits)",
+ );
+ await installPageFreeze(page);
+ const {surface} = await openPopover(
+ page,
+ 'core-popover--keyboard-avoidance',
+ 'Add note',
+ );
+ await installTimerGate(page);
+ await page.getByRole('textbox', {name: 'Title'}).focus();
+ // The scene stops in the first frame that shows the cap, before the layer
+ // keeps the focused field in view, however late this process reacts.
+ const capped = freezePageWhen(
+ page,
+ () => {
+ const layer = document.querySelector('[popover]:has([role="dialog"])');
+ return (
+ layer != null &&
+ getComputedStyle(layer)
+ .getPropertyValue('--_layer-keyboard-max-block-size')
+ .trim()
+ .endsWith('px')
+ );
+ },
+ null,
+ );
+ await keyboard(page, COVER);
+ await capped;
+ // The person pans the content up as far as it goes, then lifts at rest.
+ const box = await surface.boundingBox();
+ if (box == null) {
+ throw new Error('no popover surface');
+ }
+ const x = Math.round(box.x + box.width / 2);
+ const y = Math.round(box.y + box.height * 0.8);
+ const driver = await touchDriver(page);
+ await driver.play(
+ drag({x, y}, {x, y: y - 200}, {durationMs: 300, hz: 60, restMs: 100}),
+ );
+ const placed = await surface.evaluate(element => element.scrollTop);
+ expect(placed).toBeGreaterThan(0);
+ // The held frames run, the field reveal's among them.
+ await thawPage(page);
+ await frames(page, 4);
+ expect(await surface.evaluate(element => element.scrollTop)).toBe(placed);
+});
+
test('opened while the keyboard is already up, it opens clear of the keyboard', async ({
page,
browserName,