Skip to content

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

TypeScript

feat(core): one touch presentation resolver (#8062)

Christopher Chedeaucd3787bac67e
diff --git a/.changeset/touch-presentation.md b/.changeset/touch-presentation.md
new file mode 100644
index 0000000000..ad0ae3ff44
--- /dev/null
+++ b/.changeset/touch-presentation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] `presentation="adaptive"` on DropdownMenu, ContextMenu, MoreMenu, Selector and MultiSelector, and a DropdownMenu's or ContextMenu's default sub-menu drill-in, now use the theme's compact definition with a coarse primary pointer: a viewport narrower than the theme's `md` point (768px by default) or shorter than 500px. This is a behavior change. The old default was a bottom sheet at 768px wide and below on a coarse pointer. Now a coarse-pointer screen exactly 768px wide keeps the anchored popover, and a phone in landscape (wider than 768px but shorter than 500px) gets the bottom sheet and the drilled-in sub-menu. A theme that moves `md` moves the edge with it. To pin a component's presentation regardless of the rule, pass `presentation="popover"` or `presentation="bottom-sheet"`; to keep a sub-menu's flyout, pass `presentation="flyout"` on `DropdownMenuSubMenu`. Mouse and keyboard users on desktop see no change, because every case requires a coarse pointer.
+
+@vjeux
diff --git a/apps/storybook/stories/ContextMenu.stories.tsx b/apps/storybook/stories/ContextMenu.stories.tsx
index 9ee6b0bbc5..5c144b8bf4 100644
--- a/apps/storybook/stories/ContextMenu.stories.tsx
+++ b/apps/storybook/stories/ContextMenu.stories.tsx
@@ -494,7 +494,7 @@ export const AdaptivePresentation: Story = {
docs: {
description: {
story:
- 'Uses the built-in adaptive policy: BottomSheet at 768px and below with a coarse primary pointer, cursor-positioned popover otherwise. Important actions still need a visible MoreMenu or equivalent entry point.',
+ 'Uses the built-in adaptive policy: BottomSheet on a compact touch screen (a coarse primary pointer, and a viewport narrower than the theme `md` breakpoint (768px by default) or shorter than 500px), cursor-positioned popover otherwise. Important actions still need a visible MoreMenu or equivalent entry point.',
},
},
},
diff --git a/apps/storybook/stories/MoreMenu.stories.tsx b/apps/storybook/stories/MoreMenu.stories.tsx
index ad736177ae..a922c4b2e7 100644
--- a/apps/storybook/stories/MoreMenu.stories.tsx
+++ b/apps/storybook/stories/MoreMenu.stories.tsx
@@ -316,7 +316,7 @@ export const AdaptivePresentation: Story = {
docs: {
description: {
story:
- 'Uses the built-in adaptive policy: BottomSheet at 768px and below with a coarse primary pointer, anchored popover otherwise. Use device emulation to exercise the touch branch.',
+ 'Uses the built-in adaptive policy: BottomSheet on a compact touch screen (a coarse primary pointer, and a viewport narrower than the theme `md` breakpoint (768px by default) or shorter than 500px), anchored popover otherwise. Use device emulation to exercise the touch branch.',
},
},
},
diff --git a/packages/core/src/ContextMenu/ContextMenu.doc.mjs b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
index 644acf3389..f8ee2c5659 100644
--- a/packages/core/src/ContextMenu/ContextMenu.doc.mjs
+++ b/packages/core/src/ContextMenu/ContextMenu.doc.mjs
@@ -132,7 +132,7 @@ export const docs = {
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'adaptive'",
description:
- 'Presentation policy. `popover` opens at the pointer position, `bottom-sheet` always uses an action sheet, and `adaptive` uses the BottomSheet at 768px and below when the primary pointer is coarse.',
+ 'Presentation policy. `popover` opens at the pointer position, `bottom-sheet` always uses an action sheet, and `adaptive` uses the BottomSheet on a compact touch screen: a coarse primary pointer, and a viewport narrower than the theme `md` breakpoint (768px by default) or shorter than 500px.',
default: "'popover'",
},
{
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index 2015dc90c3..5cf78ae48a 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -28,6 +28,7 @@ import {DropdownMenuSubMenu} from '../DropdownMenu/DropdownMenuSubMenu';
import {Divider} from '../Divider';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {warmMenuBottomSheet} from '../DropdownMenu/__tests__/warmMenuBottomSheet';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
// The touch sheet is loaded lazily; resolve its modules once up front, so
// ContextMenu's own lazy sheet renders within the cases' waitFor.
@@ -309,7 +310,7 @@ describe('ContextMenu', () => {
vi.stubGlobal(
'matchMedia',
vi.fn().mockImplementation((query: string) => ({
- matches: query === '(max-width: 768px) and (pointer: coarse)',
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
media: query,
onchange: null,
addEventListener: vi.fn(),
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 324eda6207..60c5d471b4 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -34,6 +34,7 @@ import {rtlStyles} from '../utils';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {spacingVars} from '../theme/tokens.stylex';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
// Mock showPopover and hidePopover methods since they're not implemented in jsdom
beforeEach(() => {
@@ -341,7 +342,7 @@ describe('DropdownMenu', () => {
vi.stubGlobal(
'matchMedia',
vi.fn().mockImplementation((query: string) => ({
- matches: query === '(max-width: 768px) and (pointer: coarse)',
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
media: query,
onchange: null,
addEventListener: vi.fn(),
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
index 7e61b16df2..271fad83ff 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -26,6 +26,7 @@ import {warmMenuBottomSheet} from './__tests__/warmMenuBottomSheet';
import {IconButton} from '../IconButton';
import {RadioList, RadioListItem} from '../RadioList';
import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
+import {Theme, defineTheme} from '../theme';
import {rtlStyles} from '../utils';
beforeEach(() => {
@@ -1455,6 +1456,62 @@ describe('DropdownMenuSubMenu drill-in on a phone', () => {
await waitFor(() => shownRow('Back to Actions'));
});
+ it("follows the theme's md point: a 900 px touch screen drills in under md 1000, and keeps the flyout under the default (spec:AST-012 FR9)", async () => {
+ // A query-aware stand-in for a 900 × 1024 coarse-pointer screen: `,` is
+ // or, `and` is and.
+ const screenSize = {width: 900, height: 1024};
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: query.split(', ').some(alternative =>
+ alternative.split(' and ').every(part => {
+ if (part === '(pointer: coarse)') {
+ return true;
+ }
+ const range = /^\((width|height) < (\d+)px\)$/.exec(part);
+ return (
+ range != null &&
+ screenSize[range[1] as 'width' | 'height'] < Number(range[2])
+ );
+ }),
+ ),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ const wideMd = defineTheme({
+ name: 'wide-md-drill-in',
+ adaptations: {widthBreakpoints: {md: 1000, lg: 1100}},
+ });
+ const user = userEvent.setup();
+ const menu = (
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuSubMenu label="Move to">
+ <DropdownMenuItem label="Folder A" onClick={() => {}} />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+ );
+ // The default md point (768): not compact, so the sub-menu flies out.
+ const {unmount} = render(menu);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ fireEvent.click(await waitFor(() => shownRow('Move to')), {detail: 1});
+ const flyout = await waitFor(() => shownMenu('Move to'));
+ expect(flyout.closest('[popover]')).not.toBe(
+ shownMenu('Actions').closest('[popover]'),
+ );
+ unmount();
+ // A theme whose md is 1000: the same screen is compact, and it drills in.
+ render(<Theme theme={wideMd}>{menu}</Theme>);
+ await user.click(screen.getByRole('button', {name: /Actions/}));
+ fireEvent.click(await waitFor(() => shownRow('Move to')), {detail: 1});
+ await waitFor(() => shownRow('Back to Actions'));
+ });
+
it('closing the menu resets the drilled view', async () => {
stubCompactTouch(true);
const user = userEvent.setup();
diff --git a/packages/core/src/DropdownMenu/useMenuDrillIn.tsx b/packages/core/src/DropdownMenu/useMenuDrillIn.tsx
index ee8ef97b27..59868eb3c1 100644
--- a/packages/core/src/DropdownMenu/useMenuDrillIn.tsx
+++ b/packages/core/src/DropdownMenu/useMenuDrillIn.tsx
@@ -23,20 +23,21 @@
import {useCallback, useMemo, useState, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {DropdownMenuDrillIn} from './DropdownMenuContext';
-import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
+import {useCompactDefinition} from '../utils/touchPresentation';
/**
- * The same query the root presentation uses to decide the bottom sheet, so
+ * The same compact-touch condition the root presentation uses to decide the
+ * bottom sheet (the active theme's, spec:AST-012 FR9), so
* one component carries one meaning of "adaptive". A bare `(pointer: coarse)`
* would disagree with it on a large touch tablet: the menu would stay an
* anchored popover while its sub-menus replaced rows in place, a combination
* nobody designed.
*/
-function matchesCompactTouch(): boolean {
+function matchesCompactTouch(query: string): boolean {
return (
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function' &&
- window.matchMedia(COMPACT_TOUCH_PRESENTATION_QUERY).matches
+ window.matchMedia(query).matches
);
}
@@ -70,6 +71,7 @@ export interface UseMenuDrillInReturn {
* opens and the stack empties when it closes.
*/
export function useMenuDrillIn(isOpen: boolean): UseMenuDrillInReturn {
+ const compactTouchQuery = useCompactDefinition().coarsePointerQuery;
const [isCompactTouch, setIsCompactTouch] = useState(false);
const [viewStack, setViewStack] = useState<ReadonlyArray<string>>([]);
const [host, setHost] = useState<HTMLElement | null>(null);
@@ -81,7 +83,7 @@ export function useMenuDrillIn(isOpen: boolean): UseMenuDrillInReturn {
if (wasOpen !== isOpen) {
setWasOpen(isOpen);
if (isOpen) {
- setIsCompactTouch(matchesCompactTouch());
+ setIsCompactTouch(matchesCompactTouch(compactTouchQuery));
} else if (viewStack.length > 0) {
setViewStack([]);
}
diff --git a/packages/core/src/MoreMenu/MoreMenu.doc.mjs b/packages/core/src/MoreMenu/MoreMenu.doc.mjs
index b832728442..514bc166cb 100644
--- a/packages/core/src/MoreMenu/MoreMenu.doc.mjs
+++ b/packages/core/src/MoreMenu/MoreMenu.doc.mjs
@@ -104,7 +104,7 @@ export const docs = {
{
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'adaptive'",
- description: 'Presentation policy forwarded to DropdownMenu. `adaptive` keeps the anchored popover on pointer-based layouts and uses a BottomSheet at 768px and below when the primary pointer is coarse.',
+ description: 'Presentation policy forwarded to DropdownMenu. `adaptive` keeps the anchored popover on pointer-based layouts and uses a BottomSheet on a compact touch screen: a coarse primary pointer, and a viewport narrower than the theme `md` breakpoint (768px by default) or shorter than 500px.',
default: "'popover'",
},
{
@@ -204,7 +204,7 @@ export const docsZh = {
{
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'adaptive'",
- description: '菜单呈现策略。`adaptive` 在指针布局中使用锚定浮层,在主指针为粗略指针且宽度不超过 768px 时使用 BottomSheet。',
+ description: '菜单呈现策略。`adaptive` 在指针布局中使用锚定浮层,在主指针为粗略指针且视口宽度小于主题的 `md` 断点(默认 768px)或高度小于 500px 时使用 BottomSheet。',
default: "'popover'",
},
{
diff --git a/packages/core/src/MultiSelector/MultiSelector.test.tsx b/packages/core/src/MultiSelector/MultiSelector.test.tsx
index c2ea5dc873..fb6cfc0362 100644
--- a/packages/core/src/MultiSelector/MultiSelector.test.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.test.tsx
@@ -36,6 +36,7 @@ import {selectorPresentationStyles} from '../Selector/selectorPresentation.style
import {groupStyles} from '../InputGroup/groupStyles';
import {InputGroup, InputGroupText} from '../InputGroup';
import {colorVars, focusVars} from '../theme/tokens.stylex';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
/**
* Enters a search query as one change. Typing it key by key can land several
@@ -160,7 +161,7 @@ describe('MultiSelector', () => {
vi.stubGlobal(
'matchMedia',
vi.fn().mockImplementation((query: string) => ({
- matches: query === '(max-width: 768px) and (pointer: coarse)',
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
media: query,
onchange: null,
addEventListener: vi.fn(),
@@ -2197,7 +2198,7 @@ describe('MultiSelector', () => {
vi.mocked(matchMedia).mockImplementation(
(query: string) =>
({
- matches: query === '(max-width: 768px) and (pointer: coarse)',
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
media: query,
onchange: null,
addEventListener: vi.fn(),
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index dc3b6faa6c..274a9bba70 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -39,6 +39,7 @@ import {generateThemeCSS} from '../theme/generateThemeRules';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {selectorPresentationStyles} from './selectorPresentation.stylex';
import {groupStyles} from '../InputGroup/groupStyles';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
/**
* Enters a search query as one change. Typing it key by key can land several
@@ -392,7 +393,7 @@ describe('Selector', () => {
vi.stubGlobal(
'matchMedia',
vi.fn().mockImplementation((query: string) => ({
- matches: query === '(max-width: 768px) and (pointer: coarse)',
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
media: query,
onchange: null,
addEventListener: vi.fn(),
@@ -2831,7 +2832,7 @@ describe('Selector', () => {
vi.mocked(matchMedia).mockImplementation(
(query: string) =>
({
- matches: query === '(max-width: 768px) and (pointer: coarse)',
+ matches: query === COMPACT_TOUCH_PRESENTATION_QUERY,
media: query,
onchange: null,
addEventListener: vi.fn(),
diff --git a/packages/core/src/hooks/useAdaptivePresentation.ts b/packages/core/src/hooks/useAdaptivePresentation.ts
index 199be1186d..df5dcbd507 100644
--- a/packages/core/src/hooks/useAdaptivePresentation.ts
+++ b/packages/core/src/hooks/useAdaptivePresentation.ts
@@ -4,11 +4,16 @@
/**
* @file useAdaptivePresentation.ts
- * @input Uses the shared SSR-safe media-query hook
+ * @input Uses the shared SSR-safe media-query hook and the touch
+ * presentation's compact-touch query
* @output Resolves popover/bottom-sheet presentation policy
* @position Internal overlay policy shared across component families
*/
+import {
+ COMPACT_TOUCH_QUERY,
+ useCompactDefinition,
+} from '../utils/touchPresentation';
import {useMediaQuery} from './useMediaQuery';
export type AdaptivePresentation = 'popover' | 'bottom-sheet' | 'adaptive';
@@ -17,16 +22,18 @@ export type ResolvedAdaptivePresentation = Exclude<
'adaptive'
>;
-// Width keeps desktop-class tablets and large touch displays anchored by
-// default. Pointer capability, rather than `hover: none`, avoids excluding
-// touch browsers that also report hover capability.
-export const COMPACT_TOUCH_PRESENTATION_QUERY =
- '(max-width: 768px) and (pointer: coarse)';
+// A sheet needs both a compact viewport and a coarse primary pointer: tablets
+// and large touch displays stay anchored, phones in either orientation get
+// the sheet. Compact is the active theme's definition (spec:AST-012 FR9);
+// this constant is its value at the default width points.
+export const COMPACT_TOUCH_PRESENTATION_QUERY = COMPACT_TOUCH_QUERY;
export function useAdaptivePresentation(
presentation: AdaptivePresentation,
): ResolvedAdaptivePresentation {
- const isCompactTouch = useMediaQuery(COMPACT_TOUCH_PRESENTATION_QUERY);
+ const isCompactTouch = useMediaQuery(
+ useCompactDefinition().coarsePointerQuery,
+ );
return presentation === 'adaptive'
? isCompactTouch
? 'bottom-sheet'
diff --git a/packages/core/src/utils/touchPresentation.test.ts b/packages/core/src/utils/touchPresentation.test.ts
new file mode 100644
index 0000000000..9d62a1379b
--- /dev/null
+++ b/packages/core/src/utils/touchPresentation.test.ts
@@ -0,0 +1,323 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file touchPresentation.test.ts
+ * @input Uses vitest, React Testing Library, react-dom/server and a
+ * query-aware matchMedia stub
+ * @output The touch presentation's answers: touch from the primary pointer,
+ * compact from the width, both for presentations, the same answer on every
+ * engine; the server default and hints; live updates; the one-moment read;
+ * core's compact-touch media keys and iOS style-gate keys spelled and nested
+ * as the shared queries; the adaptive presentation reading them
+ * @position Unit tests of packages/core/src/utils/touchPresentation.ts
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {act, renderHook} from '@testing-library/react';
+import {createElement, type ComponentProps, type ReactNode} from 'react';
+import {renderToString} from 'react-dom/server';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {
+ COMPACT_TOUCH_PRESENTATION_QUERY,
+ useAdaptivePresentation,
+} from '../hooks/useAdaptivePresentation';
+import {DEFAULT_COMPACT_DEFINITION} from '../theme/themeAdaptations';
+import {Theme, defineTheme} from '../theme';
+import {
+ COMPACT_QUERY,
+ COMPACT_TOUCH_QUERY,
+ IOS_SUPPORTS_QUERY,
+ IOS_TOUCH_STYLE_KEYS,
+ TOUCH_QUERY,
+ readTouchPresentation,
+ useTouchPresentation,
+} from './touchPresentation';
+
+/**
+ * A device: what its primary pointer is, how big its viewport is, and
+ * whether its engine is iOS WebKit (implements -webkit-touch-callout).
+ */
+const device = {coarse: false, width: 1280, height: 800, iosWebKit: false};
+const listeners = new Set<() => void>();
+
+/** Answers a media query list: `,` is or, `and` is and. */
+function answer(query: string): boolean {
+ return query.split(', ').some(alternative =>
+ alternative.split(' and ').every(part => {
+ if (part === '(pointer: coarse)') {
+ return device.coarse;
+ }
+ const range = /^\((width|height) < (\d+)px\)$/.exec(part);
+ if (range != null) {
+ return device[range[1] as 'width' | 'height'] < Number(range[2]);
+ }
+ throw new Error(`unexpected query ${query}`);
+ }),
+ );
+}
+
+function setDevice(next: Partial<typeof device>): void {
+ Object.assign(device, next);
+ for (const listener of [...listeners]) {
+ listener();
+ }
+}
+
+beforeEach(() => {
+ setDevice({coarse: false, width: 1280, height: 800, iosWebKit: false});
+ vi.stubGlobal('CSS', {
+ supports: (condition: string) =>
+ condition === IOS_SUPPORTS_QUERY && device.iosWebKit,
+ });
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn((query: string) => ({
+ get matches() {
+ return answer(query);
+ },
+ media: query,
+ addEventListener: (_type: string, listener: () => void) =>
+ listeners.add(listener),
+ removeEventListener: (_type: string, listener: () => void) =>
+ listeners.delete(listener),
+ })),
+ );
+});
+
+afterEach(() => {
+ listeners.clear();
+ vi.unstubAllGlobals();
+});
+
+describe('touch presentation', () => {
+ it('keys touch on the primary pointer and compact on the width', () => {
+ const {result} = renderHook(() => useTouchPresentation());
+ expect(result.current).toEqual({
+ isTouch: false,
+ isCompact: false,
+ });
+ // A tablet: a finger at any width.
+ act(() => setDevice({coarse: true, width: 1024, height: 1366}));
+ expect(result.current).toEqual({
+ isTouch: true,
+ isCompact: false,
+ });
+ // A narrowed desktop window: compact, still a mouse.
+ act(() => setDevice({coarse: false, width: 600, height: 900}));
+ expect(result.current).toEqual({
+ isTouch: false,
+ isCompact: true,
+ });
+ // A phone: both.
+ act(() => setDevice({coarse: true, width: 390, height: 844}));
+ expect(result.current).toEqual({
+ isTouch: true,
+ isCompact: true,
+ });
+ });
+
+ it('answers the same on every engine: iOS WebKit and Android alike', () => {
+ const {result} = renderHook(() => useTouchPresentation());
+ // An Android phone: a finger, no -webkit-touch-callout.
+ act(() => setDevice({coarse: true, width: 412, height: 915}));
+ const android = result.current;
+ // The same phone size in iOS WebKit gets the same answer.
+ act(() => setDevice({iosWebKit: true}));
+ expect(result.current).toEqual(android);
+ expect(result.current).toEqual({isTouch: true, isCompact: true});
+ });
+
+ it('keeps one answer object while nothing changes', () => {
+ const {result, rerender} = renderHook(() => useTouchPresentation());
+ const first = result.current;
+ rerender();
+ expect(result.current).toBe(first);
+ });
+
+ it('answers the server default, or the server hint, before hydration', () => {
+ const Probe = (props: {hint?: boolean}) => {
+ const presentation = useTouchPresentation(
+ props.hint === true ? {isTouch: true, isCompact: true} : {},
+ );
+ return createElement(
+ 'span',
+ null,
+ `${presentation.isTouch}/${presentation.isCompact}`,
+ );
+ };
+ setDevice({iosWebKit: true, coarse: true, width: 390, height: 844});
+ expect(renderToString(createElement(Probe))).toContain('false/false');
+ expect(renderToString(createElement(Probe, {hint: true}))).toContain(
+ 'true/true',
+ );
+ });
+
+ it('is the theme compact definition: width below md or height below 500 (spec:AST-012 FR9)', () => {
+ const {result} = renderHook(() => useTouchPresentation());
+ // At the md point and taller than 500: not compact.
+ act(() => setDevice({coarse: true, width: 768, height: 1024}));
+ expect(result.current.isCompact).toBe(false);
+ // One pixel narrower: compact.
+ act(() => setDevice({coarse: true, width: 767, height: 1024}));
+ expect(result.current.isCompact).toBe(true);
+ // A phone in landscape: wide, but shorter than 500.
+ act(() => setDevice({coarse: true, width: 852, height: 393}));
+ expect(result.current.isCompact).toBe(true);
+ // A wide, short window at exactly 500 tall: not compact.
+ act(() => setDevice({coarse: true, width: 1024, height: 500}));
+ expect(result.current.isCompact).toBe(false);
+ });
+
+ it('reads the conditions at one moment, and without a window', () => {
+ setDevice({coarse: true, width: 390, height: 844});
+ expect(readTouchPresentation(window, DEFAULT_COMPACT_DEFINITION)).toEqual({
+ isTouch: true,
+ isCompact: true,
+ });
+ expect(readTouchPresentation(null, DEFAULT_COMPACT_DEFINITION)).toEqual({
+ isTouch: false,
+ isCompact: false,
+ });
+ });
+
+ it('keeps every iOS gate in core spelled and nested as the resolver', () => {
+ // The gate is the media query outside and the supports query inside; a
+ // single supports query that names the pointer never matches anywhere.
+ expect(IOS_TOUCH_STYLE_KEYS).toEqual([
+ '@media (pointer: coarse)',
+ '@supports (-webkit-touch-callout: none)',
+ ]);
+ const root = path.resolve(__dirname, '..');
+ const problems: string[] = [];
+ let gates = 0;
+ const walk = (dir: string): void => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name !== '__tests__' && entry.name !== 'node_modules') {
+ walk(full);
+ }
+ } else if (
+ /\.(ts|tsx)$/.test(entry.name) &&
+ !/\.test\.|\.spec\./.test(entry.name) &&
+ entry.name !== 'touchPresentation.ts'
+ ) {
+ const lines = fs.readFileSync(full, 'utf8').split('\n');
+ lines.forEach((line, index) => {
+ for (const match of line.matchAll(/'@supports ([^']*)'/g)) {
+ const where = `${path.relative(root, full)}:${index + 1}`;
+ if (match[1].includes('pointer')) {
+ problems.push(`${where}: @supports ${match[1]} never matches`);
+ }
+ if (!match[1].includes('touch-callout')) {
+ continue;
+ }
+ gates++;
+ if (`@supports ${match[1]}` !== IOS_TOUCH_STYLE_KEYS[1]) {
+ problems.push(`${where}: @supports ${match[1]}`);
+ }
+ const outer = lines
+ .slice(0, index)
+ .reverse()
+ .find(previous => /'@(media|supports) /.test(previous));
+ if (
+ outer == null ||
+ !outer.includes(`'${IOS_TOUCH_STYLE_KEYS[0]}'`)
+ ) {
+ problems.push(
+ `${where}: not inside ${IOS_TOUCH_STYLE_KEYS[0]}`,
+ );
+ }
+ }
+ });
+ }
+ }
+ };
+ walk(root);
+ expect(problems).toEqual([]);
+ // Core already gates its 16px input floor this way.
+ expect(gates).toBeGreaterThan(0);
+ });
+
+ it('keeps every compact-touch media key in core spelled as the resolver', () => {
+ // A style key that joins a coarse pointer with a width or height is a
+ // presentation decision: it must be the shared query, not its own.
+ const root = path.resolve(__dirname, '..');
+ const found: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name !== '__tests__' && entry.name !== 'node_modules') {
+ walk(full);
+ }
+ } else if (
+ /\.(ts|tsx)$/.test(entry.name) &&
+ !/\.test\.|\.spec\./.test(entry.name)
+ ) {
+ const source = fs.readFileSync(full, 'utf8');
+ for (const match of source.matchAll(/'@media ([^']*)'/g)) {
+ const query = match[1];
+ if (
+ query.includes('pointer: coarse') &&
+ /\b(width|height)\b/.test(query)
+ ) {
+ found.push(`${path.relative(root, full)}: ${query}`);
+ }
+ }
+ }
+ }
+ };
+ walk(root);
+ for (const entry of found) {
+ expect(entry.slice(entry.indexOf(': ') + 2), entry).toBe(
+ COMPACT_TOUCH_QUERY,
+ );
+ }
+ expect(TOUCH_QUERY).toBe('(pointer: coarse)');
+ expect(COMPACT_QUERY).toBe(DEFAULT_COMPACT_DEFINITION.query);
+ expect(COMPACT_TOUCH_QUERY).toBe(
+ DEFAULT_COMPACT_DEFINITION.coarsePointerQuery,
+ );
+ });
+
+ it("follows the active theme's md point (spec:AST-012 FR9)", () => {
+ const wideMd = defineTheme({
+ name: 'wide-md-touch',
+ adaptations: {widthBreakpoints: {md: 1000, lg: 1100}},
+ });
+ const wrapper = ({children}: {children: ReactNode}) =>
+ createElement(
+ Theme,
+ {theme: wideMd} as ComponentProps<typeof Theme>,
+ children,
+ );
+ setDevice({coarse: true, width: 900, height: 1024});
+ // Under the default md point (768) this screen is not compact.
+ const plain = renderHook(() => useAdaptivePresentation('adaptive'));
+ expect(plain.result.current).toBe('popover');
+ plain.unmount();
+ // Under a theme whose md is 1000, the same screen is compact.
+ const themed = renderHook(() => useAdaptivePresentation('adaptive'), {
+ wrapper,
+ });
+ expect(themed.result.current).toBe('bottom-sheet');
+ const touch = renderHook(() => useTouchPresentation(), {wrapper});
+ expect(touch.result.current.isCompact).toBe(true);
+ });
+
+ it('is the query the adaptive popover-or-sheet presentation reads', () => {
+ expect(COMPACT_TOUCH_PRESENTATION_QUERY).toBe(COMPACT_TOUCH_QUERY);
+ const {result} = renderHook(() => useAdaptivePresentation('adaptive'));
+ expect(result.current).toBe('popover');
+ act(() => setDevice({coarse: true, width: 390, height: 844}));
+ expect(result.current).toBe('bottom-sheet');
+ // A phone in landscape too.
+ act(() => setDevice({coarse: true, width: 852, height: 393}));
+ expect(result.current).toBe('bottom-sheet');
+ // A tablet at the md point keeps the anchored popover.
+ act(() => setDevice({coarse: true, width: 768, height: 1024}));
+ expect(result.current).toBe('popover');
+ });
+});
diff --git a/packages/core/src/utils/touchPresentation.ts b/packages/core/src/utils/touchPresentation.ts
new file mode 100644
index 0000000000..4093bee836
--- /dev/null
+++ b/packages/core/src/utils/touchPresentation.ts
@@ -0,0 +1,153 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file touchPresentation.ts
+ * @input Uses the SSR-safe useMediaQuery hook and window.matchMedia
+ * @output The one definition of when a component presents itself the touch
+ * way: TOUCH_QUERY, COMPACT_QUERY, COMPACT_TOUCH_QUERY, the iOS style gate
+ * (IOS_SUPPORTS_QUERY and its StyleX keys); the hook useTouchPresentation;
+ * readTouchPresentation for a decision taken at one moment
+ * @position Internal shared resolver beside interactionModality.ts
+ *
+ * Two questions, answered once:
+ *
+ * - TOUCH behaviours (the press model, gesture recognizers, UIKit springs and
+ * timings) key on the PRIMARY pointer being coarse: a finger. A touchscreen
+ * laptop reports its trackpad (fine) and keeps pointer behaviours; a tablet
+ * reports coarse and gets touch ones at any width. Not `hover: none` (some
+ * touch browsers report hover) and not `any-pointer` (a laptop's touch
+ * screen is not how it is driven).
+ * - LAYOUT behaviours key on the available size, whatever the pointer:
+ * the theme's one compact definition (`spec:AST-012` FR9), width below the
+ * `md` point or height below 500, the same numbers on every platform. A
+ * phone in landscape is compact by its height; no platform size class is
+ * consulted.
+ * - A presentation that needs both (a bottom sheet in place of a popover, a
+ * drilled-in sub-menu in place of a flyout) asks for both.
+ *
+ * Touch behaviour is one model on every touch device, iOS and Android alike;
+ * nothing here chooses a platform. Touch motion reads the theme's motion
+ * roles, whose defaults are the measured table.
+ *
+ * CSS first: a style that changes with these conditions writes the same
+ * query as a StyleX media key, spelled exactly as here (`@media` followed by
+ * the constant's text), so the right rule paints before hydration. The iOS
+ * gate is two nested keys, the media query outside and the supports query
+ * inside (IOS_TOUCH_STYLE_KEYS):
+ *
+ * '@media (pointer: coarse)': {
+ * '@supports (-webkit-touch-callout: none)': value,
+ * },
+ *
+ * One `@supports (-webkit-touch-callout: none) and (pointer: coarse)` never
+ * matches anywhere (`pointer` is not a property), so it is not written. A
+ * test keeps core's compact-touch keys identical to COMPACT_TOUCH_QUERY and
+ * every touch-callout key spelled and nested as above. The iOS style gate
+ * is only for a style iOS WebKit itself requires (core's 16px input floor);
+ * it never selects a behaviour. The keys are literal because the Astryx
+ * StyleX build does not resolve a key shared across files through
+ * `defineConsts`. The hook is for behaviour. It answers the server default
+ * (not touch, not compact) until hydrated unless the caller passes a server
+ * hint, and follows the pointer and size when they change (a tablet docking
+ * a mouse).
+ *
+ * SYNC: When modified, update touchPresentation.test.ts and every StyleX
+ * media key that spells these queries.
+ */
+
+import {useMemo} from 'react';
+import {useMediaQuery} from '../hooks/useMediaQuery';
+import {
+ DEFAULT_COMPACT_DEFINITION,
+ compactDefinition,
+ type CompactDefinition,
+} from '../theme/themeAdaptations';
+import {useThemeDefinition} from '../theme/useTheme';
+
+/** The primary pointer is coarse: touch behaviours. */
+export const TOUCH_QUERY = '(pointer: coarse)';
+
+/**
+ * The viewport is compact at the default width points: layout behaviours
+ * (`spec:AST-012` FR9). A StyleX media key, which cannot read the theme,
+ * spells this; behaviour reads the active theme's definition
+ * (useCompactDefinition), so a theme that moves `md` moves compact with it.
+ */
+export const COMPACT_QUERY = DEFAULT_COMPACT_DEFINITION.query;
+
+/** Both, at the default width points: a sheet in place of a popover. */
+export const COMPACT_TOUCH_QUERY =
+ DEFAULT_COMPACT_DEFINITION.coarsePointerQuery;
+
+/**
+ * The engine is WebKit on iOS or iPadOS: the only one that implements
+ * `-webkit-touch-callout`. For a style iOS WebKit requires, never a
+ * behaviour.
+ */
+export const IOS_SUPPORTS_QUERY = '(-webkit-touch-callout: none)';
+
+/**
+ * The iOS gate as StyleX keys, nested in this order: the media query
+ * outside, the supports query inside.
+ */
+export const IOS_TOUCH_STYLE_KEYS = [
+ `@media ${TOUCH_QUERY}`,
+ `@supports ${IOS_SUPPORTS_QUERY}`,
+] as const;
+
+export interface TouchPresentation {
+ /** The primary pointer is coarse (a finger). */
+ readonly isTouch: boolean;
+ /** The viewport is compact. */
+ readonly isCompact: boolean;
+}
+
+/**
+ * The active theme's compact definition (`spec:AST-012` FR9): width below the
+ * theme's effective `md` point, or height below 500.
+ */
+export function useCompactDefinition(): CompactDefinition {
+ const points = useThemeDefinition()?.__adaptations?.widthBreakpoints;
+ return useMemo(
+ () =>
+ points == null ? DEFAULT_COMPACT_DEFINITION : compactDefinition(points),
+ [points],
+ );
+}
+
+/**
+ * The touch presentation now. SSR-safe: hooks render the server default and
+ * update after hydration.
+ */
+export function useTouchPresentation(
+ serverDefault: Partial<TouchPresentation> = {},
+): TouchPresentation {
+ const compact = useCompactDefinition();
+ const isTouch = useMediaQuery(TOUCH_QUERY, serverDefault.isTouch ?? false);
+ const isCompact = useMediaQuery(
+ compact.query,
+ serverDefault.isCompact ?? false,
+ );
+ return useMemo(() => ({isTouch, isCompact}), [isTouch, isCompact]);
+}
+
+/**
+ * The touch presentation at this moment, for a decision taken once (a menu
+ * deciding how it presents as it opens). `compact` is the active theme's
+ * definition (`useCompactDefinition()`, read while rendering), required so a
+ * theme that moves `md` is never ignored (spec:AST-012 FR9). Not touch and
+ * not compact where there is no window.
+ */
+export function readTouchPresentation(
+ view: Window | null,
+ compact: CompactDefinition,
+): TouchPresentation {
+ if (view == null || typeof view.matchMedia !== 'function') {
+ return {isTouch: false, isCompact: false};
+ }
+ const isTouch = view.matchMedia(TOUCH_QUERY).matches;
+ const isCompact = view.matchMedia(compact.query).matches;
+ return {isTouch, isCompact};
+}