Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/modal-keyboard-safe-area.md
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions .changeset/use-virtual-keyboard.md
Original file line number Diff line number Diff line change
@@ -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
7 changes: 6 additions & 1 deletion packages/reshaped/src/components/Modal/Modal.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
3 changes: 3 additions & 0 deletions packages/reshaped/src/components/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -78,6 +79,7 @@ const Modal: FC<T.Props> = (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<HTMLDivElement>(null);
Expand Down Expand Up @@ -148,6 +150,7 @@ const Modal: FC<T.Props> = (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}
Expand Down
35 changes: 35 additions & 0 deletions packages/reshaped/src/components/Modal/tests/Modal.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,41 @@ export const className: StoryObj = {
},
};

export const virtualKeyboard: StoryObj = {
name: "test: virtual keyboard",
render: () => <Demo position="end" title="Modal title" />,
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: () => {
Expand Down
41 changes: 41 additions & 0 deletions packages/reshaped/src/hooks/tests/useVirtualKeyboard.stories.tsx
Original file line number Diff line number Diff line change
@@ -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 <div data-testid="root">{height}</div>;
},
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"));
},
};
22 changes: 22 additions & 0 deletions packages/reshaped/src/hooks/useVirtualKeyboard.ts
Original file line number Diff line number Diff line change
@@ -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;
1 change: 1 addition & 0 deletions packages/reshaped/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand Down
1 change: 1 addition & 0 deletions packages/utilities/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
2 changes: 2 additions & 0 deletions packages/utilities/src/viewport/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Internal
export { getVirtualKeyboardHeight, subscribeVirtualKeyboard } from "./virtualKeyboard";
84 changes: 84 additions & 0 deletions packages/utilities/src/viewport/tests/virtualKeyboard.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
60 changes: 60 additions & 0 deletions packages/utilities/src/viewport/virtualKeyboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
type Listener = () => void;

const listeners = new Set<Listener>();
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);
};
};
Loading