An open source design system that's fully customizable and agent ready
TypeScript
chore(core): the touch motion tables register FR4's roles as internal motion roles (#8257)
Christopher Chedeau61480b5c2f4e
diff --git a/.changeset/touch-motion-theme-roles.md b/.changeset/touch-motion-theme-roles.mdnew file mode 100644index 0000000000..02eb1ec171--- /dev/null+++ b/.changeset/touch-motion-theme-roles.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the touch motion tables register their springs, durations and curves as internal motion roles, each read once when a motion starts, so every component keeps its measured value. Nothing public changes: themes do not set motion roles, and no shipped component reads the roles yet.++@vjeuxdiff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.mdindex 1de471ca79..03e0e801d0 100644--- a/packages/core/src/motion/README.md+++ b/packages/core/src/motion/README.md@@ -5,8 +5,9 @@ UIKit constants table (every spring, duration, deceleration rate, rubber-bandconstant, curve and gesture threshold a touch presentation uses, each with itssource) and the spring, decay, rubber-band and projection math UIKit uses.Nothing here is exported from the package entry point. Core's motion and-gesture modules read the table by path; components take touch motion from the-theme's motion roles (`spec:AST-094` FR4), not from this table.+gesture modules read the table by path; components read touch motion through+its internal motion roles (`roles.ts`), so each keeps its measured value; no+shipped component reads the roles yet.## Filesdiff --git a/packages/core/src/motion/roleValue.ts b/packages/core/src/motion/roleValue.tsnew file mode 100644index 0000000000..2ca32e922b--- /dev/null+++ b/packages/core/src/motion/roleValue.ts@@ -0,0 +1,105 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file roleValue.ts+ * @input A role id, or a role's kind and value+ * @output isMotionRoleId, motionRoleVariable and formatMotionRoleValue (a+ * role value's CSS form), with the role kinds+ * @position The value half of the internal motion roles: no registry and+ * no parsing. roles.ts holds the registry and re-exports these.+ *+ * SYNC: When modified, update /packages/core/src/motion/roles.test.ts.+ */++import {durationBounceOf, toSpring, type SpringDescription} from './spring';++/** The three kinds of value a role can hold. */+export type MotionRoleKind = 'spring' | 'duration' | 'curve';++/** Cubic-bézier control points `[x1, y1, x2, y2]`. */+export type MotionCurvePoints = readonly [number, number, number, number];++const ROLE_ID = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;++/** Whether `id` is a well-formed role name (a dotted table path). */+export function isMotionRoleId(id: string): boolean {+ return ROLE_ID.test(id);+}++/** The CSS custom property for a role: `--motion-` + the path in kebab case. */+export function motionRoleVariable(id: string): string {+ if (!isMotionRoleId(id)) {+ throw new Error(+ `motion role "${id}" must be a dotted table path such as "springs.sheetPresent"`,+ );+ }+ return `--motion-${id+ .split('.')+ .map(part => part.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`))+ .join('-')}`;+}++export function isSpring(value: unknown): value is SpringDescription {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ return false;+ }+ return (+ ('response' in value && 'dampingRatio' in value) ||+ ('duration' in value && 'bounce' in value) ||+ ('stiffness' in value && 'damping' in value)+ );+}++export function isCurve(value: unknown): value is MotionCurvePoints {+ return (+ Array.isArray(value) &&+ value.length === 4 &&+ value.every(n => typeof n === 'number')+ );+}++/** Six significant digits: enough for any motion, free of float noise. */+export function short(n: number): string {+ return String(Number(n.toPrecision(6)));+}++/**+ * A role value as its CSS custom property holds it:+ * - spring: SwiftUI's duration and bounce, `0.5s 0.15` (exact for every+ * spring: mass folds into the duration, overdamping into a negative bounce);+ * - duration: `250ms`;+ * - curve: `cubic-bezier(0.42, 0, 0.58, 1)`, usable as is in CSS.+ * Throws on a value that is not a valid value of its kind.+ */+export function formatMotionRoleValue(+ kind: MotionRoleKind,+ value: unknown,+): string {+ if (kind === 'spring') {+ if (!isSpring(value)) {+ throw new TypeError(+ 'a spring is {response, dampingRatio}, {duration, bounce} or {mass?, stiffness, damping}',+ );+ }+ const {duration, bounce} = durationBounceOf(toSpring(value));+ if (!(bounce < 1)) {+ throw new RangeError(+ 'a spring must settle: its bounce must be below 1 (a damping ratio above 0)',+ );+ }+ return `${short(duration)}s ${short(bounce)}`;+ }+ if (kind === 'duration') {+ if (!(typeof value === 'number' && Number.isFinite(value) && value >= 0)) {+ throw new TypeError('a duration is a finite number of milliseconds ≥ 0');+ }+ return `${short(value)}ms`;+ }+ if (!isCurve(value) || !value.every(Number.isFinite)) {+ throw new TypeError('a curve is four finite numbers [x1, y1, x2, y2]');+ }+ if (value[0] < 0 || value[0] > 1 || value[2] < 0 || value[2] > 1) {+ throw new RangeError("a curve's x1 and x2 must lie in [0, 1]");+ }+ return `cubic-bezier(${value.map(short).join(', ')})`;+}diff --git a/packages/core/src/motion/roles.test.ts b/packages/core/src/motion/roles.test.tsnew file mode 100644index 0000000000..d3f8b1003c--- /dev/null+++ b/packages/core/src/motion/roles.test.ts@@ -0,0 +1,256 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file roles.test.ts+ * @input roles.ts and the shared UIKit tables (registered on import)+ * @output Proof that each spring, duration and curve of a registered table is+ * a role named by its path, that non-motion values are not, and that a+ * role's CSS value reads back as the same motion+ * @position Testing for /packages/core/src/motion/roles.ts+ */++import {readFileSync} from 'node:fs';+import {resolve} from 'node:path';+import {describe, expect, it} from 'vitest';+import {+ formatMotionRoleValue,+ isMotionRoleId,+ listMotionRoles,+ motionRoleIn,+ motionRoleOf,+ motionRoleVariable,+ parseMotionRoleValue,+ registerMotionTable,+} from './roles';+import {dampingRatioOf, naturalFrequency, toSpring} from './spring';+import {navigation, scroll, springs, timing} from './uikit';+import {+ motionTableFiles,+ REGISTER_EXPORT,+} from '../../../../scripts/motion-table-files.mjs';++// Every table the role list is generated from, registered the way the+// generator does: through each module's register<Name>Table.+for (const file of motionTableFiles(resolve(__dirname, '..'))) {+ const module = (await import(file)) as Record<string, unknown>;+ for (const [name, value] of Object.entries(module)) {+ if (REGISTER_EXPORT.test(name) && typeof value === 'function') {+ (value as () => void)();+ }+ }+}+// The tables that discovery registered, before any test adds a fixture.+const DISCOVERED = new Set(+ listMotionRoles().map(role => role.id.split('.')[0]),+);++describe('motion roles', () => {+ it('names a role by its table path, and its CSS variable in kebab case', () => {+ expect(isMotionRoleId('sheet.present')).toBe(true);+ expect(isMotionRoleId('timing.curves.move')).toBe(true);+ expect(isMotionRoleId('sheet')).toBe(false);+ expect(isMotionRoleId('Sheet.present')).toBe(false);+ expect(motionRoleVariable('springs.sheetDetent')).toBe(+ '--motion-springs-sheet-detent',+ );+ expect(motionRoleVariable('timing.curves.move')).toBe(+ '--motion-timing-curves-move',+ );+ expect(() => motionRoleVariable('sheet')).toThrow(/dotted table path/);+ });++ it('leaves a table value FR4 does not name an internal constant', () => {+ const shared = {response: 0.4, dampingRatio: 0.9};+ const table = {+ present: shared,+ dismiss: shared,+ fadeMs: 200,+ curves: {out: [0, 0, 0.58, 1] as const},+ };+ registerMotionTable('fixture', table);+ // No role, no CSS variable, and the table is untouched.+ expect(motionRoleOf(table.present)).toBeUndefined();+ expect(table.dismiss).toBe(table.present);+ expect(motionRoleIn(table, 'fadeMs')).toBeUndefined();+ expect(motionRoleOf(table.curves.out)).toBeUndefined();+ expect(listMotionRoles().some(role => role.id.startsWith('fixture.'))).toBe(+ false,+ );+ });++ it('has exactly the roles spec:AST-094 FR4 names', () => {+ const spec = readFileSync(+ resolve(+ __dirname,+ '../../../../docs/specs/AST-094-touch-presentations/spec.md',+ ),+ 'utf8',+ );+ const fr4 = spec.slice(spec.indexOf('**FR4'), spec.indexOf('**FR5'));+ const named = [...fr4.matchAll(/^\s*\| `([a-z][\w.]*)`\s*\|/gm)].map(+ match => match[1],+ );+ expect(named.length).toBeGreaterThan(0);+ // Every table registered, the roles are exactly FR4's (other tests+ // here register a fixture, which lists none).+ expect(new Set(listMotionRoles().map(role => role.id))).toEqual(+ new Set(named),+ );+ });++ it('names the shared roles for their use, as spec:AST-094 FR4 does', () => {+ expect(+ [+ springs.fingerTracking,+ springs.emphasis,+ springs.settle,+ springs.quickChange,+ springs.viewChange,+ springs.timedChange,+ springs.stateChange,+ springs.directChange,+ springs.menuOpen,+ springs.menuClose,+ timing.curves.viewChange,+ timing.curves.exit,+ timing.curves.entrance,+ timing.curves.move,+ ].map(leaf => motionRoleOf(leaf)?.id),+ ).toEqual([+ 'springs.fingerTracking',+ 'springs.emphasis',+ 'springs.settle',+ 'springs.quickChange',+ 'springs.viewChange',+ 'springs.timedChange',+ 'springs.stateChange',+ 'springs.directChange',+ 'springs.menuOpen',+ 'springs.menuClose',+ 'timing.curves.viewChange',+ 'timing.curves.exit',+ 'timing.curves.entrance',+ 'timing.curves.move',+ ]);+ expect(motionRoleIn(timing, 'stateChangeMs')?.id).toBe(+ 'timing.stateChangeMs',+ );+ // A preset or curve-shape name is no role id.+ for (const old of [+ 'springs.smooth',+ 'springs.bouncy',+ 'timing.curves.easeInOut',+ 'timing.implicitAnimationMs',+ ]) {+ expect(listMotionRoles().map(role => role.id)).not.toContain(old);+ }+ });++ it("leaves the keyboard's motion out: it rides the keyboard (FR4)", () => {+ expect(motionRoleOf(springs.keyboard)).toBeUndefined();+ expect(motionRoleIn(timing, 'keyboardNotificationMs')).toBeUndefined();+ });++ it('refuses a spring that never settles', () => {+ expect(() =>+ formatMotionRoleValue('spring', {duration: 0.5, bounce: 1}),+ ).toThrow(/must settle/);+ expect(() =>+ formatMotionRoleValue('spring', {response: 0.5, dampingRatio: 0}),+ ).toThrow(/must settle/);+ expect(parseMotionRoleValue('spring', '0.5s 1')).toBeNull();+ });++ it('makes the roles of the shared tables, and keeps every other value internal', () => {+ expect(motionRoleOf(springs.viewChange)?.id).toBe('springs.viewChange');+ expect(motionRoleOf(timing.curves.move)?.kind).toBe('curve');+ expect(motionRoleIn(timing, 'stateChangeMs')?.kind).toBe('duration');+ // A component's measured value is an internal constant, not a role.+ expect(motionRoleOf(springs.sheetPresent)).toBeUndefined();+ expect(springs.sheetPresent).toEqual(springs.viewChange);+ expect(motionRoleOf(scroll.bounce)).toBeUndefined();+ expect(motionRoleIn(timing.press, 'flashMs')).toBeUndefined();+ expect(motionRoleIn(navigation, 'transitionMs')).toBeUndefined();+ // The Reduced Motion fade, UIKit's menu spring under Reduce Motion, the+ // thresholds and the arbitration timings are not motion roles either.+ expect(motionRoleIn(timing, 'reducedMotionCrossFadeMs')).toBeUndefined();+ expect(motionRoleOf(springs.menuReducedMotion)).toBeUndefined();+ expect(motionRoleIn(timing.press, 'scrollBrakeMs')).toBeUndefined();+ expect(motionRoleIn(scroll, 'delaysContentTouchesMs')).toBeUndefined();+ expect(motionRoleIn(navigation, 'parallax')).toBeUndefined();+ const ids = listMotionRoles().map(role => role.id);+ expect(ids.some(id => id.startsWith('gestures.'))).toBe(false);+ // Every role has its own CSS variable.+ const variables = listMotionRoles().map(role => role.variable);+ expect(new Set(variables).size).toBe(variables.length);+ });++ it('registers exactly the roles spec:AST-094 FR4 names, internally', () => {+ // Every table discovery registered (other tests here add fixtures).+ const discovered = listMotionRoles().filter(role =>+ DISCOVERED.has(role.id.split('.')[0]),+ );+ expect(+ Object.fromEntries(discovered.map(role => [role.id, role.kind])),+ ).toEqual({+ 'springs.directChange': 'spring',+ 'springs.emphasis': 'spring',+ 'springs.fingerTracking': 'spring',+ 'springs.menuClose': 'spring',+ 'springs.menuOpen': 'spring',+ 'springs.quickChange': 'spring',+ 'springs.settle': 'spring',+ 'springs.stateChange': 'spring',+ 'springs.subMenuBack': 'spring',+ 'springs.subMenuOpen': 'spring',+ 'springs.timedChange': 'spring',+ 'springs.viewChange': 'spring',+ 'timing.curves.entrance': 'curve',+ 'timing.curves.exit': 'curve',+ 'timing.curves.move': 'curve',+ 'timing.curves.viewChange': 'curve',+ 'timing.stateChangeMs': 'duration',+ });+ });++ it('writes every table value in CSS form and reads back the same motion', () => {+ for (const role of listMotionRoles()) {+ const text = formatMotionRoleValue(role.kind, role.value);+ const back = parseMotionRoleValue(role.kind, text);+ expect(back, `${role.id}: ${text}`).not.toBeNull();+ if (role.kind === 'spring') {+ const a = toSpring(role.value as Parameters<typeof toSpring>[0]);+ const b = toSpring(back as Parameters<typeof toSpring>[0]);+ expect(naturalFrequency(b) / naturalFrequency(a)).toBeCloseTo(1, 5);+ expect(dampingRatioOf(b)).toBeCloseTo(dampingRatioOf(a), 5);+ } else {+ expect(back).toEqual(role.value);+ }+ }+ expect(+ formatMotionRoleValue('spring', {response: 0.5, dampingRatio: 0.85}),+ ).toBe('0.5s 0.15');+ expect(formatMotionRoleValue('duration', 250)).toBe('250ms');+ expect(formatMotionRoleValue('curve', [0.42, 0, 0.58, 1])).toBe(+ 'cubic-bezier(0.42, 0, 0.58, 1)',+ );+ });++ it('refuses invalid values and reads malformed CSS as unset', () => {+ expect(() => formatMotionRoleValue('duration', -1)).toThrow(/≥ 0/);+ expect(() => formatMotionRoleValue('curve', [2, 0, 0.5, 1])).toThrow(+ /x1 and x2/,+ );+ expect(() => formatMotionRoleValue('spring', {response: 0.5})).toThrow(+ /spring is/,+ );+ expect(parseMotionRoleValue('spring', '')).toBeNull();+ expect(parseMotionRoleValue('spring', 'fast')).toBeNull();+ expect(parseMotionRoleValue('spring', '0.4s 0.2')).toEqual({+ duration: 0.4,+ bounce: 0.2,+ });+ expect(parseMotionRoleValue('duration', ' 0.3s ')).toBe(300);+ expect(parseMotionRoleValue('curve', 'ease-in')).toBeNull();+ });+});diff --git a/packages/core/src/motion/roles.ts b/packages/core/src/motion/roles.tsnew file mode 100644index 0000000000..15381b4a3d--- /dev/null+++ b/packages/core/src/motion/roles.ts@@ -0,0 +1,262 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file roles.ts+ * @input The motion tables (motion/uikit and each component's own table)+ * @output registerMotionTable, motionRoleOf, motionRoleIn, listMotionRoles,+ * motionRoleVariable, and the CSS form of a role's value+ * (formatMotionRoleValue, parseMotionRoleValue)+ * @position Motion foundation, internal to core: read by the code that+ * resolves a role when a motion starts. No public API writes a role: touch+ * motion stays internal until the public motion-token set is decided.+ *+ * A motion role is one value of a motion table: a+ * spring, a duration (a key ending in `Ms`, in milliseconds) or a curve (four+ * cubic-bézier control points). The roles are the ones `spec:AST-094` FR4+ * names, each by its table path, such as `springs.settle` or+ * `timing.curves.move`: a table lists its roles when it registers, and every+ * other value, a component's measured spring included, stays an internal+ * constant. No shipped component reads the roles yet.+ * A role is carried by one CSS custom property, `--motion-` followed by its id+ * in kebab case (`--motion-springs-settle`), which nothing public writes; an+ * empty property means the table's value, so the table stays the one measured+ * source of every value.+ *+ * Gesture thresholds, the velocity filter, the timings that decide who gets a+ * touch and haptics are not motion: they are not roles (tables leave them out+ * with `exclude`).+ *+ * SYNC: When modified, update /packages/core/src/motion/roles.test.ts.+ */++import {+ formatMotionRoleValue,+ isCurve,+ isMotionRoleId,+ isSpring,+ motionRoleVariable,+ type MotionCurvePoints,+ type MotionRoleKind,+} from './roleValue';+import type {DurationBounce, SpringDescription} from './spring';++export {formatMotionRoleValue, isMotionRoleId, motionRoleVariable};+export type {MotionCurvePoints, MotionRoleKind};++/** One registered role. */+export interface MotionRole {+ /** The table path, e.g. `springs.sheetDetent`. */+ readonly id: string;+ readonly kind: MotionRoleKind;+ /** The CSS custom property that carries the role's value. */+ readonly variable: string;+ /** The table's value: what plays when the property is empty. */+ readonly value: SpringDescription | number | MotionCurvePoints;+}++const rolesById = new Map<string, MotionRole>();+/** A table id → the table registered under it. */+const tablesById = new Map<string, object>();+/** A spring or curve leaf → its role. */+const roleOfLeaf = new WeakMap<object, MotionRole>();+/** A table or one of its groups → its path. */+const pathOfGroup = new WeakMap<object, string>();+/** A table path → the role id it is registered under, when renamed. */+const roleIdOfPath = new Map<string, string>();++/**+ * Registers a motion table: each spring, `…Ms` duration and curve leaf that+ * `roles` lists (its role name, relative to the table) becomes a role named+ * by its path under `id`; the table's other values stay internal constants. A leaf object the table shares between+ * two keys is replaced in the table by an equal copy, so each role has its own+ * object (an animator resolves a role from the object it is handed).+ * `exclude` lists paths, relative to the table, that are not motion;+ * `rename` maps a path, relative to the table, to the role name it is+ * registered under (relative too), so a role is named for its use while the+ * table keeps its source's name. Registering the same table under the same id+ * again does nothing.+ */+export function registerMotionTable(+ id: string,+ table: object,+ {+ roles = [],+ exclude = [],+ rename = {},+ }: {+ roles?: ReadonlyArray<string>;+ exclude?: ReadonlyArray<string>;+ rename?: Readonly<Record<string, string>>;+ } = {},+): void {+ if (!/^[a-z][A-Za-z0-9]*$/.test(id)) {+ throw new Error(`motion table id "${id}" must be one camelCase word`);+ }+ // Registering the same table again changes nothing: each table's+ // register function may run from every touch module that uses it.+ if (tablesById.get(id) === table) {+ return;+ }+ tablesById.set(id, table);+ const skip = new Set(exclude.map(path => `${id}.${path}`));+ const listed = new Set(roles.map(name => `${id}.${name}`));+ const walk = (group: Record<string, unknown>, prefix: string) => {+ pathOfGroup.set(group, prefix);+ for (const [key, value] of Object.entries(group)) {+ const path = `${prefix}.${key}`;+ if (skip.has(path)) {+ continue;+ }+ let kind: MotionRoleKind | null = null;+ if (isSpring(value)) {+ kind = 'spring';+ } else if (isCurve(value)) {+ kind = 'curve';+ } else if (typeof value === 'number' && key.endsWith('Ms')) {+ kind = 'duration';+ } else if (+ value !== null &&+ typeof value === 'object' &&+ !Array.isArray(value)+ ) {+ walk(value as Record<string, unknown>, path);+ continue;+ }+ if (kind == null) {+ continue;+ }+ const relative = path.slice(id.length + 1);+ const roleId = relative in rename ? `${id}.${rename[relative]}` : path;+ // Only the roles the table lists; every other value stays internal.+ if (!listed.has(roleId)) {+ continue;+ }+ if (roleId !== path) {+ roleIdOfPath.set(path, roleId);+ }+ let leaf = value as SpringDescription | number | MotionCurvePoints;+ if (typeof leaf === 'object') {+ const taken = roleOfLeaf.get(leaf);+ if (taken != null && taken.id !== roleId) {+ leaf = Object.freeze(Array.isArray(leaf) ? [...leaf] : {...leaf}) as+ SpringDescription | MotionCurvePoints;+ group[key] = leaf;+ }+ }+ const role: MotionRole = {+ id: roleId,+ kind,+ variable: motionRoleVariable(roleId),+ value: leaf,+ };+ rolesById.set(roleId, role);+ if (typeof leaf === 'object') {+ roleOfLeaf.set(leaf, role);+ }+ }+ };+ walk(table as Record<string, unknown>, id);+}++/** The role a spring or curve leaf of a registered table plays, if any. */+export function motionRoleOf(leaf: unknown): MotionRole | undefined {+ return leaf !== null && typeof leaf === 'object'+ ? roleOfLeaf.get(leaf)+ : undefined;+}++/**+ * The role `group[key]` plays, for a table or one of its groups: the way to+ * name a duration, which is a bare number.+ */+export function motionRoleIn(+ group: object,+ key: string,+): MotionRole | undefined {+ const prefix = pathOfGroup.get(group);+ if (prefix == null) {+ return undefined;+ }+ const path = `${prefix}.${key}`;+ return rolesById.get(roleIdOfPath.get(path) ?? path);+}++/** The role with this id, once its table is registered. */+export function motionRole(id: string): MotionRole | undefined {+ return rolesById.get(id);+}++/** Every registered role, by id. */+export function listMotionRoles(): MotionRole[] {+ return [...rolesById.values()].sort((a, b) => (a.id < b.id ? -1 : 1));+}++const NUMBER = '(-?(?:\\d+\\.?\\d*|\\.\\d+)(?:e-?\\d+)?)';+const SPRING_VALUE = new RegExp(`^${NUMBER}s\\s+${NUMBER}$`);+const DURATION_VALUE = new RegExp(`^${NUMBER}(ms|s)$`);+const CURVE_VALUE = new RegExp(+ `^cubic-bezier\\(\\s*${NUMBER}\\s*,\\s*${NUMBER}\\s*,\\s*${NUMBER}\\s*,\\s*${NUMBER}\\s*\\)$`,+);++/**+ * Reads a role value back from its CSS custom property. Returns null for an+ * empty or malformed value: the caller then uses the table's value.+ */+export function parseMotionRoleValue(+ kind: 'spring',+ text: string,+): DurationBounce | null;+export function parseMotionRoleValue(+ kind: 'duration',+ text: string,+): number | null;+export function parseMotionRoleValue(+ kind: 'curve',+ text: string,+): MotionCurvePoints | null;+export function parseMotionRoleValue(+ kind: MotionRoleKind,+ text: string,+): DurationBounce | number | MotionCurvePoints | null;+export function parseMotionRoleValue(+ kind: MotionRoleKind,+ text: string,+): DurationBounce | number | MotionCurvePoints | null {+ const value = text.trim();+ if (value === '') {+ return null;+ }+ if (kind === 'spring') {+ const m = SPRING_VALUE.exec(value);+ if (m == null) {+ return null;+ }+ const duration = Number(m[1]);+ const bounce = Number(m[2]);+ // A bounce of 1 is undamped: it never settles.+ return duration > 0 && bounce > -1 && bounce < 1+ ? {duration, bounce}+ : null;+ }+ if (kind === 'duration') {+ const m = DURATION_VALUE.exec(value);+ if (m == null) {+ return null;+ }+ const ms = Number(m[1]) * (m[2] === 's' ? 1000 : 1);+ return ms >= 0 ? ms : null;+ }+ const m = CURVE_VALUE.exec(value);+ if (m == null) {+ return null;+ }+ const points = [m[1], m[2], m[3], m[4]].map(Number) as unknown as [+ number,+ number,+ number,+ number,+ ];+ return points[0] >= 0 && points[0] <= 1 && points[2] >= 0 && points[2] <= 1+ ? points+ : null;+}diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.tsindex 6eb75fba2d..317b51207a 100644--- a/packages/core/src/motion/uikit/index.ts+++ b/packages/core/src/motion/uikit/index.ts@@ -3,7 +3,8 @@/*** @file index.ts* @input The domain files of the UIKit constants table- * @output Re-exports `springs`, `scroll`, `timing`, `navigation` and the+ * @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`,+ * …), `scroll`, `timing`, `navigation` and the* gesture thresholds (one `UIKIT_*` group per recognizer, their union* `UIKIT_GESTURES`, and the haptic tables)* @position Entry of the UIKit constants table (motion/uikit). Internal to@@ -37,7 +38,43 @@ export {type GestureConstantUnit,type HapticFeedbackKind,} from './gestures';-export {navigation} from './navigation';-export {scroll} from './scroll';-export {springs} from './springs';-export {timing} from './timing';+export {navigation, registerNavigationTable} from './navigation';+export {registerScrollTable, scroll} from './scroll';+export {+ ACTION_SHEET_DISMISS_SPRING,+ ACTION_SHEET_PRESENT_SPRING,+ ALERT_DISMISS_SPRING,+ ALERT_PRESENT_SPRING,+ BANNER_SPRING,+ CONTEXT_MENU_DISMISS_SPRING,+ CONTEXT_MENU_LIFT_SPRING,+ DIRECT_CHANGE_SPRING,+ EMPHASIS_SPRING,+ FINGER_TRACKING_SPRING,+ KEYBOARD_SPRING,+ MENU_CLOSE_SPRING,+ MENU_OPEN_SPRING,+ MENU_REDUCED_MOTION_SPRING,+ NAVIGATION_BAR_ELEMENTS_SPRING,+ NAVIGATION_INTERACTIVE_POP_FINISH_SPRING,+ NAVIGATION_POP_SPRING,+ NAVIGATION_PUSH_SPRING,+ QUICK_CHANGE_SPRING,+ SEGMENTED_THUMB_SPRING,+ SETTLE_SPRING,+ SHEET_DETENT_SPRING,+ SHEET_DISMISS_SPRING,+ SHEET_DISMISS_SWIPE_SPRING,+ SHEET_PRESENT_SPRING,+ SHEET_RELEASE_FAST_SPRING,+ STATE_CHANGE_SPRING,+ SUB_MENU_BACK_SPRING,+ SUB_MENU_OPEN_SPRING,+ SWITCH_THUMB_MOVE_SPRING,+ SWITCH_THUMB_STRETCH_SPRING,+ TIMED_CHANGE_SPRING,+ VIEW_CHANGE_SPRING,+ registerSpringsTable,+ springs,+} from './springs';+export {registerTimingTable, timing} from './timing';diff --git a/packages/core/src/motion/uikit/navigation.ts b/packages/core/src/motion/uikit/navigation.tsindex 62dd928f4c..4d4a7eebcf 100644--- a/packages/core/src/motion/uikit/navigation.ts+++ b/packages/core/src/motion/uikit/navigation.ts@@ -24,6 +24,7 @@* SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md*/+import {registerMotionTable} from '../roles';export const navigation = {/*** The push and pop springs start moving at this many travels per second@@ -71,3 +72,12 @@ export const navigation = {*/interactivePopFinishThreshold: 0.5,} as const;++/**+ * Registers this table with the motion registry (motion/roles.ts). It lists+ * no role: spec:AST-094 FR4 names none of its values, so each plays as+ * measured. Nothing registers on import, and a second call does nothing.+ */+export function registerNavigationTable(): void {+ registerMotionTable('navigation', navigation);+}diff --git a/packages/core/src/motion/uikit/scroll.ts b/packages/core/src/motion/uikit/scroll.tsindex 4c85d6ed55..7158a8d947 100644--- a/packages/core/src/motion/uikit/scroll.ts+++ b/packages/core/src/motion/uikit/scroll.ts@@ -18,6 +18,8 @@* - /packages/core/src/motion/MEASUREMENTS.md (measurement tasks)*/+import {registerMotionTable} from '../roles';+// The value of `scroll.delaysContentTouchesMs` (sourced there), its own// export so the press clocks read it without the rest of the table// (`architecture:component-style-authoring` INV6).@@ -125,3 +127,15 @@ export const scroll = {*/scrollToTopRate: 0.99035,} as const;++/**+ * Registers this table with the motion registry (motion/roles.ts). It lists+ * no role: spec:AST-094 FR4 names none of its values, so each plays as+ * measured. Nothing registers on import, and a second call does nothing.+ */+export function registerScrollTable(): void {+ registerMotionTable('scroll', scroll, {+ // Arbitration: who gets the touch, not how anything moves.+ exclude: ['delaysContentTouchesMs'],+ });+}diff --git a/packages/core/src/motion/uikit/springRows.test.ts b/packages/core/src/motion/uikit/springRows.test.tsnew file mode 100644index 0000000000..01debd8ad2--- /dev/null+++ b/packages/core/src/motion/uikit/springRows.test.ts@@ -0,0 +1,71 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file springRows.test.ts+ * @input springs.ts, bundled with esbuild in a child process+ * @output Fails when a bundle that imports one spring row, or registers the+ * motion roles, carries a spring it does not use+ * (`architecture:component-style-authoring` INV6)+ */++import {execFileSync} from 'node:child_process';+import {describe, expect, it} from 'vitest';++/** The minified bundle of `entry`, an ES module next to springs.ts. */+function bundle(entry: string): string {+ // esbuild runs in its own Node process: jsdom's TextEncoder fails its+ // startup check.+ return execFileSync(+ process.execPath,+ [+ '--input-type=module',+ '-e',+ [+ "import {build} from 'esbuild';",+ 'const result = await build({',+ ` stdin: {contents: ${JSON.stringify(entry)}, resolveDir: process.cwd(), loader: 'ts'},`,+ " bundle: true, write: false, format: 'esm', minify: true, logLevel: 'silent',",+ '});',+ 'process.stdout.write(result.outputFiles[0].text);',+ ].join('\n'),+ ],+ {cwd: __dirname, encoding: 'utf8'},+ );+}++// Numbers only one row carries, as a minified bundle writes them.+const KEYBOARD = '555.0265';+const ALERT = '522.35';+const SHEET_DETENT = '.3441442326';+const FINGER_TRACKING = '.86';+const DIRECT_CHANGE = '.825';++describe('spring rows', () => {+ it('a bundle that imports one row carries no other', () => {+ const keyboard = bundle(+ "import {KEYBOARD_SPRING} from './springs'; export const s = KEYBOARD_SPRING;",+ );+ expect(keyboard).toContain(KEYBOARD);+ for (const other of [ALERT, SHEET_DETENT, FINGER_TRACKING, DIRECT_CHANGE]) {+ expect(keyboard).not.toContain(other);+ }+ const detent = bundle(+ "import {SHEET_DETENT_SPRING} from './springs'; export const s = SHEET_DETENT_SPRING;",+ );+ expect(detent).toContain(SHEET_DETENT);+ for (const other of [KEYBOARD, ALERT, FINGER_TRACKING, DIRECT_CHANGE]) {+ expect(detent).not.toContain(other);+ }+ });++ it('registering the motion roles carries only the springs that are roles', () => {+ const roles = bundle(+ "import {registerSpringsTable} from './springs'; registerSpringsTable();",+ );+ expect(roles).toContain(FINGER_TRACKING);+ expect(roles).toContain(DIRECT_CHANGE);+ for (const other of [KEYBOARD, ALERT, SHEET_DETENT]) {+ expect(roles).not.toContain(other);+ }+ });+});diff --git a/packages/core/src/motion/uikit/springs.ts b/packages/core/src/motion/uikit/springs.tsindex cd6d1a152e..f94b102884 100644--- a/packages/core/src/motion/uikit/springs.ts+++ b/packages/core/src/motion/uikit/springs.ts@@ -3,10 +3,11 @@/*** @file springs.ts* @input Nothing; data only- * @output Exports `springs`, every UIKit / SwiftUI interaction spring the- * touch presentations use, each in the vocabulary of its source- * (SpringDescription: duration/bounce, response/dampingRatio or- * mass/stiffness/damping; a reader normalizes them to one form)+ * @output One export per UIKit / SwiftUI interaction spring the touch+ * presentations use (`SHEET_PRESENT_SPRING`, `SETTLE_SPRING`, …), each in+ * the vocabulary of its source (SpringDescription: duration/bounce,+ * response/dampingRatio or mass/stiffness/damping; a reader normalizes them+ * to one form), and `springs`, the table of all of them by row name* @position The springs domain of the UIKit constants table (motion/uikit)** Every leaf carries one or more `@source` (apple-docs | wwdc | webkit |@@ -26,305 +27,488 @@* - /packages/core/src/motion/MEASUREMENTS.md (measurement tasks)*/+import {registerMotionTable} from '../roles';++// ---------------------------------------------------------------------+// Sourced presets+// ---------------------------------------------------------------------+/**- * UIKit's default spring (see `springs.viewChange` for its sources), shared- * by the system transitions measured to run on it.+ * SwiftUI `.smooth`: no bounce. Also SwiftUI's `Spring()` and+ * `.spring(duration:bounce:)` defaults.+ * @source apple-docs https://developer.apple.com/documentation/swiftui/spring/smooth(duration:extrabounce:)*/-const UIKIT_DEFAULT_SPRING = {mass: 3, stiffness: 1000, damping: 500} as const;+export const SETTLE_SPRING = {duration: 0.5, bounce: 0} as const;-/** Push and pop (see `springs.navigationPush`). */-const NAVIGATION_SPRING = {response: 0.3, dampingRatio: 1} as const;+/**+ * SwiftUI `.snappy`: "small amount of bounce", base bounce 0.15.+ * @source apple-docs https://developer.apple.com/documentation/swiftui/spring/snappy(duration:extrabounce:)+ */+export const QUICK_CHANGE_SPRING = {duration: 0.5, bounce: 0.15} as const;/**- * A sheet's fast release and swipe dismissal (see `springs.sheetReleaseFast`):- * the presentation's pace at 80 % damping.+ * SwiftUI `.bouncy`: base bounce 0.3.+ * @source apple-docs https://developer.apple.com/documentation/swiftui/spring/bouncy(duration:extrabounce:)*/-const SHEET_RELEASE_FAST_SPRING = {+export const EMPHASIS_SPRING = {duration: 0.5, bounce: 0.3} as const;++/**+ * SwiftUI `interactiveSpring()` defaults: for a value that tracks a finger.+ * @source apple-docs https://developer.apple.com/documentation/swiftui/animation/interactivespring(response:dampingfraction:blendduration:)+ */+export const FINGER_TRACKING_SPRING = {+ response: 0.15,+ dampingRatio: 0.86,+} as const;++/**+ * SwiftUI `Animation.default` since iOS 17 (what `withAnimation` uses).+ * @source apple-docs https://developer.apple.com/documentation/swiftui/animation/default+ */+export const STATE_CHANGE_SPRING = {response: 0.55, dampingRatio: 1} as const;++/**+ * SwiftUI `.spring(response:dampingFraction:blendDuration:)` defaults.+ * @source apple-docs https://developer.apple.com/documentation/swiftui/animation/spring(response:dampingfraction:blendduration:)+ */+export const DIRECT_CHANGE_SPRING = {+ response: 0.5,+ dampingRatio: 0.825,+} as const;++/**+ * UIKit `UIView.animate(springDuration:bounce:…)` defaults (iOS 17).+ * @source apple-docs https://developer.apple.com/documentation/uikit/uiview/animate(springduration:bounce:initialspringvelocity:delay:options:animations:completion:)+ */+export const TIMED_CHANGE_SPRING = {duration: 0.5, bounce: 0} as const;++/**+ * UIKit's default spring, `UISpringTimingParameters()`: Apple documents+ * its damping ratio as 4.56, which is exactly 500 ÷ (2·√(3·1000)).+ * Overdamped on paper; Core Animation treats overdamping as critical+ * unless told otherwise, so in effect it is a critically+ * damped spring with ω₀ = 18.26 rad/s (response 0.344 s) that settles in+ * 0.506 s. The keyboard does not use it (see `keyboard`).+ * @source apple-docs https://developer.apple.com/documentation/uikit/uispringtimingparameters/init() (damping ratio 4.56)+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CAAnimation read, Oct 23 2026: UISpringTimingParameters()+ * is mass 3, stiffness 1000, damping 500; UIKit runs it for 0.505824 s+ * (clamped to critical) whatever duration the animator was given, and+ * `UIView.animate` with curve 7 outside the keyboard is this spring with+ * its duration forced to 0.5 s+ */+export const VIEW_CHANGE_SPRING = {+ mass: 3,+ stiffness: 1000,+ damping: 500,+} as const;++// ---------------------------------------------------------------------+// Navigation (UINavigationController)+// ---------------------------------------------------------------------++/**+ * Push (programmatic or a row tap): the incoming card slides in from the+ * trailing edge, the outgoing card shifts by `navigation.parallax`. The+ * spring does not start from rest: it starts at+ * `navigation.pushVelocity` × the travel per second.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, time-free fit of the (value, velocity) pairs UIKit+ * writes to the cards' CAPresentationModifiers every frame (rms 5e-4 of+ * the travel), Oct 23 2026+ */+export const NAVIGATION_PUSH_SPRING = {response: 0.3, dampingRatio: 1} as const;++/**+ * Pop (back button or programmatic): identical to the push.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CAPresentationModifier fit as for the push, Oct 23 2026+ */+export const NAVIGATION_POP_SPRING = {response: 0.3, dampingRatio: 1} as const;++/**+ * Interactive pop finishing or cancelling after the finger lifts, starting+ * from the finger's velocity; which one is `navigation.interactivePop*`.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CAPresentationModifier fit over released swipes,+ * Oct 23 2026+ */+export const NAVIGATION_INTERACTIVE_POP_FINISH_SPRING = {+ response: 0.3,+ dampingRatio: 0.85,+} as const;++/**+ * Navigation bar elements (Liquid Glass) moving during a push or pop.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIView.animate(springDuration: 0.6, bounce: 0,+ * .beginFromCurrentState) calls hooked during transitions, Oct 23 2026+ */+export const NAVIGATION_BAR_ELEMENTS_SPRING = {+ duration: 0.6,+ bounce: 0,+} as const;++// ---------------------------------------------------------------------+// Sheets (UISheetPresentationController)+// ---------------------------------------------------------------------++/**+ * Sheet presented programmatically: UIKit's default spring+ * (`UIViewPropertyAnimator(duration: 0.4, timingParameters:+ * UISpringTimingParameters())`), which renders critically damped at+ * response 0.344 s; the same at the medium and large detents.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CAAnimation dump (mass 3, stiffness 1000, damping 500,+ * duration 0.5, allowsOverdamping off), Oct 23 2026+ */+export const SHEET_PRESENT_SPRING = {+ mass: 3,+ stiffness: 1000,+ damping: 500,+} as const;++/**+ * Sheet dismissed programmatically (Cancel / Done / a scrim tap).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CAAnimation dump, the same spring as the presentation,+ * Oct 23 2026+ */+export const SHEET_DISMISS_SPRING = {+ mass: 3,+ stiffness: 1000,+ damping: 500,+} as const;++/**+ * Detent change (`animateChanges`) and the settle after a slow release+ * (below the sheet's fast-release speed, which the sheet's own table+ * records): critically damped at the same pace as the presentation.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, `_UISpringParameters(dampingRatio: 1, response:+ * 0.3441442326)` hooked, CASpringAnimation mass 1, stiffness 333.333,+ * damping 36.515, Oct 23 2026+ */+export const SHEET_DETENT_SPRING = {+ response: 0.3441442326,+ dampingRatio: 1,+} as const;++/**+ * The settle after a fast release (from the sheet's fast-release speed+ * on), toward a detent or out of the screen: same pace, 80 % damping;+ * UIKit hands it the finger's velocity.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CASpringAnimation dump over 36 releases (mass 1,+ * stiffness 333.333, damping 29.212), Oct 23 2026+ */+export const SHEET_RELEASE_FAST_SPRING = {response: 0.3441442326,dampingRatio: 0.8,} as const;/**- * Alerts and action sheets, presenting and dismissing (see- * `springs.alertPresent`): UIKit's legacy 0.404 s spring, critically damped.+ * Sheet dismissed by a swipe: the fast-release spring.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CASpringAnimation dump (300 pt swipe in 0.15 s:+ * stiffness 333.333, damping 29.212), Oct 23 2026*/-const ALERT_SPRING = {mass: 1, stiffness: 522.35, damping: 45.71} as const;+export const SHEET_DISMISS_SWIPE_SPRING = {+ response: 0.3441442326,+ dampingRatio: 0.8,+} as const;-/** Menus and context menus opening (see `springs.menuOpen`). */-const MENU_OPEN_SPRING = {response: 0.32, dampingRatio: 0.8} as const;+// ---------------------------------------------------------------------+// Alerts, action sheets, menus+// ----------------------------------------------------------------------/** Menus and context menus closing (see `springs.menuClose`). */-const MENU_CLOSE_SPRING = {response: 0.35, dampingRatio: 0.85} as const;+/**+ * Alert (UIAlertController .alert) appearing: fades in and scales from+ * 1.2 to 1, the dimming fading in alongside. UIKit asks+ * `UIView.animate(withDuration: 0.404, usingSpringWithDamping: 600,+ * initialSpringVelocity: 0)`; the damping clamps to critical, and the+ * spring settles at 0.404 s.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, UIView.animate hooked and CASpringAnimation dumped+ * (mass 1, stiffness 522.350, damping 45.710, duration 0.404),+ * Oct 23 2026+ */+export const ALERT_PRESENT_SPRING = {+ mass: 1,+ stiffness: 522.35,+ damping: 45.71,+} as const;++/**+ * Alert dismissing: the same spring, opacity only.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CASpringAnimation dump, Oct 23 2026+ */+export const ALERT_DISMISS_SPRING = {+ mass: 1,+ stiffness: 522.35,+ damping: 45.71,+} as const;+/**+ * Action sheet (UIAlertController .actionSheet) appearing: identical to+ * the alert.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CASpringAnimation dump, Oct 23 2026+ */+export const ACTION_SHEET_PRESENT_SPRING = {+ mass: 1,+ stiffness: 522.35,+ damping: 45.71,+} as const;++/**+ * Action sheet dismissing: identical to the alert.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CASpringAnimation dump, Oct 23 2026+ */+export const ACTION_SHEET_DISMISS_SPRING = {+ mass: 1,+ stiffness: 522.35,+ damping: 45.71,+} as const;++/**+ * UIMenu (from a button) opening; UIKit drives it per frame and lets it+ * track a finger still on the screen.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, `_animateUsingSpringWithDampingRatio:response:tracking:`+ * hooked (0.8, 0.32, tracking), Oct 23 2026+ */+export const MENU_OPEN_SPRING = {response: 0.32, dampingRatio: 0.8} as const;++/**+ * UIMenu closing (a tap outside).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, the same hook (0.85, 0.35, not tracking), Oct 23 2026+ */+export const MENU_CLOSE_SPRING = {response: 0.35, dampingRatio: 0.85} as const;++/**+ * A sub-menu opening in place (its row tapped on a phone): a card laid over+ * the parent's rows from the tapped row grows down to fit the sub-menu, the+ * menu's box with it, and the parent's rows recede, on this spring+ * (spec:AST-094 FR34).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, a pull-down button at y 150 whose menu opens downward+ * (Alpha, Beta, Sort By ▸ (Name, Date, Size), Delete), every menu label,+ * image and view read per 60 Hz tick, Oct 24 2026 (t from the tap-down;+ * the lift at 60 ms): the menu's box kept its top and grew 188 → 190.9+ * (106 ms), 198.1 (123), 218.1 (156), 238.5 (189), 255.6 (223), 268.2+ * (256), 276.7 (289), 282.1 (324), 285.2 (359), 286.8 (389), 287.6 (424),+ * settling at 287.2; the parent rows' opacity followed it (1 → 0.5 by 389+ * ms). UIKit's own spring for it, logged as the+ * `UIViewSpringAnimationBehavior` it starts a few ms after the lift on+ * every sub-menu row (four captures): damping ratio 0.85, response 0.4 s.+ * It fits the box's eleven frames to 0.12 pt rms of the 99 pt travel+ * (start 89.5 ms), as a free single-spring fit does (0.86, 0.395)+ */+export const SUB_MENU_OPEN_SPRING = {+ response: 0.4,+ dampingRatio: 0.85,+} as const;++/**+ * Back out of a sub-menu (its header tapped): the card shrinks back up into+ * the row, the menu's box with it, and the parent's rows come back, on this+ * spring (spec:AST-094 FR34).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, the same menu and readings, Oct 24 2026 (t from the+ * tap-down; the lift at 60 ms): the box 287.2 → 284.3 (128 ms), 268.7+ * (160), 249.9 (195), 233 (228), 219.6 (260), 209.6 (296), 202.5 (329),+ * 197.6 (361), 194.3 (395), 192.1 (428), 189.7 (494), 188 (628); the+ * parent rows' opacity 0.5 → 0.59 (160), 0.69 (195), 0.77 (228), 0.84+ * (260), 0.89 (296), 0.93 (329), 0.95 (361), 0.97 (395), 0.99 (461), 1+ * (527). UIKit's own spring for it, logged as the+ * `UIViewSpringAnimationBehavior` it starts on every header back (three+ * captures): damping ratio 1, response 0.4 s. It fits the box's twelve+ * frames to 0.28 pt rms of the 99 pt travel (start 111 ms), the opacity to+ * 0.0055 rms+ */+export const SUB_MENU_BACK_SPRING = {response: 0.4, dampingRatio: 1} as const;++/**+ * Context menu (UIContextMenuInteraction): the preview lifting once the+ * long press commits.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, the same hook (0.8, 0.32, tracking), Oct 23 2026+ */+export const CONTEXT_MENU_LIFT_SPRING = {+ response: 0.32,+ dampingRatio: 0.8,+} as const;++/**+ * Context menu dismissing (a tap outside).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, the same hook (0.85, 0.35, not tracking), Oct 23 2026+ */+export const CONTEXT_MENU_DISMISS_SPRING = {+ response: 0.35,+ dampingRatio: 0.85,+} as const;++/**+ * What UIKit plays for a menu with Reduce Motion on: critically damped,+ * slower, no overshoot. A reference reading of UIKit only, never played:+ * under reduced motion no core transition springs (`design:reduced-motion`+ * DR1); a touch presentation cross-fades instead (DR2), and nothing opts+ * out (DR4, `spec:AST-094` FR8).+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, `_animateUsingSpringWithDampingRatio:response:tracking:`+ * hooked with Reduce Motion on (1.0, 0.4), Oct 23 2026+ */+export const MENU_REDUCED_MOTION_SPRING = {+ response: 0.4,+ dampingRatio: 1,+} as const;++// ---------------------------------------------------------------------+// Controls+// ---------------------------------------------------------------------++/**+ * UISwitch thumb travelling between off and on.+ * @source webkit Source/WebCore/rendering/cocoa/RenderThemeCocoa.mm+ * `thumbMoveSpring = SpringSolver(1.0, 438.649…, 31.4159…)`, "Values+ * chosen for consistency with UIKit" (= response 0.30 s, ratio 0.75);+ * its settling duration is WebKit's iOS switch duration 0.48801 s+ * (RenderThemeIOS.h). These are WebKit's iOS 18 values: UIKit's own+ * switch frames differ, and a switch reads its measured table instead.+ * @measure M-SW02+ */+export const SWITCH_THUMB_MOVE_SPRING = {+ response: 0.3,+ dampingRatio: 0.75,+} as const;++/**+ * UISwitch thumb stretching while pressed and relaxing on release.+ * @source webkit Source/WebCore/rendering/cocoa/RenderThemeCocoa.mm+ * `thumbPressSpring = SpringSolver(1.0, 322.272…, 31.2364…)`, "Values+ * chosen for consistency with UIKit" (= response 0.35 s, ratio 0.87);+ * settles in WebKit's held duration 0.50740 s (RenderThemeIOS.h). As+ * for `switchThumbMove`, UIKit's own frames differ.+ * @measure M-SW03+ */+export const SWITCH_THUMB_STRETCH_SPRING = {+ response: 0.35,+ dampingRatio: 0.87,+} as const;++/**+ * UISegmentedControl selection thumb sliding to a new segment.+ * @source GUESS — WebKit's UIKit-matched switch thumb spring, the nearest+ * sourced control thumb+ * @measure M-SG02+ * @measure M-SG03+ */+export const SEGMENTED_THUMB_SPRING = {+ response: 0.3,+ dampingRatio: 0.75,+} as const;++// ---------------------------------------------------------------------+// System+// ---------------------------------------------------------------------++/**+ * Keyboard frame animation, show and hide alike: critically damped,+ * response 0.2667 s. The notification reports curve 7 and 0.3833 s+ * (`timing.keyboardNotificationMs`); Core Animation cuts the spring there.+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,+ * iPhone 17 Pro, CAAnimation read on the keyboard host and a+ * keyboardLayoutGuide-pinned view, Oct 23 2026+ */+export const KEYBOARD_SPRING = {+ mass: 1,+ stiffness: 555.0265,+ damping: 47.118,+} as const;++/**+ * Banner / toast sliding in from the top edge (system notification+ * banner as the reference).+ * @source GUESS — UIKit's default spring+ * @measure M-T1+ */+export const BANNER_SPRING = {mass: 3, stiffness: 1000, damping: 500} as const;++/**+ * Every spring above, by row name: the table the existing readers use. A+ * component imports only the rows it plays (`architecture:component-style-authoring`+ * INV6), each the same object as its row here.+ */export const springs = {- // ---------------------------------------------------------------------- // Sourced presets- // ----------------------------------------------------------------------- /**- * SwiftUI `.smooth`: no bounce. Also SwiftUI's `Spring()` and- * `.spring(duration:bounce:)` defaults.- * @source apple-docs https://developer.apple.com/documentation/swiftui/spring/smooth(duration:extrabounce:)- */- settle: {duration: 0.5, bounce: 0},- /**- * SwiftUI `.snappy`: "small amount of bounce", base bounce 0.15.- * @source apple-docs https://developer.apple.com/documentation/swiftui/spring/snappy(duration:extrabounce:)- */- quickChange: {duration: 0.5, bounce: 0.15},- /**- * SwiftUI `.bouncy`: base bounce 0.3.- * @source apple-docs https://developer.apple.com/documentation/swiftui/spring/bouncy(duration:extrabounce:)- */- emphasis: {duration: 0.5, bounce: 0.3},- /**- * SwiftUI `interactiveSpring()` defaults: for a value that tracks a finger.- * @source apple-docs https://developer.apple.com/documentation/swiftui/animation/interactivespring(response:dampingfraction:blendduration:)- */- fingerTracking: {response: 0.15, dampingRatio: 0.86},- /**- * SwiftUI `Animation.default` since iOS 17 (what `withAnimation` uses).- * @source apple-docs https://developer.apple.com/documentation/swiftui/animation/default- */- stateChange: {response: 0.55, dampingRatio: 1},- /**- * SwiftUI `.spring(response:dampingFraction:blendDuration:)` defaults.- * @source apple-docs https://developer.apple.com/documentation/swiftui/animation/spring(response:dampingfraction:blendduration:)- */- directChange: {response: 0.5, dampingRatio: 0.825},- /**- * UIKit `UIView.animate(springDuration:bounce:…)` defaults (iOS 17).- * @source apple-docs https://developer.apple.com/documentation/uikit/uiview/animate(springduration:bounce:initialspringvelocity:delay:options:animations:completion:)- */- timedChange: {duration: 0.5, bounce: 0},- /**- * UIKit's default spring, `UISpringTimingParameters()`: Apple documents- * its damping ratio as 4.56, which is exactly 500 ÷ (2·√(3·1000)).- * Overdamped on paper; Core Animation treats overdamping as critical- * unless told otherwise, so in effect it is a critically- * damped spring with ω₀ = 18.26 rad/s (response 0.344 s) that settles in- * 0.506 s. The keyboard does not use it (see `keyboard`).- * @source apple-docs https://developer.apple.com/documentation/uikit/uispringtimingparameters/init() (damping ratio 4.56)- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CAAnimation read, Oct 23 2026: UISpringTimingParameters()- * is mass 3, stiffness 1000, damping 500; UIKit runs it for 0.505824 s- * (clamped to critical) whatever duration the animator was given, and- * `UIView.animate` with curve 7 outside the keyboard is this spring with- * its duration forced to 0.5 s- */- viewChange: UIKIT_DEFAULT_SPRING,-- // ---------------------------------------------------------------------- // Navigation (UINavigationController)- // ----------------------------------------------------------------------- /**- * Push (programmatic or a row tap): the incoming card slides in from the- * trailing edge, the outgoing card shifts by `navigation.parallax`. The- * spring does not start from rest: it starts at- * `navigation.pushVelocity` × the travel per second.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, time-free fit of the (value, velocity) pairs UIKit- * writes to the cards' CAPresentationModifiers every frame (rms 5e-4 of- * the travel), Oct 23 2026- */- navigationPush: NAVIGATION_SPRING,- /**- * Pop (back button or programmatic): identical to the push.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CAPresentationModifier fit as for the push, Oct 23 2026- */- navigationPop: NAVIGATION_SPRING,- /**- * Interactive pop finishing or cancelling after the finger lifts, starting- * from the finger's velocity; which one is `navigation.interactivePop*`.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CAPresentationModifier fit over released swipes,- * Oct 23 2026- */- navigationInteractivePopFinish: {response: 0.3, dampingRatio: 0.85},- /**- * Navigation bar elements (Liquid Glass) moving during a push or pop.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, UIView.animate(springDuration: 0.6, bounce: 0,- * .beginFromCurrentState) calls hooked during transitions, Oct 23 2026- */- navigationBarElements: {duration: 0.6, bounce: 0},-- // ---------------------------------------------------------------------- // Sheets (UISheetPresentationController)- // ----------------------------------------------------------------------- /**- * Sheet presented programmatically: UIKit's default spring- * (`UIViewPropertyAnimator(duration: 0.4, timingParameters:- * UISpringTimingParameters())`), which renders critically damped at- * response 0.344 s; the same at the medium and large detents.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CAAnimation dump (mass 3, stiffness 1000, damping 500,- * duration 0.5, allowsOverdamping off), Oct 23 2026- */- sheetPresent: UIKIT_DEFAULT_SPRING,- /**- * Sheet dismissed programmatically (Cancel / Done / a scrim tap).- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CAAnimation dump, the same spring as the presentation,- * Oct 23 2026- */- sheetDismiss: UIKIT_DEFAULT_SPRING,- /**- * Detent change (`animateChanges`) and the settle after a slow release- * (below the sheet's fast-release speed, which the sheet's own table- * records): critically damped at the same pace as the presentation.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, `_UISpringParameters(dampingRatio: 1, response:- * 0.3441442326)` hooked, CASpringAnimation mass 1, stiffness 333.333,- * damping 36.515, Oct 23 2026- */- sheetDetent: {response: 0.3441442326, dampingRatio: 1},- /**- * The settle after a fast release (from the sheet's fast-release speed- * on), toward a detent or out of the screen: same pace, 80 % damping;- * UIKit hands it the finger's velocity.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CASpringAnimation dump over 36 releases (mass 1,- * stiffness 333.333, damping 29.212), Oct 23 2026- */+ settle: SETTLE_SPRING,+ quickChange: QUICK_CHANGE_SPRING,+ emphasis: EMPHASIS_SPRING,+ fingerTracking: FINGER_TRACKING_SPRING,+ stateChange: STATE_CHANGE_SPRING,+ directChange: DIRECT_CHANGE_SPRING,+ timedChange: TIMED_CHANGE_SPRING,+ viewChange: VIEW_CHANGE_SPRING,+ navigationPush: NAVIGATION_PUSH_SPRING,+ navigationPop: NAVIGATION_POP_SPRING,+ navigationInteractivePopFinish: NAVIGATION_INTERACTIVE_POP_FINISH_SPRING,+ navigationBarElements: NAVIGATION_BAR_ELEMENTS_SPRING,+ sheetPresent: SHEET_PRESENT_SPRING,+ sheetDismiss: SHEET_DISMISS_SPRING,+ sheetDetent: SHEET_DETENT_SPRING,sheetReleaseFast: SHEET_RELEASE_FAST_SPRING,- /**- * Sheet dismissed by a swipe: the fast-release spring.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CASpringAnimation dump (300 pt swipe in 0.15 s:- * stiffness 333.333, damping 29.212), Oct 23 2026- */- sheetDismissSwipe: SHEET_RELEASE_FAST_SPRING,-- // ---------------------------------------------------------------------- // Alerts, action sheets, menus- // ----------------------------------------------------------------------- /**- * Alert (UIAlertController .alert) appearing: fades in and scales from- * 1.2 to 1, the dimming fading in alongside. UIKit asks- * `UIView.animate(withDuration: 0.404, usingSpringWithDamping: 600,- * initialSpringVelocity: 0)`; the damping clamps to critical, and the- * spring settles at 0.404 s.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, UIView.animate hooked and CASpringAnimation dumped- * (mass 1, stiffness 522.350, damping 45.710, duration 0.404),- * Oct 23 2026- */- alertPresent: ALERT_SPRING,- /**- * Alert dismissing: the same spring, opacity only.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CASpringAnimation dump, Oct 23 2026- */- alertDismiss: ALERT_SPRING,- /**- * Action sheet (UIAlertController .actionSheet) appearing: identical to- * the alert.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CASpringAnimation dump, Oct 23 2026- */- actionSheetPresent: ALERT_SPRING,- /**- * Action sheet dismissing: identical to the alert.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CASpringAnimation dump, Oct 23 2026- */- actionSheetDismiss: ALERT_SPRING,- /**- * UIMenu (from a button) opening; UIKit drives it per frame and lets it- * track a finger still on the screen.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, `_animateUsingSpringWithDampingRatio:response:tracking:`- * hooked (0.8, 0.32, tracking), Oct 23 2026- */+ sheetDismissSwipe: SHEET_DISMISS_SWIPE_SPRING,+ alertPresent: ALERT_PRESENT_SPRING,+ alertDismiss: ALERT_DISMISS_SPRING,+ actionSheetPresent: ACTION_SHEET_PRESENT_SPRING,+ actionSheetDismiss: ACTION_SHEET_DISMISS_SPRING,menuOpen: MENU_OPEN_SPRING,- /**- * UIMenu closing (a tap outside).- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, the same hook (0.85, 0.35, not tracking), Oct 23 2026- */menuClose: MENU_CLOSE_SPRING,- /**- * Context menu (UIContextMenuInteraction): the preview lifting once the- * long press commits.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, the same hook (0.8, 0.32, tracking), Oct 23 2026- */- contextMenuLift: MENU_OPEN_SPRING,- /**- * Context menu dismissing (a tap outside).- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, the same hook (0.85, 0.35, not tracking), Oct 23 2026- */- contextMenuDismiss: MENU_CLOSE_SPRING,- /**- * What UIKit plays for a menu with Reduce Motion on: critically damped,- * slower, no overshoot. A reference reading of UIKit only, never played:- * under reduced motion no core transition springs (`design:reduced-motion`- * DR1); a touch presentation cross-fades instead (DR2), and nothing opts- * out (DR4, `spec:AST-094` FR8).- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, `_animateUsingSpringWithDampingRatio:response:tracking:`- * hooked with Reduce Motion on (1.0, 0.4), Oct 23 2026- */- menuReducedMotion: {response: 0.4, dampingRatio: 1},-- // ---------------------------------------------------------------------- // Controls- // ----------------------------------------------------------------------- /**- * UISwitch thumb travelling between off and on.- * @source webkit Source/WebCore/rendering/cocoa/RenderThemeCocoa.mm- * `thumbMoveSpring = SpringSolver(1.0, 438.649…, 31.4159…)`, "Values- * chosen for consistency with UIKit" (= response 0.30 s, ratio 0.75);- * its settling duration is WebKit's iOS switch duration 0.48801 s- * (RenderThemeIOS.h). These are WebKit's iOS 18 values: UIKit's own- * switch frames differ, and a switch reads its measured table instead.- * @measure M-SW02- */- switchThumbMove: {response: 0.3, dampingRatio: 0.75},- /**- * UISwitch thumb stretching while pressed and relaxing on release.- * @source webkit Source/WebCore/rendering/cocoa/RenderThemeCocoa.mm- * `thumbPressSpring = SpringSolver(1.0, 322.272…, 31.2364…)`, "Values- * chosen for consistency with UIKit" (= response 0.35 s, ratio 0.87);- * settles in WebKit's held duration 0.50740 s (RenderThemeIOS.h). As- * for `switchThumbMove`, UIKit's own frames differ.- * @measure M-SW03- */- switchThumbStretch: {response: 0.35, dampingRatio: 0.87},- /**- * UISegmentedControl selection thumb sliding to a new segment.- * @source GUESS — WebKit's UIKit-matched switch thumb spring, the nearest- * sourced control thumb- * @measure M-SG02- * @measure M-SG03- */- segmentedThumb: {response: 0.3, dampingRatio: 0.75},-- // ---------------------------------------------------------------------- // System- // ----------------------------------------------------------------------- /**- * Keyboard frame animation, show and hide alike: critically damped,- * response 0.2667 s. The notification reports curve 7 and 0.3833 s- * (`timing.keyboardNotificationMs`); Core Animation cuts the spring there.- * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,- * iPhone 17 Pro, CAAnimation read on the keyboard host and a- * keyboardLayoutGuide-pinned view, Oct 23 2026- */- keyboard: {mass: 1, stiffness: 555.0265, damping: 47.118},- /**- * Banner / toast sliding in from the top edge (system notification- * banner as the reference).- * @source GUESS — UIKit's default spring- * @measure M-T1- */- banner: UIKIT_DEFAULT_SPRING,+ subMenuOpen: SUB_MENU_OPEN_SPRING,+ subMenuBack: SUB_MENU_BACK_SPRING,+ contextMenuLift: CONTEXT_MENU_LIFT_SPRING,+ contextMenuDismiss: CONTEXT_MENU_DISMISS_SPRING,+ menuReducedMotion: MENU_REDUCED_MOTION_SPRING,+ switchThumbMove: SWITCH_THUMB_MOVE_SPRING,+ switchThumbStretch: SWITCH_THUMB_STRETCH_SPRING,+ segmentedThumb: SEGMENTED_THUMB_SPRING,+ keyboard: KEYBOARD_SPRING,+ banner: BANNER_SPRING,} as const;++/**+ * The springs spec:AST-094 FR4 names: the only ones that are motion roles.+ * The registry takes these rows alone, so registering ships no other spring.+ */+const SPRING_ROLES = {+ fingerTracking: FINGER_TRACKING_SPRING,+ emphasis: EMPHASIS_SPRING,+ settle: SETTLE_SPRING,+ quickChange: QUICK_CHANGE_SPRING,+ viewChange: VIEW_CHANGE_SPRING,+ timedChange: TIMED_CHANGE_SPRING,+ stateChange: STATE_CHANGE_SPRING,+ directChange: DIRECT_CHANGE_SPRING,+ menuOpen: MENU_OPEN_SPRING,+ menuClose: MENU_CLOSE_SPRING,+ subMenuOpen: SUB_MENU_OPEN_SPRING,+ subMenuBack: SUB_MENU_BACK_SPRING,+};++/**+ * Registers the springs spec:AST-094 FR4 names as internal motion roles+ * (motion/roles.ts), by their row names (`springs.settle`). Every other+ * spring, UIKit's menu spring under Reduce Motion and the keyboard's+ * included, is not a role. Nothing registers on import: the touch code that+ * plays a role calls it once (it is idempotent), so a page that never does+ * ships no registry.+ */+export function registerSpringsTable(): void {+ registerMotionTable('springs', SPRING_ROLES, {+ roles: Object.keys(SPRING_ROLES),+ });+}diff --git a/packages/core/src/motion/uikit/timing.ts b/packages/core/src/motion/uikit/timing.tsindex 8ce8079df0..e67f5a02dc 100644--- a/packages/core/src/motion/uikit/timing.ts+++ b/packages/core/src/motion/uikit/timing.ts@@ -24,6 +24,8 @@* there and must agree; uikit/uikit.test.ts checks it)*/+import {registerMotionTable} from '../roles';+/*** The touch press clocks, its own export so a reader of one clock does not* bundle the rest of the table (`architecture:component-style-authoring`@@ -160,3 +162,32 @@ export const timing = {*/reducedMotionCrossFadeMs: 500,} as const;++/**+ * Registers the springs, durations and curves above that spec:AST-094 FR4+ * names as internal motion roles (motion/roles.ts). Nothing registers on import: the touch code that+ * animates with this table calls it once (it is idempotent), so a page that+ * never does ships no registry.+ */+export function registerTimingTable(): void {+ registerMotionTable('timing', timing, {+ // Arbitration: who gets the touch, not how anything moves; the Reduced+ // Motion fade, which nothing may lengthen (design:reduced-motion DR4);+ // and the keyboard's own timing, which motion in step with the keyboard+ // rides (spec:AST-094 FR4).+ exclude: [+ 'press.scrollBrakeMs',+ 'reducedMotionCrossFadeMs',+ 'keyboardNotificationMs',+ ],+ // The motion roles: only the ones spec:AST-094 FR4 names. The press+ // clocks and every other value are internal measured constants.+ roles: [+ 'stateChangeMs',+ 'curves.viewChange',+ 'curves.exit',+ 'curves.entrance',+ 'curves.move',+ ],+ });+}diff --git a/packages/core/src/motion/uikit/uikit.test.ts b/packages/core/src/motion/uikit/uikit.test.tsindex ce0accc192..7783bdd8d3 100644--- a/packages/core/src/motion/uikit/uikit.test.ts+++ b/packages/core/src/motion/uikit/uikit.test.ts@@ -59,21 +59,49 @@ interface Leaf {function leavesOf(file: string): Leaf[] {const text = fs.readFileSync(path.resolve(__dirname, file), 'utf8');const lines = text.split('\n');- // Every exported table object: a domain may export a group of its own- // (the press clocks) so a reader takes that group alone.- const starts = lines.flatMap((line, index) =>- /^export const \w+ = \{$/.test(line) ? [index] : [],- );+ // Every exported object: a row when its own JSDoc carries the source (one+ // spring, exported so a reader takes it alone), otherwise a table or a+ // group of its own (the press clocks) whose leaves carry the sources.+ const starts: number[] = [];+ const rows: Leaf[] = [];+ // The groups and rows this file exports itself: a leaf that only names one+ // of them is checked where it is declared.+ const exported = new Set<string>();+ lines.forEach((line, index) => {+ const match = /^export const (\w+) = \{/.exec(line);+ if (match == null) {+ return;+ }+ exported.add(match[1]);+ const doc = docAbove(lines, index);+ // A one-line export is a row whether or not it is sourced, so an+ // unsourced one fails the source check below instead of being skipped.+ if (/^@source /m.test(doc) || !line.endsWith('{')) {+ rows.push({file, key: match[1], doc});+ } else {+ starts.push(index);+ }+ });expect(starts.length).toBeGreaterThan(0);- // The groups this file exports itself: a leaf that only names one of them- // is checked where that group is declared.- const exported = new Set(- lines.flatMap(line => {- const match = /^export const (\w+) = \{$/.exec(line);- return match == null ? [] : [match[1]];- }),- );- return starts.flatMap(start => leavesFrom(file, lines, start, exported));+ return [+ ...starts.flatMap(start => leavesFrom(file, lines, start, exported)),+ ...rows,+ ];+}++/** The JSDoc block right above line `index`, without its comment markers. */+function docAbove(lines: string[], index: number): string {+ if (!lines[index - 1]?.trim().endsWith('*/')) {+ return '';+ }+ let first = index - 1;+ while (first > 0 && !lines[first].trim().startsWith('/**')) {+ first--;+ }+ return lines+ .slice(first, index)+ .map(text => text.trim().replace(/^\/?\*+\/?\s?/, '') + '\n')+ .join('');}function leavesFrom(@@ -273,6 +301,31 @@ describe('UIKit constants table: values', () => {expect(timing).not.toHaveProperty('implicitAnimationMs');});+ it('rows measured on one spring stay equal', () => {+ // Each row is its own literal so a bundle keeps only the rows it+ // imports (springRows.test.ts); these were measured to share a spring.+ for (const group of [+ // UIKit's default spring.+ ['viewChange', 'sheetPresent', 'sheetDismiss', 'banner'],+ ['navigationPush', 'navigationPop'],+ // The presentation's pace at 80 % damping.+ ['sheetReleaseFast', 'sheetDismissSwipe'],+ // UIKit's legacy 0.404 s spring, critically damped.+ [+ 'alertPresent',+ 'alertDismiss',+ 'actionSheetPresent',+ 'actionSheetDismiss',+ ],+ ['menuOpen', 'contextMenuLift'],+ ['menuClose', 'contextMenuDismiss'],+ ] as const) {+ for (const name of group.slice(1)) {+ expect(springs[name], name).toEqual(springs[group[0]]);+ }+ }+ });+it('UIKit\u2019s default spring has the documented damping ratio 4.56 before clamping', () => {const {mass, stiffness, damping} = springs.viewChange;expect(damping / (2 * Math.sqrt(stiffness * mass))).toBeCloseTo(4.56, 2);diff --git a/packages/core/src/theme/expandMotionScale.test.ts b/packages/core/src/theme/expandMotionScale.test.tsindex aa56dd6658..3141cd356b 100644--- a/packages/core/src/theme/expandMotionScale.test.ts+++ b/packages/core/src/theme/expandMotionScale.test.ts@@ -1,5 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import fs from 'node:fs';+import path from 'node:path';import {describe, it, expect} from 'vitest';import {expandMotionScale} from './expandMotionScale';@@ -126,3 +128,18 @@ describe('expandMotionScale', () => {expect(slow).toBeLessThan(slowMax);});});++// @ts-expect-error The role-keyed theme types are not public: motion stays internal.+import type {MotionRoleValues as _NotPublic} from '../index';++describe('touch motion stays internal', () => {+ it('exports no motion-role surface from the theme entry or the package root', () => {+ // The package root re-exports the theme entry and nothing from motion/.+ const read = (file: string) =>+ fs.readFileSync(path.resolve(__dirname, file), 'utf8');+ expect(read('../index.ts')).not.toMatch(/from '\.\/motion/);+ expect(read('./index.ts')).not.toMatch(+ /expandMotionRoles|motionScaleOf|MotionConfig|MotionRoleValues|MotionCurvePoints|registerMotionTable|motion\/role/,+ );+ });+});diff --git a/scripts/motion-table-files.d.mts b/scripts/motion-table-files.d.mtsnew file mode 100644index 0000000000..4033efe964--- /dev/null+++ b/scripts/motion-table-files.d.mts@@ -0,0 +1,6 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** Every motion table module under `dir`, sorted. */+export function motionTableFiles(dir: string): string[];+/** A module export that registers a table. */+export const REGISTER_EXPORT: RegExp;diff --git a/scripts/motion-table-files.mjs b/scripts/motion-table-files.mjsnew file mode 100644index 0000000000..dfba34a78e--- /dev/null+++ b/scripts/motion-table-files.mjs@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file motion-table-files.mjs+ * @input packages/core/src+ * @output motionTableFiles: every non-test source file that registers a motion+ * table (a `register<Name>Table` function, or a legacy module-level+ * `registerMotionTable` call)+ * @position Used by packages/core/src/motion/roles.test.ts to register every+ * table the way discovery would. Tooling only: nothing at runtime registers+ * every table.+ */++import {readdirSync, readFileSync} from 'node:fs';+import {join} from 'node:path';++/**+ * Every motion table module under `dir`, sorted.+ * @param {string} dir+ * @returns {string[]}+ */+export function motionTableFiles(dir) {+ /** @type {string[]} */+ const files = [];+ for (const entry of readdirSync(dir, {withFileTypes: true})) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (entry.name !== 'node_modules' && entry.name !== '__tests__') {+ files.push(...motionTableFiles(path));+ }+ } else if (+ /\.tsx?$/.test(entry.name) &&+ !/\.(test|spec|stories)\.tsx?$/.test(entry.name) &&+ entry.name !== 'roles.ts' &&+ /registerMotionTable\(/.test(readFileSync(path, 'utf8'))+ ) {+ files.push(path);+ }+ }+ return files.sort();+}++/** A module export that registers a table. */+export const REGISTER_EXPORT = /^register[A-Z]\w*Table$/;