Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/motion-tables-register-at-import.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[chore] Internal: each spring role, and the navigation, paging and picker motion tables, register themselves when their module loads, so a spring role plays at the theme's `tempo` wherever it plays, with no register call. A page that plays no spring ships no springs registry. A module that imports single spring rows carries only those rows, unless it also reads the whole `springs` table or calls `registerSpringsTable()`. Not exported from the package entry point.

@vjeux
6 changes: 3 additions & 3 deletions packages/core/src/DateInput/PickerWheel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,9 @@ const styles = stylex.create({

/**
* The motion tables the wheel resolves internal roles from: the timing curve,
* the scroll bounce and the picker's tap spin. Nothing registers on import
* (motion/roles.ts) and each register is idempotent, so the wheel calls this
* right before it resolves a role.
* the scroll bounce and the picker's tap spin. The picker table registers as
* its module loads, but the timing and scroll tables do not. Each register is
* idempotent, so the wheel calls this right before it resolves a role.
*/
function registerWheelTables(): void {
registerTimingTable();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -492,9 +492,9 @@ export class SegmentedSelectionMotion {
}),
options: SegmentedSelectionMotionOptions = {},
) {
// The chase plays the shared `springs.fingerTracking` role, and the slide
// plays the segmented role. Both register before the first animation,
// because nothing registers on import. A second call does nothing.
// The chase plays the shared `springs.fingerTracking` role, which
// registers as its module loads. The slide plays the segmented role, which
// registers here before the first animation. A second call does nothing.
Comment on lines +495 to +497

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: the first sentence only explains why the registerSpringsTable() call below does nothing. Deleting that call leaves one sentence to keep: "The slide plays the segmented role, which registers here before the first animation."

registerSpringsTable();
registerSegmentedTable();
this.now = options.now ?? defaultNow;
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/animator/createAnimator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ export function createAttachableAnimator(): {
if (inactive() || Object.keys(to).length === 0) {
return;
}
// The role registry is written on first use, never on import.
// The spring roles registered as their module loaded, so this call
// registers nothing new.
Comment on lines +215 to +216

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: this comment explains a call that now does nothing. Deleting registerSpringsTable() here, with the comment, says it better; this module reads the whole springs table, so its bundle keeps the same rows either way.

registerSpringsTable();
const velocity = motionValues(options?.velocity);
await motion.animate(to, {
Expand Down
17 changes: 8 additions & 9 deletions packages/core/src/motion/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,13 @@ names for their use (`springs.settle`, `timing.stateChangeMs`,
a plain constant. The per-role tables stay internal (`spec:AST-094` DEC-15): a
role plays its table value at the theme's tempo, and nothing reads the
role's own CSS variable (`--motion-springs-settle`), so no page or theme
style sets a role. A table's
roles exist once its `register<Name>Table()` has run: the animator registers
the Reduce Motion fade's curve, and code that plays the shared springs calls
`registerSpringsTable()` before its first motion. The animator resolves each
role it is handed when the motion starts; code that times something itself
style sets a role. A table's roles exist once its `register<Name>Table()`
has run. A page that plays no spring ships no springs registry; each spring
role registers itself when the module that plays it loads (one idempotent
in-memory write, no DOM). The navigation, paging and picker tables register
themselves at import, and the animator registers the Reduce Motion fade's
curve. The animator resolves each role it is handed when the
motion starts; code that times something itself
calls `resolveMotion(element, timing, 'stateChangeMs')`. Gesture thresholds and
the timings that decide who gets a touch are not roles.

Expand All @@ -74,10 +76,7 @@ import {createMotionEngine} from '../motion/animator';
import {coast} from '../motion/coast';
import {solveSpringTowardRamp, toSpring} from '../motion/spring';
import {resolveMotion} from '../motion/resolveMotion';
import {registerSpringsTable, springs} from '../motion/uikit';

// Once, so the springs are registered as their roles:
registerSpringsTable();
import {springs} from '../motion/uikit';

const animator = createMotionEngine(sheet);
// The animator plays a motion role (spec:AST-094 FR4), its table value, as the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
* @output Proof that the springs follow the tempo of the theme they play
* in. A spring the animator plays inside a scope at tempo 1.5 is
* inherited through a nested element. At 1.5 × t it draws what the same
* spring draws at t outside the scope. Finger tracking draws the same in
* both. Under three real themes that set only `motion.tempo`, the
* spring draws at t outside the scope. A page that imports only the
* springs and the engine, and never registers them, plays at its tempo
* too. Finger tracking draws the same in both. Under three real themes that set only `motion.tempo`, the
* animated-layout glide lasts 0.75, 1 and 1.5 times as long, with a
* finger or a mouse. A theme with only a duration scale, nested in one at
* tempo 1.5, glides at its own pace
Expand Down Expand Up @@ -53,38 +54,41 @@ test.afterAll(async () => {

const TRAVEL = 300;

// A real navigation (not setContent): the page keeps its own window. The
// A real navigation (not setContent): the page keeps its own window. Each
// scope writes the private property a theme that sets `tempo` writes.
async function openScopes(page: Page) {
async function openScopes(page: Page, {register = true} = {}) {
const html = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1">
<style>
html, body { margin: 0; background: #fff; }
.box { position: relative; width: 48px; height: 48px; margin: 8px 0; background: #36c; }
.slow { --_astryx-motion-tempo: 1.5; }
.quick { --_astryx-motion-tempo: 0.75; }
</style>
<div class="box" id="base"></div>
<div class="slow"><section><div class="box" id="slowed"></div></section></div>
<div class="quick"><section><div class="box" id="quick"></div></section></div>
<script>${script}</script>
<script>Motion.registerSpringsTable();</script>`;
${register ? '<script>Motion.registerSpringsTable();</script>' : ''}`;
await page.route('http://tempo.test/', async route =>
route.fulfill({contentType: 'text/html', body: html}),
);
await page.goto('http://tempo.test/');
}

/**
* Plays `role` on both boxes and reads each one's travel, paused at each of
* `times` (ms), the slowed box at its time times `scale`.
* Plays `role` on the base box and the `scaled` one. Reads each one's travel,
* paused at each of `times` (ms), the scaled box at its time times `scale`.
*/
async function travels(
page: Page,
role: 'settle' | 'fingerTracking',
times: number[],
scale: number,
scaled: 'slowed' | 'quick' = 'slowed',
): Promise<{base: number; slowed: number}[]> {
return page.evaluate(
async ({role, times, scale, travel}) => {
const boxes = ['base', 'slowed'].map(
async ({role, times, scale, travel, scaled}) => {
const boxes = ['base', scaled].map(
id => document.getElementById(id) as HTMLElement,
);
const handles = boxes.map(box =>
Expand All @@ -108,7 +112,7 @@ async function travels(
return {base: xOf(boxes[0]), slowed: xOf(boxes[1])};
});
},
{role, times, scale, travel: TRAVEL},
{role, times, scale, travel: TRAVEL, scaled},
);
}

Expand All @@ -126,6 +130,24 @@ test.describe('the springs follow the theme tempo (spec:AST-108 FR3)', () => {
}
});

test('a page that imports only the springs and the engine, with no register call, plays settle at 0.75 and 1.5 × t', async ({
page,
}) => {
// A page whose only motion is one spring role, as a Lightbox is.
for (const [scaled, scale] of [
['slowed', 1.5],
['quick', 0.75],
] as const) {
await openScopes(page, {register: false});
const read = await travels(page, 'settle', [40, 120, 240], scale, scaled);
expect(read[0].base).toBeGreaterThan(5);
expect(read[0].base).toBeLessThan(TRAVEL - 5);
for (const {base, slowed} of read) {
expect(Math.abs(slowed - base), scaled).toBeLessThan(1.5);
}
}
});

test('finger tracking plays as measured inside the scope (FR4)', async ({
page,
}) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/motion/animator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@
* release (`touchRelease`) and at once elsewhere (DR2, DR3).
*
* Roles: every spring and curve the animator plays passes through
* resolveMotion.ts, which names the motion role it plays (`springs.settle`
* once `registerSpringsTable()` has run, the Reduce Motion fade's curve,
* which the animator registers alone). The per-role tables stay internal
* resolveMotion.ts, which names the motion role it plays. `springs.settle`
* registers as its module loads, and the animator registers the Reduce Motion
* fade's curve alone. The per-role tables stay internal
* (`spec:AST-094` DEC-15), so a role plays its table value: nothing reads a
* role's own CSS variable. Its time scales by the tempo of the element's
* theme. A spring written inline at the call
Expand Down
29 changes: 29 additions & 0 deletions packages/core/src/motion/roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,35 @@ export function registerMotionTable(
walk(table as Record<string, unknown>, id);
}

/**
* Registers `leaf` as the spring role `id` (a table path such as
* `springs.settle`) and returns it, so a table row can register itself. A row
* that calls it under a pure annotation drops out of a bundle that does not
* use it, call included. Registering the same leaf under the same id again
* does nothing.
*/
export function registerSpringRole<T extends SpringDescription>(
id: string,
leaf: T,
): T {
if (!isMotionRoleId(id)) {
throw new Error(
`motion role "${id}" must be a dotted table path such as "springs.settle"`,
);
}
if (roleOfLeaf.get(leaf)?.id !== id) {
const role: MotionRole = {
id,
kind: 'spring',
variable: motionRoleVariable(id),
value: leaf,
};
rolesById.set(id, role);
roleOfLeaf.set(leaf, role);
}
return leaf;
}

/** 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'
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/motion/uikit/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,12 @@ export const navigation = {
/**
* 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.
* measured. A page that plays no navigation motion ships no navigation
* registry. The module registers its own table at import (one idempotent
* in-memory write, no DOM).
*/
export function registerNavigationTable(): void {
registerMotionTable('navigation', navigation);
}

registerNavigationTable();
5 changes: 4 additions & 1 deletion packages/core/src/motion/uikit/paging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,11 +183,14 @@ export const paging = {
* then reads `setContentOffset(_:animated:)`'s duration and curve through
* `resolveMotion`, as it reads every touch motion. The table lists no role,
* because no motion role names any of its values, so each plays as measured.
* Nothing registers on import, and a second call does nothing.
* A page that plays no paging motion ships no paging registry. The module
* registers its own table at import (one idempotent in-memory write, no DOM).
*/
export function registerPagingTable(): void {
registerMotionTable('paging', paging, {
// Who gets the touch, not how anything moves.
exclude: ['catchStopMs'],
});
}

registerPagingTable();
7 changes: 5 additions & 2 deletions packages/core/src/motion/uikit/picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,12 @@ export const picker = {
* Registers the tap spin's duration as an internal motion role,
* `picker.tapSpin.durationMs`. Every other value stays an internal measured
* constant. The tap spin's curve is the shared role `timing.curves.move`, and
* the bounce at an end is `scroll.bounce`. Nothing registers on import, and
* registering again does nothing.
* the bounce at an end is `scroll.bounce`. A page that plays no picker motion
* ships no picker registry. The module registers its own table at import (one
* idempotent in-memory write, no DOM).
*/
export function registerPickerTable(): void {
registerMotionTable('picker', picker, {roles: ['tapSpin.durationMs']});
}

registerPickerTable();
96 changes: 96 additions & 0 deletions packages/core/src/motion/uikit/selfRegistration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file selfRegistration.test.ts
* @input vitest (jsdom); each touch table imported in a fresh module graph,
* with no call to its register function
* @output Checks that each spring role row, and the navigation, paging and
* picker tables, register at import, so a role plays at the theme's tempo
* @position Testing; validates uikit/springs.ts, navigation.ts, paging.ts and
* picker.ts
*/

import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';

const TEMPO_PROPERTY = '--_astryx-motion-tempo';
/** The tempo the stubbed theme writes; empty where no theme sets one. */
let tempo = '';

beforeEach(() => {
vi.resetModules();
tempo = '';
vi.spyOn(window, 'getComputedStyle').mockImplementation(
() =>
({
getPropertyValue: (name: string) =>
name === TEMPO_PROPERTY ? tempo : '',
}) as unknown as CSSStyleDeclaration,
);
});

afterEach(() => {
vi.doUnmock('../roles');
vi.restoreAllMocks();
document.body.innerHTML = '';
});

function element(): HTMLElement {
const child = document.createElement('div');
document.body.append(child);
return child;
}

describe('the touch tables register at import', () => {
it('a page that imports only the settle row plays it at the tempo', async () => {
const {SETTLE_SPRING} = await import('./springs');
const {resolveMotion} = await import('../resolveMotion');
const {solveSpring, toSpring} = await import('../spring');
const target = element();
const base = solveSpring(toSpring(SETTLE_SPRING), {from: 0, to: 1});
for (const scale of [0.75, 1.5]) {
tempo = String(scale);
const played = solveSpring(
toSpring(resolveMotion(target, SETTLE_SPRING)),
{from: 0, to: 1},
);
expect(played.settleTime(0.001)).toBeCloseTo(
base.settleTime(0.001) * scale,
6,
);
}
});

it('a page that imports only the picker plays its tap spin at the tempo', async () => {
const {picker} = await import('./picker');
const {resolveMotion} = await import('../resolveMotion');
tempo = '1.5';
expect(resolveMotion(element(), picker.tapSpin, 'durationMs')).toBe(
picker.tapSpin.durationMs * 1.5,
);
});

it('each role row and table registers itself, at import', async () => {
const registered: string[] = [];
vi.doMock('../roles', async importOriginal => {
const actual = await importOriginal<typeof import('../roles')>();
return {
...actual,
registerMotionTable: (
...args: Parameters<typeof actual.registerMotionTable>
) => {
registered.push(args[0]);
actual.registerMotionTable(...args);
},
};
});
const {SETTLE_SPRING, KEYBOARD_SPRING} = await import('./springs');
await import('./navigation');
await import('./paging');
await import('./picker');
const {motionRoleOf} = await import('../roles');
expect(motionRoleOf(SETTLE_SPRING)?.id).toBe('springs.settle');
// The keyboard's spring is a measured constant, not a role.
expect(motionRoleOf(KEYBOARD_SPRING)).toBeUndefined();
expect(registered).toEqual(['navigation', 'paging', 'picker']);
});
});
Loading
Loading