An open source design system that's fully customizable and agent ready
TypeScript
fix(Popover): in a Picture-in-Picture window, it scrolls once its window is too short (#9098)
Christopher Chedeauf233ad6b21d9
diff --git a/.changeset/a-popover-in-a-document-picture-in-picture-windo-9gwo.md b/.changeset/a-popover-in-a-document-picture-in-picture-windo-9gwo.mdnew file mode 100644index 0000000000..3b5bb08c9d--- /dev/null+++ b/.changeset/a-popover-in-a-document-picture-in-picture-windo-9gwo.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] A `Popover` in a Document Picture-in-Picture window now scrolls once that window gets too short for it or its content grows past it, instead of being cut off: it measures its overflow from the window it renders in, not the page.+@vjeuxdiff --git a/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx b/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsxindex 26882b281c..d6f49b8e59 100644--- a/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx+++ b/apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx@@ -4,8 +4,8 @@* @file PopoverSecondDocumentA11y.stories.tsx* @input Uses Popover, Button, VStack and HStack from core, and React portals* @output The fixture the second-document Popover spec drives in a real- * browser: the same two popovers in the page, in a same-origin iframe, and in- * a Document Picture-in-Picture window.+ * browser: the same popovers in the page, in a same-origin iframe, and in a+ * Document Picture-in-Picture window.* @position The reproduction path for* `packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts`* (`docs/specs/AST-009/spec.md` FR30: a browser claim is checked against a@@ -13,8 +13,9 @@** An app can render part of its UI into a second document through a React* portal: a same-origin iframe, or a Document Picture-in-Picture window that- * floats above the page. A Popover there opens, traps Tab, closes on Escape and- * hands focus back exactly as it does in the page itself.+ * floats above the page. A Popover there opens, traps Tab, closes on Escape,+ * hands focus back, and scrolls once its window is too short for it, exactly as+ * it does in the page itself.** SYNC: The spec navigates to this story id and finds the frame, the Pop out* button and the popover controls by name. Nothing at compile time catches a@@ -39,7 +40,7 @@ const meta: Meta = {docs: {description: {component:- 'The same two popovers in the page, in a same-origin iframe, and in a Picture-in-Picture window (Pop out). In every document, opening focuses First, Tab stays inside, Escape closes either popover, and closing hands focus back to its trigger.',+ 'The same popovers in the page, in a same-origin iframe, and in a Picture-in-Picture window (Pop out). In every document, opening focuses First, Tab stays inside, Escape closes either settings popover, and closing hands focus back to its trigger. Long list scrolls once its window is too short for it.',},},},@@ -55,7 +56,7 @@ const styles = stylex.create({borderStyle: 'solid',borderColor: 'currentColor',},- // Clear of either open popover, so a press on it is a press outside.+ // Clear of either open settings popover, so a press on it is a press outside.outside: {marginBlockStart: 96,},@@ -86,7 +87,13 @@ function adoptPageStyles(target: Document) {}}-/** The default popover, and one that closes only on request. */+/** Ten rows: taller than a short window, shorter than a tall one. */+const LONG_LIST = Array.from({length: 10}, (_, index) => `Row ${index + 1}`);++/**+ * The default popover, one that closes only on request, and a long one that+ * scrolls once its window is too short for it.+ */function Popovers() {const controls = (<HStack gap={2}>@@ -105,6 +112,17 @@ function Popovers() {content={controls}><Button label="Pinned settings" /></Popover>+ <Popover+ label="Long list"+ content={+ <VStack gap={1}>+ {LONG_LIST.map(row => (+ <span key={row}>{row}</span>+ ))}+ </VStack>+ }>+ <Button label="Long list" />+ </Popover><p {...stylex.props(styles.outside)}>Outside</p></VStack>);@@ -165,7 +183,7 @@ function PictureInPicturePopovers() {}/**- * Two popovers in each of three documents: the page, a same-origin iframe, and+ * The popovers in each of three documents: the page, a same-origin iframe, and* a Picture-in-Picture window that Pop out opens.*/export const SecondDocuments: StoryObj = {diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsxindex 8d4b045563..b3f3fe95b6 100644--- a/packages/core/src/Popover/Popover.test.tsx+++ b/packages/core/src/Popover/Popover.test.tsx@@ -1221,6 +1221,46 @@ describe('Popover', () => {fireEvent.keyDown(secondDocument, {key: 'Escape'});expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false);});++ it('re-measures its overflow when its own window resizes', () => {+ const {trigger, surface} = renderInSecondDocument();+ const secondWindow = secondDocument.defaultView!;+ const frames: FrameRequestCallback[] = [];+ const requestFrame = vi+ .spyOn(secondWindow, 'requestAnimationFrame')+ .mockImplementation(callback => {+ frames.push(callback);+ return frames.length;+ });+ const runFrames = () =>+ act(() => frames.splice(0).forEach(callback => callback(0)));+ fireEvent.click(trigger, {detail: 1});+ runFrames();+ expect(surface.className).not.toContain(+ 'Popover__styles.surfaceScrollable',+ );++ // The window the Popover renders in gets too short for its content.+ const {prototype} = secondWindow.HTMLElement;+ const sizes = [+ vi.spyOn(prototype, 'clientHeight', 'get').mockReturnValue(100),+ vi.spyOn(prototype, 'scrollHeight', 'get').mockReturnValue(200),+ vi.spyOn(prototype, 'clientWidth', 'get').mockReturnValue(200),+ vi.spyOn(prototype, 'scrollWidth', 'get').mockReturnValue(200),+ ];+ try {+ act(() => {+ secondWindow.dispatchEvent(new secondWindow.Event('resize'));+ });+ runFrames();+ expect(surface.className).toContain(+ 'Popover__styles.surfaceScrollable',+ );+ } finally {+ sizes.forEach(size => size.mockRestore());+ requestFrame.mockRestore();+ }+ });});describe('surface padding', () => {diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsxindex 8788ac2f63..7800ff5585 100644--- a/packages/core/src/Popover/Popover.tsx+++ b/packages/core/src/Popover/Popover.tsx@@ -446,6 +446,15 @@ const styles = stylex.create({},});+/**+ * The window that holds `element`: the page's own, or a second document's (a+ * same-origin iframe, a Document Picture-in-Picture window) when the Popover+ * renders there.+ */+function windowOf(element: Element | null): Window & typeof globalThis {+ return element?.ownerDocument.defaultView ?? window;+}+// =============================================================================// Component// =============================================================================@@ -512,7 +521,7 @@ export function Popover({}: PopoverProps): ReactElement {const t = useTranslator();const wrapperRef = useRef<HTMLDivElement>(null);- const measurementFrameRef = useRef<number | null>(null);+ const measurementFrameRef = useRef<{id: number; view: Window} | null>(null);const [hasOverflow, setHasOverflow] = useState(false);const isControlled = isOpen !== undefined;// The bottom-sheet presentation: the surface it resolves to now, and@@ -711,11 +720,16 @@ export function Popover({if (measurementFrameRef.current != null) {return;}- measurementFrameRef.current = window.requestAnimationFrame(() => {- measurementFrameRef.current = null;- measureOverflow();- });- }, [measureOverflow]);+ // The surface's own window paints it, so its frame runs the measurement.+ const view = windowOf(popover.contentRef.current);+ measurementFrameRef.current = {+ view,+ id: view.requestAnimationFrame(() => {+ measurementFrameRef.current = null;+ measureOverflow();+ }),+ };+ }, [measureOverflow, popover.contentRef]);useIsomorphicLayoutEffect(() => {if (!popover.isOpen) {@@ -725,11 +739,16 @@ export function Popover({if (!surface) {return;}+ // Observe from the surface's own window. A Popover rendered into a second+ // document resizes with that document's window, and a ResizeObserver the+ // page created checks a box in a Picture-in-Picture window only while the+ // page itself renders frames.+ const view = windowOf(surface);measureOverflow();const resizeObserver =- typeof ResizeObserver === 'undefined'+ typeof view.ResizeObserver === 'undefined'? null- : new ResizeObserver(scheduleOverflowMeasurement);+ : new view.ResizeObserver(scheduleOverflowMeasurement);const mutationObserver =typeof MutationObserver === 'undefined'? null@@ -741,8 +760,8 @@ export function Popover({subtree: true,});surface.addEventListener('load', scheduleOverflowMeasurement, true);- window.addEventListener('resize', scheduleOverflowMeasurement);- window.visualViewport?.addEventListener(+ view.addEventListener('resize', scheduleOverflowMeasurement);+ view.visualViewport?.addEventListener('resize',scheduleOverflowMeasurement,);@@ -750,13 +769,14 @@ export function Popover({resizeObserver?.disconnect();mutationObserver?.disconnect();surface.removeEventListener('load', scheduleOverflowMeasurement, true);- window.removeEventListener('resize', scheduleOverflowMeasurement);- window.visualViewport?.removeEventListener(+ view.removeEventListener('resize', scheduleOverflowMeasurement);+ view.visualViewport?.removeEventListener('resize',scheduleOverflowMeasurement,);- if (measurementFrameRef.current != null) {- window.cancelAnimationFrame(measurementFrameRef.current);+ const frame = measurementFrameRef.current;+ if (frame != null) {+ frame.view.cancelAnimationFrame(frame.id);measurementFrameRef.current = null;}};diff --git a/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts b/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.tsindex a0bc30e406..6b79e4c105 100644--- a/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts+++ b/packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts@@ -8,12 +8,13 @@* @output Real-browser evidence that a Popover rendered into a second document* (a same-origin iframe, a Document Picture-in-Picture window) focuses its* first control on open, keeps Tab inside, closes on Escape through the layer- * stack with and without light dismiss, and hands focus back to its trigger- * after an outside click, exactly as the same Popover does in the page.+ * stack with and without light dismiss, hands focus back to its trigger after+ * an outside click, and scrolls once its own window is too short for it or+ * its content grows past it, exactly as the same Popover does in the page.* @position The half of the second-document rule jsdom cannot honestly reach:- * real key delivery to another window, native light dismiss, and the- * browser's own close watcher. The Vitest cases in `Popover/Popover.test.tsx`- * model the same rule with an iframe.+ * real key delivery to another window, native light dismiss, the browser's+ * own close watcher, and layout in another window. The Vitest cases in+ * `Popover/Popover.test.tsx` model the same rule with an iframe.** SYNC: Fixture lives in* /apps/storybook/stories/PopoverSecondDocumentA11y.stories.tsx.@@ -54,6 +55,8 @@ type Where = 'page' | 'iframe' | 'Picture-in-Picture window';interface Surface {frame: Frame;keyboard: Keyboard;+ /** Give the document's own window this height, in CSS pixels. */+ resize: (height: number) => Promise<void>;}/** Load the story and return the document the test drives. */@@ -67,20 +70,39 @@ async function mountStory(page: Page, where: Where): Promise<Surface> {await popOut.waitFor();if (where === 'page') {- return {frame: page.mainFrame(), keyboard: page.keyboard};+ const viewport = page.viewportSize();+ if (viewport == null) {+ throw new Error('the page has no viewport size');+ }+ return {+ frame: page.mainFrame(),+ keyboard: page.keyboard,+ resize: async height => {+ await page.setViewportSize({width: viewport.width, height});+ },+ };}if (where === 'iframe') {const element = await page.locator('iframe[title="Second document"]').elementHandle();const frame = await element?.contentFrame();- if (frame == null) {+ if (element == null || frame == null) {throw new Error('the story renders no iframe');}await frame.getByRole('button', {name: 'Settings', exact: true}).waitFor();// Key presses go to whichever frame holds focus; the clicks below put it// in this one.- return {frame, keyboard: page.keyboard};+ return {+ frame,+ keyboard: page.keyboard,+ // The frame's window is as tall as the iframe element.+ resize: async height => {+ await element.evaluate((iframe, to) => {+ (iframe as HTMLElement).style.height = `${to}px`;+ }, height);+ },+ };}// Opening the window needs a user gesture; the click is one.const [pictureInPicture] = await Promise.all([@@ -90,9 +112,19 @@ async function mountStory(page: Page, where: Where): Promise<Surface> {await pictureInPicture.getByRole('button', {name: 'Settings', exact: true}).waitFor();+ const pictureInPictureViewport = pictureInPicture.viewportSize();+ if (pictureInPictureViewport == null) {+ throw new Error('the Picture-in-Picture window has no viewport size');+ }return {frame: pictureInPicture.mainFrame(),keyboard: pictureInPicture.keyboard,+ resize: async height => {+ await pictureInPicture.setViewportSize({+ width: pictureInPictureViewport.width,+ height,+ });+ },};}@@ -181,6 +213,36 @@ for (const where of [await expect(trigger).toBeFocused();});+ test('scrolls once its own window is too short for it, and stops once it fits', async ({+ page,+ }) => {+ const {frame, resize} = await mountStory(page, where);+ await resize(700);+ await open(frame, 'Long list');+ const surface = frame.getByRole('dialog', {name: 'Long list'});+ await expect(surface).toHaveCSS('overflow-y', 'visible');++ await resize(240);+ await expect(surface).toHaveCSS('overflow-y', 'auto');+ await resize(700);+ await expect(surface).toHaveCSS('overflow-y', 'visible');+ });++ test('scrolls once its content grows past its window', async ({page}) => {+ const {frame, resize} = await mountStory(page, where);+ await resize(700);+ await open(frame, 'Long list');+ const surface = frame.getByRole('dialog', {name: 'Long list'});+ await expect(surface).toHaveCSS('overflow-y', 'visible');++ // An inline style is an attribute change the popover's mutation+ // observer ignores, so only its ResizeObserver can see the growth.+ await surface.evaluate(element => {+ (element.firstElementChild as HTMLElement).style.minHeight = '2000px';+ });+ await expect(surface).toHaveCSS('overflow-y', 'auto');+ });+if (where !== 'page') {test('an Escape press affects only the document it was made in', async ({page,