diff --git a/.changeset/keyboard-pan-handover.md b/.changeset/keyboard-pan-handover.md new file mode 100644 index 000000000..812f1ab5e --- /dev/null +++ b/.changeset/keyboard-pan-handover.md @@ -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 diff --git a/packages/reshaped/src/components/Reshaped/Reshaped.tsx b/packages/reshaped/src/components/Reshaped/Reshaped.tsx index 35c1ed286..03e08be4e 100644 --- a/packages/reshaped/src/components/Reshaped/Reshaped.tsx +++ b/packages/reshaped/src/components/Reshaped/Reshaped.tsx @@ -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"; @@ -29,6 +30,10 @@ const Reshaped: React.FC = (props) => { const scopeRef = React.useRef(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 ( diff --git a/packages/utilities/src/internal.ts b/packages/utilities/src/internal.ts index 5bd3e7a40..e068a6aa3 100644 --- a/packages/utilities/src/internal.ts +++ b/packages/utilities/src/internal.ts @@ -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"; diff --git a/packages/utilities/src/scroll/index.ts b/packages/utilities/src/scroll/index.ts index 28acb6410..dd1a6c09b 100644 --- a/packages/utilities/src/scroll/index.ts +++ b/packages/utilities/src/scroll/index.ts @@ -3,3 +3,4 @@ export { lockScroll } from "./lock"; // Internal export { disableScroll, enableScroll } from "./disable"; +export { handOverIOSKeyboardPan } from "./keyboardPan"; diff --git a/packages/utilities/src/scroll/keyboardPan.ts b/packages/utilities/src/scroll/keyboardPan.ts new file mode 100644 index 000000000..60cab0294 --- /dev/null +++ b/packages/utilities/src/scroll/keyboardPan.ts @@ -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 when it has its own overflow value, + * and propagates from 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 | 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() : () => {}); diff --git a/packages/utilities/src/scroll/lockSafari.ts b/packages/utilities/src/scroll/lockSafari.ts index 6752aab8c..2981c7f66 100644 --- a/packages/utilities/src/scroll/lockSafari.ts +++ b/packages/utilities/src/scroll/lockSafari.ts @@ -1,33 +1,28 @@ import { StyleCache } from "@/css"; +import { getViewportScroller, handOverKeyboardPan } from "./keyboardPan"; const styleCache = new StyleCache(); -/** - * Viewport overflow comes from when it has its own overflow value, - * and propagates from 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; diff --git a/packages/utilities/src/scroll/tests/keyboardPan.test.ts b/packages/utilities/src/scroll/tests/keyboardPan.test.ts new file mode 100644 index 000000000..32058cf21 --- /dev/null +++ b/packages/utilities/src/scroll/tests/keyboardPan.test.ts @@ -0,0 +1,171 @@ +import { afterEach, beforeEach, describe, expect, test } from "vitest"; + +import { handOverKeyboardPan } from "../keyboardPan"; + +const original = Object.getOwnPropertyDescriptor(window, "visualViewport")!; +let viewport: EventTarget & { height: number; offsetTop: number; scale: number }; +let release: (() => void) | undefined; + +const resize = (height: number) => { + viewport.height = height; + viewport.dispatchEvent(new Event("resize")); +}; + +const touch = (type: "touchstart" | "touchend") => { + const point = new Touch({ identifier: 1, target: document.body, clientX: 10, clientY: 10 }); + const touches = type === "touchstart" ? [point] : []; + document.body.dispatchEvent(new TouchEvent(type, { bubbles: true, touches })); +}; + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Container scrolled to its end with the focused field in it, on a page the user can't scroll and Safari can pan */ +const render = (args?: { boxSizing?: "content-box"; scrollable?: boolean }) => { + if (!args?.scrollable) document.body.style.overflow = "hidden"; + const root = document.createElement("div"); + root.innerHTML = ` +
+
+ +
+
+ `; + document.body.appendChild(root); + + const scrollEl = root.querySelector("[data-scroll]")!; + scrollEl.scrollTop = scrollEl.scrollHeight; + root.querySelector("input")!.focus({ preventScroll: true }); + + return { scrollEl, endScrollTop: scrollEl.scrollTop }; +}; + +describe("scroll/handOverKeyboardPan", () => { + beforeEach(() => { + document.body.innerHTML = ""; + viewport = Object.assign(new EventTarget(), { + height: window.innerHeight, + offsetTop: 0, + scale: 1, + }); + Object.defineProperty(window, "visualViewport", { configurable: true, value: viewport }); + }); + + afterEach(() => { + release?.(); + release = undefined; + document.body.innerHTML = ""; + document.body.style.overflow = ""; + window.scrollTo(0, 0); + Object.defineProperty(window, "visualViewport", original); + }); + + test("hands the page pan over to the container of the focused field, with room for it at the end", async () => { + const { scrollEl, endScrollTop } = render(); + release = handOverKeyboardPan(); + + resize(window.innerHeight - 300); + window.scrollTo(0, 120); + + await expect.poll(() => window.scrollY).toBe(0); + expect(scrollEl.scrollTop).toBe(endScrollTop + 120); + expect(scrollEl.style.paddingBottom).toBe("120px"); + + resize(window.innerHeight); + + expect(scrollEl.style.paddingBottom).toBe(""); + }); + + test("scrolls the page back to where it rested before the field was focused", async () => { + release = handOverKeyboardPan(); + const content = document.createElement("div"); + content.style.height = "3000px"; + document.body.appendChild(content); + const scrolled = new Promise((resolve) => + window.addEventListener("scroll", resolve, { once: true }) + ); + window.scrollTo(0, 300); + await scrolled; + const { scrollEl, endScrollTop } = render(); + + resize(window.innerHeight - 300); + window.scrollTo(0, 420); + + await expect.poll(() => window.scrollY).toBe(300); + expect(scrollEl.scrollTop).toBe(endScrollTop + 120); + }); + + test("leaves a page the user can scroll alone", async () => { + const { scrollEl, endScrollTop } = render({ scrollable: true }); + release = handOverKeyboardPan(); + + resize(window.innerHeight - 300); + window.scrollTo(0, 120); + await wait(400); + + expect(window.scrollY).toBe(120); + expect(scrollEl.scrollTop).toBe(endScrollTop); + }); + + test("waits for the finger to leave the screen", async () => { + const { scrollEl, endScrollTop } = render(); + release = handOverKeyboardPan(); + resize(window.innerHeight - 300); + + touch("touchstart"); + window.scrollTo(0, 120); + await wait(400); + + expect(window.scrollY).toBe(120); + + touch("touchend"); + + await expect.poll(() => window.scrollY).toBe(0); + expect(scrollEl.scrollTop).toBe(endScrollTop + 120); + }); + + test("keeps the pan when the container grows with the room instead of scrolling", async () => { + const { scrollEl, endScrollTop } = render({ boxSizing: "content-box" }); + release = handOverKeyboardPan(); + + resize(window.innerHeight - 300); + window.scrollTo(0, 120); + await wait(400); + + expect(window.scrollY).toBe(120); + expect(scrollEl.scrollTop).toBe(endScrollTop); + expect(scrollEl.style.paddingBottom).toBe(""); + }); + + test("leaves the page scroll alone without the keyboard", async () => { + const { scrollEl, endScrollTop } = render(); + release = handOverKeyboardPan(); + + window.scrollTo(0, 120); + await wait(400); + + expect(window.scrollY).toBe(120); + expect(scrollEl.scrollTop).toBe(endScrollTop); + }); + + test("keeps handing over until everything using it releases it", async () => { + const { scrollEl, endScrollTop } = render(); + const releaseFirst = handOverKeyboardPan(); + release = handOverKeyboardPan(); + releaseFirst(); + releaseFirst(); + resize(window.innerHeight - 300); + + window.scrollTo(0, 120); + + await expect.poll(() => window.scrollY).toBe(0); + expect(scrollEl.scrollTop).toBe(endScrollTop + 120); + + release(); + release = undefined; + window.scrollTo(0, 120); + await wait(400); + + expect(window.scrollY).toBe(120); + expect(scrollEl.style.paddingBottom).toBe(""); + }); +});