An open source design system that's fully customizable and agent ready
TypeScript
fix(theme): text follows the reader's text size in Safari on iPhone, in every theme (#10416)
Cindy Zhang7bdeb06d766c
diff --git a/.changeset/theme-dynamic-type.md b/.changeset/theme-dynamic-type.mdnew file mode 100644index 0000000000..29638ea43a--- /dev/null+++ b/.changeset/theme-dynamic-type.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[fix] In Safari on iPhone, text follows the reader's text size (Dynamic Type) in every theme, branded included. Where the browser exposes that size through `font: -apple-system-body`, as Safari on iPhone does, the theme's font sizes scale with the size the reader picked in Settings (Display & Text Size, then Larger Text), each size on the curve of the iOS text style it plays: body text like Body, `heading-1` like Title 1, display text like Large Title, with every role kept in order. A semantic size a theme fixes at a length, such as the 0.75rem supporting text of Butter, Stone and Y2K, scales on the curve of the step it reads by default. At the default size every font size is the theme's own; the family, spacing, line-height ratios and the root font size never change, text inputs keep their 16px floor on iOS, and browsers without the keyword see no change. There is no option, prop or document attribute: the root `Theme` reads the reader's size from a hidden element. `astryx docs typography/type-scale` describes it.++@vjeuxdiff --git a/apps/storybook/stories/ThemeDynamicType.stories.tsx b/apps/storybook/stories/ThemeDynamicType.stories.tsxnew file mode 100644index 0000000000..b0c47733e1--- /dev/null+++ b/apps/storybook/stories/ThemeDynamicType.stories.tsx@@ -0,0 +1,110 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import * as React from 'react';+import {Theme} from '@astryxdesign/core/theme';+import {Stack} from '@astryxdesign/core/Stack';+import {Heading, Text} from '@astryxdesign/core/Text';+import {neutralTheme} from '@astryxdesign/theme-neutral';+import {y2kTheme} from '@astryxdesign/theme-y2k';++const meta: Meta = {+ title: 'Core/Themes/Dynamic Type',+};++export default meta;++// When this page was loaded: it changes only on a reload, so a text size+// change that restyles the page while it stays open leaves it alone.+const LOADED_AT = new Date().toLocaleTimeString('en-US', {hour12: false});++// The readout is instrumentation rather than sample text, so it keeps one+// small fixed size at every text size.+const readoutStyle: React.CSSProperties = {+ font: '12px/16px system-ui, sans-serif',+ color: '#555',+};++/**+ * The samples, in `theme`, under a readout of the body text's size; without+ * `headings`, only the text sizes, so the page fits on a phone at AX5.+ */+function DynamicTypeSamples({+ theme,+ headings = true,+}: {+ theme: React.ComponentProps<typeof Theme>['theme'];+ headings?: boolean;+}) {+ const samplesRef = React.useRef<HTMLDivElement>(null);+ const [bodySize, setBodySize] = React.useState<string | null>(null);+ React.useEffect(() => {+ // The body text sample's own size: it follows the reader's text size+ // where the browser exposes it, so it changes in place when they do. The+ // sample is inline, which a ResizeObserver never reports, so its block+ // wrapper is observed: the wrapper's height follows the text's.+ const wrapper = samplesRef.current?.querySelector<HTMLElement>(+ '[data-testid="body-sample"]',+ );+ const body = wrapper?.firstElementChild;+ if (wrapper == null || body == null) {+ return;+ }+ const read = () => setBodySize(getComputedStyle(body).fontSize);+ read();+ const observer = new ResizeObserver(read);+ observer.observe(wrapper);+ return () => observer.disconnect();+ }, []);+ return (+ <Theme theme={theme}>+ <Stack+ ref={samplesRef}+ direction="vertical"+ gap={3}+ style={{padding: 16}}>+ <div style={readoutStyle}>+ <span data-testid="body-size">Body text: {bodySize ?? '…'}</span>+ {' · '}+ <span data-testid="page-loaded-at">page loaded at {LOADED_AT}</span>+ </div>+ {headings && (+ <>+ <Heading level={1} type="display-1">+ Display 1+ </Heading>+ <Heading level={1}>Heading 1</Heading>+ <Heading level={2}>Heading 2</Heading>+ <Heading level={3}>Heading 3</Heading>+ </>+ )}+ <div data-testid="body-sample">+ <Text type="body">Body text</Text>+ </div>+ <Text type="supporting">Supporting text</Text>+ </Stack>+ </Theme>+ );+}++/**+ * In Safari on iPhone, every theme follows the reader's text size (Settings ›+ * Display & Text Size › Larger Text): every size grows or shrinks on the curve+ * of the iOS text style it plays. At the default size, and wherever the+ * browser does not expose the reader's text size (`font: -apple-system-body`),+ * these are the theme's own sizes. Change the text size with this page open:+ * it restyles in place, and the time it was loaded stays the same.+ */+export const DynamicType: StoryObj = {+ render: () => <DynamicTypeSamples theme={neutralTheme} />,+};++/**+ * Y2K fixes supporting text at a length (0.75rem) instead of reading a step+ * of its type scale. A size a theme fixes at a length scales on the curve of+ * the step it reads by default, so here supporting text follows the reader+ * like Footnote rather than staying fixed while the rest grows.+ */+export const FixedSupportingSize: StoryObj = {+ render: () => <DynamicTypeSamples theme={y2kTheme} headings={false} />,+};diff --git a/docs/architecture/component-style-authoring.md b/docs/architecture/component-style-authoring.mdindex 7621a1f4b3..0f37bc0b1d 100644--- a/docs/architecture/component-style-authoring.md+++ b/docs/architecture/component-style-authoring.md@@ -13,6 +13,8 @@ applies_to: [packages/core/src/, packages/lab/src/]verified_by:[internal/stylex-capabilities/scan.mjs,+ packages/core/src/theme/dynamicType.test.ts,+ packages/core/src/theme/Theme.test.tsx,internal/eslint-plugin-astryx/no-border-shorthand.test.mjs,internal/eslint-plugin-astryx/no-stylex-null-override.test.mjs,internal/eslint-plugin-astryx/no-style-only-wrapper.test.mjs,@@ -133,7 +135,11 @@ not evidence of conformance or violation.never through extra elements. A pseudo-element carries decoration that hasno semantic role and never repeats content. Content renders once: no hiddentwin to measure or reserve space, because CSS can size and reserve it on the- element that shows it (INV2). A layer mounts exactly one presentation. The+ element that shows it (INV2). The theme runtime may own one shared, empty,+ aria-hidden probe element per document, outside every component's DOM, used+ only to read a platform text size; it renders no content, is not a theming+ target, and is removed with the last root Theme. A layer mounts exactly one+ presentation. Theonly second copy is one transient copy during an exit, a presentationswitch, a lift from the trigger (`architecture:layer-runtime` INV15), or ahandoff between sheets, such as the cross-fade@@ -305,4 +311,5 @@ RSC owners retain the delegated decisions above.| INV5 | Wrapper mutations in default and host-composed render paths | Removing a wrapper changes no semantic, behavior/ref, formatting-context, outside-border-spacing, or required style-bearing DOM boundary || INV6 | Pull-request size report against base, with value-table import fixtures | A changed component with no base-against-head gzip JavaScript or CSS figure; a touch-only feature over 2 KB gzip JavaScript or 1 KB gzip CSS per component that is not flagged; importing a component pulls in value-table rows only other components read || INV7 | Story element counts (`document.body.querySelectorAll('*').length`) at rest and open under a fine and a coarse pointer, base against head, plus render inspection for duplicated content | An element beyond the component's roles, themable parts, and INV5 wrappers, or a duplicated or hidden twin of content; a state or variant rendered as an extra element; a pseudo-element repeating content; a layer with two presentations mounted outside the transient copy, content mounted twice, more elements under a coarse pointer than a fine one beyond the allowance of `spec:AST-017` FR60, a transient copy made by a component itself, or one left past 1 second; an added element with no measured counts, or a budget exceeded with no recorded owner exception; a second reorder preview, or one left after the drop |+| INV7 (probe) | `dynamicType.test.ts` shared-probe, cleanup, and capability-gate cases; `Theme.test.tsx` nested-Theme and no-capability cases | More than one probe in a document; a probe a nested Theme creates; a probe left after the last root Theme unmounts; a probe where the engine has no `font: -apple-system-body` || Capability registry | Registry generation against the installed StyleX package | Recorded and installed StyleX versions differ, so capability-dependent cases are untestable |diff --git a/docs/specs/AST-102-typography-theme-owned/spec.md b/docs/specs/AST-102-typography-theme-owned/spec.mdindex 573e75c89e..4b0898a57b 100644--- a/docs/specs/AST-102-typography-theme-owned/spec.md+++ b/docs/specs/AST-102-typography-theme-owned/spec.md@@ -111,7 +111,10 @@ the person's device.element size tokens keep their values when a size is set; a control growswith its text under FR4.- Defects under FR3 and FR4:- - On iOS and iPadOS, text ignores Dynamic Type in every theme.+ - Safari on iPhone follows Dynamic Type in every theme, recorded in the iOS+ simulator at the current implementation. Safari on iPad and other iOS+ browsers are unverified, and macOS Safari at its default text size is a+ recorded follow-up verification.- Controls hold fixed heights, such as 40 px elements, `component:Badge`FR1's block size, `component:Token` FR1's element size, and InputGroup'srow height in `family:input-fields`, so a larger label can overflow; those@@ -121,12 +124,12 @@ the person's device.## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | Source check over Core and Lab component styles plus token review | family, size, and line height of rendered text in component styles; an inherited value; a `1em` icon size; coarse and fine pointer; a platform font keyword; the iOS text-entry floor | A Core or Lab web component sets the family, size, or line height of text it renders outside typography tokens and not by inheritance, or applies a platform font keyword directly; icon sizing, the family floor, and a hidden internal element that only measures a platform text style are not failures |-| FR2 | Theme token review plus Safari on iOS, top-level document | an unbranded shipped theme using the system body font family; a branded theme; the default theme | A branded theme's body font replaced by the system font, or a system body font applied by a component instead of a theme token |-| FR3 | Safari on iOS across Dynamic Type categories; Chrome on Android in the emulator with font scale; a desktop browser with a larger default font size and with zoom; theme review; `scripts/check-theme-text-size-units.test.mjs` (no first-party theme sets a text or font size in px) | a branded and an unbranded theme; no size set; default category; a size set on each platform; macOS Safari | Text that ignores a size the person set; text that differs from the theme's family or size when none is set, other than the `family:input-fields` FR9 iOS text-entry floor; a theme family replaced; a public option, prop, or document attribute; a changed root font size |-| FR4 | Desktop browser at 200%, 250%, and 300% text size, plus Safari on iOS at accessibility categories | reading text; a button, text input, tab, badge, table cell, and segmented control | Lost content or function at 200% or less; a label clipped by its control's height at any size; a control that keeps a fixed height while its text grows |+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1 | Source check over Core and Lab component styles plus token review | family, size, and line height of rendered text in component styles; an inherited value; a `1em` icon size; coarse and fine pointer; a platform font keyword; the iOS text-entry floor | A Core or Lab web component sets the family, size, or line height of text it renders outside typography tokens and not by inheritance, or applies a platform font keyword directly; icon sizing, the family floor, and a hidden internal element that only measures a platform text style are not failures |+| FR2 | Theme token review plus Safari on iOS, top-level document | an unbranded shipped theme using the system body font family; a branded theme; the default theme | A branded theme's body font replaced by the system font, or a system body font applied by a component instead of a theme token |+| FR3 | Safari on iOS across Dynamic Type categories; Chrome on Android in the emulator with font scale; a desktop browser with a larger default font size and with zoom; theme review; `scripts/check-theme-text-size-units.test.mjs` (no first-party theme sets a text or font size in px) | a branded and an unbranded theme; no size set; default category; a size set on each platform; macOS Safari at its default text size, whose fixed 13 px Body names no category, so every scale stays 1 (`dynamicType.test.ts`; a browser reading is a recorded follow-up) | Text that ignores a size the person set; text that differs from the theme's family or size when none is set, other than the `family:input-fields` FR9 iOS text-entry floor; a theme family replaced; a public option, prop, or document attribute; a changed root font size |+| FR4 | Desktop browser at 200%, 250%, and 300% text size, plus Safari on iOS at accessibility categories | reading text; a button, text input, tab, badge, table cell, and segmented control | Lost content or function at 200% or less; a label clipped by its control's height at any size; a control that keeps a fixed height while its text grows |## Decision logdiff --git a/packages/cli/assets/docs/tree/type-scale.doc.mjs b/packages/cli/assets/docs/tree/type-scale.doc.mjsindex f907f9246b..d26958cc3f 100644--- a/packages/cli/assets/docs/tree/type-scale.doc.mjs+++ b/packages/cli/assets/docs/tree/type-scale.doc.mjs@@ -2,7 +2,8 @@/*** @file `astryx docs typography/type-scale`: line height, semantic type scale,- * display text, headings and text components, and custom type scales.+ * display text, headings and text components, custom type scales, and the+ * reader's text size on iOS.*//** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */@@ -14,13 +15,15 @@ export const docs = {placement: {parent: 'namespace:typography', slot: 'guides', order: 20},category: 'foundations',description:- 'Line height, semantic type scale tokens, display text, Heading and Text components, and custom type scales via defineTheme.',+ "Line height, semantic type scale tokens, display text, Heading and Text components, custom type scales via defineTheme, and following the reader's text size on iOS.",keywords: ['line height','leading','defineTheme','base','ratio',+ 'dynamic type',+ 'text size',],sections: [@@ -143,5 +146,19 @@ const denseTheme = defineTheme({},],},+ {+ id: 'dynamic-type',+ title: "Following the reader's text size on iOS",+ content: [+ {+ type: 'prose',+ text: "On iPhone, readers pick a text size in Settings (Display & Text Size, then Larger Text), and native apps grow or shrink their text with it. Every theme does the same in Safari on iPhone, which exposes that choice through `font: -apple-system-body`: each font size follows the reader's choice on the curve of the iOS text style it plays, so body text scales like Body, `heading-1` like Title 1 and display text like Large Title, and every role keeps its order. A size the theme fixes at a length, such as a 12px supporting size, scales on the curve of the step it reads by default; a size in `em` or `%` follows its parent, and one that reads a variable follows that variable. At the default size every font size is the theme's own. The family, spacing, radius and the root font size never change, line heights keep their ratios, text inputs keep their 16px floor on iOS, and browsers without the keyword see no change. There is nothing to turn on: no theme option, prop or document attribute.",+ },+ {+ type: 'prose',+ text: 'Fixed-height controls such as the text inputs keep their height, so their text can overflow at the accessibility sizes. A labelled `Button` grows with its label.',+ },+ ],+ },],};diff --git a/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs b/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjsindex 039245c0ac..d755de845d 100644--- a/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs+++ b/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs@@ -277,7 +277,10 @@ describe('theme build adaptations', () => {css.indexOf('@media (width < 768px) and (pointer: coarse)'),css.indexOf('@media (prefers-contrast: more)'),);- expect(scaleBlock).toContain('--font-size-base: 0.875rem');+ // Raw steps follow the reader's text size (spec:AST-102 FR3; 1 elsewhere).+ expect(scaleBlock).toContain(+ '--_scaled-font-size-base: min(calc(0.875rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg))',+ );expect(scaleBlock).not.toContain('.astryx-text');expect(scaleBlock).not.toContain('.astryx-heading');expect(scaleBlock).not.toContain('.astryx-button');@@ -303,6 +306,70 @@ describe('theme build adaptations', () => {},);+ it("writes a built theme's font sizes following the reader's text size, as at runtime", async () => {+ const {defineTheme, generateAdaptationCSS, generateThemeCSS} =+ await import('@astryxdesign/core/theme');+ const project = path.join(tmpDir, 'project');+ const themesDir = path.join(project, 'themes');+ // Butter's shape: a fixed supporting size, and a phone rule whose scale+ // turns it back into a step.+ const input = {+ name: 'dynamic-type-built',+ typography: {scale: {base: 14, ratio: 1.25}},+ tokens: {'--text-supporting-size': '12px'},+ adaptations: {+ rules: [+ {+ when: {width: {below: 'lg'}, pointer: 'coarse'},+ value: {typography: {scale: {base: 16, ratio: 1.2225}}},+ },+ ],+ },+ };+ const themeFile = writeTheme(themesDir, input.name, JSON.stringify(input));+ const result = await build(project, themeFile);+ expect(result.code, result.stderr).toBe(0);+ const css = fs.readFileSync(+ path.join(themesDir, 'dynamic-type-built.css'),+ 'utf8',+ );+ const compact = value => value.replace(/\s+/g, ' ').trim();+ const source = defineTheme(input);+ const runtime = generateThemeCSS(source);+ // The built CSS writes the sizes as the runtime does: the root's steps and+ // its fixed supporting size scaled, and the phone rule's steps scaled+ // inside its own condition.+ const adaptationCSS = generateAdaptationCSS(source).component;+ expect(compact(css)).toContain(compact(adaptationCSS));+ expect(adaptationCSS).toContain(+ '--_scaled-font-size-base: min(calc(1rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg));',+ );+ expect(css).toContain(+ '--_scaled-font-size-base: min(calc(0.875rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg));',+ );+ expect(css).toContain(+ '--text-supporting-size: calc(12px * var(--_dynamic-type-footnote, 1));',+ );++ // The built module and a theme extending it compile to the same CSS as+ // the source.+ const {dynamicTypeBuiltTheme: builtTheme} = await import(+ pathToFileURL(path.join(themesDir, 'dynamic-type-built.js')).href+ );+ expect(generateThemeCSS(builtTheme)).toEqual(runtime);+ const childInput = {+ name: 'dynamic-type-child',+ tokens: {'--text-body-size': '15px'},+ };+ expect(+ generateThemeCSS(defineTheme({...childInput, extends: builtTheme})),+ ).toEqual(generateThemeCSS(defineTheme({...childInput, extends: source})));+ expect(+ generateThemeCSS(defineTheme({...childInput, extends: builtTheme}))+ .component,+ ).toContain('--text-body-size: calc(15px * var(--_dynamic-type-body, 1));');+ });+it('resolves a plain object whose only input-only field is adaptations', async () => {const project = path.join(tmpDir, 'project');const themesDir = path.join(project, 'themes');@@ -459,7 +526,9 @@ describe('theme build adaptations', () => {'utf-8',);expect(rebuiltCss).toContain('@media (width < 700px)');- expect(rebuiltCss).toContain('--font-size-lg: 1.25rem');+ expect(rebuiltCss).toContain(+ '--_scaled-font-size-lg: min(calc(1.25rem * var(--_dynamic-type-title3, 1)), var(--_scaled-font-size-xl))',+ );expect(rebuiltCss).toContain('light-dark(#111111, #eeeeee)');expect(rebuiltCss).toContain(':root { color-scheme: light dark; }');expect(`${rebuilt.stdout}${rebuilt.stderr}`).toContain(diff --git a/packages/cli/test/__golden__/no-icon-set/docs-tree.json b/packages/cli/test/__golden__/no-icon-set/docs-tree.jsonindex 27c393b879..3b8325f9df 100644--- a/packages/cli/test/__golden__/no-icon-set/docs-tree.json+++ b/packages/cli/test/__golden__/no-icon-set/docs-tree.json@@ -1415,7 +1415,8 @@"type-scale","display-text","usage",- "custom-type-scale"+ "custom-type-scale",+ "dynamic-type"],"mentions": []},diff --git a/packages/core/src/privateAttributes/textSizeProbe.stylex.ts b/packages/core/src/privateAttributes/textSizeProbe.stylex.tsnew file mode 100644index 0000000000..0ef51fa308--- /dev/null+++ b/packages/core/src/privateAttributes/textSizeProbe.stylex.ts@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/textSizeProbe.stylex.ts+ * @input The hidden element that measures the reader's text size+ * @output markTextSizeProbe, which marks that element, and isTextSizeProbe,+ * which reads the mark+ * @position Owner module of the private text-size-probe attribute: the only+ * file that writes its name. theme/dynamicType.ts marks the one probe the+ * root Theme runtime keeps on `<body>`. No package entry exports it.+ */++const TEXT_SIZE_PROBE = 'data-astryx-text-size-probe';++/** Marks the hidden element that measures the reader's text size. */+export function markTextSizeProbe(element: Element): void {+ element.setAttribute(TEXT_SIZE_PROBE, '');+}++/** Whether `target` is that hidden element. */+export function isTextSizeProbe(target: EventTarget | null): boolean {+ return target instanceof Element && target.hasAttribute(TEXT_SIZE_PROBE);+}diff --git a/packages/core/src/theme/Theme.test.tsx b/packages/core/src/theme/Theme.test.tsxindex f0631d8dd5..178c5fb67b 100644--- a/packages/core/src/theme/Theme.test.tsx+++ b/packages/core/src/theme/Theme.test.tsx@@ -8,6 +8,7 @@ import React from 'react';import {Theme} from './Theme';import {defineTheme} from './defineTheme';import type * as DefineThemeModule from './defineTheme';+import {dynamicTypeScaleRule} from './dynamicType';const {generateThemeCSSSpy} = vi.hoisted(() => ({generateThemeCSSSpy: vi.fn(),@@ -336,6 +337,108 @@ describe('Theme', () => {expect(injected).toContain('@layer reset, astryx-base, astryx-theme;');expect(injected).not.toContain(':root {');});+ // The gate is the capability alone, never a platform idiom (one touch+ // behavior on every touch device): a touch callout without+ // `font: -apple-system-body` reads nothing.+ it('reads no text size where the engine has no font: -apple-system-body', () => {+ vi.stubGlobal('CSS', {+ supports: vi.fn(+ (property: string) => property === '-webkit-touch-callout',+ ),+ });+ vi.stubGlobal(+ 'CSSStyleSheet',+ class {+ replaceSync() {}+ },+ );+ Object.defineProperty(document, 'adoptedStyleSheets', {+ configurable: true,+ writable: true,+ value: [],+ });+ try {+ render(+ <Theme theme={testTheme}>+ <span>web</span>+ </Theme>,+ );+ expect(+ document.querySelector('[data-astryx-text-size-probe]'),+ ).toBeNull();+ expect(document.adoptedStyleSheets).toEqual([]);+ } finally {+ vi.unstubAllGlobals();+ delete (document as {adoptedStyleSheets?: unknown}).adoptedStyleSheets;+ }+ });++ it('keeps the page on the reader text size wherever the engine provides it, from the root Theme only, with nothing on <html>', () => {+ // The capability and nothing else: no touch callout.+ vi.stubGlobal('CSS', {+ supports: vi.fn(+ (property: string, value?: string) =>+ property === 'font' && value === '-apple-system-body',+ ),+ });+ class FakeSheet {+ text = '';+ replaceSync(text: string) {+ this.text = text;+ }+ }+ vi.stubGlobal('CSSStyleSheet', FakeSheet);+ Object.defineProperty(document, 'adoptedStyleSheets', {+ configurable: true,+ writable: true,+ value: [],+ });+ const adoptedText = () =>+ (document.adoptedStyleSheets as unknown as FakeSheet[])+ .map(sheet => sheet.text)+ .join('');+ const real = window.getComputedStyle.bind(window);+ const computed = vi+ .spyOn(window, 'getComputedStyle')+ .mockImplementation(element =>+ element instanceof HTMLElement &&+ element.hasAttribute('data-astryx-text-size-probe')+ ? ({fontSize: '33px'} as CSSStyleDeclaration)+ : real(element),+ );+ const before = document.documentElement.getAttributeNames();+ try {+ const {unmount} = render(+ <Theme theme={testTheme}>+ <Theme theme={altTheme}>+ <span>nested</span>+ </Theme>+ </Theme>,+ );+ // Body at 33px is the second accessibility size; its scales reach the+ // page through an adopted stylesheet, from the root Theme alone.+ expect(adoptedText()).toBe(dynamicTypeScaleRule('ax2'));+ expect(+ document.querySelectorAll('[data-astryx-text-size-probe]'),+ ).toHaveLength(1);+ expect(+ document.documentElement+ .getAttributeNames()+ .filter(name => name.includes('text-size')),+ ).toEqual([]);++ unmount();+ expect(adoptedText()).toBe('');+ expect(+ document.querySelector('[data-astryx-text-size-probe]'),+ ).toBeNull();+ expect(document.documentElement.getAttributeNames()).toEqual(before);+ } finally {+ vi.unstubAllGlobals();+ computed.mockRestore();+ delete (document as {adoptedStyleSheets?: unknown}).adoptedStyleSheets;+ }+ });it('keeps the shared CSS until the last Theme using it unmounts', () => {function App({showInner}: {showInner: boolean}) {diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsxindex 96ddbe0620..6495acba16 100644--- a/packages/core/src/theme/Theme.tsx+++ b/packages/core/src/theme/Theme.tsx@@ -18,6 +18,11 @@* - `data-astryx-theme` — enables @scope'd theme CSS to reach elements rendered* outside the Theme wrapper (portals, toast fallback viewports).*+ * The root Theme also reads the reader's text size (iOS Dynamic Type) from a+ * hidden, empty `font: -apple-system-body` probe and keeps the page's scales+ * in an adopted stylesheet; every theme's font sizes follow them, and no+ * attribute is written (see dynamicType.ts).+ ** For RSC / SSR, set `data-theme` on `<html>` in your root server layout* to avoid a flash of wrong theme before hydration:*@@ -43,6 +48,7 @@ import {colorVars, typographyVars} from './tokens.stylex';import {generateThemeCSS, type DefinedTheme} from './defineTheme';import {registerTheme} from './themeRegistry';import {dataAttr} from '../naming';+import {syncReaderTextSize} from './dynamicType';import {ThemeContext} from './useTheme';import {warnOnce} from '../utils/devWarning';import {REDUCED_MOTION_PROPERTY, resolveMotionKnobs} from './themeMotion';@@ -317,6 +323,21 @@ function useRootThemeSync(}, [isNested, mode, themeName, reducesMotion]);}+/**+ * Hook to keep the page's text size scales on the reader's text size (iOS+ * Dynamic Type) for the root provider; see dynamicType.ts. Skipped for nested+ * Theme instances, and a no-op where the engine has no+ * `font: -apple-system-body`.+ */+function useRootTextSizeSync(isNested: boolean): void {+ useIsomorphicLayoutEffect(() => {+ if (isNested || typeof document === 'undefined') {+ return;+ }+ return syncReaderTextSize(document);+ }, [isNested]);+}+// =============================================================================// Component// =============================================================================@@ -349,6 +370,7 @@ export function Theme({const reducesMotion =resolveMotionKnobs(theme.__axes?.motion).reducedMotion === 'always';useRootThemeSync(isNested, mode, theme.name, reducesMotion);+ useRootTextSizeSync(isNested);// Get color-scheme styleconst colorSchemeStyle =diff --git a/packages/core/src/theme/dynamicType.test.ts b/packages/core/src/theme/dynamicType.test.tsnew file mode 100644index 0000000000..62b2d59c0c--- /dev/null+++ b/packages/core/src/theme/dynamicType.test.ts@@ -0,0 +1,1099 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file dynamicType.test.ts+ * @input vitest, dynamicType.ts, the UIKit typography table, defineTheme and+ * generateThemeCSS+ * @output Proves the Dynamic Type rules: Body's size names the reader's+ * category; each raw font-size step scales exactly on its UIKit curve, in+ * order, and is the theme's own size at Large; every theme writes its sizes+ * that way at its root and in its adaptation rules, with no option and no+ * reference cycle; and the root sync reads a hidden probe and adopts a+ * stylesheet with the category's scales, writing nothing on `<html>`+ * @position Testing; validates theme/dynamicType.ts and its use in+ * generateThemeRules.ts without a browser (the iOS evidence is the+ * simulator's)+ */++import fs from 'node:fs';+import path from 'node:path';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {typography} from './uikitTypography';+import {defineTheme, generateThemeCSS} from './defineTheme';+import {generateOnMediaCSS} from './generateThemeRules';+import {+ FONT_SIZE_STEP_STYLES,+ TEXT_SIZE_CATEGORIES,+ dynamicTypeScale,+ dynamicTypeScaleProperty,+ dynamicTypeScaleRule,+ scaledFontSizeEntries,+ scaledStepProperty,+ syncReaderTextSize,+ textSizeCategoryForBodySize,+ type DynamicTypeStyle,+} from './dynamicType';+import {textSizeDefaults} from './tokens.stylex';++const STYLES = Object.keys(typography) as DynamicTypeStyle[];++/** A `rem` or `px` length, in px (16px to the rem). */+function lengthInPx(value: string | undefined): number {+ const match = /^(-?[\d.]+)(rem|px)$/.exec(value ?? '');+ if (match == null) {+ throw new Error(`not a length: ${value}`);+ }+ return Number(match[1]) * (match[2] === 'rem' ? 16 : 1);+}++/**+ * What the browser computes for emitted custom properties at one category,+ * in px, aligned with `entries`: each expression evaluated (min, max, calc of+ * a length times a category scale, variables with their fallbacks), resolving+ * each variable by name. A reference cycle, which a browser would compute to+ * nothing, throws.+ */+function computedSizes(+ entries: ReadonlyArray<readonly [string, string]>,+ category: (typeof TEXT_SIZE_CATEGORIES)[number],+): number[] {+ const expressions = new Map(entries);+ const scales = new Map<string, number>();+ for (const style of STYLES) {+ scales.set(+ dynamicTypeScaleProperty(style),+ dynamicTypeScale(style, category),+ );+ }+ const memo = new Map<string, number>();+ const visiting = new Set<string>();+ const resolve = (name: string, fallback: string | undefined): number => {+ const scale = scales.get(name);+ if (scale !== undefined) {+ return scale;+ }+ const known = memo.get(name);+ if (known !== undefined) {+ return known;+ }+ const expression = expressions.get(name);+ if (expression === undefined) {+ if (fallback === undefined) {+ throw new Error(`unset ${name}`);+ }+ return evaluate(fallback);+ }+ if (visiting.has(name)) {+ throw new Error(`reference cycle through ${name}`);+ }+ visiting.add(name);+ const value = evaluate(expression.replace(/\s*!important$/, ''));+ visiting.delete(name);+ memo.set(name, value);+ return value;+ };+ const evaluate = (source: string): number => {+ let at = 0;+ const read = (text: string) => {+ if (!source.startsWith(text, at)) {+ throw new Error(`expected "${text}" at ${at} in ${source}`);+ }+ at += text.length;+ };+ const skipSpaces = () => {+ while (source[at] === ' ') {+ at += 1;+ }+ };+ const term = (): number => {+ skipSpaces();+ for (const [name, pick] of [+ ['min(', Math.min],+ ['max(', Math.max],+ ] as const) {+ if (source.startsWith(name, at)) {+ read(name);+ const first = term();+ read(',');+ const second = term();+ skipSpaces();+ read(')');+ return pick(first, second);+ }+ }+ if (source.startsWith('calc(', at)) {+ read('calc(');+ const left = term();+ skipSpaces();+ read('*');+ const right = term();+ skipSpaces();+ read(')');+ return left * right;+ }+ if (source.startsWith('var(', at)) {+ read('var(');+ let depth = 1;+ let end = at;+ while (depth > 0) {+ if (source[end] === '(') {+ depth += 1;+ } else if (source[end] === ')') {+ depth -= 1;+ }+ end += 1;+ }+ const inner = source.slice(at, end - 1);+ at = end;+ const comma = inner.indexOf(',');+ return comma === -1+ ? resolve(inner.trim(), undefined)+ : resolve(+ inner.slice(0, comma).trim(),+ inner.slice(comma + 1).trim(),+ );+ }+ const match = /^-?[\d.]+(rem|px)?/.exec(source.slice(at));+ if (match == null) {+ throw new Error(`unexpected input at ${at} in ${source}`);+ }+ at += match[0].length;+ return match[1] === undefined ? Number(match[0]) : lengthInPx(match[0]);+ };+ const value = term();+ skipSpaces();+ if (at !== source.length) {+ throw new Error(`trailing input at ${at} in ${source}`);+ }+ return value;+ };+ return entries.map(([name]) => resolve(name, undefined));+}++/** The emitted entries' computed sizes at one category, by name. */+function sizesByName(+ entries: ReadonlyArray<readonly [string, string]>,+ category: (typeof TEXT_SIZE_CATEGORIES)[number],+): Record<string, number> {+ const sizes = computedSizes(entries, category);+ return Object.fromEntries(entries.map(([name], i) => [name, sizes[i]]));+}++describe('the reader text size category', () => {+ it('has one category per column of the UIKit table, Large fourth', () => {+ for (const style of STYLES) {+ expect(typography[style]).toHaveLength(TEXT_SIZE_CATEGORIES.length);+ }+ expect(TEXT_SIZE_CATEGORIES[3]).toBe('l');+ });++ it('is named by the size of Body alone', () => {+ TEXT_SIZE_CATEGORIES.forEach((category, index) => {+ expect(textSizeCategoryForBodySize(typography.body[index])).toBe(+ category,+ );+ });+ // Sub-pixel rounding of a computed size still names the category.+ expect(textSizeCategoryForBodySize(17.2)).toBe('l');+ });++ it('names nothing for a size Safari does not produce', () => {+ expect(textSizeCategoryForBodySize(18)).toBeNull();+ expect(textSizeCategoryForBodySize(16.5)).toBeNull();+ expect(textSizeCategoryForBodySize(Number.NaN)).toBeNull();+ });+});++describe('the UIKit point sizes', () => {+ // Every row names where its values come from, and a measurement names its+ // subject, the iOS version and the date.+ const MEASURED =+ /^@source measured: .*iOS \d.*(\b20\d\d-\d\d-\d\d\b|\b(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{1,2},? 20\d\d\b)/;+ const SOURCE_KINDS =+ /^@source (apple-docs https:\/\/developer\.apple\.com\/|wwdc \d{4}-\d+ |webkit Source\/|measured: .*iOS \d|GUESS — )/;++ /** Each row's key and the `@source` tags of the JSDoc block above it. */+ function rowSources(): Map<string, string[]> {+ const text = fs.readFileSync(+ path.resolve(__dirname, 'uikitTypography.ts'),+ 'utf8',+ );+ const body = text.slice(text.indexOf('export const typography = {'));+ const rows = new Map<string, string[]>();+ const pattern = /\/\*\*([\s\S]*?)\*\/\s*(\w+): \[/g;+ for (const match of body.matchAll(pattern)) {+ const doc = (match[1] ?? '')+ .split('\n')+ .map(line => line.replace(/^\s*\*\s?/, ''))+ .join('\n');+ // A tag continues on the following lines until the next tag.+ const tags = doc+ .split(/\n(?=@)/)+ .map(tag => tag.replace(/\s*\n\s*/g, ' ').trim())+ .filter(tag => tag.startsWith('@source'));+ rows.set(match[2] ?? '', tags);+ }+ return rows;+ }++ it('names a source for every row, and the iOS version and date of every measurement', () => {+ const rows = rowSources();+ expect([...rows.keys()].sort()).toEqual(STYLES.slice().sort());+ for (const [style, tags] of rows) {+ expect(tags.length, style).toBeGreaterThan(0);+ for (const tag of tags) {+ expect(tag, style).toMatch(SOURCE_KINDS);+ if (tag.startsWith('@source measured:')) {+ expect(tag, style).toMatch(MEASURED);+ }+ }+ }+ });+});++describe('the UIKit curves', () => {+ it('maps every raw font-size step to a UIKit text style', () => {+ expect(Object.keys(FONT_SIZE_STEP_STYLES).sort()).toEqual(+ Object.keys(textSizeDefaults).sort(),+ );+ for (const style of Object.values(FONT_SIZE_STEP_STYLES)) {+ expect(STYLES).toContain(style);+ }+ });++ it('leaves every size alone at Large', () => {+ for (const style of STYLES) {+ expect(dynamicTypeScale(style, 'l')).toBe(1);+ }+ });++ it('turns a Large size into the UIKit size at every category', () => {+ // A theme step that equals the style's Large size lands on UIKit's own+ // size everywhere: UIFontMetrics' rule for custom fonts.+ for (const style of STYLES) {+ const large = typography[style][3];+ TEXT_SIZE_CATEGORIES.forEach((category, index) => {+ expect(large * dynamicTypeScale(style, category)).toBeCloseTo(+ typography[style][index],+ 10,+ );+ });+ }+ expect(dynamicTypeScale('body', 'ax5')).toBeCloseTo(53 / 17, 10);+ expect(dynamicTypeScale('largeTitle', 'xs')).toBeCloseTo(31 / 34, 10);+ });++ it('gives the page a category its scales on :root, Large and an unnamed size none', () => {+ expect(dynamicTypeScaleRule('l')).toBe('');+ expect(dynamicTypeScaleRule(null)).toBe('');+ const ax5 = dynamicTypeScaleRule('ax5');+ expect(ax5).toMatch(/\n:root \{\n {2}--_dynamic-type-/);+ expect(ax5).toContain(`${dynamicTypeScaleProperty('body')}: 3.1176;`);+ expect(ax5).toContain(`${dynamicTypeScaleProperty('largeTitle')}: 1.7647;`);+ expect(dynamicTypeScaleProperty('largeTitle')).toBe(+ '--_dynamic-type-large-title',+ );+ });++ it('scales only the raw font-size steps it is given at a length, each capped by the next', () => {+ expect(+ scaledFontSizeEntries({+ '--font-size-base': '1rem',+ '--font-size-5xl': '2.625rem',+ '--spacing-4': '1rem',+ }),+ ).toEqual([+ // Each step's scaled size is private; the step reads it.+ [+ '--_scaled-font-size-base',+ 'min(calc(1rem * var(--_dynamic-type-body, 1)), max(var(--_scaled-font-size-lg, 1rem), 1rem))',+ ],+ ['--font-size-base', 'var(--_scaled-font-size-base)'],+ // The largest step has nothing above it.+ [+ '--_scaled-font-size-5xl',+ 'calc(2.625rem * var(--_dynamic-type-large-title, 1))',+ ],+ ['--font-size-5xl', 'var(--_scaled-font-size-5xl)'],+ ]);+ // A step written as a variable or relative to its parent follows what it+ // reads, and the step below it is not capped by it.+ expect(+ scaledFontSizeEntries({+ '--font-size-base': '1rem',+ '--font-size-lg': 'var(--font-size-base)',+ '--font-size-xl': '1.25em',+ }),+ ).toEqual([+ ['--_scaled-font-size-base', 'calc(1rem * var(--_dynamic-type-body, 1))'],+ ['--font-size-base', 'var(--_scaled-font-size-base)'],+ ]);+ });++ it('keeps every ramp in order at every category, and its own sizes at Large', () => {+ // The ramps a theme gets from `typography.scale`: the neutral phone+ // profile, and the dense, default and airy starting points. A tight ramp+ // is the hard case: below Large, Body shrinks faster than Footnote (17 to+ // 14 against 13 to 12 at xs), so supporting text could pass body text.+ const ramps = [+ {base: 16, ratio: 1.1736},+ {base: 12, ratio: 1.125},+ {base: 14, ratio: 1.2},+ {base: 16, ratio: 1.25},+ ];+ const steps = Object.keys(FONT_SIZE_STEP_STYLES);+ for (const scale of ramps) {+ const theme = defineTheme({+ name: `dt-ramp-${scale.base}-${scale.ratio}`,+ typography: {scale},+ });+ const entries = scaledFontSizeEntries(theme.tokens);+ expect(+ entries.map(([name]) => name).filter(name => !name.startsWith('--_')),+ ).toEqual(steps);+ const own = steps.map(name => lengthInPx(theme.tokens[name]));+ for (const category of TEXT_SIZE_CATEGORIES) {+ const byName = sizesByName(entries, category);+ const sizes = steps.map(name => byName[name]);+ const ramp = `${scale.base}/${scale.ratio} at ${category}`;+ for (let index = 1; index < steps.length; index += 1) {+ expect(+ sizes[index],+ `${steps[index]}, ${ramp}`,+ ).toBeGreaterThanOrEqual(sizes[index - 1] - 1e-9);+ }+ if (category === 'l') {+ sizes.forEach((size, index) => {+ expect(size, `${steps[index]}, ${ramp}`).toBeCloseTo(own[index], 9);+ });+ }+ }+ }+ // Uncapped, heading 2 (Title 2) would pass heading 1 (Title 1) at AX5.+ const own = (index: number) => 16 * 1.1736 ** (index - 5);+ expect(own(7) * dynamicTypeScale('title2', 'ax5')).toBeGreaterThan(+ own(8) * dynamicTypeScale('title1', 'ax5'),+ );+ });+});++describe('every theme follows the reader text size', () => {+ /**+ * The value of `property` that wins where the media queries `holds` accepts+ * hold: the last declaration whose media queries all hold. Every declaration+ * a theme emits sits in its own scope at the same specificity, so source+ * order decides.+ */+ const winning = (+ css: string,+ property: string,+ holds: (query: string) => boolean,+ ): string | undefined => {+ const open: string[] = [];+ let value: string | undefined;+ for (const raw of css.split('\n')) {+ const line = raw.trim();+ if (line.endsWith('{') && !line.includes('}')) {+ open.push(line);+ } else if (line === '}') {+ open.pop();+ } else if (line.startsWith(`${property}:`)) {+ const media = open+ .filter(rule => rule.startsWith('@media '))+ .map(rule => rule.slice('@media '.length, -1).trim());+ if (media.every(holds)) {+ value = line.slice(property.length + 1, -1).trim();+ }+ }+ }+ return value;+ };+ const nowhere = () => false;+ const scaled = (name: string, value: string) =>+ `${name === '--font-size-5xl' ? '' : 'min('}calc(${value} * var(${dynamicTypeScaleProperty(FONT_SIZE_STEP_STYLES[name as keyof typeof FONT_SIZE_STEP_STYLES])}, 1))`;++ it('writes every font-size step a theme sets scaled, branded included, keeping its family', () => {+ for (const theme of [+ defineTheme({+ name: 'dt-scale',+ typography: {scale: {base: 15, ratio: 1.25}},+ }),+ defineTheme({+ name: 'dt-brand',+ typography: {+ scale: {base: 16, ratio: 1.2},+ body: {family: 'Outfit', fallbacks: 'sans-serif'},+ },+ }),+ ]) {+ const css = generateThemeCSS(theme).component;+ for (const name of Object.keys(textSizeDefaults)) {+ const value = theme.tokens[name];+ expect(value).toBeDefined();+ const step = scaledStepProperty(+ name as keyof typeof FONT_SIZE_STEP_STYLES,+ );+ expect(+ winning(css, step, nowhere)?.startsWith(scaled(name, value)),+ ).toBe(true);+ expect(winning(css, name, nowhere)).toBe(`var(${step})`);+ }+ // Only sizes follow the reader: no family, line height, spacing or+ // anything else reads a scale.+ const readers = [+ ...css.matchAll(/(--[a-z0-9_-]+|[a-z-]+): [^;]*--_dynamic-type-/g),+ ].map(match => match[1]);+ expect(readers.length).toBeGreaterThan(0);+ expect(+ readers.every(name =>+ /^--(_scaled-font-size-|text-[a-z0-9-]+-size$)/.test(name),+ ),+ ).toBe(true);+ }+ expect(+ winning(+ generateThemeCSS(+ defineTheme({+ name: 'dt-brand-family',+ typography: {body: {family: 'Outfit', fallbacks: 'sans-serif'}},+ }),+ ).component,+ '--font-family-body',+ nowhere,+ ),+ ).toContain('Outfit');+ });++ it('leaves a theme that sets no type scale on the sizes it inherits, already scaled', () => {+ // A nested theme with no type scale of its own keeps the outer theme's+ // sizes; at the top of the page they are the core defaults, which the+ // root stylesheet scales below every theme.+ const css = generateThemeCSS(+ defineTheme({name: 'dt-colors-only', tokens: {'--color-accent': 'red'}}),+ ).component;+ for (const name of Object.keys(textSizeDefaults)) {+ expect(winning(css, name, nowhere)).toBeUndefined();+ }+ const rule = dynamicTypeScaleRule('ax5');+ expect(rule.startsWith('@layer astryx-base {\n:root {')).toBe(true);+ for (const [name, value] of Object.entries(textSizeDefaults)) {+ const step = scaledStepProperty(+ name as keyof typeof FONT_SIZE_STEP_STYLES,+ );+ expect(rule).toContain(` ${step}: ${scaled(name, value)}`);+ expect(rule).toContain(` ${name}: var(${step});`);+ }+ });++ it('scales the sizes a theme writes for media surfaces (onDark, onLight)', () => {+ // A MediaTheme surface re-declares the theme's onDark or onLight tokens on+ // a descendant; written raw, they would undo the reader's text size there.+ const theme = defineTheme({+ name: 'dt-media',+ typography: {scale: {base: 14, ratio: 1.2}},+ onDark: {tokens: {'--font-size-base': '15px'}},+ onLight: {tokens: {'--text-supporting-size': '12px'}},+ });+ const css = generateOnMediaCSS(theme);+ const block = (surface: string) => {+ const start = css.indexOf(`[data-astryx-media="${surface}"] {`);+ expect(start, surface).toBeGreaterThan(-1);+ return css.slice(start, css.indexOf('}', start));+ };+ expect(block('dark')).toContain(+ '--_scaled-font-size-base: min(calc(15px * var(--_dynamic-type-body, 1)), max(var(--_scaled-font-size-lg, 15px), 15px));',+ );+ expect(block('dark')).toContain(+ '--font-size-base: var(--_scaled-font-size-base);',+ );+ expect(block('dark')).not.toMatch(/--font-size-base: 15px/);+ expect(block('light')).toContain(+ '--text-supporting-size: calc(12px * var(--_dynamic-type-footnote, 1));',+ );+ });++ it('adds no theme option, prop or document attribute', () => {+ defineTheme({+ name: 'dt-no-option',+ // @ts-expect-error following the reader text size is not an option+ typography: {dynamicType: true},+ });+ const css = generateThemeCSS(+ defineTheme({+ name: 'dt-attr',+ typography: {scale: {base: 14, ratio: 1.2}},+ }),+ ).component;+ // The theme reads only the private scales the root Theme provides.+ expect(css).not.toContain('data-astryx-text-size');+ expect(css).not.toMatch(/:root/);+ });++ it('scales the sizes an adaptation rule writes inside its own condition', () => {+ const theme = defineTheme({+ name: 'dt-phone',+ typography: {scale: {base: 14, ratio: 1.2}},+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse', width: {below: 'lg'}},+ value: {typography: {scale: {base: 16, ratio: 1.1736}}},+ },+ ],+ },+ });+ const css = generateThemeCSS(theme).component;+ const phone = (query: string) => query.includes('pointer: coarse');+ // A full ramp in order: each step is capped at the next one's scaled size.+ expect(winning(css, '--_scaled-font-size-base', phone)).toBe(+ 'min(calc(1rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg))',+ );+ expect(winning(css, '--_scaled-font-size-base', nowhere)).toBe(+ 'min(calc(0.875rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg))',+ );+ expect(winning(css, '--font-size-base', phone)).toBe(+ 'var(--_scaled-font-size-base)',+ );+ });++ it('scales a size the theme fixes on the curve of the step it reads', () => {+ // Butter, Stone and Y2K fix supporting text at 12px. Supporting text reads+ // --font-size-sm by default, so the fixed size scales like Footnote+ // instead of staying 12px while every step grows.+ const theme = defineTheme({+ name: 'dt-fixed',+ tokens: {'--text-supporting-size': '12px'},+ });+ const css = generateThemeCSS(theme).component;+ const value = winning(css, '--text-supporting-size', nowhere);+ expect(value).toBe('calc(12px * var(--_dynamic-type-footnote, 1))');+ for (const category of TEXT_SIZE_CATEGORIES) {+ expect(+ computedSizes([['--text-supporting-size', value ?? '']], category)[0],+ ).toBeCloseTo(12 * dynamicTypeScale('footnote', category), 6);+ }+ });++ it('keeps the size each adaptation rule writes, scaling it when the rule fixes it', () => {+ // Butter and Stone's shape: a fixed size at the root, and a phone rule+ // whose scale turns it back into a step.+ const theme = defineTheme({+ name: 'dt-fixed-rules',+ typography: {scale: {base: 14, ratio: 1.25}},+ tokens: {'--text-supporting-size': '12px'},+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse', width: {below: 'lg'}},+ value: {typography: {scale: {base: 16, ratio: 1.2225}}},+ },+ {+ when: {pointer: 'fine'},+ value: {tokens: {'--text-supporting-size': '13px'}},+ },+ ],+ },+ });+ const css = generateThemeCSS(theme).component;+ const phone = (query: string) => query.includes('pointer: coarse');+ const mouse = (query: string) => query.includes('pointer: fine');+ // Outside every rule, the root's fixed size scales.+ expect(winning(css, '--text-supporting-size', nowhere)).toBe(+ 'calc(12px * var(--_dynamic-type-footnote, 1))',+ );+ // On a phone the rule's step wins, and the step itself scales.+ expect(winning(css, '--text-supporting-size', phone)).toBe(+ 'var(--font-size-sm)',+ );+ // A rule that fixes the size gets it scaled inside its own condition.+ expect(winning(css, '--text-supporting-size', mouse)).toBe(+ 'calc(13px * var(--_dynamic-type-footnote, 1))',+ );+ });++ /**+ * The custom properties that win where `holds` accepts every media query,+ * with any `!important` dropped.+ */+ const winningAll = (+ css: string,+ holds: (query: string) => boolean,+ ): Map<string, string> => {+ const names = new Set(+ [...css.matchAll(/^\s*(--[a-z0-9_-]+):/gim)].map(match => match[1]),+ );+ const out = new Map<string, string>();+ for (const name of names) {+ const value = winning(css, name, holds);+ if (value !== undefined) {+ out.set(name, value.replace(/\s*!important$/, ''));+ }+ }+ return out;+ };+ /** The first reference cycle among the winning custom properties, if any. */+ const cycleIn = (properties: Map<string, string>): string[] | null => {+ const state = new Map<string, 'open' | 'done'>();+ const visit = (name: string, path: string[]): string[] | null => {+ if (state.get(name) === 'done' || !properties.has(name)) {+ return null;+ }+ if (state.get(name) === 'open') {+ return [...path.slice(path.indexOf(name)), name];+ }+ state.set(name, 'open');+ for (const [, next] of (properties.get(name) ?? '').matchAll(+ /var\((--[a-z0-9_-]+)/g,+ )) {+ const found = visit(next, [...path, name]);+ if (found) {+ return found;+ }+ }+ state.set(name, 'done');+ return null;+ };+ for (const name of properties.keys()) {+ const found = visit(name, []);+ if (found) {+ return found;+ }+ }+ return null;+ };+ const fontSizes = (properties: Map<string, string>) =>+ [...properties].filter(([name]) => /^--(_scaled-)?font-size-/.test(name));++ it('follows a step a theme writes as a variable, with no reference cycle', () => {+ // A scale whose large text is body text: the step follows what it reads,+ // unscaled, so nothing scales twice and no cap reads it back.+ const theme = defineTheme({+ name: 'dt-alias',+ typography: {scale: {base: 14, ratio: 1.2}},+ tokens: {'--font-size-lg': 'var(--font-size-base)'},+ });+ const css = generateThemeCSS(theme).component;+ expect(winning(css, '--font-size-lg', nowhere)).toBe(+ 'var(--font-size-base)',+ );+ expect(winning(css, '--_scaled-font-size-lg', nowhere)).toBeUndefined();+ // Body text, whose next step is now a variable, scales uncapped.+ expect(winning(css, '--_scaled-font-size-base', nowhere)).toBe(+ 'calc(0.875rem * var(--_dynamic-type-body, 1))',+ );+ const properties = winningAll(css, nowhere);+ expect(cycleIn(properties)).toBeNull();+ // Evaluated: the theme's own sizes at Large, its order at AX5.+ const large = sizesByName(fontSizes(properties), 'l');+ expect(large['--font-size-base']).toBeCloseTo(14, 9);+ expect(large['--font-size-lg']).toBeCloseTo(14, 9);+ expect(large['--font-size-sm']).toBeCloseTo(+ lengthInPx(theme.tokens['--font-size-sm']),+ 9,+ );+ const ax5 = sizesByName(fontSizes(properties), 'ax5');+ expect(ax5['--font-size-lg']).toBeCloseTo(ax5['--font-size-base'], 9);+ expect(ax5['--font-size-sm']).toBeLessThanOrEqual(+ ax5['--font-size-base'] + 1e-9,+ );+ });++ it('closes no reference cycle when an adaptation rule aliases a step the root writes at a length', () => {+ // A fixed ramp at the root, and a phone rule that makes large text body+ // text: on a phone the root's cap on body text reads the private scaled+ // size, never the rule's alias, so the two blocks form no loop.+ const theme = defineTheme({+ name: 'dt-alias-rule',+ typography: {scale: {base: 14, ratio: 1.2}},+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse', width: {below: 'lg'}},+ value: {tokens: {'--font-size-lg': 'var(--font-size-base)'}},+ },+ ],+ },+ });+ const css = generateThemeCSS(theme).component;+ const phone = (query: string) => query.includes('pointer: coarse');+ expect(winning(css, '--font-size-lg', phone)).toBe('var(--font-size-base)');+ for (const holds of [nowhere, phone]) {+ const properties = winningAll(css, holds);+ expect(cycleIn(properties)).toBeNull();+ for (const category of TEXT_SIZE_CATEGORIES) {+ expect(() =>+ sizesByName(fontSizes(properties), category),+ ).not.toThrow();+ }+ expect(+ sizesByName(fontSizes(properties), 'l')['--font-size-base'],+ ).toBeCloseTo(14, 9);+ }+ });++ it('emits no reference cycle with a step aliased at the root and its neighbour aliased in a rule', () => {+ const steps = Object.keys(FONT_SIZE_STEP_STYLES);+ const coarse = (query: string) => query.includes('pointer: coarse');+ const themes = [+ defineTheme({name: 'dt-acyclic-plain'}),+ defineTheme({+ name: 'dt-acyclic-scale',+ typography: {scale: {base: 15, ratio: 1.25}},+ }),+ // Each step aliased to the one below at the root, the next one aliased+ // to it in a rule.+ ...steps.slice(1).map((name, at) =>+ defineTheme({+ name: `dt-acyclic-alias-${at + 1}`,+ typography: {scale: {base: 14, ratio: 1.2}},+ tokens: {[name]: `var(${steps[at]})`},+ adaptations: {+ rules:+ at + 2 < steps.length+ ? [+ {+ when: {pointer: 'coarse'},+ value: {tokens: {[steps[at + 2]]: `var(${name})`}},+ },+ ]+ : [],+ },+ }),+ ),+ // A fixed ramp at the root and each step aliased to the one below in a+ // rule (the cross-block case, at every position).+ ...steps.slice(1).map((name, at) =>+ defineTheme({+ name: `dt-acyclic-rule-alias-${at + 1}`,+ typography: {scale: {base: 14, ratio: 1.2}},+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse'},+ value: {tokens: {[name]: `var(${steps[at]})`}},+ },+ ],+ },+ }),+ ),+ ];+ for (const theme of themes) {+ const css = generateThemeCSS(theme).component;+ for (const holds of [nowhere, coarse]) {+ expect(cycleIn(winningAll(css, holds)), theme.name).toBeNull();+ }+ }+ expect(+ cycleIn(winningAll(dynamicTypeScaleRule('ax5'), nowhere)),+ ).toBeNull();+ });++ it('keeps !important outside the scaling expression, on a fixed size and on a step', () => {+ // `!important` inside calc() makes the value invalid where it is used, so+ // the text would fall back to its parent's size in every browser.+ const css = generateThemeCSS(+ defineTheme({+ name: 'dt-important',+ tokens: {+ '--text-supporting-size': '12px !important',+ '--font-size-base': '1rem !important',+ },+ }),+ ).component;+ expect(winning(css, '--text-supporting-size', nowhere)).toBe(+ 'calc(12px * var(--_dynamic-type-footnote, 1)) !important',+ );+ const [[, plain]] = scaledFontSizeEntries({'--font-size-base': '1rem'});+ expect(winning(css, '--_scaled-font-size-base', nowhere)).toBe(plain);+ expect(winning(css, '--font-size-base', nowhere)).toBe(+ 'var(--_scaled-font-size-base) !important',+ );+ // The importance does not hide a length from the order check.+ expect(+ scaledFontSizeEntries({+ '--font-size-sm': '0.75rem',+ '--font-size-base': '0.875rem !important',+ }),+ ).toEqual([+ [+ '--_scaled-font-size-sm',+ 'min(calc(0.75rem * var(--_dynamic-type-footnote, 1)), var(--_scaled-font-size-base))',+ ],+ ['--font-size-sm', 'var(--_scaled-font-size-sm)'],+ [+ '--_scaled-font-size-base',+ 'min(calc(0.875rem * var(--_dynamic-type-body, 1)), max(var(--_scaled-font-size-lg, 0.875rem), 0.875rem))',+ ],+ ['--font-size-base', 'var(--_scaled-font-size-base) !important'],+ ]);+ for (const name of ['--text-supporting-size', '--_scaled-font-size-base']) {+ expect(+ winning(css, name, nowhere)?.replace(/ !important$/, ''),+ name,+ ).not.toContain('!important');+ }+ });++ it('scales only fixed sizes: a size that reads a variable or its parent is never scaled twice', () => {+ const tokens = {+ '--text-supporting-size': '0.75rem',+ '--text-heading-6-size': 'clamp(10px, 1vw + 6px, 12px)',+ '--text-heading-5-size': 'var(--font-size-xs)',+ '--text-label-size': 'calc(var(--font-size-base) + 1px)',+ '--text-code-size': '0.9em',+ '--text-large-size': '110%',+ };+ const css = generateThemeCSS(+ defineTheme({name: 'dt-fixed-only', tokens}),+ ).component;+ expect(winning(css, '--text-supporting-size', nowhere)).toBe(+ 'calc(0.75rem * var(--_dynamic-type-footnote, 1))',+ );+ expect(winning(css, '--text-heading-6-size', nowhere)).toBe(+ 'calc(clamp(10px, 1vw + 6px, 12px) * var(--_dynamic-type-caption1, 1))',+ );+ // The others keep what the theme wrote: a step already follows the+ // reader, and em or % follows the parent's size.+ for (const name of [+ '--text-heading-5-size',+ '--text-label-size',+ '--text-code-size',+ '--text-large-size',+ ] as const) {+ expect(winning(css, name, nowhere)).toBe(tokens[name]);+ }+ });++ it('lets a set size replace the phone base, smaller or larger, and scales the pinned role too', () => {+ // neutral's shape: a 14/1.2 scale whose phone rule moves the base to 16px+ // and pins Display 1 at its desktop 42px (design:mobile-typography DR1,+ // DR2). A size the reader set replaces that base and lifts the pin.+ const theme = defineTheme({+ name: 'dt-phone-profile',+ typography: {scale: {base: 14, ratio: 1.2}},+ adaptations: {+ rules: [+ {+ when: {pointer: 'coarse', width: {below: 'lg'}},+ value: {typography: {scale: {base: 16, ratio: 1.1736}}},+ },+ ],+ },+ });+ const phone = (+ theme as unknown as {+ __adaptationRules: {tokens: Record<string, string>}[];+ }+ ).__adaptationRules[0].tokens;+ const entries = scaledFontSizeEntries(phone);+ const at = (category: (typeof TEXT_SIZE_CATEGORIES)[number]) => {+ const sizes = computedSizes(entries, category);+ return Object.fromEntries(entries.map(([name], i) => [name, sizes[i]]));+ };+ // No size set: the phone base and the pinned Display 1 are the theme's.+ expect(at('l')['--font-size-base']).toBeCloseTo(16, 6);+ expect(at('l')['--font-size-5xl']).toBeCloseTo(42, 6);+ // A smaller size goes below the 16px base, a larger one above it.+ expect(at('xs')['--font-size-base']).toBeCloseTo((16 * 14) / 17, 6);+ expect(at('ax5')['--font-size-base']).toBeCloseTo((16 * 53) / 17, 6);+ // The pinned role scales too.+ expect(at('ax5')['--font-size-5xl']).toBeCloseTo((42 * 60) / 34, 6);+ });++ it('keeps the iOS text-entry floor: the root font size never changes, so text inputs stay at 16px', () => {+ // Only custom properties change, the root's font size never+ // (design:mobile-typography DR4): the page's rule declares nothing else.+ const rule = dynamicTypeScaleRule('xs');+ for (const line of rule.split('\n').filter(l => l.includes(':'))) {+ expect(line.trim().startsWith('--') || line.startsWith(':root')).toBe(+ true,+ );+ }+ // TextInput's iOS floor is 1rem, which therefore stays 16px however small+ // body text gets (family:input-fields FR9).+ const textInput = fs.readFileSync(+ path.resolve(__dirname, '../TextInput/TextInput.tsx'),+ 'utf8',+ );+ expect(textInput).toContain(+ "`max(1rem, ${typeScaleVars['--text-body-size']})`",+ );+ });+});++describe('the root sync', () => {+ const html = document.documentElement;+ let observerCallback: ((entries: {target: Element}[]) => void) | null = null;+ let probeSize = '17px';++ /** A stylesheet as the sync can see one: its whole text. */+ class FakeSheet {+ text = '';+ replaceSync(text: string) {+ this.text = text;+ }+ }++ /**+ * An engine as the sync can see it: whether it provides+ * `font: -apple-system-body` (the capability), whether it has a touch+ * callout (an iOS idiom the sync must not look at), and whether it can+ * construct a stylesheet for the document to adopt.+ */+ function pretendEngine({+ textSize,+ touchCallout = textSize,+ constructable = true,+ }: {+ textSize: boolean;+ touchCallout?: boolean;+ constructable?: boolean;+ }) {+ vi.stubGlobal('CSS', {+ supports: vi.fn((property: string, value?: string) =>+ property === 'font' && value === '-apple-system-body'+ ? textSize+ : property === '-webkit-touch-callout'+ ? touchCallout+ : false,+ ),+ });+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(callback: (entries: {target: Element}[]) => void) {+ observerCallback = callback;+ }+ observe() {}+ unobserve() {}+ disconnect() {+ observerCallback = null;+ }+ },+ );+ vi.stubGlobal('CSSStyleSheet', constructable ? FakeSheet : undefined);+ Object.defineProperty(document, 'adoptedStyleSheets', {+ configurable: true,+ writable: true,+ value: constructable ? [] : undefined,+ });+ const real = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element =>+ element instanceof HTMLElement &&+ element.hasAttribute('data-astryx-text-size-probe')+ ? ({fontSize: probeSize} as CSSStyleDeclaration)+ : real(element),+ );+ }++ /** The page's scales, from the stylesheets the document adopted. */+ const adoptedText = () =>+ ((document.adoptedStyleSheets ?? []) as unknown as FakeSheet[])+ .map(sheet => sheet.text)+ .join('');+ const htmlAttributes = () => html.getAttributeNames().sort().join(' ');++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ delete (document as {adoptedStyleSheets?: unknown}).adoptedStyleSheets;+ probeSize = '17px';+ });++ // The gate is the capability alone, never a platform idiom (one touch+ // behavior on every touch device).+ it('does nothing where the engine has no font: -apple-system-body, touch callout or not', () => {+ pretendEngine({textSize: false, touchCallout: true});+ expect(syncReaderTextSize(document)).toBeUndefined();+ expect(document.querySelector('[data-astryx-text-size-probe]')).toBeNull();+ expect(document.adoptedStyleSheets).toEqual([]);+ });++ it('follows the reader text size wherever the engine provides it, with no platform check', () => {+ pretendEngine({textSize: true, touchCallout: false});+ probeSize = '23px';+ const cleanup = syncReaderTextSize(document);+ expect(adoptedText()).toBe(dynamicTypeScaleRule('xxxl'));+ expect(adoptedText()).toContain(+ `${dynamicTypeScaleProperty('body')}: 1.3529;`,+ );+ cleanup?.();+ });++ it('scales nothing where the keyword follows no reader setting (a fixed 13px Body, as on a Mac)', () => {+ pretendEngine({textSize: true, touchCallout: false});+ probeSize = '13px';+ const cleanup = syncReaderTextSize(document);+ expect(cleanup).toBeTypeOf('function');+ expect(adoptedText()).toBe('');+ cleanup?.();+ });++ it('writes the scales, follows a change and cleans up, with an empty probe and nothing on <html>', () => {+ pretendEngine({textSize: true});+ const before = htmlAttributes();+ probeSize = '23px';+ const cleanup = syncReaderTextSize(document);+ const probe = document.querySelector<HTMLElement>(+ '[data-astryx-text-size-probe]',+ );+ if (probe == null) {+ throw new Error('The sync added no probe.');+ }+ // A hidden box, 1em square, that renders no text.+ expect(probe.getAttribute('aria-hidden')).toBe('true');+ expect(probe.style.getPropertyValue('visibility')).toBe('hidden');+ expect(probe.style.getPropertyValue('inline-size')).toBe('1em');+ expect(probe.textContent).toBe('');+ expect(adoptedText()).toBe(dynamicTypeScaleRule('xxxl'));++ // The reader moves the slider while the page is open: the probe resizes.+ probeSize = '53px';+ observerCallback?.([{target: probe}]);+ expect(adoptedText()).toBe(dynamicTypeScaleRule('ax5'));++ // A size that names no category clears the scales rather than guessing.+ probeSize = '18px';+ observerCallback?.([{target: probe}]);+ expect(adoptedText()).toBe('');+ expect(htmlAttributes()).toBe(before);++ cleanup?.();+ expect(document.adoptedStyleSheets).toEqual([]);+ expect(document.querySelector('[data-astryx-text-size-probe]')).toBeNull();+ expect(observerCallback).toBeNull();+ });++ it('shares one probe and one stylesheet among root Themes, and the last one out removes them', () => {+ pretendEngine({textSize: true});+ probeSize = '23px';+ const first = syncReaderTextSize(document);+ const second = syncReaderTextSize(document);+ expect(+ document.querySelectorAll('[data-astryx-text-size-probe]'),+ ).toHaveLength(1);+ expect(document.adoptedStyleSheets).toHaveLength(1);++ first?.();+ // A second call to the same cleanup releases nothing more.+ first?.();+ expect(+ document.querySelectorAll('[data-astryx-text-size-probe]'),+ ).toHaveLength(1);+ expect(adoptedText()).toBe(dynamicTypeScaleRule('xxxl'));++ second?.();+ expect(document.querySelector('[data-astryx-text-size-probe]')).toBeNull();+ expect(document.adoptedStyleSheets).toEqual([]);+ });++ it('does nothing where the engine cannot construct a stylesheet', () => {+ pretendEngine({textSize: true, constructable: false});+ probeSize = '53px';+ expect(syncReaderTextSize(document)).toBeUndefined();+ expect(document.querySelector('[data-astryx-text-size-probe]')).toBeNull();+ expect(document.querySelector('style')?.textContent ?? '').not.toContain(+ '--_dynamic-type-',+ );+ });+});diff --git a/packages/core/src/theme/dynamicType.ts b/packages/core/src/theme/dynamicType.tsnew file mode 100644index 0000000000..e06ff1e26b--- /dev/null+++ b/packages/core/src/theme/dynamicType.ts@@ -0,0 +1,419 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file dynamicType.ts+ * @input The UIKit point sizes per text style (uikitTypography.ts), the raw+ * font-size tokens (tokens.stylex.ts)+ * @output The reader's text size categories, the category a measured Body+ * size names, each raw font-size step's UIKit curve and scale, the rule that+ * gives a category its scales, the scaled raw font-size declarations every+ * theme emits and the semantic sizes it fixes, and the root Theme's text+ * size sync+ * @position Theme utility; read by generateThemeRules.ts (every theme's font+ * sizes, as it writes them) and Theme.tsx (the root provider keeps the+ * scales current)+ *+ * On iOS the reader picks a text size in Settings, and each UIKit text style+ * follows it on its own curve. Mobile Safari shows the choice only through+ * the `font: -apple-system-*` keywords, and the root font size stays 16px.+ * So the root Theme runtime keeps one hidden, empty probe with+ * `font: -apple-system-body` on `<body>`, reads the category from its size,+ * and gives the page that category's scales in an adopted stylesheet. It+ * reads again when the probe resizes. Each theme writes a font size as its+ * own value times the scale of the text style it plays, so only sizes move.+ * Every scale is 1 at the default category and in every other browser.+ * macOS Safari knows the keyword, but its fixed 13px Body names no category.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/theme/dynamicType.test.ts+ * - /packages/core/src/theme/generateThemeRules.ts (readerTextSizeEntries)+ */++import {typography} from './uikitTypography';+import {markTextSizeProbe} from '../privateAttributes/textSizeProbe.stylex';+import {observeResize} from '../utils/sharedResizeObserver';+import {textSizeDefaults, typeScaleDefaults} from './tokens.stylex';++// =============================================================================+// Categories+// =============================================================================++/**+ * The reader's text size categories, smallest to largest, in the order of the+ * UIKit typography table: the seven standard sizes, then the five+ * accessibility sizes Larger Accessibility Sizes unlocks. `l` (Large) is the+ * default.+ */+export const TEXT_SIZE_CATEGORIES = [+ 'xs',+ 's',+ 'm',+ 'l',+ 'xl',+ 'xxl',+ 'xxxl',+ 'ax1',+ 'ax2',+ 'ax3',+ 'ax4',+ 'ax5',+] as const;++/** One of the reader's text size categories. */+export type TextSizeCategory = (typeof TEXT_SIZE_CATEGORIES)[number];++/** Index of Large, the default category, in every table row. */+const LARGE = 3;++/**+ * The category whose Body size this is, or null when no category has it (a+ * size Safari does not produce, so nothing can be inferred from it). Body has+ * a distinct size in every category, so it names the category alone.+ */+export function textSizeCategoryForBodySize(+ px: number,+): TextSizeCategory | null {+ return TEXT_SIZE_CATEGORIES[columnForBodySize(px)] ?? null;+}++/** The table column whose Body size this is, or -1. */+function columnForBodySize(px: number): number {+ return typography.body.findIndex(size => Math.abs(size - px) < 0.5);+}++// =============================================================================+// Curves+// =============================================================================++/** A UIKit text style the theme's sizes can scale on. */+export type DynamicTypeStyle = keyof typeof typography;++/** A raw font-size token. */+export type FontSizeToken = keyof typeof textSizeDefaults;++/**+ * The UIKit text style each raw font-size step scales like. A step follows+ * the style of the roles built on it: the base step carries body, label, code+ * and heading 4 (Body); one step up, heading 3 and large text (Title 3); then+ * heading 2 (Title 2), heading 1 and display 3 (Title 1), display 2 and 1+ * (Large Title); one step down, supporting text and heading 5 (Footnote,+ * supporting text being the common one); heading 6 (Caption 1); the sub-scale+ * steps (Caption 2).+ */+export const FONT_SIZE_STEP_STYLES = {+ '--font-size-4xs': 'caption2',+ '--font-size-3xs': 'caption2',+ '--font-size-2xs': 'caption2',+ '--font-size-xs': 'caption1',+ '--font-size-sm': 'footnote',+ '--font-size-base': 'body',+ '--font-size-lg': 'title3',+ '--font-size-xl': 'title2',+ '--font-size-2xl': 'title1',+ '--font-size-3xl': 'title1',+ '--font-size-4xl': 'largeTitle',+ '--font-size-5xl': 'largeTitle',+} as const satisfies Record<FontSizeToken, DynamicTypeStyle>;++/** How much `style` grows (or shrinks) at `category`, relative to Large. */+export function dynamicTypeScale(+ style: DynamicTypeStyle,+ category: TextSizeCategory,+): number {+ const row = typography[style];+ return row[TEXT_SIZE_CATEGORIES.indexOf(category)] / row[LARGE];+}++/** The custom property that carries `style`'s scale. The root Theme's stylesheet sets it on `:root`. */+export function dynamicTypeScaleProperty(style: DynamicTypeStyle): string {+ return `--_dynamic-type-${style.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`)}`;+}++/** The styles some step scales on, in table order. */+const SCALED_STYLES = (Object.keys(typography) as DynamicTypeStyle[]).filter(+ style => Object.values(FONT_SIZE_STEP_STYLES).includes(style as never),+);++// =============================================================================+// CSS+// =============================================================================++/** A scale written to four decimals, without trailing zeros. */+function formatScale(scale: number): string {+ return String(Number(scale.toFixed(4)));+}++/**+ * The rule that gives the page a category's scales, for the root Theme's+ * stylesheet: one custom property per scaled style on `:root`. Large, and a+ * size that names no category, need none: every scaled declaration falls back+ * to 1.+ */+export function dynamicTypeScaleRule(+ category: TextSizeCategory | null,+): string {+ return scaleRuleForColumn(+ category === null ? -1 : TEXT_SIZE_CATEGORIES.indexOf(category),+ );+}++/**+ * The rule for one table column. Large and -1 get none. It also scales Core's+ * default steps in the base layer, below every theme. So a page or theme with+ * no type scale follows too.+ */+function scaleRuleForColumn(column: number): string {+ if (column < 0 || column === LARGE) {+ return '';+ }+ const declarations = (entries: [string, string][]) =>+ entries.map(([name, value]) => ` ${name}: ${value};`).join('\n');+ return `@layer astryx-base {\n:root {\n${declarations(scaledFontSizeEntries(textSizeDefaults))}\n}\n}\n:root {\n${declarations(+ SCALED_STYLES.map(style => [+ dynamicTypeScaleProperty(style),+ formatScale(typography[style][column] / typography[style][LARGE]),+ ]),+ )}\n}`;+}++/**+ * The private custom property holding a step's scaled size+ * (`--_scaled-font-size-base`). Only this module writes it, and only from a+ * fixed length, so the cap that reads the next step's can never read back a+ * variable a theme wrote: a theme that sets `--font-size-lg` to+ * `var(--font-size-base)`, at its root or in any adaptation rule, closes no+ * reference cycle.+ */+export function scaledStepProperty(step: FontSizeToken): string {+ return `--_scaled-${step.slice(2)}`;+}++/**+ * The raw font-size writes a theme scales: for each step among `tokens` set+ * to a fixed length (`isFixedSize`), its private scaled size (the value times+ * its curve's scale, 1 when no category is set) and the step itself reading+ * it, as `[token, value]` pairs. A step written as a variable or relative to+ * its parent is left as written: it follows what it reads, so it never scales+ * twice. The caller emits them through its declaration checks.+ *+ * A step never outgrows the step above it. UIKit's curves differ: above+ * Large its smaller styles grow faster than its larger ones (a theme whose+ * ramp is tighter than UIKit's would see heading 2 pass heading 1 at the+ * largest accessibility sizes), and below Large Body shrinks faster than+ * Footnote (supporting text could pass body text). So each step is capped at+ * the next step's scaled size. When the theme's own step is no larger than+ * its next one, as in every ramp `typography.scale` generates, that cap is+ * the theme's own size at Large and binds at every other category; for a+ * ramp that is out of order, or a next step this block does not set (it+ * keeps the scaled size it inherits), the cap never goes below the step's own+ * size, so the theme's sizes at Large stay exactly its own. A next step the+ * block writes as a variable caps nothing: the theme tied it to what it reads.+ */+export function scaledFontSizeEntries(+ tokens: Record<string, string>,+): [string, string][] {+ const steps = Object.keys(FONT_SIZE_STEP_STYLES) as FontSizeToken[];+ const fixedValue = (name: FontSizeToken | undefined) => {+ const [value, important] = splitImportant((name && tokens[name]) || '');+ return isFixedSize(value) ? {value, important} : null;+ };+ return steps.flatMap((name, index): [string, string][] => {+ const own = fixedValue(name);+ if (own === null) {+ return [];+ }+ const {value, important} = own;+ const scaled = `calc(${value} * var(${dynamicTypeScaleProperty(FONT_SIZE_STEP_STYLES[name])}, 1))`;+ const next = steps[index + 1];+ const nextOwn = fixedValue(next);+ let expression = scaled;+ if (next !== undefined && (tokens[next] === undefined || nextOwn)) {+ const ownPx = lengthInPx(value);+ const nextPx = nextOwn && lengthInPx(nextOwn.value);+ expression =+ ownPx !== null && nextPx != null && ownPx <= nextPx+ ? `min(${scaled}, var(${scaledStepProperty(next)}))`+ : `min(${scaled}, max(var(${scaledStepProperty(next)}, ${value}), ${value}))`;+ }+ return [+ [scaledStepProperty(name), expression],+ [name, `var(${scaledStepProperty(name)})${important}`],+ ];+ });+}++/**+ * The raw step each semantic font size reads in the core defaults+ * (`--text-supporting-size` reads `--font-size-sm`), in their order.+ */+const TEXT_SIZE_STEPS = Object.entries(typeScaleDefaults).flatMap(+ ([name, value]): [string, FontSizeToken][] => {+ const step = /^var\((--font-size-[a-z0-9]+)\)$/.exec(value)?.[1];+ return name.endsWith('-size') &&+ step !== undefined &&+ step in FONT_SIZE_STEP_STYLES+ ? [[name, step as FontSizeToken]]+ : [];+ },+);++/**+ * Whether a size stays where the theme put it. That is a length, such as+ * `12px`, `0.75rem` or a `clamp()` of them, that reads no variable. Sizes in+ * `em` or `%` follow the parent.+ */+function isFixedSize(value: string): boolean {+ return (+ /\d[a-z]/i.test(value) && !/var\(|%|\d(?:em|ex|ch|ic|cap|lh)\b/i.test(value)+ );+}++/**+ * A block's token declarations, in order, with its font sizes following the+ * reader's text size: each raw font-size step it writes at a fixed length+ * becomes its private scaled size and the step reading it+ * (`scaledFontSizeEntries`), and each semantic size (`--text-*-size`) it+ * fixes at a length becomes that length times the scale of the step that+ * size reads by default, so supporting text fixed at `12px` scales like+ * Footnote. A size that reads a variable follows what it reads, and one+ * relative to its parent (`em`, `%`) follows the parent, so neither scales+ * twice; a fixed size is not capped, since the theme that fixes it also fixes+ * its place in the hierarchy. A step the block does not write keeps the value+ * it inherits, already scaled. A value written `!important` stays important.+ * Every other declaration keeps its value and its place.+ */+export function readerTextSizeEntries(+ entries: ReadonlyArray<readonly [string, string]>,+): [string, string][] {+ const scaled = new Map(scaledFontSizeEntries(Object.fromEntries(entries)));+ const fixedSteps = new Map(TEXT_SIZE_STEPS);+ return entries.flatMap(([name, raw]): [string, string][] => {+ const step = scaled.get(name);+ if (step !== undefined) {+ const property = scaledStepProperty(name as FontSizeToken);+ return [+ [property, scaled.get(property) ?? ''],+ [name, step],+ ];+ }+ const [value, important] = splitImportant(raw);+ const reads = fixedSteps.get(name);+ return [+ [+ name,+ reads !== undefined && isFixedSize(value)+ ? `calc(${value} * var(${dynamicTypeScaleProperty(FONT_SIZE_STEP_STYLES[reads])}, 1))${important}`+ : raw,+ ],+ ];+ });+}++/**+ * A value and its trailing `!important`, apart. `!important` inside `calc()`+ * makes the value invalid. So the scale wraps only the value, and+ * `!important` goes after the expression.+ */+function splitImportant(value: string): [string, string] {+ const match = /\s*!\s*important\s*$/i.exec(value);+ return match ? [value.slice(0, match.index), ' !important'] : [value, ''];+}++/** A `px` or `rem` length in px (16px to the rem); null for anything else. */+function lengthInPx(value: string | undefined): number | null {+ const match = /^(-?\d*\.?\d+)(px|rem)$/.exec(value?.trim() ?? '');+ if (match == null) {+ return null;+ }+ return Number(match[1]) * (match[2] === 'rem' ? 16 : 1);+}++// =============================================================================+// Root sync+// =============================================================================++/**+ * Measure the reader's text size and give the page its scales; returns the+ * cleanup. Does nothing where the engine has no `font: -apple-system-body` or+ * cannot construct a stylesheet (every supported browser that has the keyword+ * can); where its Body size names no category (macOS Safari's fixed 13px),+ * every scale stays 1.+ *+ * The probe is a hidden, empty `font: -apple-system-body` box, 1em square,+ * appended to `<body>` outside every app subtree: it renders no text, and it+ * resizes when the reader's text size changes, which is when the size is read+ * again. The scales go to a stylesheet the document adopts, so nothing else is+ * added to the DOM or written on `<html>`. A document has one probe and one+ * stylesheet however many root Themes it holds: they share them, and the last+ * one to go removes them.+ */+export function syncReaderTextSize(doc: Document): (() => void) | undefined {+ let shared = sharedSyncs.get(doc);+ if (shared == null) {+ const stop = startReaderTextSizeSync(doc);+ if (stop == null) {+ return undefined;+ }+ shared = {holders: 0, stop};+ sharedSyncs.set(doc, shared);+ }+ shared.holders += 1;+ const held = shared;+ let isReleased = false;+ return () => {+ if (isReleased) {+ return;+ }+ isReleased = true;+ held.holders -= 1;+ if (held.holders === 0) {+ sharedSyncs.delete(doc);+ held.stop();+ }+ };+}++/** Each document's shared probe and stylesheet, and how many roots hold them. */+const sharedSyncs = new WeakMap<+ Document,+ {holders: number; stop: () => void}+>();++function startReaderTextSizeSync(doc: Document): (() => void) | undefined {+ const view = doc.defaultView;+ if (+ !view?.CSS?.supports?.('font', '-apple-system-body') ||+ typeof view.CSSStyleSheet !== 'function' ||+ !Array.isArray(doc.adoptedStyleSheets)+ ) {+ return undefined;+ }++ const probe = doc.createElement('span');+ probe.setAttribute('aria-hidden', 'true');+ markTextSizeProbe(probe);+ probe.style.cssText =+ 'position:fixed;inset:0 auto auto 0;inline-size:1em;block-size:1em;visibility:hidden;pointer-events:none;font:-apple-system-body';+ (doc.body ?? doc.documentElement).append(probe);++ const sheet = new view.CSSStyleSheet();+ doc.adoptedStyleSheets = [...doc.adoptedStyleSheets, sheet];+ const read = () =>+ sheet.replaceSync(+ scaleRuleForColumn(+ columnForBodySize(+ Number.parseFloat(view.getComputedStyle(probe).fontSize),+ ),+ ),+ );+ // observeResize reads once now and again whenever the probe resizes.+ const stopObserving = observeResize(probe, read);++ return () => {+ stopObserving();+ probe.remove();+ doc.adoptedStyleSheets = doc.adoptedStyleSheets.filter(+ adopted => adopted !== sheet,+ );+ };+}diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.tsindex 5ec4f08246..bd66ed0896 100644--- a/packages/core/src/theme/generateThemeRules.test.ts+++ b/packages/core/src/theme/generateThemeRules.test.ts@@ -91,9 +91,17 @@ describe('generateThemeRules', () => {it('includes :scope token block with type scale tokens', () => {const scopeRule = rules.find(r => r.includes(':scope'));expect(scopeRule).toBeDefined();- // Raw size tokens are rem values- expect(scopeRule).toContain('--font-size-base: 0.875rem');- expect(scopeRule).toContain('--font-size-2xl: 1.5rem');+ // Raw size tokens are rem values, scaled by the reader's text size where+ // the root Theme gives the page one (spec:AST-102 FR3; 1 elsewhere)+ expect(scopeRule).toContain(+ '--_scaled-font-size-base: min(calc(0.875rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg))',+ );+ expect(scopeRule).toContain(+ '--font-size-base: var(--_scaled-font-size-base)',+ );+ expect(scopeRule).toContain(+ '--_scaled-font-size-2xl: min(calc(1.5rem * var(--_dynamic-type-title1, 1)), var(--_scaled-font-size-3xl))',+ );// Semantic tokens are var() refsexpect(scopeRule).toContain('--text-heading-1-size: var(--font-size-2xl)');expect(scopeRule).toContain('--text-heading-4-size: var(--font-size-base)');@@ -118,9 +126,16 @@ describe('generateThemeRules', () => {'--font-size-4xl',];for (const token of rawSizeTokens) {- const match = scopeRule.match(new RegExp(`${token}: ([^;]+)`));+ const match = scopeRule.match(new RegExp(`\\s${token}: ([^;]+)`));expect(match).not.toBeNull();- expect(match![1]).toMatch(/rem$/);+ // The step reads its private scaled size: the theme's own rem value,+ // times the reader's scale for its step.+ const scaled = `--_scaled-${token.slice(2)}`;+ expect(match![1]).toBe(`var(${scaled})`);+ const own = scopeRule.match(new RegExp(`${scaled}: ([^;]+)`));+ expect(own![1]).toMatch(+ /^min\(calc\([\d.]+rem \* var\(--_dynamic-type-[a-z0-9-]+, 1\)\), var\(--_scaled-font-size-[a-z0-9]+\)\)$/,+ );}});diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.tsindex 6c8e290081..9cc9d299aa 100644--- a/packages/core/src/theme/generateThemeRules.ts+++ b/packages/core/src/theme/generateThemeRules.ts@@ -42,6 +42,7 @@ import {checkDeclarationName,checkDeclarationValue,} from './declarationBoundary';+import {readerTextSizeEntries} from './dynamicType';import {PRESS_BELIEVED_SELECTOR} from '../privateAttributes/press';/**@@ -1015,7 +1016,13 @@ function tokenBlock(tokenEntries: [string, string][] = Object.entries(source.tokens),): string | null {const declarations = [- joinDeclarations(tokenEntries, `${location}tokens`, sink),+ // Font sizes follow the reader's text size where the root Theme sets the+ // scales. Elsewhere each scale is 1.+ joinDeclarations(+ readerTextSizeEntries(tokenEntries),+ `${location}tokens`,+ sink,+ ),joinDeclarations(Object.entries(source.localTokens ?? {}),`${location}localTokens`,@@ -1726,8 +1733,10 @@ export function generateOnMediaCSS(...statusRoleDefaults,];if (tokenEntries.length > 0) {+ // The surface re-declares font sizes the way a theme's root does, so they+ // keep following the reader's text size there (see dynamicType.ts).const declarations = joinDeclarations(- tokenEntries,+ readerTextSizeEntries(tokenEntries),`${location}tokens`,sink,);diff --git a/packages/core/src/theme/themeAdaptations.test.ts b/packages/core/src/theme/themeAdaptations.test.tsindex 1f9de2df3a..b68e5786cd 100644--- a/packages/core/src/theme/themeAdaptations.test.ts+++ b/packages/core/src/theme/themeAdaptations.test.ts@@ -830,7 +830,12 @@ describe('adapted type-scale component defaults', () => {expect(rule.tokens['--font-size-5xl']).not.toBe(theme.tokens['--font-size-5xl'],);- expect(adaptiveCSS).toContain('--font-size-base: 0.875rem');+ expect(adaptiveCSS).toContain(+ '--_scaled-font-size-base: min(calc(0.875rem * var(--_dynamic-type-body, 1)), var(--_scaled-font-size-lg))',+ );+ expect(adaptiveCSS).toContain(+ '--font-size-base: var(--_scaled-font-size-base)',+ );// The root owns the var() wiring and its authored overrides. Re-emitting// either would turn an unrelated scale change into a component write.expect(rule.components).toBeUndefined();diff --git a/packages/core/src/theme/uikitTypography.ts b/packages/core/src/theme/uikitTypography.tsnew file mode 100644index 0000000000..93b0ffabcb--- /dev/null+++ b/packages/core/src/theme/uikitTypography.ts@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file uikitTypography.ts+ * @input Nothing; data only+ * @output Exports `typography`: the point size of each UIKit text style at each+ * content size category (Dynamic Type), from xSmall to AX5+ * @position Theme data: theme/dynamicType.ts scales a theme's own type scale+ * on these curves when the reader changes their text size.+ *+ * Every row lists the twelve content size categories in order: xSmall, Small,+ * Medium, Large (the default), xLarge, xxLarge, xxxLarge, then the five+ * accessibility sizes AX1–AX5 that Larger Accessibility Sizes unlocks. A row+ * is what `UIFont.preferredFont(forTextStyle:compatibleWith:)` returns for that+ * style, and what Mobile Safari computes for the matching+ * `font: -apple-system-*` keyword (`title0` is Large Title, `title1`–`title3`+ * are Title 1–3).+ *+ * Only the styles a theme role scales on are listed (theme/dynamicType.ts maps+ * each raw font-size step to one of them).+ *+ * Every row carries one or more `@source`: Apple's documentation, a WWDC+ * session, WebKit's own source, or a measurement naming its subject, the iOS+ * version and the date. dynamicType.test.ts enforces it.+ *+ * SYNC: When modified, update /packages/core/src/theme/dynamicType.ts+ */++export const typography = {+ /**+ * Large Title, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-title0` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ largeTitle: [31, 32, 33, 34, 36, 38, 40, 44, 48, 52, 56, 60],+ /**+ * Title 1, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-title1` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ title1: [25, 26, 27, 28, 30, 32, 34, 38, 43, 48, 53, 58],+ /**+ * Title 2, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-title2` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ title2: [19, 20, 21, 22, 24, 26, 28, 34, 39, 44, 50, 56],+ /**+ * Title 3, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-title3` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ title3: [17, 18, 19, 20, 22, 24, 26, 31, 37, 43, 49, 55],+ /**+ * Body, in points per content size category (xSmall … AX5). Every+ * category has its own Body size, so Body alone identifies the category.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-body` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ body: [14, 15, 16, 17, 19, 21, 23, 28, 33, 40, 47, 53],+ /**+ * Footnote, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-footnote` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ footnote: [12, 12, 12, 13, 15, 17, 19, 23, 27, 33, 38, 44],+ /**+ * Caption 1, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-caption1` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ caption1: [11, 11, 11, 12, 14, 16, 18, 22, 26, 32, 37, 43],+ /**+ * Caption 2, in points per content size category (xSmall … AX5).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIFont.preferredFont(forTextStyle:compatibleWith:) at+ * each content size category, Oct 23 2026+ * @source measured: Mobile Safari, iOS 26.2 simulator, iPhone 17 Pro,+ * computed font-size of `font: -apple-system-caption2` at each category,+ * Oct 24 2026+ * @source apple-docs https://developer.apple.com/design/human-interface-guidelines/typography+ */+ caption2: [11, 11, 11, 11, 13, 15, 17, 20, 24, 29, 34, 40],+} as const;