Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): a presentation resolves with no matchMedia, as in a test DOM (#10275)

Christopher Chedeaue348759a9455
diff --git a/.changeset/presentation-without-matchmedia.md b/.changeset/presentation-without-matchmedia.md
new file mode 100644
index 0000000000..32abeffa20
--- /dev/null
+++ b/.changeset/presentation-without-matchmedia.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `presentation="adaptive"` no longer crashes in environments without `matchMedia` (jsdom tests).
+
+@vjeux
diff --git a/packages/core/src/Popover/Popover.tsx b/packages/core/src/Popover/Popover.tsx
index c30e6df2e8..af4fde1fe8 100644
--- a/packages/core/src/Popover/Popover.tsx
+++ b/packages/core/src/Popover/Popover.tsx
@@ -57,6 +57,7 @@ import {
import {useThemeDefinition} from '../theme/useTheme';
import * as stylex from '@stylexjs/stylex';
import {devWarn} from '../utils/devWarning';
+import {matchesMediaQuery, watchMediaQuery} from '../utils/coarsePointer';
import type {BaseProps} from '../BaseProps';
import {FALLBACK_CLOSE_SELECTOR, usePopoverInternal} from './usePopover';
import {usePopoverSurfaceMotion} from './PopoverTouch';
@@ -113,15 +114,12 @@ function usePresentationSurface(
[points],
);
const subscribe = useCallback(
- (onStoreChange: () => void) => {
- const mql = window.matchMedia(query);
- mql.addEventListener('change', onStoreChange);
- return () => mql.removeEventListener('change', onStoreChange);
- },
+ (onStoreChange: () => void) =>
+ watchMediaQuery(window, query, onStoreChange),
[query],
);
const getSnapshot = useCallback(
- () => window.matchMedia(query).matches,
+ () => matchesMediaQuery(window, query),
[query],
);
const isCompactTouch = useSyncExternalStore(
diff --git a/packages/core/src/hooks/useAdaptivePresentation.ts b/packages/core/src/hooks/useAdaptivePresentation.ts
index 2a21100a4f..5c689b0476 100644
--- a/packages/core/src/hooks/useAdaptivePresentation.ts
+++ b/packages/core/src/hooks/useAdaptivePresentation.ts
@@ -4,8 +4,9 @@
/**
* @file useAdaptivePresentation.ts
- * @input Uses React's external-store subscription over window.matchMedia
- * and the touch presentation's compact-touch query
+ * @input Uses React's external-store subscription over matchesMediaQuery
+ * and watchMediaQuery (utils/coarsePointer.ts) and the touch
+ * presentation's compact-touch query
* @output Resolves popover/bottom-sheet presentation policy
* @position Internal overlay policy shared across component families. A
* component that also switches input modes under a finger resolves its
@@ -14,6 +15,7 @@
*/
import {useCallback, useSyncExternalStore} from 'react';
+import {matchesMediaQuery, watchMediaQuery} from '../utils/coarsePointer';
import {
COMPACT_TOUCH_QUERY,
useCompactDefinition,
@@ -48,18 +50,14 @@ export function useAdaptivePresentation(
const isAdaptive = presentation === 'adaptive';
const query = useCompactDefinition().coarsePointerQuery;
const subscribe = useCallback(
- (onStoreChange: () => void) => {
- if (!isAdaptive) {
- return noSubscription();
- }
- const mql = window.matchMedia(query);
- mql.addEventListener('change', onStoreChange);
- return () => mql.removeEventListener('change', onStoreChange);
- },
+ (onStoreChange: () => void) =>
+ isAdaptive
+ ? watchMediaQuery(window, query, onStoreChange)
+ : noSubscription(),
[isAdaptive, query],
);
const getSnapshot = useCallback(
- () => (isAdaptive ? window.matchMedia(query).matches : false),
+ () => isAdaptive && matchesMediaQuery(window, query),
[isAdaptive, query],
);
const isCompactTouch = useSyncExternalStore(
diff --git a/packages/core/src/utils/coarsePointer.test.ts b/packages/core/src/utils/coarsePointer.test.ts
index a58285ec20..fa33ea258f 100644
--- a/packages/core/src/utils/coarsePointer.test.ts
+++ b/packages/core/src/utils/coarsePointer.test.ts
@@ -3,14 +3,15 @@
/**
* @file coarsePointer.test.ts
* @input coarsePointer.ts and the gestures' pointer test helper
- * @output The gate reads and follows the primary pointer, and watches any
- * media query
+ * @output The gate reads and follows the primary pointer, and reads and
+ * watches any media query, also where the window has no matchMedia
* @position Unit tests of packages/core/src/utils/coarsePointer.ts
*/
import {describe, expect, it} from 'vitest';
import {
isCoarsePointer,
+ matchesMediaQuery,
watchCoarsePointer,
watchMediaQuery,
} from './coarsePointer';
@@ -39,6 +40,22 @@ describe('coarsePointer', () => {
expect(watchCoarsePointer(null, () => {})).toBeTypeOf('function');
});
+ it('reads any media query, and matches nothing where the window has no matchMedia', () => {
+ const view = {
+ matchMedia: (query: string) => ({
+ media: query,
+ matches: query === '(max-width: 600px)',
+ }),
+ } as unknown as Window;
+ expect(matchesMediaQuery(view, '(max-width: 600px)')).toBe(true);
+ expect(matchesMediaQuery(view, '(min-width: 601px)')).toBe(false);
+ const bare = {} as unknown as Window;
+ expect(matchesMediaQuery(bare, '(max-width: 600px)')).toBe(false);
+ expect(watchMediaQuery(bare, '(max-width: 600px)', () => {})).toBeTypeOf(
+ 'function',
+ );
+ });
+
it('watches any media query, through the older pair where there is no addEventListener', () => {
const handlers = new Set<() => void>();
let matches = false;
diff --git a/packages/core/src/utils/coarsePointer.ts b/packages/core/src/utils/coarsePointer.ts
index 14b727cba5..0183d30305 100644
--- a/packages/core/src/utils/coarsePointer.ts
+++ b/packages/core/src/utils/coarsePointer.ts
@@ -3,12 +3,13 @@
/**
* @file coarsePointer.ts
* @input A window
- * @output Exports isCoarsePointer, watchCoarsePointer and watchMediaQuery:
- * whether the primary pointer is coarse (TOUCH_QUERY), and when it or any
- * media query changes
+ * @output Exports isCoarsePointer, matchesMediaQuery, watchCoarsePointer and
+ * watchMediaQuery: whether the primary pointer is coarse (TOUCH_QUERY) or
+ * any media query matches, and when either changes
* @position The coarse-pointer gate of packages/core/src/gestures and of
* the press controller (pressFeedback.ts): touch-only work registers only
- * while it holds. useMediaQuery watches through watchMediaQuery
+ * while it holds. useMediaQuery and the presentation resolvers read and
+ * watch through matchesMediaQuery and watchMediaQuery
*
* Under a coarse primary pointer, a phone's touch work stays registered: the
* gesture host's page listeners, the page hold and the finger scroll. Under a
@@ -23,9 +24,19 @@ import {TOUCH_QUERY} from './touchQueries';
/** Whether the primary pointer of `view` is coarse now. */
export function isCoarsePointer(view: Window | null | undefined): boolean {
+ return matchesMediaQuery(view, TOUCH_QUERY);
+}
+
+/**
+ * Whether `query` matches in `view` now. False where `view` has no
+ * `matchMedia`, as in a test DOM.
+ */
+export function matchesMediaQuery(
+ view: Window | null | undefined,
+ query: string,
+): boolean {
return (
- typeof view?.matchMedia === 'function' &&
- view.matchMedia(TOUCH_QUERY).matches
+ typeof view?.matchMedia === 'function' && view.matchMedia(query).matches
);
}
diff --git a/packages/core/src/utils/presentation.test.ts b/packages/core/src/utils/presentation.test.ts
index fd2a7ffc2b..1b86905d63 100644
--- a/packages/core/src/utils/presentation.test.ts
+++ b/packages/core/src/utils/presentation.test.ts
@@ -366,6 +366,25 @@ describe('presentation: a caller choice wins over touch defaults', () => {
});
});
+ it('answers the default presentation where the window has no matchMedia, as in a test DOM', () => {
+ vi.stubGlobal('matchMedia', undefined);
+ expect(resolve(undefined, 'touch')).toEqual({
+ surface: 'popover',
+ touchModes: false,
+ });
+ expect(resolve('adaptive')).toEqual({
+ surface: 'popover',
+ touchModes: false,
+ });
+ expect(resolve('bottom-sheet')).toEqual({
+ surface: 'bottom-sheet',
+ touchModes: false,
+ });
+ expect(
+ renderHook(() => useAdaptivePresentation('adaptive')).result.current,
+ ).toBe('popover');
+ });
+
it('reads the compact definition it is given, so a theme that moves md moves the sheet (spec:AST-012 FR9)', () => {
setDevice({...IPHONE, width: 900, height: 1024});
expect(
diff --git a/packages/core/src/utils/presentation.ts b/packages/core/src/utils/presentation.ts
index 5ec319726c..1fc7db2499 100644
--- a/packages/core/src/utils/presentation.ts
+++ b/packages/core/src/utils/presentation.ts
@@ -37,6 +37,7 @@
import {useCallback, useMemo, useSyncExternalStore} from 'react';
import type {AdaptivePresentation} from '../hooks/useAdaptivePresentation';
+import {matchesMediaQuery, watchMediaQuery} from './coarsePointer';
import type {CompactDefinition} from '../theme/themeAdaptations';
import {
readTouchPresentation,
@@ -101,22 +102,19 @@ const matchesNothing = () => false;
/**
* A media query's match, subscribed only while `query` is given. False on
- * the server and while hydrating.
+ * the server, while hydrating, and where the window has no `matchMedia`, as
+ * in a test DOM.
*/
function useMatchWhileRead(query: string | null): boolean {
const subscribe = useCallback(
- (onStoreChange: () => void) => {
- if (query == null) {
- return noSubscription();
- }
- const mql = window.matchMedia(query);
- mql.addEventListener('change', onStoreChange);
- return () => mql.removeEventListener('change', onStoreChange);
- },
+ (onStoreChange: () => void) =>
+ query == null
+ ? noSubscription()
+ : watchMediaQuery(window, query, onStoreChange),
[query],
);
const getSnapshot = useCallback(
- () => query != null && window.matchMedia(query).matches,
+ () => query != null && matchesMediaQuery(window, query),
[query],
);
return useSyncExternalStore(subscribe, getSnapshot, matchesNothing);
diff --git a/packages/core/src/utils/presentationWithoutMatchMedia.test.tsx b/packages/core/src/utils/presentationWithoutMatchMedia.test.tsx
new file mode 100644
index 0000000000..f520374576
--- /dev/null
+++ b/packages/core/src/utils/presentationWithoutMatchMedia.test.tsx
@@ -0,0 +1,61 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file presentationWithoutMatchMedia.test.tsx
+ * @input vitest, React Testing Library, ContextMenu, DropdownMenu and
+ * Popover, and a window with no matchMedia, as in a plain test DOM
+ * @output Components that resolve a presentation render their default
+ * surface where the window has no matchMedia, and do not throw
+ * @position Unit tests of utils/presentation.ts,
+ * hooks/useAdaptivePresentation.ts and Popover's own resolver
+ */
+
+import {render, screen} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {ContextMenu} from '../ContextMenu/ContextMenu';
+import {DropdownMenu} from '../DropdownMenu/DropdownMenu';
+import {Popover} from '../Popover/Popover';
+
+beforeEach(() => {
+ // The shared test setup gives jsdom a matchMedia. An app's test DOM may
+ // have none.
+ vi.stubGlobal('matchMedia', undefined);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('a window with no matchMedia', () => {
+ it('renders an adaptive ContextMenu around its target', () => {
+ render(
+ <ContextMenu presentation="adaptive" items={[{label: 'Item 1'}]}>
+ <div>Target</div>
+ </ContextMenu>,
+ );
+ expect(screen.getByText('Target')).toBeTruthy();
+ });
+
+ it('renders an adaptive DropdownMenu with its button', () => {
+ render(
+ <DropdownMenu
+ presentation="adaptive"
+ button={{label: 'Actions'}}
+ items={[{label: 'Item 1'}]}
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'Actions'})).toBeTruthy();
+ });
+
+ it('renders an adaptive Popover with its trigger', () => {
+ render(
+ <Popover
+ presentation="adaptive"
+ content={<span>Content</span>}
+ label="Details">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ expect(screen.getByRole('button', {name: 'Open'})).toBeTruthy();
+ });
+});