diff --git a/.changeset/modal-keyboard-safe-area.md b/.changeset/modal-keyboard-safe-area.md new file mode 100644 index 000000000..9d35e7f38 --- /dev/null +++ b/.changeset/modal-keyboard-safe-area.md @@ -0,0 +1,5 @@ +--- +"reshaped": patch +--- + +`Modal` doesn't keep the bottom safe area inset while the on-screen keyboard covers it. iOS keeps reporting the home indicator inset with the keyboard open, which left a gap between the keyboard and the modals with `start` and `end` positions, and an extra bottom padding in the modals with `bottom` position diff --git a/.changeset/use-virtual-keyboard.md b/.changeset/use-virtual-keyboard.md new file mode 100644 index 000000000..fedb268f9 --- /dev/null +++ b/.changeset/use-virtual-keyboard.md @@ -0,0 +1,5 @@ +--- +"reshaped": minor +--- + +Added `useVirtualKeyboard` hook returning the `height` of the area the on-screen keyboard covers at the bottom of the viewport. It's 0 when the keyboard is closed and when the browser resizes the layout to fit above the keyboard diff --git a/packages/reshaped/src/components/Modal/Modal.module.css b/packages/reshaped/src/components/Modal/Modal.module.css index 93c239e3d..00aafe876 100644 --- a/packages/reshaped/src/components/Modal/Modal.module.css +++ b/packages/reshaped/src/components/Modal/Modal.module.css @@ -14,7 +14,12 @@ --rs-modal-container-height: 100vh; --rs-modal-padding: calc(var(--rs-modal-p) * var(--rs-unit-x1)); --rs-modal-env-top: env(safe-area-inset-top, 0px); - --rs-modal-env-bottom: env(safe-area-inset-bottom, 0px); + + /* iOS keeps reporting the bottom safe area while the on-screen keyboard covers it */ + --rs-modal-env-bottom: max( + 0px, + env(safe-area-inset-bottom, 0px) - var(--rs-modal-keyboard-height, 0px) + ); --rs-modal-env-start: env(safe-area-inset-left, 0px); --rs-modal-env-end: env(safe-area-inset-right, 0px); diff --git a/packages/reshaped/src/components/Modal/Modal.tsx b/packages/reshaped/src/components/Modal/Modal.tsx index 7cd5ac0d4..e19d060b4 100644 --- a/packages/reshaped/src/components/Modal/Modal.tsx +++ b/packages/reshaped/src/components/Modal/Modal.tsx @@ -7,6 +7,7 @@ import Overlay, { type OverlayInstance } from "@/components/Overlay"; import Text from "@/components/Text"; import useElementId from "@/hooks/useElementId"; import useResponsiveClientValue from "@/hooks/useResponsiveClientValue"; +import useVirtualKeyboard from "@/hooks/useVirtualKeyboard"; import { responsiveClassNames, responsiveVariables } from "@/utilities/props"; import type * as T from "./Modal.types"; import useModalDrag from "./useModalDrag"; @@ -78,6 +79,7 @@ const Modal: FC = (props) => { } = props; const id = useElementId(); const clientPosition = useResponsiveClientValue(position)!; + const keyboard = useVirtualKeyboard(); const [titleMounted, setTitleMounted] = useState(false); const [subtitleMounted, setSubtitleMounted] = useState(false); const internalRootRef = useRef(null); @@ -148,6 +150,7 @@ const Modal: FC = (props) => { ...responsiveVariables("--rs-modal-size", size), ...responsiveVariables("--rs-modal-p", padding), "--rs-modal-drag": "0px", + "--rs-modal-keyboard-height": `${keyboard.height}px`, } as React.CSSProperties } aria-labelledby={titleMounted ? `${id}-title` : undefined} diff --git a/packages/reshaped/src/components/Modal/tests/Modal.stories.tsx b/packages/reshaped/src/components/Modal/tests/Modal.stories.tsx index 75d192931..fde623ff8 100644 --- a/packages/reshaped/src/components/Modal/tests/Modal.stories.tsx +++ b/packages/reshaped/src/components/Modal/tests/Modal.stories.tsx @@ -410,6 +410,41 @@ export const className: StoryObj = { }, }; +export const virtualKeyboard: StoryObj = { + name: "test: virtual keyboard", + render: () => , + play: async ({ canvasElement }) => { + const canvas = within(canvasElement.ownerDocument.body); + const viewport = window.visualViewport!; + + await userEvent.click(canvas.getByRole("button", { name: "Open dialog" })); + + const root = await canvas.findByRole("dialog"); + + expect(root.style.getPropertyValue("--rs-modal-keyboard-height")).toBe("0px"); + + // On-screen keyboard shrinks the visual viewport without changing the layout + Object.defineProperty(viewport, "height", { + configurable: true, + value: window.innerHeight - 300, + }); + viewport.dispatchEvent(new Event("resize")); + + // Bottom safe area inset is reduced by the keyboard height covering it + await waitFor(() => { + expect(root.style.getPropertyValue("--rs-modal-keyboard-height")).toBe("300px"); + }); + + // @ts-expect-error Removes the stubbed value from the viewport itself + delete viewport.height; + viewport.dispatchEvent(new Event("resize")); + + await waitFor(() => { + expect(root.style.getPropertyValue("--rs-modal-keyboard-height")).toBe("0px"); + }); + }, +}; + export const edgeCases = { name: "test: edge cases", render: () => { diff --git a/packages/reshaped/src/hooks/tests/useVirtualKeyboard.stories.tsx b/packages/reshaped/src/hooks/tests/useVirtualKeyboard.stories.tsx new file mode 100644 index 000000000..95a156240 --- /dev/null +++ b/packages/reshaped/src/hooks/tests/useVirtualKeyboard.stories.tsx @@ -0,0 +1,41 @@ +import { StoryObj } from "@storybook/react-vite"; +import { expect, waitFor } from "storybook/test"; + +import useVirtualKeyboard from "../useVirtualKeyboard"; + +export default { + title: "Hooks/useVirtualKeyboard", + parameters: { + chromatic: { disableSnapshot: true }, + }, +}; + +export const height: StoryObj = { + name: "height", + render: () => { + const { height } = useVirtualKeyboard(); + + return
{height}
; + }, + play: async ({ canvas }) => { + const root = canvas.getByTestId("root"); + const viewport = window.visualViewport!; + + expect(root).toHaveTextContent("0"); + + // On-screen keyboard shrinks the visual viewport without changing the layout + Object.defineProperty(viewport, "height", { + configurable: true, + value: window.innerHeight - 300, + }); + viewport.dispatchEvent(new Event("resize")); + + await waitFor(() => expect(root).toHaveTextContent("300")); + + // @ts-expect-error Removes the stubbed value from the viewport itself + delete viewport.height; + viewport.dispatchEvent(new Event("resize")); + + await waitFor(() => expect(root).toHaveTextContent("0")); + }, +}; diff --git a/packages/reshaped/src/hooks/useVirtualKeyboard.ts b/packages/reshaped/src/hooks/useVirtualKeyboard.ts new file mode 100644 index 000000000..73a2545b0 --- /dev/null +++ b/packages/reshaped/src/hooks/useVirtualKeyboard.ts @@ -0,0 +1,22 @@ +"use client"; + +import React from "react"; +import { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "@reshaped/utilities/internal"; + +const getServerHeight = () => 0; + +/** + * Returns the height of the area the on-screen keyboard covers at the bottom of the viewport. + * It's 0 when the keyboard is closed and when the browser resizes the layout to fit above it + */ +const useVirtualKeyboard = () => { + const height = React.useSyncExternalStore( + subscribeVirtualKeyboard, + getVirtualKeyboardHeight, + getServerHeight + ); + + return React.useMemo(() => ({ height }), [height]); +}; + +export default useVirtualKeyboard; diff --git a/packages/reshaped/src/index.ts b/packages/reshaped/src/index.ts index 45db31cba..6ef092b27 100644 --- a/packages/reshaped/src/index.ts +++ b/packages/reshaped/src/index.ts @@ -154,6 +154,7 @@ export { default as useOnClickOutside } from "@/hooks/useOnClickOutside"; export { default as useRTL } from "@/hooks/useRTL"; export { default as useScrollLock } from "@/hooks/useScrollLock"; export { default as useToggle } from "@/hooks/useToggle"; +export { default as useVirtualKeyboard } from "@/hooks/useVirtualKeyboard"; export { default as useIsDismissible } from "@/hooks/useIsDismissible"; /** diff --git a/packages/utilities/src/internal.ts b/packages/utilities/src/internal.ts index 57ff0202f..5bd3e7a40 100644 --- a/packages/utilities/src/internal.ts +++ b/packages/utilities/src/internal.ts @@ -22,3 +22,4 @@ export { findParent, getShadowRoot } from "./dom"; export { rafThrottle } from "./helpers"; export { disableScroll, enableScroll } from "./scroll"; export type { Coordinates } from "./types/global"; +export { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "./viewport"; diff --git a/packages/utilities/src/viewport/index.ts b/packages/utilities/src/viewport/index.ts new file mode 100644 index 000000000..bbc808871 --- /dev/null +++ b/packages/utilities/src/viewport/index.ts @@ -0,0 +1,2 @@ +// Internal +export { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "./virtualKeyboard"; diff --git a/packages/utilities/src/viewport/tests/virtualKeyboard.test.ts b/packages/utilities/src/viewport/tests/virtualKeyboard.test.ts new file mode 100644 index 000000000..bd23faf20 --- /dev/null +++ b/packages/utilities/src/viewport/tests/virtualKeyboard.test.ts @@ -0,0 +1,84 @@ +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; + +import { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "../virtualKeyboard"; + +const original = Object.getOwnPropertyDescriptor(window, "visualViewport")!; +let viewport: EventTarget & { height: number; scale: number }; +let unsubscribe: (() => void) | undefined; + +const resize = (args: { height: number; scale?: number }) => { + viewport.height = args.height; + viewport.scale = args.scale ?? 1; + viewport.dispatchEvent(new Event("resize")); +}; + +describe("viewport/virtualKeyboard", () => { + beforeEach(() => { + viewport = Object.assign(new EventTarget(), { height: window.innerHeight, scale: 1 }); + Object.defineProperty(window, "visualViewport", { configurable: true, value: viewport }); + }); + + afterEach(() => { + unsubscribe?.(); + unsubscribe = undefined; + // @ts-expect-error Removes the stubbed value from the element itself + delete document.documentElement.clientHeight; + Object.defineProperty(window, "visualViewport", original); + }); + + test("returns the height covered by the keyboard", () => { + const listener = vi.fn(); + unsubscribe = subscribeVirtualKeyboard(listener); + + expect(getVirtualKeyboardHeight()).toBe(0); + + resize({ height: window.innerHeight - 300 }); + + expect(getVirtualKeyboardHeight()).toBe(300); + expect(listener).toHaveBeenCalledTimes(1); + + resize({ height: window.innerHeight }); + + expect(getVirtualKeyboardHeight()).toBe(0); + expect(listener).toHaveBeenCalledTimes(2); + }); + + test("measures the keyboard opened before subscribing", () => { + viewport.height = window.innerHeight - 300; + unsubscribe = subscribeVirtualKeyboard(() => {}); + + expect(getVirtualKeyboardHeight()).toBe(300); + }); + + test("ignores the pinch zoom", () => { + const listener = vi.fn(); + unsubscribe = subscribeVirtualKeyboard(listener); + + resize({ height: window.innerHeight / 2, scale: 2 }); + + expect(getVirtualKeyboardHeight()).toBe(0); + expect(listener).not.toHaveBeenCalled(); + }); + + test("ignores the document scrollbar", () => { + // Headless browsers don't render scrollbars, so the height it takes from the document is stubbed + Object.defineProperty(document.documentElement, "clientHeight", { + configurable: true, + value: window.innerHeight - 15, + }); + viewport.height = window.innerHeight - 15; + unsubscribe = subscribeVirtualKeyboard(() => {}); + + expect(getVirtualKeyboardHeight()).toBe(0); + }); + + test("stops updating without subscribers", () => { + const listener = vi.fn(); + subscribeVirtualKeyboard(listener)(); + + resize({ height: window.innerHeight - 300 }); + + expect(getVirtualKeyboardHeight()).toBe(0); + expect(listener).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/utilities/src/viewport/virtualKeyboard.ts b/packages/utilities/src/viewport/virtualKeyboard.ts new file mode 100644 index 000000000..c6e76eb1c --- /dev/null +++ b/packages/utilities/src/viewport/virtualKeyboard.ts @@ -0,0 +1,60 @@ +type Listener = () => void; + +const listeners = new Set(); +let height = 0; + +/** + * iOS, and Android by default, keep the layout as it is when the on-screen keyboard opens and only shrink the visual viewport, + * so the keyboard height is the part of the dynamic viewport the visual viewport doesn't reach. + * The dynamic viewport is measured with an element since there is no other way to resolve its units + */ +const measure = () => { + const viewport = window.visualViewport; + if (!viewport) return 0; + + const probeEl = document.createElement("div"); + probeEl.style.cssText = + "position:fixed;top:0;left:0;width:0;height:100dvh;visibility:hidden;pointer-events:none"; + document.body.appendChild(probeEl); + const dynamicHeight = probeEl.getBoundingClientRect().height; + probeEl.style.height = "100svh"; + const smallHeight = probeEl.getBoundingClientRect().height; + probeEl.remove(); + + // Viewport units include the classic scrollbar of the document, which the visual viewport leaves out + const scrollbarHeight = Math.max(0, smallHeight - document.documentElement.clientHeight); + // Visual viewport gets smaller with the pinch zoom, so it's scaled back to the layout size + const visibleHeight = viewport.height * viewport.scale; + + // Rounded down to keep the subpixel difference of a zoomed page from being treated as a keyboard + return Math.max(0, Math.floor(dynamicHeight - scrollbarHeight - visibleHeight)); +}; + +const update = () => { + const nextHeight = measure(); + if (nextHeight === height) return; + + height = nextHeight; + listeners.forEach((listener) => listener()); +}; + +/** + * Height of the area the on-screen keyboard covers at the bottom of the viewport, + * 0 when it's closed or when the browser resizes the layout to fit above the keyboard. + * Updated while there is at least one subscriber + */ +export const getVirtualKeyboardHeight = () => height; + +export const subscribeVirtualKeyboard = (listener: Listener) => { + if (!listeners.size) { + window.visualViewport?.addEventListener("resize", update); + update(); + } + + listeners.add(listener); + + return () => { + listeners.delete(listener); + if (!listeners.size) window.visualViewport?.removeEventListener("resize", update); + }; +};