Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
6.9 KB
Raw Blame
// 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',
    '',
    "The owner's goal: \"The main goals are consistent timings and well-coordinated pieces.\" The rules serve it: springs for a component whose main interaction is a gesture, including the moves a tap starts inside it; curve tokens for a component whose main interaction is a tap, tap-to-expand included; the nearest-token mapping for a measured duration; one coordinated scale for springs and curves through `tempo`, each spring paired with a timing tier (`spec:AST-094` FR45); and no per-component exceptions and no platform-native option. The owner's guidance: \"The guidance im thinking is: timing should be coordinated between spring and motion curve tokens, then use spring for gestures where velocity matters, use motion curves for taps presses and other non gesture motion.\" A component whose main interaction is a gesture plays springs for its motion, including moves a tap starts inside it (a tap on a sheet detent or a close button settles on the same spring), so its pieces stay coordinated. A component whose main interaction is a tap plays the theme's curve tokens (duration and easing, scaled by `tempo`), never a spring, since a tap carries no velocity; no character or option plays a platform-measured curve for it (owner decision, 2026-11-04). `spec:AST-094` FR45 lists which components each covers. 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. In a component whose main interaction is a tap, a role plays only for motion a gesture drives; in a gesture component, its roles also settle the moves a tap, a key or the program starts (`spec:AST-094` FR45). In a component whose main interaction is a tap, motion that a tap, a click, a hold, a key or the program starts plays the theme's duration and easing tokens, and an exit it starts plays the theme's exit duration and easing (`spec:AST-094` FR7), and a role measured for that motion stays as the native reference. Two approved motions keep their springs until their own records change: the animator's `animate` (`spec:AST-107` FR3) and `useDragToSnapPoints`'s `settleTo` (`spec:AST-107`). AST-105's glide, swap and edge reveal are tap-started layout motion and play the theme's curve tokens, except a gesture's release, which settles on its spring (`spec:AST-105` FR4). Reduce Motion substitutions and continuous busy loops (such as ProgressBar's indeterminate pulse, `component:ProgressBar` FR6) keep their named roles; they are neither gesture- nor interaction-started motion. Measured input timings, such as gesture thresholds, hold durations and flick speeds, are not motion roles.",
    '',
    '| Role | Kind | Default | Named by |',
    '| --- | --- | --- | --- |',
    ...rows,
    '',
  ].join('\n');
  return {source, unnamed};
}