An open source design system that's fully customizable and agent ready
TypeScript
chore(core): the generated motion role table lists every registered role and the record that names it (#9454)
Christopher Chedeau30e97b303f7e
diff --git a/docs/specs/AST-094-touch-presentations/motion-roles.md b/docs/specs/AST-094-touch-presentations/motion-roles.mdnew file mode 100644index 0000000000..3aa6b3bbad--- /dev/null+++ b/docs/specs/AST-094-touch-presentations/motion-roles.md@@ -0,0 +1,28 @@+<!-- Generated by scripts/generate-motion-roles.mjs from every registered motion table. Do not edit: run `pnpm generate:motion-roles`. -->++# Motion roles++Every motion role a registered table lists (`spec:AST-094` FR4, DEC-5): its kind, its default as the table measures it, and the record that names it. A role FR4 lists is named by FR4; any other role is one a component's own record measures, named by the current component records that carry its id.++| Role | Kind | Default | Named by |+| ---------------------------- | -------- | ----------------------------------- | ------------------ |+| `springs.contextMenuDismiss` | spring | response 0.35 s, damping ratio 0.85 | `spec:AST-094` FR4 |+| `springs.contextMenuLift` | spring | response 0.32 s, damping ratio 0.8 | `spec:AST-094` FR4 |+| `springs.contextMenuMorph` | spring | response 0.3 s, damping ratio 0.8 | `spec:AST-094` FR4 |+| `springs.directChange` | spring | response 0.5 s, damping ratio 0.825 | `spec:AST-094` FR4 |+| `springs.emphasis` | spring | duration 0.5 s, bounce 0.3 | `spec:AST-094` FR4 |+| `springs.fingerTracking` | spring | response 0.15 s, damping ratio 0.86 | `spec:AST-094` FR4 |+| `springs.menuClose` | spring | response 0.35 s, damping ratio 0.85 | `spec:AST-094` FR4 |+| `springs.menuOpen` | spring | response 0.32 s, damping ratio 0.8 | `spec:AST-094` FR4 |+| `springs.quickChange` | spring | duration 0.5 s, bounce 0.15 | `spec:AST-094` FR4 |+| `springs.settle` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |+| `springs.stateChange` | spring | response 0.55 s, damping ratio 1 | `spec:AST-094` FR4 |+| `springs.subMenuBack` | spring | response 0.4 s, damping ratio 1 | `spec:AST-094` FR4 |+| `springs.subMenuOpen` | spring | response 0.4 s, damping ratio 0.85 | `spec:AST-094` FR4 |+| `springs.timedChange` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |+| `springs.viewChange` | spring | mass 3, stiffness 1000, damping 500 | `spec:AST-094` FR4 |+| `timing.curves.entrance` | curve | cubic-bezier(0, 0, 0.58, 1) | `spec:AST-094` FR4 |+| `timing.curves.exit` | curve | cubic-bezier(0.42, 0, 1, 1) | `spec:AST-094` FR4 |+| `timing.curves.move` | curve | cubic-bezier(0.42, 0, 0.58, 1) | `spec:AST-094` FR4 |+| `timing.curves.viewChange` | curve | cubic-bezier(0.25, 0.1, 0.25, 1) | `spec:AST-094` FR4 |+| `timing.stateChangeMs` | duration | 250 ms | `spec:AST-094` FR4 |diff --git a/package.json b/package.jsonindex 2ed6bccaa2..4467fe1b50 100644--- a/package.json+++ b/package.json@@ -36,7 +36,7 @@"storyboards": "playwright test --config playwright.interaction.config.ts --grep @storyboard","typecheck": "pnpm -r --no-bail --workspace-concurrency=1 --if-present --filter \"!@astryxdesign/docsite\" --filter \"!@astryxdesign/sandbox\" run typecheck","check:package-boundaries": "node scripts/check-package-boundaries.js",- "check:repo": "pnpm check:visual-owner && pnpm check:sync && pnpm check:neutral-palette-refs && pnpm check:stone-palette-refs && pnpm check:gothic-palette-refs && pnpm check:matcha-palette-refs && pnpm check:butter-palette-refs && pnpm check:y2k-palette-refs && pnpm check:data-tokens && pnpm check:token-docs && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-runtime && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:cldr-month-capitals && pnpm check:fixtures && pnpm check:setup-contract",+ "check:repo": "pnpm check:visual-owner && pnpm check:sync && pnpm check:neutral-palette-refs && pnpm check:stone-palette-refs && pnpm check:gothic-palette-refs && pnpm check:matcha-palette-refs && pnpm check:butter-palette-refs && pnpm check:y2k-palette-refs && pnpm check:data-tokens && pnpm check:token-docs && pnpm check:motion-roles && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-runtime && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:cldr-month-capitals && pnpm check:fixtures && pnpm check:setup-contract","check:visual-owner": "node scripts/check-visual-workflow-owner.mjs","check:fixtures": "node internal/vibe-tests/scripts/fixture-suite.mjs verify","generate:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs",@@ -58,6 +58,8 @@"check:data-tokens": "node scripts/generate-data-tokens.mjs --check","generate:token-docs": "node scripts/generate-token-docs.mjs","check:token-docs": "node scripts/generate-token-docs.mjs --check",+ "generate:motion-roles": "node scripts/generate-motion-roles.mjs",+ "check:motion-roles": "node scripts/generate-motion-roles.mjs --check","check:use-client": "node scripts/check-use-client.mjs","lint": "pnpm check:repo && eslint . --cache","lint:strict": "pnpm check:repo && ASTRYX_STRICT_LINT=1 eslint . --cache",diff --git a/packages/core/src/motion/roles.test.ts b/packages/core/src/motion/roles.test.tsindex 74fe2c95ca..4b072edb06 100644--- a/packages/core/src/motion/roles.test.ts+++ b/packages/core/src/motion/roles.test.ts@@ -3,13 +3,16 @@/*** @file roles.test.ts* @input roles.ts and the shared UIKit tables (registered by this test)- * @output Proof that the registered roles are exactly the ones spec:AST-094- * FR4 names, each by its table path; that every other table value, a- * component's measured spring included, is no role; and that a role's CSS- * value reads back as the same motion+ * @output Proof that the registered roles are every role spec:AST-094 FR4+ * names plus the ones the generated motion role table lists, each by its+ * table path and each named by FR4 or a component's own record (DEC-5);+ * that the generated table is in step with the registered tables; that+ * every other table value, a component's measured spring included, is no+ * role; and that a role's CSS value reads back as the same motion* @position Testing for /packages/core/src/motion/roles.ts*/+import {spawnSync} from 'node:child_process';import {readFileSync} from 'node:fs';import {resolve} from 'node:path';import {describe, expect, it} from 'vitest';@@ -29,6 +32,13 @@ import {motionTableFiles,REGISTER_EXPORT,} from '../../../../scripts/motion-table-files.mjs';+import {+ fr4RoleIds,+ MOTION_ROLE_TABLE,+ tableRoleIds,+} from '../../../../scripts/motion-roles-table.mjs';++const ROOT = resolve(__dirname, '../../../..');// Every table the role list is generated from, registered the way the// generator does: through each module's register<Name>Table.@@ -44,6 +54,9 @@ for (const file of motionTableFiles(resolve(__dirname, '..'))) {const DISCOVERED = new Set(listMotionRoles().map(role => role.id.split('.')[0]),);+/** The roles of the tables discovery registered (tests here add fixtures). */+const discoveredRoles = () =>+ listMotionRoles().filter(role => DISCOVERED.has(role.id.split('.')[0]));describe('motion roles', () => {it('names a role by its table path, and its CSS variable in kebab case', () => {@@ -79,26 +92,38 @@ describe('motion roles', () => {);});- it('has exactly the roles spec:AST-094 FR4 names', () => {- const spec = readFileSync(- resolve(- __dirname,- '../../../../docs/specs/AST-094-touch-presentations/spec.md',+ it('has every role spec:AST-094 FR4 names, and exactly the roles the generated motion role table lists', () => {+ const named = fr4RoleIds(+ readFileSync(+ resolve(ROOT, 'docs/specs/AST-094-touch-presentations/spec.md'),+ 'utf8',),- '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),+ const registered = new Set(discoveredRoles().map(role => role.id));+ for (const id of named) {+ expect(registered.has(id), id).toBe(true);+ }+ // FR4's roles and the ones a component's record measures (DEC-5).+ expect(registered).toEqual(+ new Set(+ tableRoleIds(readFileSync(resolve(ROOT, MOTION_ROLE_TABLE), 'utf8')),+ ),);});+ it('keeps the generated motion role table in step with the registered tables, each role named by FR4 or a component record (spec:AST-094 DEC-5)', () => {+ // The generator registers every table itself, in its own Node process:+ // it reads the knowledge records, which this environment cannot load.+ const run = spawnSync(+ process.execPath,+ [resolve(ROOT, 'scripts/generate-motion-roles.mjs'), '--check'],+ {cwd: ROOT, encoding: 'utf8'},+ );+ expect(run.stderr).toBe('');+ expect(run.status).toBe(0);+ });+it('names the shared roles for their use, as spec:AST-094 FR4 does', () => {expect([@@ -190,14 +215,10 @@ describe('motion roles', () => {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]),- );+ it('registers the roles spec:AST-094 FR4 names internally, each of its kind', () => {expect(- Object.fromEntries(discovered.map(role => [role.id, role.kind])),- ).toEqual({+ Object.fromEntries(discoveredRoles().map(role => [role.id, role.kind])),+ ).toMatchObject({'springs.contextMenuDismiss': 'spring','springs.contextMenuLift': 'spring','springs.contextMenuMorph': 'spring',diff --git a/scripts/generate-motion-roles.mjs b/scripts/generate-motion-roles.mjsnew file mode 100644index 0000000000..bbf8037cec--- /dev/null+++ b/scripts/generate-motion-roles.mjs@@ -0,0 +1,128 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file generate-motion-roles.mjs+ * @input Every motion table under packages/core/src (scripts/motion-table-files.mjs),+ * spec:AST-094's FR4 table, and the current component records+ * @output docs/specs/AST-094-touch-presentations/motion-roles.md: the+ * generated motion role table (spec:AST-094 DEC-5), listing every+ * registered role, its kind, its default, and the record that names it+ * @position Tooling. `--check` fails when the committed table drifts from the+ * registered tables; either mode fails when a registered role is named+ * neither by FR4 nor by a component's own current record.+ * packages/core/src/motion/roles.test.ts runs the check.+ *+ * Run: pnpm generate:motion-roles+ * CI: pnpm check:motion-roles+ */++import {build} from 'esbuild';+import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {format, resolveConfig} from 'prettier';+import {+ discoverKnowledgeRecords,+ parseKnowledgeDocument,+} from './check-knowledge.mjs';+import {+ fr4RoleIds,+ MOTION_ROLE_TABLE,+ renderMotionRoleTable,+} from './motion-roles-table.mjs';+import {motionTableFiles, REGISTER_EXPORT} from './motion-table-files.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const SPEC = 'docs/specs/AST-094-touch-presentations/spec.md';++/**+ * Every registered role: each motion table module's register<Name>Table+ * runs, the way roles.test.ts registers them, in a bundle of the sources.+ * @returns {Promise<{id: string, kind: 'spring' | 'duration' | 'curve', value: unknown}[]>}+ */+async function registeredRoles() {+ const files = motionTableFiles(path.join(ROOT, 'packages/core/src'));+ const entry = [+ `import {listMotionRoles} from ${JSON.stringify(path.join(ROOT, 'packages/core/src/motion/roles.ts'))};`,+ ...files.map(+ (file, index) =>+ `import * as table${index} from ${JSON.stringify(file)};`,+ ),+ `const register = ${REGISTER_EXPORT};`,+ `for (const table of [${files.map((_, index) => `table${index}`).join(', ')}]) {`,+ ' for (const [name, value] of Object.entries(table)) {',+ " if (register.test(name) && typeof value === 'function') value();",+ ' }',+ '}',+ 'export const roles = listMotionRoles().map(({id, kind, value}) => ({id, kind, value}));',+ ].join('\n');+ const result = await build({+ stdin: {contents: entry, resolveDir: ROOT, loader: 'ts'},+ bundle: true,+ write: false,+ format: 'esm',+ platform: 'node',+ logLevel: 'silent',+ });+ const source = Buffer.from(result.outputFiles[0].text).toString('base64');+ const module = await import(`data:text/javascript;base64,${source}`);+ return module.roles;+}++/**+ * The current component records, each with its id and text: the records+ * that measure a component's own roles (spec:AST-094 FR4, DEC-5).+ * @returns {{id: string, text: string}[]}+ */+function componentRecords() {+ return discoverKnowledgeRecords(ROOT).flatMap(file => {+ const text = fs.readFileSync(file, 'utf8');+ const {frontmatter} = parseKnowledgeDocument(text, file);+ const id = frontmatter.get('id');+ return frontmatter.get('kind') === 'component' &&+ frontmatter.get('authority') === 'current' &&+ typeof id === 'string'+ ? [{id, text}]+ : [];+ });+}++async function main() {+ const check = process.argv.slice(2).includes('--check');+ const roles = await registeredRoles();+ const {source, unnamed} = renderMotionRoleTable(roles, {+ fr4: fr4RoleIds(fs.readFileSync(path.join(ROOT, SPEC), 'utf8')),+ records: componentRecords(),+ });+ if (unnamed.length > 0) {+ console.error(+ `A registered motion role must be named by spec:AST-094 FR4 or by a component's own current record (spec:AST-094 DEC-5); neither names ${unnamed.join(', ')}.`,+ );+ process.exitCode = 1;+ return;+ }+ const file = path.join(ROOT, MOTION_ROLE_TABLE);+ const markdown = await format(source, {+ ...(await resolveConfig(file)),+ filepath: file,+ });+ if (check) {+ const committed = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';+ if (committed !== markdown) {+ console.error(+ `${MOTION_ROLE_TABLE} is out of date with the registered motion tables: run \`pnpm generate:motion-roles\`.`,+ );+ process.exitCode = 1;+ return;+ }+ console.log(+ `${MOTION_ROLE_TABLE} lists the ${roles.length} registered motion roles, each named by FR4 or a component's own record.`,+ );+ return;+ }+ fs.writeFileSync(file, markdown);+ console.log(`Wrote ${MOTION_ROLE_TABLE} (${roles.length} roles).`);+}++await main();diff --git a/scripts/motion-roles-table.d.mts b/scripts/motion-roles-table.d.mtsnew file mode 100644index 0000000000..da5a105ad4--- /dev/null+++ b/scripts/motion-roles-table.d.mts@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** The generated table, relative to the repository root. */+export const MOTION_ROLE_TABLE: string;+/** The role ids spec:AST-094 FR4's table lists. */+export function fr4RoleIds(specText: string): string[];+/** The role ids a generated table lists. */+export function tableRoleIds(markdown: string): string[];+/** A role's default as its table measures it. */+export function describeDefault(+ kind: 'spring' | 'duration' | 'curve',+ value: unknown,+): string;+/**+ * The generated motion role table for `roles`, before formatting, and the+ * roles neither FR4 nor a component's own record names.+ */+export function renderMotionRoleTable(+ roles: ReadonlyArray<{+ id: string;+ kind: 'spring' | 'duration' | 'curve';+ value: unknown;+ }>,+ names: {+ fr4: ReadonlyArray<string>;+ records: ReadonlyArray<{id: string; text: string}>;+ },+): {source: string; unnamed: string[]};diff --git a/scripts/motion-roles-table.mjs b/scripts/motion-roles-table.mjsnew file mode 100644index 0000000000..21c3f26de0--- /dev/null+++ b/scripts/motion-roles-table.mjs@@ -0,0 +1,120 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file motion-roles-table.mjs+ * @input Every registered motion role ({id, kind, value}), the roles+ * `spec:AST-094` FR4's table lists, and the current component records+ * @output The generated motion role table (`spec:AST-094` DEC-5) as+ * Markdown, before formatting, and the registered roles neither FR4 nor a+ * component's own record names; the role ids FR4 and a generated table list+ * @position Used by scripts/generate-motion-roles.mjs, which writes and+ * checks docs/specs/AST-094-touch-presentations/motion-roles.md, and by+ * packages/core/src/motion/roles.test.ts, which holds the registered roles+ * to that file. Reads no file itself.+ *+ * A role FR4 lists is named by `spec:AST-094` FR4. Any other role is one a+ * component's own record measures (DEC-5): it is named by the current+ * component records whose text carries its id in backticks. A role in a+ * shared table, such as `springs`, can belong to a component's record rather+ * than the table's.+ */++/** The generated table, relative to the repository root. */+export const MOTION_ROLE_TABLE =+ 'docs/specs/AST-094-touch-presentations/motion-roles.md';+const ROLE_ROW = /^\s*\| `([a-z][\w.]*)`\s*\|/gm;++/**+ * The role ids FR4's table lists.+ * @param {string} specText spec:AST-094's record+ * @returns {string[]}+ */+export function fr4RoleIds(specText) {+ const fr4 = specText.slice(+ specText.indexOf('**FR4'),+ specText.indexOf('**FR5'),+ );+ return [...fr4.matchAll(ROLE_ROW)].map(match => match[1]);+}++/**+ * The role ids a generated table lists.+ * @param {string} markdown+ * @returns {string[]}+ */+export function tableRoleIds(markdown) {+ return [...markdown.matchAll(ROLE_ROW)].map(match => match[1]);+}++/** @param {number} value */+const number = value => String(value);++/**+ * A role's default as its table measures it.+ * @param {'spring' | 'duration' | 'curve'} kind+ * @param {unknown} value+ * @returns {string}+ */+export function describeDefault(kind, value) {+ if (kind === 'duration') {+ return `${number(/** @type {number} */ (value))} ms`;+ }+ if (kind === 'curve') {+ return `cubic-bezier(${/** @type {number[]} */ (value).map(number).join(', ')})`;+ }+ const spring = /** @type {Record<string, number>} */ (value);+ if ('response' in spring) {+ return `response ${number(spring.response)} s, damping ratio ${number(spring.dampingRatio)}`;+ }+ if ('duration' in spring) {+ return `duration ${number(spring.duration)} s, bounce ${number(spring.bounce)}`;+ }+ return [+ ...('mass' in spring ? [`mass ${number(spring.mass)}`] : []),+ `stiffness ${number(spring.stiffness)}`,+ `damping ${number(spring.damping)}`,+ ].join(', ');+}++/**+ * The generated motion role table for `roles`, before formatting, and the+ * roles neither FR4 nor a component's own record names.+ * @param {ReadonlyArray<{id: string, kind: 'spring' | 'duration' | 'curve', value: unknown}>} roles+ * @param {{fr4: ReadonlyArray<string>, records: ReadonlyArray<{id: string, text: string}>}} names+ * the roles FR4 lists, and the current component records+ * @returns {{source: string, unnamed: string[]}}+ */+export function renderMotionRoleTable(roles, {fr4, records}) {+ const listed = new Set(fr4);+ /** @type {string[]} */+ const unnamed = [];+ const rows = [...roles]+ .sort((a, b) => (a.id < b.id ? -1 : 1))+ .map(role => {+ let namedBy = '`spec:AST-094` FR4';+ if (!listed.has(role.id)) {+ const ids = records+ .filter(record => record.text.includes(`\`${role.id}\``))+ .map(record => `\`${record.id}\``)+ .sort();+ if (ids.length === 0) {+ unnamed.push(role.id);+ }+ namedBy = ids.join(', ');+ }+ return `| \`${role.id}\` | ${role.kind} | ${describeDefault(role.kind, role.value)} | ${namedBy} |`;+ });+ const source = [+ '<!-- Generated by scripts/generate-motion-roles.mjs from every registered motion table. Do not edit: run `pnpm generate:motion-roles`. -->',+ '',+ '# Motion roles',+ '',+ "Every motion role a registered table lists (`spec:AST-094` FR4, DEC-5): its kind, its default as the table measures it, and the record that names it. A role FR4 lists is named by FR4; any other role is one a component's own record measures, named by the current component records that carry its id.",+ '',+ '| Role | Kind | Default | Named by |',+ '| --- | --- | --- | --- |',+ ...rows,+ '',+ ].join('\n');+ return {source, unnamed};+}