An open source design system that's fully customizable and agent ready
TypeScript
refactor(core): a theme's reduced-motion mark, internal until 'always' ships (#9761)
Cindy Zhang2c925f7941f7
diff --git a/.changeset/theme-reduced-motion-mark-internal.md b/.changeset/theme-reduced-motion-mark-internal.mdnew file mode 100644index 0000000000..81521195da--- /dev/null+++ b/.changeset/theme-reduced-motion-mark-internal.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: a theme's reduced-motion mark and its readers are in place for `reducedMotion: 'always'`. No theme can set it yet, so nothing changes for anyone.++@vjeux @cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ea8d2eae0f..524713ae4b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2430,7 +2430,7 @@ jobs:id: scopeuses: ./.test-scope/.github/actions/test-scopewith:- paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver)|packages/core/src/privateAttributes/hapticSwitch\.stylex\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/actions/test-scope/)'+ paths: '^(packages/core/src/gestures/|packages/core/src/motion/|packages/core/src/internal/touch|packages/core/src/utils/(press|touch|primaryClick|isApplePlatform|flatTree|inputStream|clickGuard|selectionLock|coarsePointer|sharedResizeObserver)|packages/core/src/privateAttributes/(hapticSwitch|reducedMotion)\.stylex\.ts$|packages/core/src/hooks/(useMenuPress|menuPress|useLongPress|usePressFeedback|isRtlElement|useIsomorphicLayoutEffect|useAttachment|usePager|__tests__/(usePager|pagerBundle))|internal/interaction-harness/|internal/a11y-spec/|playwright\.interaction\.config\.ts$|packages/themes/[^/]+/src/|apps/storybook/|\.github/workflows/ci\.yml$|package\.json$|pnpm-lock\.yaml$|\.github/actions/test-scope/)'outside-pull-request: skiprequires-head-file: playwright.interaction.config.tsdiff --git a/packages/core/src/motion/animatedLayout.ts b/packages/core/src/motion/animatedLayout.tsindex 43c5ba9b34..d606a79289 100644--- a/packages/core/src/motion/animatedLayout.ts+++ b/packages/core/src/motion/animatedLayout.ts@@ -92,6 +92,7 @@ import {isSpring} from './roleValue';import {progressCurve} from './progress';import type {SpringDescription} from './spring';import {registerSpringsTable, SETTLE_SPRING} from './uikit/springs';+import {themeReducesMotion} from '../privateAttributes/reducedMotion.stylex';import {reducedMotionCrossFade} from './uikit/timing';/** The shared motion role (`spec:AST-105` FR4). */@@ -153,7 +154,10 @@ function springProgress(description: SpringDescription): SpringProgress {/** The motion a change in `area` plays now. */function layoutMotion(area: Element): LayoutMotion {- if (matches(area, '(prefers-reduced-motion: reduce)')) {+ if (+ matches(area, '(prefers-reduced-motion: reduce)') ||+ themeReducesMotion(area)+ ) {if (!matches(area, '(pointer: coarse)')) {return {kind: 'instant'};}diff --git a/packages/core/src/motion/animator.test.ts b/packages/core/src/motion/animator.test.tsindex f52f2cbb86..a714bf6414 100644--- a/packages/core/src/motion/animator.test.ts+++ b/packages/core/src/motion/animator.test.ts@@ -4354,3 +4354,38 @@ describe('the presented offset iOS hit testing reads', () => {animator.dispose();});});++describe("a theme's reduced-motion mark", () => {+ // The person's setting is off and the pointer is fine: only the mark can+ // reduce the motion.+ function underMark(marked: boolean) {+ stubMedia(false, false);+ const theme = document.createElement('div');+ if (marked) {+ theme.setAttribute('data-astryx-reduced-motion', '');+ }+ const element = document.createElement('div');+ theme.append(element);+ document.body.append(theme);+ const animator = createMotionAnimator(element, {+ now: () => clock,+ requestFrame,+ });+ return {theme, animator};+ }++ it('counts as the Reduce Motion setting: a move lands at once on a fine pointer', () => {+ const {theme, animator} = underMark(true);+ animator.animate({x: 100}, {spring: springs.navigationPush});+ expect(recorded).toHaveLength(0);+ expect(animator.get('x')).toBe(100);+ theme.remove();+ });++ it('without the mark, the same move springs', () => {+ const {theme, animator} = underMark(false);+ animator.animate({x: 100}, {spring: springs.navigationPush});+ expect(recorded.length).toBeGreaterThan(0);+ theme.remove();+ });+});diff --git a/packages/core/src/motion/animator.ts b/packages/core/src/motion/animator.tsindex 0a3fb468dd..3f4dd1d38b 100644--- a/packages/core/src/motion/animator.ts+++ b/packages/core/src/motion/animator.ts@@ -189,6 +189,7 @@ import {registerReducedMotionCrossFade,} from './uikit/timing';import {planReducedMotion, type ReducedMotionView} from './reducedMotionPlan';+import {themeReducesMotion} from '../privateAttributes/reducedMotion.stylex';/*** A value the animator can drive.@@ -971,8 +972,10 @@ export function createMotionAnimator(};const pseudoElement = options.pseudoElement;// Reduced Motion reads the person's settings and nothing else: no option- // overrides them (design:reduced-motion DR4).- const prefersReducedMotion = defaultPrefersReducedMotion;+ // overrides them (design:reduced-motion DR4). A theme that reduces motion+ // for everyone counts as the setting.+ const prefersReducedMotion = () =>+ defaultPrefersReducedMotion() || themeReducesMotion(target);const isCoarsePointer = defaultIsCoarsePointer;const resting: Record<MotionProperty, number> = {...IDENTITY,diff --git a/packages/core/src/motion/reducedMotion.ts b/packages/core/src/motion/reducedMotion.tsindex 32450a3281..aebb282f83 100644--- a/packages/core/src/motion/reducedMotion.ts+++ b/packages/core/src/motion/reducedMotion.ts@@ -46,6 +46,7 @@import {defaultIsCoarsePointer, defaultPrefersReducedMotion} from './animator';import {resolveMotion} from './resolveMotion';+import {themeReducesMotion} from '../privateAttributes/reducedMotion.stylex';import {reducedMotionCrossFade,registerReducedMotionCrossFade,@@ -83,7 +84,8 @@ export function reducedMotionFade(touchRelease?: boolean;} = {},): ReducedMotionFade | null {- if (!defaultPrefersReducedMotion()) {+ // A theme that reduces motion for everyone counts as the setting.+ if (!defaultPrefersReducedMotion() && !themeReducesMotion(element)) {return null;}const fades = options.touchRelease === true || defaultIsCoarsePointer();diff --git a/packages/core/src/privateAttributes/reducedMotion.stylex.ts b/packages/core/src/privateAttributes/reducedMotion.stylex.tsnew file mode 100644index 0000000000..8bf3421db1--- /dev/null+++ b/packages/core/src/privateAttributes/reducedMotion.stylex.ts@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file privateAttributes/reducedMotion.stylex.ts+ * @input Whether a theme reduces motion for everyone+ * @output reducedMotionMarkProps and setRootReducedMotionMark, which write the+ * mark, and themeReducesMotion, which reads it+ * @position Owner module of the private reduced-motion attribute: the only+ * file that writes its name. Theme marks its root, and the root theme marks+ * `<html>`; the animator, reducedMotionFade and the layout glide read it as+ * the person's Reduce Motion setting. No package entry exports it.+ */++const REDUCED_MOTION = 'data-astryx-reduced-motion';++/** Spread on a theme's root when the theme reduces motion for everyone. */+export function reducedMotionMarkProps(+ isMarked: boolean,+): Readonly<Record<string, string>> {+ return isMarked ? {[REDUCED_MOTION]: ''} : {};+}++/**+ * Marks or unmarks `<html>` for the root theme, so a layer portaled outside+ * the theme's root reads the mark too.+ */+export function setRootReducedMotionMark(+ root: HTMLElement,+ isMarked: boolean,+): void {+ if (isMarked) {+ root.setAttribute(REDUCED_MOTION, '');+ } else {+ root.removeAttribute(REDUCED_MOTION);+ }+}++/**+ * Whether the theme `element` is in reduces motion for everyone: its root,+ * or `<html>` for the root theme, carries the mark.+ */+export function themeReducesMotion(+ element: Element | null | undefined,+): boolean {+ return element?.closest?.(`[${REDUCED_MOTION}]`) != null;+}diff --git a/packages/core/src/privateAttributes/reducedMotion.test.tsx b/packages/core/src/privateAttributes/reducedMotion.test.tsxnew file mode 100644index 0000000000..2ad0507152--- /dev/null+++ b/packages/core/src/privateAttributes/reducedMotion.test.tsx@@ -0,0 +1,81 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/reducedMotion.test.tsx+ * @input vitest (jsdom), reducedMotion.stylex.ts, motion/reducedMotion.ts+ * @output Checks that `themeReducesMotion` reads the reduced-motion mark on an+ * element, an ancestor, or `<html>`, and that `reducedMotionFade` counts the+ * mark as the person's Reduce Motion setting+ * @position Testing; validates the owner module's reader and its use in+ * motion/reducedMotion.ts+ */++import {afterEach, describe, expect, it, vi} from 'vitest';+import {reducedMotionFade} from '../motion/reducedMotion';+import {timing} from '../motion/uikit/timing';+import {themeReducesMotion} from './reducedMotion.stylex';++const MARK = 'data-astryx-reduced-motion';++/** The person's settings: Reduce Motion off. */+function settings(coarse: boolean) {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: query.includes('pointer: coarse') ? coarse : false,+ media: query,+ }));+}++function inTheme(marked: boolean) {+ const theme = document.createElement('div');+ if (marked) {+ theme.setAttribute(MARK, '');+ }+ const element = document.createElement('span');+ theme.append(element);+ document.body.append(theme);+ return element;+}++afterEach(() => {+ document.body.replaceChildren();+ document.documentElement.removeAttribute(MARK);+ vi.unstubAllGlobals();+});++describe('themeReducesMotion', () => {+ it('reads the mark on an ancestor', () => {+ expect(themeReducesMotion(inTheme(true))).toBe(true);+ expect(themeReducesMotion(inTheme(false))).toBe(false);+ });++ it('reads the mark on <html>, for a layer portaled outside the theme', () => {+ const layer = document.createElement('div');+ document.body.append(layer);+ expect(themeReducesMotion(layer)).toBe(false);+ document.documentElement.setAttribute(MARK, '');+ expect(themeReducesMotion(layer)).toBe(true);+ });++ it('is false without an element', () => {+ expect(themeReducesMotion(null)).toBe(false);+ expect(themeReducesMotion(undefined)).toBe(false);+ });+});++describe('reducedMotionFade under the mark', () => {+ it('counts the mark as the setting', () => {+ settings(true);+ expect(reducedMotionFade(inTheme(false))).toBeNull();+ expect(reducedMotionFade(inTheme(true))?.duration).toBe(+ timing.reducedMotionCrossFadeMs,+ );+ });++ it('completes at once on a fine pointer', () => {+ settings(false);+ expect(reducedMotionFade(inTheme(true))).toEqual({+ duration: 0,+ easing: 'linear',+ });+ });+});diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsxindex 8b3e98d0a1..f31718ae8d 100644--- a/packages/core/src/theme/Theme.tsx+++ b/packages/core/src/theme/Theme.tsx@@ -45,6 +45,11 @@ import {registerTheme} from './themeRegistry';import {dataAttr} from '../naming';import {ThemeContext} from './useTheme';import {warnOnce} from '../utils/devWarning';+import {REDUCED_MOTION_PROPERTY, resolveMotionKnobs} from './themeMotion';+import {+ reducedMotionMarkProps,+ setRootReducedMotionMark,+} from '../privateAttributes/reducedMotion.stylex';/*** Theme provider props@@ -76,6 +81,11 @@ const wrapperStyles = stylex.create({system: {colorScheme: 'light dark',},+ // The mark's custom property (REDUCED_MOTION_PROPERTY), which every element+ // under the mark inherits.+ reducedMotion: {+ '--_astryx-reduced-motion': '1',+ },});// =============================================================================@@ -197,11 +207,16 @@ function useThemeStyleInjection(theme: DefinedTheme): void {** - 'light' | 'dark' → sets data-theme="light" | "dark"* - 'system' → removes data-theme (reset.css defaults to color-scheme: light dark)+ *+ * A theme that reduces motion for everyone also marks `<html>` with+ * `data-astryx-reduced-motion` and its custom property, so layers portaled+ * outside the wrapper reduce their motion too.*/function useRootThemeSync(isNested: boolean,mode: ThemeMode,themeName: string,+ reducesMotion: boolean,): void {useIsomorphicLayoutEffect(() => {if (isNested) {@@ -220,12 +235,20 @@ function useRootThemeSync(// Sync theme name so @scope rules reach portals/fallback viewports.document.documentElement.setAttribute(dataAttr('theme'), themeName);+ setRootReducedMotionMark(document.documentElement, reducesMotion);+ if (reducesMotion) {+ document.documentElement.style.setProperty(REDUCED_MOTION_PROPERTY, '1');+ } else {+ document.documentElement.style.removeProperty(REDUCED_MOTION_PROPERTY);+ }return () => {document.documentElement.removeAttribute('data-theme');document.documentElement.removeAttribute(dataAttr('theme'));+ setRootReducedMotionMark(document.documentElement, false);+ document.documentElement.style.removeProperty(REDUCED_MOTION_PROPERTY);};- }, [isNested, mode, themeName]);+ }, [isNested, mode, themeName, reducesMotion]);}// =============================================================================@@ -255,7 +278,11 @@ export function Theme({registerTheme(theme);useThemeStyleInjection(theme);- useRootThemeSync(isNested, mode, theme.name);+ // resolveMotionKnobs resolves no public theme to 'always', so no theme+ // marks its root.+ const reducesMotion =+ resolveMotionKnobs(theme.__axes?.motion).reducedMotion === 'always';+ useRootThemeSync(isNested, mode, theme.name, reducesMotion);// Get color-scheme styleconst colorSchemeStyle =@@ -272,8 +299,13 @@ export function Theme({<ThemeContext value={ctxValue}><ThemeNestingContext value={true}><div- {...stylex.props(wrapperStyles.base, colorSchemeStyle)}+ {...stylex.props(+ wrapperStyles.base,+ colorSchemeStyle,+ reducesMotion && wrapperStyles.reducedMotion,+ )}data-astryx-theme={theme.name}+ {...reducedMotionMarkProps(reducesMotion)}data-theme={mode === 'system' ? undefined : mode}>{children}</div>diff --git a/packages/core/src/theme/motionKnobs.ts b/packages/core/src/theme/motionKnobs.tsindex 6744c1624d..c012bef92b 100644--- a/packages/core/src/theme/motionKnobs.ts+++ b/packages/core/src/theme/motionKnobs.ts@@ -20,10 +20,11 @@export type MotionCharacter = 'crisp' | 'standard' | 'expressive';/**- * Whose Reduce Motion setting a theme follows: `'system'`, each person's own.- * Internal: no theme sets it until `'always'` ships (`spec:AST-108` FR6).+ * Whose Reduce Motion setting a theme follows: `'system'`, each person's own,+ * or `'always'`, reduced for everyone. Internal: `resolveKnobs` resolves+ * every theme to `'system'` until `'always'` ships (`spec:AST-108` FR6).*/-export type ThemeReducedMotion = 'system';+export type ThemeReducedMotion = 'system' | 'always';/** The motion knobs a theme sets (`spec:AST-108` FR1). */export interface ThemeMotionKnobs {diff --git a/packages/core/src/theme/themeMotion.ts b/packages/core/src/theme/themeMotion.tsindex 6eddb2d30d..7dc4e68a20 100644--- a/packages/core/src/theme/themeMotion.ts+++ b/packages/core/src/theme/themeMotion.ts@@ -87,6 +87,13 @@ function msOf(value: string): number {*/export const MOTION_TEMPO_PROPERTY = '--_astryx-motion-tempo';+/**+ * The custom property a theme whose `reducedMotion` resolves to `'always'`+ * sets to `1` on its root, and the root theme on `<html>`: styles that cannot+ * key a selector on the mark read it in a value.+ */+export const REDUCED_MOTION_PROPERTY = '--_astryx-reduced-motion';+/** The duration tokens at `tempo`: today's values times it, to the ms. */export function durationTokensAt(tempo: number): Record<string, string> {const tokens: Record<string, string> = {};diff --git a/packages/core/src/theme/themeReducedMotionMark.test.tsx b/packages/core/src/theme/themeReducedMotionMark.test.tsxnew file mode 100644index 0000000000..b3507b7cc2--- /dev/null+++ b/packages/core/src/theme/themeReducedMotionMark.test.tsx@@ -0,0 +1,115 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file themeReducedMotionMark.test.tsx+ * @input vitest (jsdom), React Testing Library, react-dom/server, Theme and+ * defineTheme; themeMotion's resolveMotionKnobs, mocked to resolve one+ * theme to 'always', since no public theme can yet+ * @output Checks the reduced-motion mark: a theme that resolves to 'always'+ * marks its wrapper (in a server render too) and, as the root theme,+ * `<html>`, with the attribute and its custom property; 'system' marks+ * nothing; a nested theme marks only its own wrapper; the mark leaves with+ * the theme. Every theme resolves to 'system' unmocked+ * @position Testing; validates Theme.tsx's use of themeMotion.ts+ */++import {render} from '@testing-library/react';+import {renderToString} from 'react-dom/server';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {defineTheme} from './defineTheme';+import {Theme} from './Theme';+import type * as ThemeMotion from './themeMotion';++type ThemeMotionModule = typeof ThemeMotion;++const MARK = 'data-astryx-reduced-motion';+const PROPERTY = '--_astryx-reduced-motion';+const ALWAYS_NAME = 'StillAlways';++const knobs = vi.hoisted(() => ({isAlwaysOn: false}));++vi.mock('./themeMotion', async importOriginal => {+ const actual = await importOriginal<ThemeMotionModule>();+ return {+ ...actual,+ resolveMotionKnobs: (config?: {tempo?: number}) => {+ const resolved = actual.resolveMotionKnobs(config);+ // The 'always' theme carries a tempo no other theme here uses.+ return knobs.isAlwaysOn && config?.tempo === 0.8+ ? {...resolved, reducedMotion: 'always' as const}+ : resolved;+ },+ };+});++const always = defineTheme({name: ALWAYS_NAME, motion: {tempo: 0.8}});+const system = defineTheme({name: 'StillSystem', motion: {tempo: 1.2}});++function wrapperOf(container: HTMLElement, name: string) {+ return container.querySelector(`[data-astryx-theme="${name}"]`);+}++afterEach(() => {+ knobs.isAlwaysOn = false;+ document.documentElement.removeAttribute(MARK);+ document.documentElement.style.removeProperty(PROPERTY);+});++describe('the reduced-motion mark', () => {+ it("every theme resolves to 'system' and marks nothing", () => {+ const {container} = render(+ <Theme theme={always}>+ <p>content</p>+ </Theme>,+ );+ expect(wrapperOf(container, ALWAYS_NAME)?.hasAttribute(MARK)).toBe(false);+ expect(document.documentElement.hasAttribute(MARK)).toBe(false);+ });++ it("'always' marks the wrapper and, at the root, <html>; the mark leaves with the theme", () => {+ knobs.isAlwaysOn = true;+ const {container, unmount} = render(+ <Theme theme={always}>+ <p>content</p>+ </Theme>,+ );+ expect(wrapperOf(container, ALWAYS_NAME)?.hasAttribute(MARK)).toBe(true);+ expect(document.documentElement.hasAttribute(MARK)).toBe(true);+ expect(document.documentElement.style.getPropertyValue(PROPERTY)).toBe('1');+ unmount();+ expect(document.documentElement.hasAttribute(MARK)).toBe(false);+ expect(document.documentElement.style.getPropertyValue(PROPERTY)).toBe('');+ });++ it('a nested theme marks its own wrapper only', () => {+ knobs.isAlwaysOn = true;+ const {container} = render(+ <Theme theme={system}>+ <Theme theme={always}>+ <p>content</p>+ </Theme>+ </Theme>,+ );+ expect(wrapperOf(container, 'StillSystem')?.hasAttribute(MARK)).toBe(false);+ expect(wrapperOf(container, ALWAYS_NAME)?.hasAttribute(MARK)).toBe(true);+ expect(document.documentElement.hasAttribute(MARK)).toBe(false);+ });++ it('the server renders the mark, so hydration changes nothing', () => {+ knobs.isAlwaysOn = true;+ expect(+ renderToString(+ <Theme theme={always}>+ <p>content</p>+ </Theme>,+ ),+ ).toContain(MARK);+ expect(+ renderToString(+ <Theme theme={system}>+ <p>content</p>+ </Theme>,+ ),+ ).not.toContain(MARK);+ });+});diff --git a/scripts/motion-node-load.test.mjs b/scripts/motion-node-load.test.mjsindex 2005604556..093ea9eab1 100644--- a/scripts/motion-node-load.test.mjs+++ b/scripts/motion-node-load.test.mjs@@ -66,7 +66,14 @@ describe('the touch motion foundation in plain Node', () => {it('reaches no StyleX module and no theme module', async () => {const {metafile} = await bundleFoundation();const inputs = Object.keys(metafile.inputs);- const stylex = inputs.filter(file => /\.stylex\.[cm]?[jt]sx?$/.test(file));+ // A private attribute's owner module carries the .stylex name by the+ // private-attribute rule but may call no StyleX at load: the+ // stylexImports check below holds it to that.+ const stylex = inputs.filter(+ file =>+ /\.stylex\.[cm]?[jt]sx?$/.test(file) &&+ !/\/src\/privateAttributes\//.test(file),+ );const theme = inputs.filter(file => file.includes('/src/theme/'));const stylexImports = inputs.flatMap(file =>metafile.inputs[file].imports