Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions .changeset/keyboard-pan-handover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@reshaped/utilities": patch
"reshaped": patch
---

On iOS, a pan Safari leaves on a page the user can't scroll is handed over to the scrollable container of the focused field. When a field is focused near the end of a scrolled container, Safari pans the whole page to reveal it, which moved the top of the page or of an open modal off screen with no way to scroll back while the keyboard was open. That happened under the page scroll lock and on pages that scroll inside their own container with `overflow: hidden` on the document. Once Safari is done panning, the container is scrolled by the same distance and the page is scrolled back in the same frame, with room added at the end of the container while the keyboard is open. The `Reshaped` provider and the page scroll lock run this automatically. Focusing fields and revealing them is still left to Safari, and pages the user can scroll are left alone
5 changes: 5 additions & 0 deletions packages/reshaped/src/components/Reshaped/Reshaped.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import React from "react";
import { classNames } from "@reshaped/utilities";
import { handOverIOSKeyboardPan } from "@reshaped/utilities/internal";

import { GlobalColorMode, PrivateTheme } from "@/components/Theme";
import { useGlobalColorMode } from "@/components/Theme/useTheme";
Expand Down Expand Up @@ -29,6 +30,10 @@ const Reshaped: React.FC<T.Props> = (props) => {
const scopeRef = React.useRef<HTMLDivElement>(null);
const parentGlobalColorMode = useGlobalColorMode();

// Pages scrolling inside their own container can't be scrolled back from the pan iOS adds for the keyboard,
// with or without an open modal locking the page scroll
React.useEffect(() => handOverIOSKeyboardPan(), []);

return (
<SingletonRTLProvider defaultRTL={defaultRTL}>
<SingletonKeyboardModeProvider>
Expand Down
2 changes: 1 addition & 1 deletion packages/utilities/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ export {
} from "./a11y";
export { findParent, getShadowRoot } from "./dom";
export { rafThrottle } from "./helpers";
export { disableScroll, enableScroll } from "./scroll";
export { disableScroll, enableScroll, handOverIOSKeyboardPan } from "./scroll";
export type { Coordinates } from "./types/global";
export { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "./viewport";
1 change: 1 addition & 0 deletions packages/utilities/src/scroll/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { lockScroll } from "./lock";

// Internal
export { disableScroll, enableScroll } from "./disable";
export { handOverIOSKeyboardPan } from "./keyboardPan";
195 changes: 195 additions & 0 deletions packages/utilities/src/scroll/keyboardPan.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import { findClosestScrollableContainer } from "@/dom";
import { isIOS } from "@/platform";
import { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "@/viewport";

/** Input types that don't open the on-screen keyboard */
const NON_TEXT_INPUT_TYPES = new Set([
"checkbox",
"radio",
"range",
"color",
"file",
"image",
"button",
"submit",
"reset",
]);

/** Time the page has to hold still before it's handed over, longer than the pan Safari animates with the keyboard */
const SETTLE_DELAY = 200;

/** Field that opens the on-screen keyboard when it's focused */
const isKeyboardField = (el: Element | null): el is HTMLElement => {
if (el instanceof HTMLTextAreaElement) return !el.disabled && !el.readOnly;
if (el instanceof HTMLInputElement) {
return !el.disabled && !el.readOnly && !NON_TEXT_INPUT_TYPES.has(el.type);
}

return el instanceof HTMLElement && el.isContentEditable;
};

/**
* Viewport overflow comes from <html> when it has its own overflow value,
* and propagates from <body> otherwise, so an overflow style on the other element doesn't lock the page.
*/
export const getViewportScroller = () => {
const html = document.documentElement;
const { overflowX, overflowY } = window.getComputedStyle(html);
const htmlHasOverflow = overflowX !== "visible" || overflowY !== "visible";

return htmlHasOverflow ? html : document.body;
};

/** Page the user can't scroll, locked by Reshaped or by the app itself, e.g. a layout scrolling inside its own container */
const isPageScrollLocked = () =>
/hidden|clip/.test(window.getComputedStyle(getViewportScroller()).overflowY);

/**
* iOS Safari pans the whole page to reveal a focused field when its scrollable container can't scroll far enough,
* for example when it's scrolled to its end, and does that even when the page can't be scrolled by the user:
* while its scroll is locked for a modal, or when the app scrolls its layout inside its own container.
* Fixed content, like modals, moves up with the page, and nothing can pan it back while the keyboard is open,
* so the top of the page or the modal stays off screen.
*
* Once Safari is done panning, the pan is handed over to the scrollable container of the focused field:
* the container is scrolled by the pan and the page is scrolled back to where it rested in the same frame,
* so the field stays where Safari revealed it and the rest of the content comes back on screen.
* Revealing the field is still left to Safari: focus isn't taken over and nothing moves while it's panning.
* Pages the user can scroll are left alone, since the user can scroll the pan back.
*/
const install = () => {
const viewport = window.visualViewport;
if (!viewport) return () => {};

// Where the page rests, before Safari pans it for the keyboard
let restX = window.scrollX;
let restY = window.scrollY;
let timeout: ReturnType<typeof setTimeout> | undefined;
let touching = false;
let slack: { el: HTMLElement; paddingBottom: string; basePadding: number; value: number } | null =
null;

const resetSlack = () => {
if (!slack) return;
slack.el.style.paddingBottom = slack.paddingBottom;
slack = null;
};

/** Room at the end of the container for the part of the pan it can't scroll by, kept while the keyboard is open */
const addSlack = (el: HTMLElement, value: number) => {
if (slack?.el !== el) {
resetSlack();
slack = {
el,
paddingBottom: el.style.paddingBottom,
basePadding: parseFloat(window.getComputedStyle(el).paddingBottom) || 0,
value: 0,
};
}

slack.value += Math.ceil(value);
el.style.paddingBottom = `${slack.basePadding + slack.value}px`;
};

/**
* Safari pans the page only for a focused field, and only the page the user can't scroll stays panned.
* Doesn't wait for the keyboard, since Safari can start panning before the viewport resize for it
*/
const isPanning = () => isKeyboardField(document.activeElement) && isPageScrollLocked();

const handOver = () => {
timeout = undefined;

// Zoomed page and a finger on the screen pan the page themselves
if (touching || viewport.scale !== 1 || !getVirtualKeyboardHeight() || !isPanning()) return;

const pan = window.scrollY - restY;
const field = document.activeElement as HTMLElement;
if (pan < 1 || !field.parentElement) return;

// Field scrolling its own content can't take the page pan
const container = findClosestScrollableContainer({ el: field.parentElement });
if (!container) return;

const room = container.scrollHeight - container.clientHeight - container.scrollTop;
if (room < pan) {
const clientHeight = container.clientHeight;
addSlack(container, pan - room);
// Container sized by its content grows with the padding instead of scrolling further
if (container.clientHeight !== clientHeight) resetSlack();
}

const scrollTop = container.scrollTop;
container.scrollTop = scrollTop + pan;
const scrolled = container.scrollTop - scrollTop;

// Instant behavior ignores the smooth scrolling that could be enabled for the page
window.scrollTo({ left: restX, top: restY + pan - scrolled, behavior: "instant" });
};

const scheduleHandOver = () => {
clearTimeout(timeout);
timeout = setTimeout(handOver, SETTLE_DELAY);
};

const handleScroll = () => {
if (isPanning()) {
scheduleHandOver();
return;
}

restX = window.scrollX;
restY = window.scrollY;
};

const handleTouch = (e: TouchEvent) => {
touching = e.touches.length > 0;
if (!touching) scheduleHandOver();
};

const handleKeyboardChange = () => {
if (getVirtualKeyboardHeight()) scheduleHandOver();
else resetSlack();
};

const unsubscribeKeyboard = subscribeVirtualKeyboard(handleKeyboardChange);
window.addEventListener("scroll", handleScroll, { passive: true });
viewport.addEventListener("scroll", scheduleHandOver);
document.addEventListener("focusin", scheduleHandOver);
document.addEventListener("touchstart", handleTouch, { passive: true, capture: true });
document.addEventListener("touchend", handleTouch, { passive: true, capture: true });
document.addEventListener("touchcancel", handleTouch, { passive: true, capture: true });

return () => {
clearTimeout(timeout);
resetSlack();
unsubscribeKeyboard();
window.removeEventListener("scroll", handleScroll);
viewport.removeEventListener("scroll", scheduleHandOver);
document.removeEventListener("focusin", scheduleHandOver);
document.removeEventListener("touchstart", handleTouch, { capture: true });
document.removeEventListener("touchend", handleTouch, { capture: true });
document.removeEventListener("touchcancel", handleTouch, { capture: true });
};
};

let count = 0;
let uninstall: (() => void) | null = null;

/** Starts handing over the keyboard pan, shared by everything that needs it and stopped once all of them release it */
export const handOverKeyboardPan = () => {
if (!count++) uninstall = install();

let released = false;
return () => {
if (released) return;
released = true;

if (--count) return;
uninstall?.();
uninstall = null;
};
};

/** Same as handOverKeyboardPan, only on iOS where the keyboard pans the page */
export const handOverIOSKeyboardPan = () => (isIOS() ? handOverKeyboardPan() : () => {});
23 changes: 9 additions & 14 deletions packages/utilities/src/scroll/lockSafari.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
import { StyleCache } from "@/css";
import { getViewportScroller, handOverKeyboardPan } from "./keyboardPan";

const styleCache = new StyleCache();

/**
* Viewport overflow comes from <html> when it has its own overflow value,
* and propagates from <body> otherwise, so an overflow style on the other element doesn't lock the page.
*/
const getViewportScroller = () => {
const html = document.documentElement;
const { overflowX, overflowY } = window.getComputedStyle(html);
const htmlHasOverflow = overflowX !== "visible" || overflowY !== "visible";

return htmlHasOverflow ? html : document.body;
};

/**
* iOS uses overlay scrollbars, so the document scroll is locked with overflow only.
* Body is not moved to a fixed position since that collapses the document height,
* which makes Safari lose its translucent toolbars and resets the scroll position on unlock.
* Revealing the focused fields above the on-screen keyboard is left to Safari:
* taking over its focus handling and panning makes the page jump between the positions both of them resolve
* taking over its focus handling and panning makes the page jump between the positions both of them resolve.
* A pan Safari leaves on the locked page is handed over to the field's scrollable container once it's settled.
* The Reshaped provider keeps that running on iOS too, for the pages that can't be scrolled without a lock
*/
const lockSafariScroll = () => {
const el = getViewportScroller();

// Longhands keep the original value of each axis when unlocking, e.g. overflow-x: hidden on body
styleCache.set(el, { overflowX: "hidden", overflowY: "hidden" });
const releaseKeyboardPan = handOverKeyboardPan();

return () => styleCache.reset(el);
return () => {
releaseKeyboardPan();
styleCache.reset(el);
};
};

export default lockSafariScroll;
Loading
Loading