From 4d0457f9c299b21c141076029fe38c9acab18910 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:25:11 +0800 Subject: [PATCH 1/4] feat: align MOTION.md v0.2 with DESIGN.md's Nov 2026 spec DESIGN.md (google-labs-code/design.md #178-#183) now owns motion timing tokens. MOTION.md binds them with `design` and references them with `timing: "{motion.}"` instead of restating durations and curves. - Resolve tokens into Motion IR with exact CSS easing mapping and the DESIGN.md hash; timing + literal fields is a conflict; info hint when a literal equals a token - Interleaved ```yaml blocks, `omitted`, and `@path#fragment` references with DESIGN.md semantics - Fence-aware Markdown scanning; rename missing-frontmatter to missing-machine-data - Bump spec and IR to 0.2 (no 0.1 compatibility), add design-bound example, release notes with migration, and a CI workflow Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XvGrrMtBAhmTdvPRgAnpxt --- .github/workflows/check.yml | 16 ++ CHANGELOG.md | 8 + README.md | 43 ++-- README.zh-CN.md | 43 ++-- docs/interoperability.md | 21 +- docs/motion-ir.md | 25 ++- docs/releases/v0.2.0.md | 33 +++ docs/spec.md | 101 ++++++++-- examples/design-bound/DESIGN.md | 38 ++++ examples/design-bound/MOTION.md | 150 ++++++++++++++ examples/expressive/MOTION.md | 2 +- examples/minimal/MOTION.md | 2 +- examples/procedural/MOTION.md | 2 +- examples/reduced-motion/MOTION.md | 2 +- fixtures/invalid/broken-reference.MOTION.md | 2 +- .../invalid/executable-procedure.MOTION.md | 2 +- fixtures/valid/static.MOTION.md | 2 +- package.json | 4 +- packages/cli/package.json | 2 +- packages/cli/src/index.mjs | 22 +- packages/motion-ir/package.json | 2 +- packages/motion-ir/src/index.mjs | 46 ++++- packages/parser/package.json | 2 +- packages/parser/src/design.mjs | 120 +++++++++++ packages/parser/src/document.mjs | 135 +++++++++++++ packages/parser/src/index.mjs | 157 +++++++++++---- packages/parser/src/validate.mjs | 58 +++++- schemas/motion.schema.json | 48 ++++- tests/cli.test.mjs | 10 +- tests/design.test.mjs | 189 ++++++++++++++++++ tests/motion-ir.test.mjs | 2 +- tests/parser.test.mjs | 6 +- 32 files changed, 1147 insertions(+), 148 deletions(-) create mode 100644 .github/workflows/check.yml create mode 100644 docs/releases/v0.2.0.md create mode 100644 examples/design-bound/DESIGN.md create mode 100644 examples/design-bound/MOTION.md create mode 100644 packages/parser/src/design.mjs create mode 100644 packages/parser/src/document.mjs create mode 100644 tests/design.test.mjs diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..7997b28 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,16 @@ +name: check + +on: + push: + branches: [main] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + - run: npm run check diff --git a/CHANGELOG.md b/CHANGELOG.md index 204d225..278f6e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.2.0 - 2026-11-19 + +- Aligned with the 2026-11-17 `DESIGN.md` update: `DESIGN.md` owns motion timing tokens; `MOTION.md` binds them with `design` and references them with `timing: "{motion.}"`. +- Resolved design tokens in Motion IR, including the bound `DESIGN.md` hash. +- Added interleaved YAML blocks, `omitted`, and external `@` references with `DESIGN.md` semantics. +- Added `prefer-design-token`, `timing-conflict`, `design-path`, `duplicate-key`, `unknown-omission`, and `redundant-omission` rules; renamed `missing-frontmatter` to `missing-machine-data`. +- Added the design-bound example and a CI workflow. See `docs/releases/v0.2.0.md` for migration. + ## 0.1.0 - 2026-07-20 - Established the independent `motion.md` philosophy, scope, terminology, and version policy. diff --git a/README.md b/README.md index 021a9e5..8519f41 100644 --- a/README.md +++ b/README.md @@ -6,11 +6,11 @@ A format specification for describing motion graphics and frontend animation int **English** · [简体中文](README.zh-CN.md) -[Specification](docs/spec.md) · [JSON Schema](schemas/motion.schema.json) · [Examples](examples) · [v0.1.0 release](https://github.com/2233admin/motion.md/releases/tag/v0.1.0) +[Specification](docs/spec.md) · [JSON Schema](schemas/motion.schema.json) · [Examples](examples) · [v0.2 release notes](docs/releases/v0.2.0.md) ## The Format -A `MOTION.md` file combines machine-readable motion semantics in YAML front matter with human-readable design intent in Markdown prose. +A `MOTION.md` file combines machine-readable motion semantics in YAML (front matter, or ` ```yaml ` blocks interleaved into the sections they belong to) with human-readable design intent in Markdown prose. The YAML defines exact states, events, transitions, timelines, curves, interruption rules, accessibility substitutions, and performance budgets. The prose explains why those rules exist, what the motion should communicate, and where restraint matters. @@ -19,7 +19,7 @@ The YAML defines exact states, events, transitions, timelines, curves, interrupt ```md --- -version: "0.1" +version: "0.2" name: Quiet Feedback posture: minimal states: @@ -83,7 +83,7 @@ This motion direction is authored for the product. An agent reading this file knows which state owns the result, which event causes the change, how interruption is resolved, what reduced motion preserves, and which performance limits must survive runtime selection. -See the [minimal](examples/minimal/MOTION.md), [expressive](examples/expressive/MOTION.md), [procedural](examples/procedural/MOTION.md), and [reduced-motion](examples/reduced-motion/MOTION.md) examples for complete motion systems. +See the [minimal](examples/minimal/MOTION.md), [expressive](examples/expressive/MOTION.md), [procedural](examples/procedural/MOTION.md), [reduced-motion](examples/reduced-motion/MOTION.md), and [design-bound](examples/design-bound/MOTION.md) examples for complete motion systems. The design-bound example takes its timing from a sibling `DESIGN.md`. ## Getting Started @@ -100,7 +100,7 @@ The CLI emits structured findings that coding agents can act on: { "findings": [], "format": "motion.md", - "specVersion": "0.1", + "specVersion": "0.2", "summary": { "errors": 0, "warnings": 0, @@ -123,8 +123,8 @@ The full `MOTION.md` specification lives at [`docs/spec.md`](docs/spec.md). What A `MOTION.md` file has two layers: -1. **YAML front matter** — exact motion semantics, delimited by `---` fences at the top of the file; -2. **Markdown body** — design intent and rationale organized into `##` sections. +1. **YAML** — exact motion semantics, either as front matter delimited by `---` fences or as ` ```yaml ` blocks inside the relevant section (for example `reducedMotion` under `## Reduced Motion`). All blocks merge into one tree; each top-level key may appear once; +2. **Markdown body** — design intent and rationale organized into `##` sections. Prose may point to other files with `` `@path#fragment` ``, resolved from the `MOTION.md` directory. YAML is normative for exact values and graph relationships. Markdown is normative for intent, priorities, prohibitions, and decision rationale. A conforming consumer reports conflicts instead of silently choosing one layer. @@ -135,10 +135,13 @@ YAML is normative for exact values and graph relationships. Markdown is normativ | `version` | Specification version | | `name` | Human-readable motion system name | | `posture` | `static`, `minimal`, `expressive`, or `procedural` | +| `design` | Relative path to a `DESIGN.md` whose `motion` tokens may be referenced | +| `omitted` | Prose sections deliberately left out, with optional reasons | +| `defaults` | Default timing: a `timing` token reference, or duration, delay, and curve | | `states` | Semantic product states | | `events` | User, system, data, time, viewport, media, or sensor inputs | | `curves` | Linear, Bézier, steps, spring, or procedural curves | -| `timelines` | Runtime-neutral drivers, tracks, and keyframes | +| `timelines` | Runtime-neutral drivers, tracks, and keyframes; tracks may use `timing: "{motion.}"` | | `transitions` | State changes, interruption, and cancellation policy | | `reducedMotion` | Accessibility strategy and semantic substitutions | | `performance` | Frame, input, concurrency, and determinism budgets | @@ -158,7 +161,7 @@ Markdown sections may be omitted, but those present should follow this order: 6. Performance 7. Provenance -Unknown sections are preserved. Duplicate second-level headings are invalid because they make stable section addressing ambiguous. +Unknown sections are preserved. Duplicate second-level headings are invalid because they make stable section addressing ambiguous. Sections left out on purpose are declared in `omitted`, which suppresses the `missing-section` warning. ## CLI Reference @@ -172,21 +175,21 @@ All commands accept file paths; `lint` and `parse` also accept `-` for standard | `motionmd spec` | Output the Markdown specification | | `motionmd spec --format json` | Output the JSON Schema | -`lint`, `parse`, and `diff` exit with code `1` when invalid or breaking results are found. CLI misuse and unreadable input exit with code `2`. +`design` and `@` references resolve from each input file's directory (the working directory for standard input). `lint`, `parse`, and `diff` exit with code `1` when invalid or breaking results are found. CLI misuse and unreadable input exit with code `2`. ## Relationship to DESIGN.md -The project shape deliberately aligns with Google Labs' [`design.md`](https://github.com/google-labs-code/design.md): +In November 2026 Google Labs' [`design.md`](https://github.com/google-labs-code/design.md) added a `## Motion & Micro-interaction` section and `motion` tokens (`duration`, `delay`, `timingFunction`). The split between the two files is: -| Shared convention | `DESIGN.md` | `MOTION.md` | -| --- | --- | --- | -| Portable project document | Visual identity | Motion intent and temporal behavior | -| YAML front matter | Exact design tokens | Exact states, events, timelines, and budgets | -| Markdown prose | Visual rationale | Motion rationale, hierarchy, and restraint | -| Machine contract | Schema and linting | Schema, linting, and Motion IR | -| Agent workflow | Read, validate, export | Read, validate, normalize, compare | +| Concern | Owner | +| --- | --- | +| Brand motion tone and timing vocabulary (`state-change`, `surface-enter`, …) | `DESIGN.md` | +| State graph, events, choreography, interruption, reduced motion, budgets | `MOTION.md` | +| Springs, scroll and pointer drivers, procedural curves | `MOTION.md` (no `DESIGN.md` equivalent) | + +`MOTION.md` binds with `design: DESIGN.md` and references tokens with `timing: "{motion.surface-enter}"` instead of restating 250ms and a Bézier curve. References resolve to concrete values in Motion IR together with the `DESIGN.md` hash, so a token change shows up in `motionmd diff`. A literal that happens to equal a token gets a `prefer-design-token` hint. -The formats are complementary, not nested. `DESIGN.md` owns visual identity and design-system values. `MOTION.md` owns state change, time, interruption, reduced motion, and performance. Tooling may consume both without either specification redefining the other. +Both formats share the same document conventions: front matter or interleaved YAML blocks, `##` sections, `omitted`, `{…}` token references, and `` `@path#fragment` `` external references. See [`examples/design-bound`](examples/design-bound). See [`docs/interoperability.md`](docs/interoperability.md) for the consumer boundary. @@ -204,7 +207,7 @@ Runtime adapter → evidence and QA ## Status -The `MOTION.md` format is at version `0.1` and remains a draft. The specification, JSON Schema, Motion IR, and CLI are ready for evaluation. Incompatible changes may occur before v1.0. +The `MOTION.md` format is at version `0.2` and remains a draft. The specification, JSON Schema, Motion IR, and CLI are ready for evaluation. Incompatible changes may occur before v1.0. The repository is open source under the MIT License. The package remains marked `private` only to prevent accidental npm publication while the distribution contract is still evolving. diff --git a/README.zh-CN.md b/README.zh-CN.md index 6759f22..8b77b08 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -6,11 +6,11 @@ A format specification for describing motion graphics and frontend animation int [English](README.md) · **简体中文** -[规范](docs/spec.md) · [JSON Schema](schemas/motion.schema.json) · [示例](examples) · [v0.1.0 Release](https://github.com/2233admin/motion.md/releases/tag/v0.1.0) +[规范](docs/spec.md) · [JSON Schema](schemas/motion.schema.json) · [示例](examples) · [v0.2 发布说明](docs/releases/v0.2.0.md) ## 文件格式 -一个 `MOTION.md` 文件由两部分组成:YAML front matter 中机器可读的动画语义,以及 Markdown 正文中人类与 Agent 可读的运动图形和前端动画意图。 +一个 `MOTION.md` 文件由两部分组成:YAML 中机器可读的动画语义(写在 front matter,或穿插在各章节的 ` ```yaml ` 代码块里),以及 Markdown 正文中人类与 Agent 可读的运动图形和前端动画意图。 YAML 定义精确的状态、事件、转换、时间线、曲线、中断规则、无障碍替代方案与性能预算。Markdown 解释这些规则为什么存在、动画需要传达什么,以及应该在哪里保持克制。 @@ -19,7 +19,7 @@ YAML 定义精确的状态、事件、转换、时间线、曲线、中断规则 ```md --- -version: "0.1" +version: "0.2" name: Quiet Feedback posture: minimal states: @@ -83,7 +83,7 @@ provenance: Agent 读取这个文件后,可以知道哪个状态拥有结果、什么事件触发变化、中断如何处理、Reduced Motion 必须保留什么,以及运行时选择不能破坏哪些性能限制。 -完整的动画规范可以参考[最小](examples/minimal/MOTION.md)、[表现型](examples/expressive/MOTION.md)、[程序化](examples/procedural/MOTION.md)和 [Reduced Motion](examples/reduced-motion/MOTION.md) 示例。 +完整的动画规范可以参考[最小](examples/minimal/MOTION.md)、[表现型](examples/expressive/MOTION.md)、[程序化](examples/procedural/MOTION.md)、[Reduced Motion](examples/reduced-motion/MOTION.md) 和 [DESIGN.md 绑定](examples/design-bound/MOTION.md) 示例。最后一个的时序全部来自同目录的 `DESIGN.md`。 ## 快速开始 @@ -100,7 +100,7 @@ CLI 输出编程 Agent 可以直接处理的结构化 findings: { "findings": [], "format": "motion.md", - "specVersion": "0.1", + "specVersion": "0.2", "summary": { "errors": 0, "warnings": 0, @@ -123,8 +123,8 @@ motionmd diff before/MOTION.md after/MOTION.md 一个 `MOTION.md` 文件包含两个层: -1. **YAML front matter** — 文件顶部由 `---` 分隔的精确动画语义; -2. **Markdown 正文** — 由 `##` 章节组织的动画意图与说明。 +1. **YAML** — 精确动画语义。可以写在文件顶部 `---` 分隔的 front matter 里,也可以写成穿插在对应章节内的 ` ```yaml ` 代码块(例如把 `reducedMotion` 放在 `## Reduced Motion` 下)。所有块合并成一棵树,同一顶层键只能出现一次; +2. **Markdown 正文** — 由 `##` 章节组织的动画意图与说明。正文可以用 `` `@path#fragment` `` 引用其他文件,从 `MOTION.md` 所在目录解析。 YAML 对精确数值和图关系具有规范性。Markdown 对意图、优先级、禁用规则和决策理由具有规范性。两者冲突时,合规消费者应报告冲突,而不是静默选择其中一层。 @@ -135,10 +135,13 @@ YAML 对精确数值和图关系具有规范性。Markdown 对意图、优先级 | `version` | 规范版本 | | `name` | 动画规范的人类可读名称 | | `posture` | `static`、`minimal`、`expressive` 或 `procedural` | +| `design` | 绑定的 `DESIGN.md` 相对路径,其 `motion` token 可被引用 | +| `omitted` | 有意省略的正文章节,附可选理由 | +| `defaults` | 默认时序:`timing` token 引用,或时长、延迟、曲线 | | `states` | 产品的语义状态 | | `events` | 用户、系统、数据、时间、视口、媒体或传感器输入 | | `curves` | 线性、Bézier、steps、spring 或程序曲线 | -| `timelines` | 运行时无关的驱动、轨道和关键帧 | +| `timelines` | 运行时无关的驱动、轨道和关键帧;轨道可用 `timing: "{motion.}"` 引用 DESIGN.md 时序 | | `transitions` | 状态变化、中断与取消策略 | | `reducedMotion` | 无障碍策略与语义替代方案 | | `performance` | 帧率、输入、并发与确定性预算 | @@ -158,7 +161,7 @@ Markdown 章节可以省略;已经出现的章节应遵循以下顺序: 6. Performance 7. Provenance -未知章节会被保留。重复的二级标题无效,因为它们会使稳定的章节寻址产生歧义。 +未知章节会被保留。重复的二级标题无效,因为它们会使稳定的章节寻址产生歧义。有意不写的章节在 `omitted` 中声明,即可消除 `missing-section` 警告。 ## CLI 参考 @@ -172,21 +175,21 @@ Markdown 章节可以省略;已经出现的章节应遵循以下顺序: | `motionmd spec` | 输出 Markdown 规范 | | `motionmd spec --format json` | 输出 JSON Schema | -`lint`、`parse` 和 `diff` 在发现无效或破坏性结果时以代码 `1` 退出。CLI 用法错误和无法读取的输入以代码 `2` 退出。 +`design` 与 `@` 引用从输入文件所在目录解析(标准输入则从当前目录)。`lint`、`parse` 和 `diff` 在发现无效或破坏性结果时以代码 `1` 退出。CLI 用法错误和无法读取的输入以代码 `2` 退出。 ## 与 DESIGN.md 的关系 -本项目在产品形态上有意与 Google Labs 的 [`design.md`](https://github.com/google-labs-code/design.md) 对齐: +Google Labs 的 [`design.md`](https://github.com/google-labs-code/design.md) 在 2026 年 11 月加入了 `## Motion & Micro-interaction` 章节和 `motion` token(`duration`、`delay`、`timingFunction`)。两份文件的分工因此是: -| 共享约定 | `DESIGN.md` | `MOTION.md` | -| --- | --- | --- | -| 可移植项目文档 | 视觉身份 | 运动图形与前端动画意图、时序行为 | -| YAML front matter | 精确设计 Token | 精确状态、事件、时间线与预算 | -| Markdown 正文 | 视觉设计理由 | 动画意图说明、层级与克制 | -| 机器契约 | Schema 与 lint | Schema、lint 与 Motion IR | -| Agent 工作流 | 读取、校验、导出 | 读取、校验、归一化、比较 | +| 关注点 | 归属 | +| --- | --- | +| 品牌动效基调、时序词汇(`state-change`、`surface-enter` 等 token) | `DESIGN.md` | +| 状态图、事件、编排、打断、降级、性能预算 | `MOTION.md` | +| spring、滚动/指针驱动、程序曲线 | `MOTION.md`(DESIGN.md 无对应) | + +`MOTION.md` 通过 `design: DESIGN.md` 绑定,用 `timing: "{motion.surface-enter}"` 引用 token,不再重复写 250ms 和贝塞尔曲线。引用会在 Motion IR 中解析为具体数值,并记录 `DESIGN.md` 的 hash,所以 token 一改,`motionmd diff` 就能看到。轨道上的字面值如果恰好等于某个 token,lint 会给出 `prefer-design-token` 提示。 -两个格式互补但不嵌套。`DESIGN.md` 负责视觉身份与设计系统数值;`MOTION.md` 负责状态变化、时间、中断、Reduced Motion 与性能。工具可以同时消费二者,而不需要其中一个规范重新定义另一个。 +两种格式共用同一套文档约定:front matter 或穿插 YAML 块、`##` 章节、`omitted`、`{…}` token 引用、`` `@path#fragment` `` 外部引用。完整示例见 [`examples/design-bound`](examples/design-bound)。 消费者边界详见 [`docs/interoperability.md`](docs/interoperability.md)。 @@ -204,7 +207,7 @@ runtime adapter → evidence and QA ## 当前状态 -`MOTION.md` 格式目前为 `0.1` 草案。规范、JSON Schema、Motion IR 与 CLI 已可用于评估;v1.0 之前仍可能发生不兼容变化。 +`MOTION.md` 格式目前为 `0.2` 草案。规范、JSON Schema、Motion IR 与 CLI 已可用于评估;v1.0 之前仍可能发生不兼容变化。 仓库使用 MIT License 开源。包暂时保留 `private` 标记,仅用于避免分发契约仍在演进时被误发布到 npm。 diff --git a/docs/interoperability.md b/docs/interoperability.md index c52da35..900b379 100644 --- a/docs/interoperability.md +++ b/docs/interoperability.md @@ -2,9 +2,22 @@ ## DESIGN.md -`DESIGN.md` describes visual identity and design rationale. `MOTION.md` describes behavior in time. A product may use either or both. +Since November 2026, `DESIGN.md` has its own `## Motion & Micro-interaction` section and `motion` tokens (`duration`, `delay`, `timingFunction`). The split is: -`MOTION.md` MAY refer to semantic concepts established by `DESIGN.md` in prose or namespaced extensions. It MUST NOT duplicate color, typography, spacing, component, or other visual-token systems as a competing source of truth. The v0.1 core defines no cross-file reference syntax; consumers own resolution and conflict reporting. +| Concern | Owner | +| --- | --- | +| Brand motion tone ("quick and understated", "nothing loops") | `DESIGN.md` prose | +| Timing vocabulary: purpose-named durations, delays, easing | `DESIGN.md` `motion` tokens | +| Which states change, and on which event | `MOTION.md` | +| Which targets and properties move, and in what order | `MOTION.md` timelines | +| Interruption and cancellation | `MOTION.md` | +| Reduced-motion substitutions and what they preserve | `MOTION.md` | +| Performance budgets and deterministic playback | `MOTION.md` | +| Springs, scroll/pointer drivers, procedural curves | `MOTION.md` (no `DESIGN.md` equivalent) | + +`MOTION.md` binds to a `DESIGN.md` with `design` and references its tokens with `timing: "{motion.}"` (spec section 7). It MUST NOT restate token values, and it MUST NOT duplicate color, typography, spacing, component, or other visual tokens. A project with only `DESIGN.md` motion tokens has a vocabulary but no behavior contract; a project with only `MOTION.md` declares its own curves locally. + +The two files use the same document conventions so one toolchain can read both: YAML front matter or interleaved ` ```yaml ` blocks, `##` sections, `omitted`, `{…}` token references, and `` `@path#fragment` `` external references resolved from the file's own directory. ## Designer Pipeline @@ -22,9 +35,9 @@ The Pipeline MUST consume parsed Motion IR rather than maintaining a divergent p ```json { - "motionSpec": "0.1", + "motionSpec": "0.2", "schema": "schemas/motion.schema.json", - "requiredIr": "0.1" + "requiredIr": "0.2" } ``` diff --git a/docs/motion-ir.md b/docs/motion-ir.md index 7b246c4..7381db7 100644 --- a/docs/motion-ir.md +++ b/docs/motion-ir.md @@ -1,4 +1,4 @@ -# Motion IR v0.1 +# Motion IR v0.2 Motion IR is the stable, runtime-neutral output of parsing a `MOTION.md`. It is an interchange boundary, not an executable timeline. @@ -14,34 +14,45 @@ Motion IR is the stable, runtime-neutral output of parsing a `MOTION.md`. It is ```json { - "irVersion": "0.1", - "specification": "motion.md/0.1", + "irVersion": "0.2", + "specification": "motion.md/0.2", "document": { "name": "Example", "description": "...", "posture": "minimal" }, + "design": { "path": "DESIGN.md", "sourceHash": "sha256…" }, "defaults": {}, "graph": { "states": [{ "id": "closed", "description": "..." }], "events": [{ "id": "activate", "description": "...", "source": "user" }], "transitions": [{ "id": "open", "from": "closed", "to": "open", "on": "activate" }] }, - "curves": [{ "id": "standard", "type": "cubic-bezier", "value": [0.2, 0, 0, 1] }], - "timelines": [{ "id": "reveal", "driver": { "type": "clock" }, "tracks": [] }], + "curves": [ + { "id": "motion.surface-enter", "origin": "design", "type": "cubic-bezier", "value": [0.2, 0, 0, 1] }, + { "id": "standard", "type": "cubic-bezier", "value": [0.2, 0, 0, 1] } + ], + "timelines": [{ + "id": "reveal", + "driver": { "type": "clock" }, + "tracks": [{ "target": "panel", "property": "visual.opacity", "timing": "motion.surface-enter", "curve": "motion.surface-enter", "durationMs": 250, "startMs": 0, "keyframes": [] }] + }], "policies": { "reducedMotion": {}, "performance": {} }, "provenance": [], "intent": { + "omitted": [{ "section": "hierarchy-and-choreography", "reason": "..." }], "sections": [{ "heading": "Motion Thesis", "content": "..." }] }, "extensions": {} } ``` -Named mappings are converted to arrays sorted by `id`. Track and keyframe arrays preserve authored order because order is semantic. Extension keys are collected without interpretation. +Named mappings are converted to arrays sorted by `id`. + +`timing` references are resolved before emission, so adapters never read `DESIGN.md`. A resolved track carries concrete `durationMs` and `startMs`, keeps the token path in `timing`, and names its curve by that same path. Each referenced token contributes one curve record with `origin: "design"`; its dotted id cannot collide with a local kebab-case curve id. `design.sourceHash` pins the exact `DESIGN.md` bytes, so a token change shows up in the semantic diff both as changed values and as a changed hash. Track and keyframe arrays preserve authored order because order is semantic. Extension keys are collected without interpretation. ## Capability negotiation @@ -59,4 +70,4 @@ Breaking changes include: - removing a provenance entry; - changing the declared specification version. -Other value changes are reported as modifications but are not automatically classified as breaking in v0.1. Consumers may apply stricter release policy. +Other value changes are reported as modifications but are not automatically classified as breaking. Consumers may apply stricter release policy. diff --git a/docs/releases/v0.2.0.md b/docs/releases/v0.2.0.md new file mode 100644 index 0000000..b8530bd --- /dev/null +++ b/docs/releases/v0.2.0.md @@ -0,0 +1,33 @@ +# motion.md v0.2.0 — Align with DESIGN.md / 对齐 DESIGN.md + +Google Labs' `DESIGN.md` gained a `## Motion & Micro-interaction` section and `motion` tokens on 2026-11-17, along with external `@` references, grouped tokens, interleaved YAML blocks, and `omitted`. v0.2 redraws the boundary: `DESIGN.md` owns the timing vocabulary, `MOTION.md` owns behavior and references that vocabulary instead of restating it. + +2026-11-17,Google Labs 的 `DESIGN.md` 加入了 `## Motion & Micro-interaction` 章节与 `motion` token,同时正式定义了 `@` 外部引用、分组 token、穿插 YAML 块和 `omitted`。v0.2 据此重划边界:时序词汇归 `DESIGN.md`,`MOTION.md` 只负责行为,并引用而不是复制这些词汇。 + +## Added / 新增 + +- `design`: bind a sibling `DESIGN.md`. / 绑定同目录的 `DESIGN.md`。 +- `timing: "{motion.}"` on `defaults` and tracks, with exact CSS easing mapping; `timing` plus literal `durationMs`/`curve` is an error. / 在 `defaults` 和轨道上引用 motion token,CSS easing 精确映射;与字面时序字段同时出现即报错。 +- Motion IR records resolved values, synthesized `origin: "design"` curves, and the `DESIGN.md` hash. / Motion IR 落解析后的数值、来自 design 的曲线和 `DESIGN.md` hash。 +- `prefer-design-token` info when a literal equals a token. / 字面值等于 token 时给出提示。 +- Interleaved ` ```yaml ` blocks; duplicate top-level keys are errors. / 穿插 YAML 块;顶层键重复即错误。 +- `omitted` for prose sections, with `unknown-omission` and `redundant-omission`. / 声明省略的正文章节。 +- External `` `@path#fragment` `` references with `DESIGN.md` severities. / 外部引用,严重级别与 `DESIGN.md` 一致。 +- CI runs `npm run check` on every push and pull request. / CI 在每次 push 与 PR 上运行 `npm run check`。 + +## Changed / 变更 + +- `version` is `"0.2"`; Motion IR `irVersion` is `"0.2"`. v0.1 documents are rejected. / 版本为 `"0.2"`,不再接受 v0.1 文档。 +- `missing-frontmatter` is renamed `missing-machine-data`. / 规则改名。 +- Headings and references inside fenced code are no longer read as structure. / 代码块内的标题和引用不再被当作结构。 + +## Not adopted / 未跟进 + +- Grouped tokens: `MOTION.md` maps hold named entities, not tokens; references to grouped `DESIGN.md` motion tokens work through dot paths. / 分组 token:我们的映射是命名实体而非 token;引用分组 motion token 可用点路径。 +- Voice & Content Strategy: outside motion. / 与动效无关。 + +## Migration / 迁移 + +1. Change `version: "0.1"` to `version: "0.2"`. / 把版本改成 `"0.2"`。 +2. If the project has a `DESIGN.md` with `motion` tokens, add `design: DESIGN.md` and replace each track's `durationMs` + `curve` that match a token with `timing: "{motion.}"`. `motionmd lint` lists candidates as `prefer-design-token`. / 若项目的 `DESIGN.md` 有 motion token,加上 `design`,并按 `prefer-design-token` 提示把对应字面值换成 `timing` 引用。 +3. Rename any tooling that matches `missing-frontmatter`. / 更新匹配旧规则名的工具。 diff --git a/docs/spec.md b/docs/spec.md index b48e89a..d91b88a 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -1,4 +1,4 @@ -# MOTION.md Format Specification v0.1 +# MOTION.md Format Specification v0.2 Status: draft. Normative terms **MUST**, **MUST NOT**, **SHOULD**, **SHOULD NOT**, and **MAY** are to be interpreted as requirement levels. @@ -10,12 +10,14 @@ The lowercase name `motion.md` refers to this specification and repository. The ## 2. Document structure -A document contains: +A document contains human-readable Markdown prose and machine-readable YAML. Machine data may be written in two ways, matching `DESIGN.md`: -1. Optional YAML 1.2 front matter delimited by lines containing exactly `---`. -2. A Markdown body containing human-readable intent and rationale. +1. **YAML front matter** at the start of the file, delimited by lines containing exactly `---`. +2. **Interleaved YAML code blocks**: fenced ` ```yaml ` (or ` ```yml `) blocks placed inside the section they belong to, for example `reducedMotion` under `## Reduced Motion`. -When front matter is present, it is normative for exact values and graph relationships. Markdown prose is normative for design intent, priorities, prohibitions, and decision rationale. When they conflict, a conforming consumer MUST report the conflict rather than silently choosing one layer. +Both may be used in one document. All blocks are parsed and merged into one tree. Each top-level key MUST be defined at most once across the whole document; a repeated top-level key is an error. Fenced YAML blocks are machine data, not prose: they are excluded from section content. Headings and references inside any fenced code block are not interpreted as document structure. + +Machine data is normative for exact values and graph relationships. Markdown prose is normative for design intent, priorities, prohibitions, and decision rationale. When they conflict, a conforming consumer MUST report the conflict rather than silently choosing one layer. JSON text is valid YAML 1.2 and MAY be used inside the front-matter delimiters. The reference parser implements the portable YAML subset described in section 11. @@ -31,19 +33,29 @@ A fully authored document SHOULD include these `##` sections in this order: 6. `Performance` 7. `Provenance` -Unknown sections MUST be preserved. Duplicate second-level headings are invalid because they make stable section addressing ambiguous. A prose-only document is valid but produces a `missing-frontmatter` warning and cannot yield a complete Motion IR. +Unknown sections MUST be preserved. Duplicate second-level headings are invalid because they make stable section addressing ambiguous. A prose-only document is valid but produces a `missing-machine-data` warning and cannot yield a complete Motion IR. + +A section that is deliberately absent is declared in `omitted`, either as a section key or as `{ section, reason }`. Section keys are the lower kebab-case headings: `motion-thesis`, `motion-principles`, `hierarchy-and-choreography`, `interruption`, `reduced-motion`, `performance`, `provenance`. A declared omission suppresses the `missing-section` warning. An unknown key produces `unknown-omission`; a key whose section is present produces `redundant-omission`. `omitted` covers prose only: required machine fields such as `reducedMotion` and `performance` cannot be omitted. + +```yaml +omitted: + - section: hierarchy-and-choreography + reason: Only one element moves. +``` -## 4. Front-matter root +## 4. Machine-data root The normative schema is [../schemas/motion.schema.json](../schemas/motion.schema.json). | Field | Requirement | Meaning | | --- | --- | --- | -| `version` | required | Specification version. v0.1 documents use `"0.1"`. | +| `version` | required | Specification version. v0.2 documents use `"0.2"`. | | `name` | required | Human-readable motion system name. | | `description` | optional | Short machine-readable summary. | | `posture` | required | `static`, `minimal`, `expressive`, or `procedural`. | -| `defaults` | optional | Default duration, delay, and curve references. | +| `design` | optional | Relative path to the `DESIGN.md` whose motion tokens this document references. See section 7. | +| `omitted` | optional | Prose sections that are deliberately absent. See section 3. | +| `defaults` | optional | Default timing token, or default duration, delay, and curve references. | | `states` | conditional | Named semantic product states. Required for non-static postures. | | `events` | conditional | Named semantic inputs or observed changes. Required for non-static postures. | | `curves` | optional | Named easing, spring, step, or procedural curve definitions. | @@ -99,9 +111,37 @@ Curve types: - `spring`: positive mass and stiffness, non-negative damping, optional initial velocity, and explicit settle thresholds. - `procedural`: a named generator or restricted expression plus parameters and a sampling contract. -A procedural curve MUST declare `sample.rateHz` and `sample.durationMs`. If it uses randomness it MUST declare an integer `seed`. Expressions are data, not code: function calls, property access, assignment, imports, statements, and host-language callbacks are forbidden. The v0.1 expression vocabulary is arithmetic over `t`, `progress`, declared parameters, numeric constants, parentheses, and the pure functions `sin`, `cos`, `tan`, `abs`, `min`, `max`, `clamp`, `pow`, `sqrt`, `exp`, and `log`. +A procedural curve MUST declare `sample.rateHz` and `sample.durationMs`. If it uses randomness it MUST declare an integer `seed`. Expressions are data, not code: function calls, property access, assignment, imports, statements, and host-language callbacks are forbidden. The expression vocabulary is arithmetic over `t`, `progress`, declared parameters, numeric constants, parentheses, and the pure functions `sin`, `cos`, `tan`, `abs`, `min`, `max`, `clamp`, `pow`, `sqrt`, `exp`, and `log`. + +## 7. Design motion tokens + +`DESIGN.md` owns the brand's motion vocabulary: purpose-named `motion` tokens with `duration`, `delay`, and `timingFunction`, such as `state-change`, `surface-enter`, and `surface-exit`. `MOTION.md` owns behavior: which states change, what drives the change, how tracks are choreographed, how interruption resolves, what reduced motion preserves, and the performance budget. A `MOTION.md` MUST NOT restate token values; it references them. + +### 7.1 Binding + +`design` names the `DESIGN.md` relative to the directory containing `MOTION.md`. It MUST be a relative path ending in `.md`; a leading `/`, a drive letter, a backslash, or a path that resolves outside that directory is an error (`design-path`). A missing file is an error (`broken-ref`). + +Consumers read only the `motion` key of the bound `DESIGN.md`, from its front matter or an interleaved YAML block. Other `DESIGN.md` content is outside this specification. + +### 7.2 References + +`defaults.timing` and a track's `timing` reference a token with the `DESIGN.md` token-reference syntax: `"{motion.}"`, or `"{motion..}"` for grouped tokens. A reference to a missing token is an error (`broken-ref`), as is a `timing` reference in a document with no `design`. + +`timing` replaces the fields it would otherwise duplicate. A track with `timing` MUST NOT also declare `durationMs` or `curve`; `defaults` with `timing` MUST NOT also declare `durationMs`, `delayMs`, or `curve` (`timing-conflict`). A track MAY still declare `startMs`, because placement inside a timeline is choreography, which `MOTION.md` owns. + +### 7.3 Resolution -## 7. Timelines and tracks +A referenced token resolves as follows: + +- `duration` and `delay` are integer milliseconds written with an `ms` suffix. `delay` defaults to `0ms`. +- `timingFunction` defaults to `ease`. CSS keywords map to curves exactly as CSS Easing Functions Level 1 defines them: `linear`; `ease` = `[0.25, 0.1, 0.25, 1]`; `ease-in` = `[0.42, 0, 1, 1]`; `ease-out` = `[0, 0, 0.58, 1]`; `ease-in-out` = `[0.42, 0, 0.58, 1]`; `cubic-bezier(x1, y1, x2, y2)`; `steps(n[, jump-start|jump-end|jump-none|jump-both|start|end])`; `step-start`; `step-end`. Any other value, including multi-point `linear(...)`, is an error (`unsupported-timing-function`); consumers MUST NOT approximate it. +- A track's resolved `durationMs` is the token duration, and its resolved `startMs` is the authored `startMs` (default `0`) plus the token delay. + +### 7.4 Single source of truth + +When a track declares a literal `durationMs` and a `curve` that together equal a bound token, the linter reports `prefer-design-token` (`info`) so the literal can be replaced with a reference. + +## 8. Timelines and tracks A timeline owns a `driver` and an ordered array of tracks. @@ -115,11 +155,12 @@ A track declares: - `target`: semantic target name, not a selector; - `property`: runtime-neutral property path such as `visual.opacity`, `spatial.translate-y`, or `content.reveal-progress`; - `keyframes`: two or more `{ at, value }` entries ordered by non-decreasing progress; -- optional `curve`, `startMs`, and `durationMs` overrides. +- optional `timing` (section 7), or optional `curve` and `durationMs` overrides; +- optional `startMs`. Track order is authored order. Overlap is represented by `startMs` and duration, not by runtime-specific timeline syntax. Consumers MUST preserve semantic target/property names through normalization even when an adapter cannot implement them. -## 8. Reduced motion +## 9. Reduced motion `reducedMotion.strategy` is one of: @@ -129,13 +170,13 @@ Track order is authored order. Overlap is represented by `startMs` and duration, Every substitution MUST declare the meanings it preserves. Common values are `state`, `content`, `focus`, `selection`, `input`, and `continuity`. A consumer MUST NOT infer that reduced motion permits hiding content or delaying task completion. -## 9. Performance and deterministic playback +## 10. Performance and deterministic playback The performance object defines budgets, not implementation choices. It includes target frame rate, maximum main-thread milliseconds per frame, maximum concurrent tracks, input-ready time, property classes, and deterministic playback. When `deterministic` is true, the same Motion IR, event sequence, viewport inputs, time samples, and declared seeds MUST produce the same semantic samples. Adapters MUST report unsupported budgets or nondeterministic behavior instead of silently changing the design. -## 10. Provenance +## 11. Provenance Each provenance entry has a stable `id`, `kind`, and `description`. @@ -146,9 +187,9 @@ Kinds: - `derived`: calculated or normalized from another declared rule; - `research`: informed by an attributed external source. -Non-authored entries MUST include `source`. An optional `license` records relevant reuse terms. Provenance describes evidence and influence; it does not transfer permission to copy implementations. +Non-authored entries MUST include `source`. Values derived from `DESIGN.md` tokens SHOULD be recorded as a `derived` entry whose `source` is the `design` path. An optional `license` records relevant reuse terms. Provenance describes evidence and influence; it does not transfer permission to copy implementations. -## 11. Portable YAML subset +## 12. Portable YAML subset The reference parser intentionally has no runtime dependencies. It accepts the interoperable subset needed by the schema: @@ -159,13 +200,27 @@ The reference parser intentionally has no runtime dependencies. It accepts the i Tabs, anchors, aliases, tags, directives, merge keys, block scalars, multi-document streams, and implicit timestamps are rejected. Tooling that supports full YAML 1.2 MAY accept a wider syntax, but MUST normalize to the same data model and MUST reject values outside the JSON-compatible schema. -## 12. Extensions and forward compatibility +The subset applies to the bound `DESIGN.md` only for its top-level `motion` block. Other `DESIGN.md` YAML is not parsed, so it may use syntax outside the subset. + +## 13. External references + +Prose MAY point to other files with the `DESIGN.md` external-reference syntax: an inline code span whose entire content is `@[#]`. `` uses `/` separators, contains no whitespace, and ends in a file extension. `` `@media` `` and `` `@scope/package` `` are not references; neither is text outside a code span or inside a fenced block. + +Every reference resolves from the directory containing `MOTION.md`, never from the file it appears in. Fragments name a Markdown heading by slug (`` `@DESIGN.md#motion--micro-interaction` ``) or an HTML element `id` or `` marker. A consumer that does not understand a fragment for a file type uses the whole file. + +The `broken-ref` rule reports: + +- a leading `/` or a path that resolves outside the `MOTION.md` directory as an `error`; +- a missing file, or a missing Markdown or HTML fragment, as a `warning`; +- a fragment on any other file type as `info`. + +## 14. Extensions and forward compatibility Core objects accept keys prefixed with `x-`. The value MUST be JSON-compatible. Consumers MUST preserve unknown `x-*` fields and MUST NOT treat them as core conformance requirements unless they explicitly support that extension. Unknown unprefixed YAML keys are errors. Unknown Markdown sections are preserved without error. This makes the machine contract strict while allowing the human design language to grow through use. -## 13. Stable parse output +## 15. Stable parse output `parse` emits: @@ -174,18 +229,20 @@ Unknown unprefixed YAML keys are errors. Unknown Markdown sections are preserved - `sourceHash` using SHA-256 over the original bytes; - normalized `document` data; - ordered Markdown `sections`; -- normalized `ir` as defined in [motion-ir.md](motion-ir.md); +- normalized `ir` as defined in [motion-ir.md](motion-ir.md), with `timing` references resolved and the bound `DESIGN.md` path and SHA-256 hash recorded; - parser `findings`. Object keys in emitted JSON are sorted lexicographically. Authored arrays retain their order. -## 14. CLI conformance +## 16. CLI conformance The reference CLI provides: - `lint `: parse and validate; exit `1` when errors exist, `0` otherwise, and `2` for unreadable input or CLI misuse. - `parse `: emit stable parsed JSON; exit `1` for invalid input. - `diff `: emit semantic IR and prose-section changes; exit `1` when breaking changes are detected. -- `spec [--format markdown|json]`: emit this specification or the front-matter JSON Schema. +- `spec [--format markdown|json]`: emit this specification or the machine-data JSON Schema. + +`lint`, `parse`, and `diff` resolve `design` and external references from the directory of each input file, and from the working directory for standard input. A library consumer supplies the same resolution through a `resolveFile(relativePath)` callback; without one, a `design` binding is an error (`unresolved-design`) and external references are checked for syntax only. All diagnostic records contain `rule`, `severity`, `path`, and `message`. Severity is `error`, `warning`, or `info`. diff --git a/examples/design-bound/DESIGN.md b/examples/design-bound/DESIGN.md new file mode 100644 index 0000000..a2fda35 --- /dev/null +++ b/examples/design-bound/DESIGN.md @@ -0,0 +1,38 @@ +--- +version: alpha +name: Harbor Ledger +description: Calm financial workspace with dense data and quiet surfaces. +colors: + primary: "#1F3A4D" + on-primary: "#FFFFFF" + surface: "#F6F7F5" + on-surface: "#1A1C1E" +--- + +## Overview + +A ledger for operators who read numbers all day. Surfaces are flat and quiet so figures stay the loudest thing on screen. + +## Colors + +Deep harbor blue carries primary actions; everything else stays neutral. + +## Motion & Micro-interaction + +Motion is quick and understated. Feedback on a control lands within a tenth of a second. Surfaces that enter decelerate into place; surfaces that leave accelerate away and take less time than they took to arrive. Nothing loops and nothing moves for decoration. Honor `prefers-reduced-motion`. + +```yaml +motion: + state-change: + duration: 100ms + delay: 0ms + timingFunction: ease-out + surface-enter: + duration: 250ms + delay: 0ms + timingFunction: cubic-bezier(0.2, 0, 0, 1) + surface-exit: + duration: 150ms + delay: 0ms + timingFunction: cubic-bezier(0.3, 0, 1, 1) +``` diff --git a/examples/design-bound/MOTION.md b/examples/design-bound/MOTION.md new file mode 100644 index 0000000..473e6fc --- /dev/null +++ b/examples/design-bound/MOTION.md @@ -0,0 +1,150 @@ +--- +version: "0.2" +name: Harbor Ledger Detail Sheet +description: A transaction detail sheet whose timing vocabulary comes from DESIGN.md. +posture: minimal +design: DESIGN.md +states: + closed: + description: The ledger table owns the screen; no detail is shown. + invariants: ["table scroll position is stable"] + open: + description: The detail sheet shows one transaction beside the table. + invariants: ["selected row remains visible", "focus is inside the sheet"] +events: + open-detail: + description: The user selects a transaction row. + source: user + close-detail: + description: The user dismisses the sheet or presses Escape. + source: user +timelines: + sheet-enter: + description: The sheet arrives from the edge it is anchored to, then its figures settle. + driver: + type: clock + tracks: + - target: detail-sheet + property: spatial.translate-x + timing: "{motion.surface-enter}" + keyframes: + - at: 0 + value: 24 + - at: 1 + value: 0 + - target: detail-sheet + property: visual.opacity + timing: "{motion.surface-enter}" + keyframes: + - at: 0 + value: 0 + - at: 1 + value: 1 + - target: detail-figures + property: visual.opacity + timing: "{motion.state-change}" + startMs: 120 + keyframes: + - at: 0 + value: 0 + - at: 1 + value: 1 + sheet-exit: + description: The sheet leaves as one surface; figures do not get their own beat. + driver: + type: clock + tracks: + - target: detail-sheet + property: spatial.translate-x + timing: "{motion.surface-exit}" + keyframes: + - at: 0 + value: 0 + - at: 1 + value: 24 + - target: detail-sheet + property: visual.opacity + timing: "{motion.surface-exit}" + keyframes: + - at: 0 + value: 1 + - at: 1 + value: 0 +transitions: + open-sheet: + from: closed + to: open + on: open-detail + timeline: sheet-enter + interruption: + policy: reverse + cancellation: + policy: nearest + close-sheet: + from: open + to: closed + on: close-detail + timeline: sheet-exit + interruption: + policy: replace + cancellation: + policy: target +performance: + targetFps: 60 + maxMainThreadMsPerFrame: 3 + maxConcurrentTracks: 3 + inputReadyMs: 0 + allowedProperties: ["transform", "opacity"] + forbiddenProperties: ["layout"] + deterministic: true +provenance: + - id: ledger-sheet + kind: authored + description: Original choreography for the detail sheet. + - id: design-timing + kind: derived + source: DESIGN.md + description: Durations and easing come from the DESIGN.md motion tokens. +--- + +## Motion Thesis + +The sheet is a reading surface, not an event. It arrives fast enough that selecting a row feels like opening it, and leaves faster than it came. + +## Motion Principles + +- Timing values belong to the brand: `@DESIGN.md#motion--micro-interaction` owns them, this file only decides who uses which. +- The selected row never moves. +- Figures fade in after the sheet edge has mostly landed so the eye reads position first, numbers second. + +## Hierarchy and Choreography + +The sheet travels and fades as one surface using `surface-enter`. Figures are a second, smaller beat using `state-change`, offset by 120 milliseconds. Exit is a single beat with `surface-exit`. + +## Interruption + +Closing while the sheet is arriving reverses from current progress. Selecting a different row while open does not animate the sheet; only the content swaps. + +## Reduced Motion + +Spatial travel is removed. The sheet opens with a crossfade and closes instantly; focus moves the same way in both modes. + +```yaml +reducedMotion: + strategy: substitute + substitutions: + open-sheet: + mode: crossfade + preserves: ["state", "content", "focus"] + close-sheet: + mode: instant + preserves: ["state", "focus", "input"] +``` + +## Performance + +Only transform and opacity animate. The sheet's layout is committed before the first frame. + +## Provenance + +Choreography is authored here. Every duration and curve is derived from DESIGN.md. diff --git a/examples/expressive/MOTION.md b/examples/expressive/MOTION.md index 3b35562..8925a78 100644 --- a/examples/expressive/MOTION.md +++ b/examples/expressive/MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Editorial Reveal description: A confident editorial expansion with one hero beat and restrained supporting motion. posture: expressive diff --git a/examples/minimal/MOTION.md b/examples/minimal/MOTION.md index b81e814..c9c3dce 100644 --- a/examples/minimal/MOTION.md +++ b/examples/minimal/MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Quiet Control Surface description: Immediate operational feedback with short distance and no decorative entrance motion. posture: minimal diff --git a/examples/procedural/MOTION.md b/examples/procedural/MOTION.md index 6f68035..3c24cce 100644 --- a/examples/procedural/MOTION.md +++ b/examples/procedural/MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Seeded Signal Field description: A deterministic ambient signal that becomes calmer during direct interaction. posture: procedural diff --git a/examples/reduced-motion/MOTION.md b/examples/reduced-motion/MOTION.md index 795e1ef..b4f3ef8 100644 --- a/examples/reduced-motion/MOTION.md +++ b/examples/reduced-motion/MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Semantic Detail Navigation description: Spatial continuity in the default mode and a non-spatial state-preserving substitution when motion is reduced. posture: expressive diff --git a/fixtures/invalid/broken-reference.MOTION.md b/fixtures/invalid/broken-reference.MOTION.md index 3db0b13..eccc483 100644 --- a/fixtures/invalid/broken-reference.MOTION.md +++ b/fixtures/invalid/broken-reference.MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Broken Reference posture: minimal states: diff --git a/fixtures/invalid/executable-procedure.MOTION.md b/fixtures/invalid/executable-procedure.MOTION.md index 189f98a..7f016a5 100644 --- a/fixtures/invalid/executable-procedure.MOTION.md +++ b/fixtures/invalid/executable-procedure.MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Executable Procedure posture: procedural states: diff --git a/fixtures/valid/static.MOTION.md b/fixtures/valid/static.MOTION.md index 928be5d..89446fc 100644 --- a/fixtures/valid/static.MOTION.md +++ b/fixtures/valid/static.MOTION.md @@ -1,5 +1,5 @@ --- -version: "0.1" +version: "0.2" name: Authored Stillness description: A deliberately static product surface. posture: static diff --git a/package.json b/package.json index e67930e..fa71369 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "motion.md", - "version": "0.1.0", + "version": "0.2.0", "private": true, "description": "Runtime-neutral MOTION.md specification and reference tooling", "type": "module", @@ -13,7 +13,7 @@ "scripts": { "lint": "node packages/cli/bin/motionmd.mjs lint examples/minimal/MOTION.md", "test": "node --test tests/*.test.mjs", - "check": "npm run test && node packages/cli/bin/motionmd.mjs lint examples/minimal/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/expressive/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/procedural/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/reduced-motion/MOTION.md" + "check": "npm run test && node packages/cli/bin/motionmd.mjs lint examples/minimal/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/expressive/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/procedural/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/reduced-motion/MOTION.md && node packages/cli/bin/motionmd.mjs lint examples/design-bound/MOTION.md" }, "license": "MIT" } diff --git a/packages/cli/package.json b/packages/cli/package.json index f13f793..a7eeb06 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@motion-md/cli", - "version": "0.1.0", + "version": "0.2.0", "type": "module", "bin": { "motionmd": "bin/motionmd.mjs" diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs index 66bee9d..0afdfcd 100644 --- a/packages/cli/src/index.mjs +++ b/packages/cli/src/index.mjs @@ -1,6 +1,6 @@ -import { readFileSync } from 'node:fs'; +import { existsSync, readFileSync, statSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { dirname, resolve } from 'node:path'; +import { dirname, isAbsolute, relative, resolve } from 'node:path'; import { diffMotion, stableStringify } from '../../motion-ir/src/index.mjs'; import { lintMotion, parseMotion } from '../../parser/src/index.mjs'; @@ -11,6 +11,17 @@ function readInput(path) { return readFileSync(resolve(process.cwd(), path), 'utf8'); } +// Resolve references from the MOTION.md directory (cwd for stdin), never outside it. +function resolverFor(path) { + const base = path === '-' ? process.cwd() : dirname(resolve(process.cwd(), path)); + return (relativePath) => { + const target = resolve(base, relativePath); + const inside = relative(base, target); + if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) return null; + return existsSync(target) && statSync(target).isFile() ? readFileSync(target, 'utf8') : null; + }; +} + function option(args, name, fallback) { const index = args.indexOf(name); if (index < 0) return fallback; @@ -46,7 +57,8 @@ export function run(argv, io = { stdout: process.stdout, stderr: process.stderr const path = args.find((arg) => !arg.startsWith('--')); if (!path) throw new Error(`${command} requires a file path or -`); const source = readInput(path); - const result = command === 'lint' ? lintMotion(source) : parseMotion(source); + const options = { resolveFile: resolverFor(path) }; + const result = command === 'lint' ? lintMotion(source, options) : parseMotion(source, options); emit(io, result); return result.summary.errors > 0 ? 1 : 0; } @@ -54,8 +66,8 @@ export function run(argv, io = { stdout: process.stdout, stderr: process.stderr if (command === 'diff') { const paths = args.filter((arg) => !arg.startsWith('--')); if (paths.length !== 2) throw new Error('diff requires before and after file paths'); - const before = parseMotion(readInput(paths[0])); - const after = parseMotion(readInput(paths[1])); + const before = parseMotion(readInput(paths[0]), { resolveFile: resolverFor(paths[0]) }); + const after = parseMotion(readInput(paths[1]), { resolveFile: resolverFor(paths[1]) }); if (before.summary.errors || after.summary.errors) { emit(io, { error: 'Both documents must be valid before semantic diffing.', diff --git a/packages/motion-ir/package.json b/packages/motion-ir/package.json index d446bf1..2502f06 100644 --- a/packages/motion-ir/package.json +++ b/packages/motion-ir/package.json @@ -1,6 +1,6 @@ { "name": "@motion-md/motion-ir", - "version": "0.1.0", + "version": "0.2.0", "type": "module", "exports": "./src/index.mjs", "license": "MIT" diff --git a/packages/motion-ir/src/index.mjs b/packages/motion-ir/src/index.mjs index eba7323..a652e5e 100644 --- a/packages/motion-ir/src/index.mjs +++ b/packages/motion-ir/src/index.mjs @@ -29,25 +29,60 @@ function extensionsOf(value = {}) { ); } -export function normalizeMotion(frontmatter, sections = []) { +const tokenPath = (ref) => ref.slice(1, -1); + +// Replace `timing` references with the DESIGN.md values they name. The token path stays on +// the record so adapters and diffs can see where the values came from. +function resolveTimelines(timelines = {}, design) { + return Object.fromEntries(Object.entries(timelines).map(([id, timeline]) => [id, { + ...timeline, + tracks: (timeline.tracks ?? []).map((track) => { + if (track.timing === undefined || !design) return track; + const path = tokenPath(track.timing); + const token = design.tokens.get(path); + return { ...track, timing: path, curve: path, durationMs: token.durationMs, startMs: (track.startMs ?? 0) + token.delayMs }; + }), + }])); +} + +function resolveDefaults(defaults = {}, design) { + if (defaults.timing === undefined || !design) return defaults; + const path = tokenPath(defaults.timing); + const token = design.tokens.get(path); + return { ...defaults, timing: path, curve: path, durationMs: token.durationMs, delayMs: token.delayMs }; +} + +function designCurves(frontmatter, design) { + if (!design) return []; + const used = new Set(); + if (frontmatter.defaults?.timing) used.add(tokenPath(frontmatter.defaults.timing)); + for (const timeline of Object.values(frontmatter.timelines ?? {})) { + for (const track of timeline.tracks ?? []) if (track.timing) used.add(tokenPath(track.timing)); + } + return [...used].sort().map((path) => stableValue({ id: path, origin: 'design', ...design.tokens.get(path).curve })); +} + +export function normalizeMotion(frontmatter, sections = [], design = null) { if (!frontmatter) return null; return stableValue({ - irVersion: '0.1', + irVersion: '0.2', specification: `motion.md/${frontmatter.version ?? 'unknown'}`, document: { name: frontmatter.name ?? null, description: frontmatter.description ?? null, posture: frontmatter.posture ?? null, }, - defaults: frontmatter.defaults ?? {}, + design: design ? { path: design.path, sourceHash: design.sourceHash } : null, + defaults: resolveDefaults(frontmatter.defaults, design), graph: { states: namedRecords(frontmatter.states), events: namedRecords(frontmatter.events), transitions: namedRecords(frontmatter.transitions), }, - curves: namedRecords(frontmatter.curves), - timelines: namedRecords(frontmatter.timelines), + curves: [...namedRecords(frontmatter.curves), ...designCurves(frontmatter, design)] + .sort((left, right) => left.id.localeCompare(right.id)), + timelines: namedRecords(resolveTimelines(frontmatter.timelines, design)), policies: { reducedMotion: frontmatter.reducedMotion ?? null, performance: frontmatter.performance ?? null, @@ -56,6 +91,7 @@ export function normalizeMotion(frontmatter, sections = []) { .map(stableValue) .sort((left, right) => String(left.id).localeCompare(String(right.id))), intent: { + omitted: (frontmatter.omitted ?? []).map((entry) => (typeof entry === 'string' ? { section: entry } : entry)), sections: sections.map(({ heading, content }) => ({ heading, content })), }, extensions: extensionsOf(frontmatter), diff --git a/packages/parser/package.json b/packages/parser/package.json index 3f33f8e..269dba3 100644 --- a/packages/parser/package.json +++ b/packages/parser/package.json @@ -1,6 +1,6 @@ { "name": "@motion-md/parser", - "version": "0.1.0", + "version": "0.2.0", "type": "module", "exports": "./src/index.mjs", "license": "MIT" diff --git a/packages/parser/src/design.mjs b/packages/parser/src/design.mjs new file mode 100644 index 0000000..38eef93 --- /dev/null +++ b/packages/parser/src/design.mjs @@ -0,0 +1,120 @@ +import { createHash } from 'node:crypto'; +import { parseYaml } from './yaml-lite.mjs'; +import { extractYamlBlocks, splitFrontmatter } from './document.mjs'; + +export const TIMING_REF = /^\{motion(\.[a-z][a-z0-9-]*)+\}$/; + +// CSS Easing Functions Level 1 keyword definitions. +const KEYWORDS = { + ease: [0.25, 0.1, 0.25, 1], + 'ease-in': [0.42, 0, 1, 1], + 'ease-out': [0, 0, 0.58, 1], + 'ease-in-out': [0.42, 0, 0.58, 1], +}; +const JUMPS = { + 'jump-start': 'start', start: 'start', + 'jump-end': 'end', end: 'end', + 'jump-none': 'none', 'jump-both': 'both', +}; + +export function parseTimingFunction(input) { + const value = String(input).trim(); + if (value === 'linear') return { type: 'linear' }; + if (KEYWORDS[value]) return { type: 'cubic-bezier', value: KEYWORDS[value] }; + if (value === 'step-start') return { type: 'steps', count: 1, jump: 'start' }; + if (value === 'step-end') return { type: 'steps', count: 1, jump: 'end' }; + let match = value.match(/^cubic-bezier\(([^)]*)\)$/); + if (match) { + const numbers = match[1].split(',').map((part) => Number(part.trim())); + if (numbers.length !== 4 || numbers.some((n) => !Number.isFinite(n))) return null; + if (numbers[0] < 0 || numbers[0] > 1 || numbers[2] < 0 || numbers[2] > 1) return null; + return { type: 'cubic-bezier', value: numbers }; + } + match = value.match(/^steps\(\s*(\d+)\s*(?:,\s*([a-z-]+)\s*)?\)$/); + if (match) { + const count = Number(match[1]); + const jump = JUMPS[match[2] ?? 'end']; + if (!jump || count < 1 || (jump === 'none' && count < 2)) return null; + return { type: 'steps', count, jump }; + } + return null; +} + +function parseDuration(value) { + if (typeof value !== 'string') return null; + const match = value.trim().match(/^(\d+)ms$/); + return match ? Number(match[1]) : null; +} + +// Extract only the top-level `motion:` block from a YAML source. DESIGN.md owns the rest of +// its tree, and its other sections may use YAML outside the portable subset. +function motionBlock(yaml) { + const lines = yaml.replace(/\r\n?/g, '\n').split('\n'); + const start = lines.findIndex((line) => /^motion:\s*(#.*)?$/.test(line)); + if (start < 0) return null; + let end = start + 1; + while (end < lines.length && (lines[end].trim() === '' || /^\s/.test(lines[end]) || /^#/.test(lines[end]))) end += 1; + return lines.slice(start, end).join('\n'); +} + +function flatten(map, prefix, out) { + for (const [key, value] of Object.entries(map ?? {})) { + const path = `${prefix}.${key}`; + if (value && typeof value === 'object' && !Array.isArray(value) && !('duration' in value || 'delay' in value || 'timingFunction' in value)) { + flatten(value, path, out); + } else { + out.set(path, value); + } + } +} + +/** + * Load motion tokens from DESIGN.md source text. + * Returns { tokens: Map, findings, sourceHash }. + */ +export function loadDesignMotion(source, designPath) { + const findings = []; + const tokens = new Map(); + const add = (rule, severity, path, message) => findings.push({ rule, severity, path, message }); + const { yaml, markdown } = splitFrontmatter(source); + const blocks = [yaml, ...extractYamlBlocks(markdown).map((block) => block.yaml)].filter((text) => text != null); + const motionSources = blocks.map(motionBlock).filter(Boolean); + + if (motionSources.length > 1) add('design-motion', 'error', '/design', `${designPath} defines the motion key more than once.`); + if (motionSources.length === 1) { + let raw; + try { + raw = parseYaml(motionSources[0]).motion; + } catch (error) { + add('design-motion', 'error', '/design', `${designPath} motion tokens are not portable YAML: ${error.message}`); + } + const flat = new Map(); + flatten(raw, 'motion', flat); + for (const [path, token] of flat) { + if (!token || typeof token !== 'object') { + add('design-motion', 'error', '/design', `${designPath} ${path} must be a motion token object.`); + continue; + } + const durationMs = parseDuration(token.duration); + const delayMs = token.delay === undefined ? 0 : parseDuration(token.delay); + const curve = parseTimingFunction(token.timingFunction ?? 'ease'); + if (durationMs === null) add('design-motion', 'error', '/design', `${designPath} ${path}.duration must be integer milliseconds such as "250ms".`); + if (delayMs === null) add('design-motion', 'error', '/design', `${designPath} ${path}.delay must be integer milliseconds such as "0ms".`); + if (!curve) add('unsupported-timing-function', 'error', '/design', `${designPath} ${path}.timingFunction is not a supported CSS easing function.`); + if (durationMs !== null && delayMs !== null && curve) tokens.set(path, { durationMs, delayMs, curve }); + } + } + + return { tokens, findings, sourceHash: createHash('sha256').update(source).digest('hex') }; +} + +export function isSafeRelativePath(path) { + if (typeof path !== 'string' || path === '' || path.startsWith('/') || path.includes('\\') || /^[A-Za-z]:/.test(path)) return false; + let depth = 0; + for (const part of path.split('/')) { + if (part === '..') depth -= 1; + else if (part !== '.' && part !== '') depth += 1; + if (depth < 0) return false; + } + return true; +} diff --git a/packages/parser/src/document.mjs b/packages/parser/src/document.mjs new file mode 100644 index 0000000..e76bdc4 --- /dev/null +++ b/packages/parser/src/document.mjs @@ -0,0 +1,135 @@ +import { YamlLiteError } from './yaml-lite.mjs'; + +const FENCE = /^(`{3,}|~{3,})\s*([A-Za-z0-9_-]*)\s*$/; + +export function splitFrontmatter(source) { + const normalized = source.replace(/^/, '').replace(/\r\n?/g, '\n'); + const lines = normalized.split('\n'); + if (lines[0] !== '---') return { yaml: null, markdown: normalized, bodyLine: 1 }; + const closing = lines.findIndex((line, index) => index > 0 && line === '---'); + if (closing < 0) throw new YamlLiteError('Front matter is missing a closing --- delimiter', 1); + return { + yaml: lines.slice(1, closing).join('\n'), + markdown: lines.slice(closing + 1).join('\n'), + bodyLine: closing + 2, + }; +} + +// Walk Markdown lines, tracking fenced code blocks so headings and references inside +// code are never interpreted as structure. +function scan(markdown) { + const lines = markdown.split('\n'); + const out = []; + let fence = null; + for (const [index, line] of lines.entries()) { + const match = line.match(FENCE); + if (fence) { + if (match && match[1][0] === fence.marker[0] && match[1].length >= fence.marker.length && !match[2]) { + out.push({ index, line, kind: 'fence-close', fence }); + fence = null; + } else { + fence.lines.push(line); + out.push({ index, line, kind: 'code', fence }); + } + continue; + } + if (match) { + fence = { marker: match[1], info: match[2].toLowerCase(), lines: [], startIndex: index }; + out.push({ index, line, kind: 'fence-open', fence }); + continue; + } + out.push({ index, line, kind: 'text' }); + } + if (fence) throw Object.assign(new Error('Unterminated fenced code block'), { rule: 'markdown-structure', path: '/' }); + return out; +} + +/** Fenced ```yaml blocks are machine data, matching DESIGN.md interleaved token blocks. */ +export function extractYamlBlocks(markdown) { + const blocks = []; + let heading = null; + for (const item of scan(markdown)) { + if (item.kind === 'text') { + const match = item.line.match(/^##\s+(.+?)\s*#*\s*$/); + if (match) heading = match[1].trim(); + } + if (item.kind === 'fence-close' && ['yaml', 'yml'].includes(item.fence.info)) { + blocks.push({ heading, yaml: item.fence.lines.join('\n'), startIndex: item.fence.startIndex }); + } + } + return blocks; +} + +/** Second-level sections; prose excludes machine YAML blocks so intent and data never double count. */ +export function parseSections(markdown) { + const sections = []; + const seen = new Set(); + let current = null; + for (const item of scan(markdown)) { + if (item.kind === 'text') { + const match = item.line.match(/^##\s+(.+?)\s*#*\s*$/); + if (match) { + const heading = match[1].trim(); + if (seen.has(heading)) { + throw Object.assign(new Error(`Duplicate Markdown section: ${heading}`), { rule: 'duplicate-section', path: `/sections/${heading}` }); + } + seen.add(heading); + current = { heading, lines: [] }; + sections.push(current); + continue; + } + } + if (!current) continue; + if (['yaml', 'yml'].includes(item.fence?.info)) continue; + current.lines.push(item.line); + } + return sections.map(({ heading, lines }) => ({ heading, content: lines.join('\n').trim() })); +} + +const REFERENCE = /^@((?:[^\s#/`]+\/)*[^\s#/`]+\.[A-Za-z0-9]+)(?:#([^\s`]+))?$/; + +/** Inline code spans whose whole content is `@path[#fragment]`, outside fenced code. */ +export function findReferences(markdown) { + const refs = []; + let heading = null; + for (const item of scan(markdown)) { + if (item.kind !== 'text') continue; + const match = item.line.match(/^##\s+(.+?)\s*#*\s*$/); + if (match) heading = match[1].trim(); + for (const span of item.line.matchAll(/(`+)([^`]+?)\1(?!`)/g)) { + const content = span[2].trim(); + if (content.startsWith('@/')) { + refs.push({ heading, raw: content, path: content.slice(1).split('#')[0], fragment: null, absolute: true }); + continue; + } + const ref = content.match(REFERENCE); + if (ref) refs.push({ heading, raw: content, path: ref[1], fragment: ref[2] ?? null, absolute: false }); + } + } + return refs; +} + +export function slugify(heading) { + return heading + .trim() + .toLowerCase() + .replace(/[^\p{L}\p{N}\s-]/gu, '') + .replace(/\s/g, '-'); +} + +export function markdownAnchors(markdown) { + const anchors = new Set(); + for (const item of scan(splitFrontmatter(markdown).markdown)) { + if (item.kind !== 'text') continue; + const match = item.line.match(/^#{1,6}\s+(.+?)\s*#*\s*$/); + if (match) anchors.add(slugify(match[1])); + } + return anchors; +} + +export function htmlAnchors(html) { + const anchors = new Set(); + for (const match of html.matchAll(/\sid\s*=\s*["']([^"']+)["']/g)) anchors.add(match[1]); + for (const match of html.matchAll(//g)) anchors.add(match[1]); + return anchors; +} diff --git a/packages/parser/src/index.mjs b/packages/parser/src/index.mjs index 6b32491..929515a 100644 --- a/packages/parser/src/index.mjs +++ b/packages/parser/src/index.mjs @@ -1,57 +1,139 @@ import { createHash } from 'node:crypto'; -import { normalizeMotion, stableValue } from '../../motion-ir/src/index.mjs'; +import { normalizeMotion, stableStringify, stableValue } from '../../motion-ir/src/index.mjs'; +import { isSafeRelativePath, loadDesignMotion } from './design.mjs'; +import { + extractYamlBlocks, findReferences, htmlAnchors, markdownAnchors, parseSections, splitFrontmatter, +} from './document.mjs'; import { parseYaml, YamlLiteError } from './yaml-lite.mjs'; import { validateMotion } from './validate.mjs'; -function parseSections(markdown) { - const lines = markdown.replace(/\r\n?/g, '\n').split('\n'); - const sections = []; - const seen = new Set(); - let current = null; +function add(findings, rule, severity, path, message) { + findings.push({ rule, severity, path, message }); +} - for (const line of lines) { - const match = line.match(/^##\s+(.+?)\s*#*\s*$/); - if (match) { - const heading = match[1].trim(); - if (seen.has(heading)) { - const error = new Error(`Duplicate Markdown section: ${heading}`); - error.rule = 'duplicate-section'; - error.path = `/sections/${heading}`; - throw error; - } - seen.add(heading); - current = { heading, content: '' }; - sections.push(current); +// Front matter and fenced ```yaml blocks merge into one tree; each top-level key may be +// defined once across the whole document (same rule as DESIGN.md). +function collectMachineData(split, findings) { + const sources = []; + if (split.yaml !== null) sources.push({ label: 'front matter', yaml: split.yaml, line: 2 }); + for (const block of extractYamlBlocks(split.markdown)) { + sources.push({ label: `yaml block in "${block.heading ?? 'preamble'}"`, yaml: block.yaml, line: split.bodyLine + block.startIndex + 1 }); + } + if (sources.length === 0) return null; + const merged = {}; + for (const source of sources) { + let data; + try { + data = parseYaml(source.yaml); + } catch (error) { + if (!(error instanceof YamlLiteError)) throw error; + const line = error.line ? source.line + error.line - 1 : source.line; + add(findings, 'yaml-syntax', 'error', '/', `${error.message.replace(/ at line \d+$/, '')} at line ${line} (${source.label})`); continue; } - if (current) current.content += `${line}\n`; + for (const [key, value] of Object.entries(data)) { + if (Object.hasOwn(merged, key)) { + add(findings, 'duplicate-key', 'error', `/${key}`, `Top-level key ${key} is defined more than once (${source.label}).`); + continue; + } + merged[key] = value; + } + } + return merged; +} + +function timingRefs(frontmatter) { + const refs = []; + if (typeof frontmatter.defaults?.timing === 'string') refs.push({ ref: frontmatter.defaults.timing, path: '/defaults/timing' }); + for (const [id, timeline] of Object.entries(frontmatter.timelines ?? {})) { + (timeline?.tracks ?? []).forEach((track, index) => { + if (typeof track?.timing === 'string') refs.push({ ref: track.timing, path: `/timelines/${id}/tracks/${index}/timing` }); + }); + } + return refs; +} + +function bindDesign(frontmatter, resolveFile, findings) { + const refs = timingRefs(frontmatter); + if (frontmatter.design === undefined) { + for (const { path } of refs) add(findings, 'broken-ref', 'error', path, 'Timing token references require a design file.'); + return null; + } + if (!resolveFile) { + add(findings, 'unresolved-design', 'error', '/design', 'The design file cannot be resolved without a base directory.'); + return null; + } + const source = resolveFile(frontmatter.design); + if (source == null) { + add(findings, 'broken-ref', 'error', '/design', `Design file ${frontmatter.design} does not exist.`); + return null; + } + const loaded = loadDesignMotion(source, frontmatter.design); + findings.push(...loaded.findings); + for (const { ref, path } of refs) { + if (!loaded.tokens.has(ref.slice(1, -1))) add(findings, 'broken-ref', 'error', path, `Motion token ${ref} does not exist in ${frontmatter.design}.`); } - return sections.map((section) => ({ ...section, content: section.content.trim() })); + // A literal duration and curve that already equal a design token is a second source of truth. + for (const [id, timeline] of Object.entries(frontmatter.timelines ?? {})) { + (timeline?.tracks ?? []).forEach((track, index) => { + if (track?.timing !== undefined || track?.durationMs === undefined || !track?.curve) return; + const curve = frontmatter.curves?.[track.curve]; + if (!curve) return; + for (const [tokenPath, token] of loaded.tokens) { + if (token.durationMs === track.durationMs && stableStringify(token.curve) === stableStringify(curve)) { + add(findings, 'prefer-design-token', 'info', `/timelines/${id}/tracks/${index}`, `Duration and curve equal {${tokenPath}}; reference it with timing instead.`); + break; + } + } + }); + } + return { path: frontmatter.design, sourceHash: loaded.sourceHash, tokens: loaded.tokens }; } -function splitDocument(source) { - const normalized = source.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n'); - const lines = normalized.split('\n'); - if (lines[0] !== '---') return { yaml: null, markdown: normalized }; - const closing = lines.findIndex((line, index) => index > 0 && line === '---'); - if (closing < 0) throw new YamlLiteError('Front matter is missing a closing --- delimiter', 1); - return { - yaml: lines.slice(1, closing).join('\n'), - markdown: lines.slice(closing + 1).join('\n').replace(/^\n/, ''), - }; +function checkReferences(markdown, resolveFile, findings) { + for (const ref of findReferences(markdown)) { + const path = `/sections/${ref.heading ?? 'preamble'}/references/${ref.raw}`; + if (ref.absolute || !isSafeRelativePath(ref.path)) { + add(findings, 'broken-ref', 'error', path, 'External references resolve from the MOTION.md directory and must stay inside it.'); + continue; + } + if (!resolveFile) continue; + const target = resolveFile(ref.path); + if (target == null) { + add(findings, 'broken-ref', 'warning', path, `Referenced file ${ref.path} does not exist.`); + continue; + } + if (!ref.fragment) continue; + const extension = ref.path.split('.').pop().toLowerCase(); + const anchors = ['md', 'markdown'].includes(extension) ? markdownAnchors(target) + : ['html', 'htm'].includes(extension) ? htmlAnchors(target) : null; + if (!anchors) add(findings, 'broken-ref', 'info', path, `Fragment #${ref.fragment} on a .${extension} file is not checked.`); + else if (!anchors.has(ref.fragment)) add(findings, 'broken-ref', 'warning', path, `Fragment #${ref.fragment} does not exist in ${ref.path}.`); + } } -export function parseMotion(source) { +/** + * @param {string} source MOTION.md text + * @param {{ resolveFile?: (relativePath: string) => string | null }} [options] + * resolveFile reads a path relative to the MOTION.md directory, returning null when absent. + */ +export function parseMotion(source, options = {}) { + const { resolveFile } = options; const findings = []; let frontmatter = null; let sections = []; + let design = null; try { - const split = splitDocument(source); - frontmatter = split.yaml === null ? null : parseYaml(split.yaml); + const split = splitFrontmatter(source); sections = parseSections(split.markdown); + frontmatter = collectMachineData(split, findings); findings.push(...validateMotion(frontmatter, sections)); + checkReferences(split.markdown, resolveFile, findings); + if (frontmatter && !findings.some((finding) => finding.severity === 'error')) { + design = bindDesign(frontmatter, resolveFile, findings); + } } catch (error) { findings.push({ rule: error.rule ?? (error instanceof YamlLiteError ? 'yaml-syntax' : 'markdown-structure'), @@ -64,7 +146,7 @@ export function parseMotion(source) { const errors = findings.filter((finding) => finding.severity === 'error').length; const warnings = findings.filter((finding) => finding.severity === 'warning').length; const info = findings.filter((finding) => finding.severity === 'info').length; - const ir = errors === 0 && frontmatter ? normalizeMotion(frontmatter, sections) : null; + const ir = errors === 0 && frontmatter ? normalizeMotion(frontmatter, sections, design) : null; return stableValue({ format: 'motion.md', @@ -78,8 +160,8 @@ export function parseMotion(source) { }); } -export function lintMotion(source) { - const parsed = parseMotion(source); +export function lintMotion(source, options = {}) { + const parsed = parseMotion(source, options); return stableValue({ format: parsed.format, specVersion: parsed.specVersion, @@ -89,4 +171,5 @@ export function lintMotion(source) { }); } +export { parseTimingFunction } from './design.mjs'; export { parseYaml, YamlLiteError } from './yaml-lite.mjs'; diff --git a/packages/parser/src/validate.mjs b/packages/parser/src/validate.mjs index 1c22f64..5de1419 100644 --- a/packages/parser/src/validate.mjs +++ b/packages/parser/src/validate.mjs @@ -1,7 +1,11 @@ +import { isSafeRelativePath, TIMING_REF } from './design.mjs'; + const ID = /^[a-z][a-z0-9-]*$/; +const CANONICAL_SECTIONS = ['Motion Thesis', 'Motion Principles', 'Hierarchy and Choreography', 'Interruption', 'Reduced Motion', 'Performance', 'Provenance']; +const sectionKey = (heading) => heading.toLowerCase().replace(/\s+/g, '-'); const PROPERTY = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/; const ROOT_KEYS = new Set([ - 'version', 'name', 'description', 'posture', 'defaults', 'states', 'events', 'curves', + 'version', 'name', 'description', 'posture', 'design', 'omitted', 'defaults', 'states', 'events', 'curves', 'timelines', 'transitions', 'reducedMotion', 'performance', 'provenance', ]); @@ -96,13 +100,50 @@ function validateCurve(findings, curve, path) { } } +// `timing` references a DESIGN.md motion token; it replaces the literal fields it would +// otherwise duplicate, so both together are two sources of truth. +function validateTiming(findings, owner, path, replaced) { + if (owner.timing === undefined) return; + if (typeof owner.timing !== 'string' || !TIMING_REF.test(owner.timing)) { + add(findings, 'timing-ref', 'error', `${path}/timing`, 'Timing must reference a design motion token such as "{motion.surface-enter}".'); + } + for (const field of replaced) if (owner[field] !== undefined) add(findings, 'timing-conflict', 'error', `${path}/${field}`, `${field} duplicates the referenced timing token.`); +} + +function validateOmitted(findings, omitted, headings) { + if (!Array.isArray(omitted)) { + add(findings, 'type', 'error', '/omitted', 'Omitted must be an array.'); + return new Set(); + } + const declared = new Set(); + omitted.forEach((entry, index) => { + const path = `/omitted/${index}`; + const section = typeof entry === 'string' ? entry : entry?.section; + if (isObject(entry)) { + unknownKeys(findings, entry, new Set(['section', 'reason']), path); + if (entry.reason !== undefined) requireString(findings, entry.reason, `${path}/reason`); + } + const canonical = CANONICAL_SECTIONS.find((heading) => sectionKey(heading) === section); + if (!canonical) { + add(findings, 'unknown-omission', 'warning', path, `Unknown section key ${section}; use one of ${CANONICAL_SECTIONS.map(sectionKey).join(', ')}.`); + return; + } + if (headings.includes(canonical)) add(findings, 'redundant-omission', 'warning', path, `${canonical} is declared omitted but present.`); + declared.add(canonical); + }); + return declared; +} + export function validateMotion(frontmatter, sections) { const findings = []; if (!frontmatter) { - add(findings, 'missing-frontmatter', 'warning', '/', 'Document has no machine-readable front matter.'); + add(findings, 'missing-machine-data', 'warning', '/', 'Document has no machine-readable front matter or yaml blocks.'); } else { unknownKeys(findings, frontmatter, ROOT_KEYS, ''); - if (frontmatter.version !== '0.1') add(findings, 'spec-version', 'error', '/version', 'v0.1 documents must declare version "0.1".'); + if (frontmatter.version !== '0.2') add(findings, 'spec-version', 'error', '/version', 'v0.2 documents must declare version "0.2".'); + if (frontmatter.design !== undefined && (!isSafeRelativePath(frontmatter.design) || !/\.md$/i.test(frontmatter.design))) { + add(findings, 'design-path', 'error', '/design', 'Design must be a relative path to a .md file inside the MOTION.md directory.'); + } requireString(findings, frontmatter.name, '/name'); if (!['static', 'minimal', 'expressive', 'procedural'].includes(frontmatter.posture)) add(findings, 'posture', 'error', '/posture', 'Posture must be static, minimal, expressive, or procedural.'); @@ -119,7 +160,8 @@ export function validateMotion(frontmatter, sections) { } if (frontmatter.defaults !== undefined && requireObject(findings, frontmatter.defaults, '/defaults')) { - unknownKeys(findings, frontmatter.defaults, new Set(['durationMs', 'delayMs', 'curve']), '/defaults'); + unknownKeys(findings, frontmatter.defaults, new Set(['timing', 'durationMs', 'delayMs', 'curve']), '/defaults'); + validateTiming(findings, frontmatter.defaults, '/defaults', ['durationMs', 'delayMs', 'curve']); for (const field of ['durationMs', 'delayMs']) if (frontmatter.defaults[field] !== undefined && (!Number.isInteger(frontmatter.defaults[field]) || frontmatter.defaults[field] < 0)) add(findings, 'time-value', 'error', `/defaults/${field}`, 'Time values must be non-negative integer milliseconds.'); if (frontmatter.defaults.curve && !curveIds.has(frontmatter.defaults.curve)) add(findings, 'broken-ref', 'error', '/defaults/curve', 'Default curve reference does not exist.'); } @@ -160,7 +202,8 @@ export function validateMotion(frontmatter, sections) { timeline.tracks.forEach((track, index) => { const trackPath = `${path}/tracks/${index}`; if (!requireObject(findings, track, trackPath)) return; - unknownKeys(findings, track, new Set(['target', 'property', 'curve', 'startMs', 'durationMs', 'keyframes']), trackPath); + unknownKeys(findings, track, new Set(['target', 'property', 'timing', 'curve', 'startMs', 'durationMs', 'keyframes']), trackPath); + validateTiming(findings, track, trackPath, ['durationMs', 'curve']); if (!ID.test(track.target ?? '')) add(findings, 'identifier', 'error', `${trackPath}/target`, 'Track target must use lower kebab-case.'); if (!PROPERTY.test(track.property ?? '')) add(findings, 'property-path', 'error', `${trackPath}/property`, 'Property must be a runtime-neutral dotted path.'); if (track.curve && !curveIds.has(track.curve)) add(findings, 'broken-ref', 'error', `${trackPath}/curve`, 'Track curve reference does not exist.'); @@ -255,9 +298,10 @@ export function validateMotion(frontmatter, sections) { } } - const canonical = ['Motion Thesis', 'Motion Principles', 'Hierarchy and Choreography', 'Interruption', 'Reduced Motion', 'Performance', 'Provenance']; + const canonical = CANONICAL_SECTIONS; const headings = sections.map((section) => section.heading); - for (const required of canonical) if (!headings.includes(required)) add(findings, 'missing-section', 'warning', `/sections/${required}`, `Recommended section is missing: ${required}.`); + const omitted = frontmatter?.omitted === undefined ? new Set() : validateOmitted(findings, frontmatter.omitted, headings); + for (const required of canonical) if (!headings.includes(required) && !omitted.has(required)) add(findings, 'missing-section', 'warning', `/sections/${required}`, `Recommended section is missing: ${required}.`); let last = -1; for (const heading of headings) { const position = canonical.indexOf(heading); diff --git a/schemas/motion.schema.json b/schemas/motion.schema.json index 753cc08..cc03d54 100644 --- a/schemas/motion.schema.json +++ b/schemas/motion.schema.json @@ -1,14 +1,36 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://motion.md/schemas/motion.schema.json", - "title": "MOTION.md front matter v0.1", + "title": "MOTION.md machine data v0.2", "type": "object", "required": ["version", "name", "posture", "reducedMotion", "performance", "provenance"], "properties": { - "version": { "const": "0.1" }, + "version": { "const": "0.2" }, "name": { "type": "string", "minLength": 1 }, "description": { "type": "string" }, "posture": { "enum": ["static", "minimal", "expressive", "procedural"] }, + "design": { + "type": "string", + "pattern": "^(?!/)(?![A-Za-z]:)[^\\s\\\\]*\\.md$", + "description": "Relative path to the DESIGN.md whose motion tokens this document references. Resolved from the MOTION.md directory; must not leave it." + }, + "omitted": { + "type": "array", + "items": { + "anyOf": [ + { "$ref": "#/$defs/sectionKey" }, + { + "type": "object", + "required": ["section"], + "properties": { + "section": { "$ref": "#/$defs/sectionKey" }, + "reason": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false + } + ] + } + }, "defaults": { "$ref": "#/$defs/defaults" }, "states": { "$ref": "#/$defs/states" }, "events": { "$ref": "#/$defs/events" }, @@ -48,6 +70,14 @@ "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, + "sectionKey": { + "enum": ["motion-thesis", "motion-principles", "hierarchy-and-choreography", "interruption", "reduced-motion", "performance", "provenance"] + }, + "timingRef": { + "type": "string", + "pattern": "^\\{motion(\\.[a-z][a-z0-9-]*)+\\}$", + "description": "Reference to a DESIGN.md motion token. Replaces the literal duration and curve fields it would duplicate." + }, "jsonValue": { "anyOf": [ { "type": ["string", "number", "boolean", "null"] }, @@ -61,6 +91,7 @@ "defaults": { "type": "object", "properties": { + "timing": { "$ref": "#/$defs/timingRef" }, "durationMs": { "type": "integer", "minimum": 0 }, "delayMs": { "type": "integer", "minimum": 0 }, "curve": { "$ref": "#/$defs/id" } @@ -68,7 +99,11 @@ "patternProperties": { "^x-[a-z0-9][a-z0-9-]*$": { "$ref": "#/$defs/jsonValue" } }, - "additionalProperties": false + "additionalProperties": false, + "if": { "required": ["timing"] }, + "then": { + "not": { "anyOf": [{ "required": ["durationMs"] }, { "required": ["delayMs"] }, { "required": ["curve"] }] } + } }, "state": { "type": "object", @@ -240,6 +275,7 @@ "properties": { "target": { "$ref": "#/$defs/id" }, "property": { "type": "string", "pattern": "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$" }, + "timing": { "$ref": "#/$defs/timingRef" }, "curve": { "$ref": "#/$defs/id" }, "startMs": { "type": "integer", "minimum": 0 }, "durationMs": { "type": "integer", "minimum": 0 }, @@ -252,7 +288,11 @@ "patternProperties": { "^x-[a-z0-9][a-z0-9-]*$": { "$ref": "#/$defs/jsonValue" } }, - "additionalProperties": false + "additionalProperties": false, + "if": { "required": ["timing"] }, + "then": { + "not": { "anyOf": [{ "required": ["durationMs"] }, { "required": ["curve"] }] } + } }, "driver": { "type": "object", diff --git a/tests/cli.test.mjs b/tests/cli.test.mjs index e655e41..98845ed 100644 --- a/tests/cli.test.mjs +++ b/tests/cli.test.mjs @@ -39,7 +39,7 @@ test('diff is formatting-neutral and reports no changes for identical documents' test('spec emits Markdown and JSON Schema', () => { const markdown = run('spec'); assert.equal(markdown.status, 0, markdown.stderr); - assert.match(markdown.stdout, /MOTION\.md Format Specification v0\.1/); + assert.match(markdown.stdout, /MOTION\.md Format Specification v0\.2/); const schema = run('spec', '--format', 'json'); assert.equal(schema.status, 0, schema.stderr); @@ -50,3 +50,11 @@ test('schema source is valid JSON', () => { const schema = JSON.parse(readFileSync(resolve(root, 'schemas/motion.schema.json'), 'utf8')); assert.equal(schema.$id, 'https://motion.md/schemas/motion.schema.json'); }); + +test('lint and parse resolve design tokens relative to the input file', () => { + const lint = run('lint', 'examples/design-bound/MOTION.md'); + assert.equal(lint.status, 0, lint.stderr); + assert.deepEqual(JSON.parse(lint.stdout).summary, { errors: 0, info: 0, warnings: 0 }); + const parse = run('parse', 'examples/design-bound/MOTION.md'); + assert.equal(JSON.parse(parse.stdout).ir.design.path, 'DESIGN.md'); +}); diff --git a/tests/design.test.mjs b/tests/design.test.mjs new file mode 100644 index 0000000..a3d4a0e --- /dev/null +++ b/tests/design.test.mjs @@ -0,0 +1,189 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import test from 'node:test'; +import { diffMotion } from '../packages/motion-ir/src/index.mjs'; +import { lintMotion, parseMotion, parseTimingFunction } from '../packages/parser/src/index.mjs'; + +const root = resolve(import.meta.dirname, '..'); +const read = (path) => readFileSync(resolve(root, path), 'utf8'); + +const DESIGN = `--- +version: alpha +name: Test +colors: + primary: "#000000" +motion: + surface-enter: + duration: 250ms + delay: 40ms + timingFunction: cubic-bezier(0.2, 0, 0, 1) + sm: + tap: + duration: 80ms +--- + +## Motion & Micro-interaction + +Quick. +`; + +const SECTIONS = ['Motion Thesis', 'Motion Principles', 'Hierarchy and Choreography', 'Interruption', 'Reduced Motion', 'Performance', 'Provenance']; + +function files(extra = {}) { + const map = { 'DESIGN.md': DESIGN, ...extra }; + return { resolveFile: (path) => map[path] ?? null }; +} + +function doc({ track = { timing: '{motion.surface-enter}' }, root: rootFields = {}, body = '', sections = SECTIONS } = {}) { + const frontmatter = { + version: '0.2', + name: 'Test', + posture: 'minimal', + design: 'DESIGN.md', + states: { closed: { description: 'Closed.' }, open: { description: 'Open.' } }, + events: { toggle: { description: 'Toggle.', source: 'user' } }, + curves: { standard: { type: 'cubic-bezier', value: [0.2, 0, 0, 1] } }, + timelines: { + reveal: { + description: 'Reveal.', + driver: { type: 'clock' }, + tracks: [{ target: 'panel', property: 'visual.opacity', keyframes: [{ at: 0, value: 0 }, { at: 1, value: 1 }], ...track }], + }, + }, + transitions: { + open: { from: 'closed', to: 'open', on: 'toggle', timeline: 'reveal', interruption: { policy: 'reverse' }, cancellation: { policy: 'nearest' } }, + }, + reducedMotion: { strategy: 'instant' }, + performance: { targetFps: 60, maxMainThreadMsPerFrame: 3, maxConcurrentTracks: 1, inputReadyMs: 0, deterministic: true }, + provenance: [{ id: 'test', kind: 'authored', description: 'Test.' }], + ...rootFields, + }; + for (const [key, value] of Object.entries(frontmatter)) if (value === undefined) delete frontmatter[key]; + const prose = sections.map((heading) => `## ${heading}\n\nText.\n`).join('\n'); + return `---\n${JSON.stringify(frontmatter, null, 2)}\n---\n\n${prose}\n${body}`; +} + +const rules = (result) => result.findings.map((finding) => `${finding.severity}:${finding.rule}`); + +test('the design-bound example resolves DESIGN.md motion tokens into Motion IR', () => { + const result = parseMotion(read('examples/design-bound/MOTION.md'), { + resolveFile: (path) => read(`examples/design-bound/${path}`), + }); + assert.deepEqual(result.summary, { errors: 0, info: 0, warnings: 0 }); + assert.equal(result.ir.design.path, 'DESIGN.md'); + const figures = result.ir.timelines.find((t) => t.id === 'sheet-enter').tracks[2]; + assert.deepEqual([figures.timing, figures.durationMs, figures.startMs, figures.curve], ['motion.state-change', 100, 120, 'motion.state-change']); + assert.deepEqual(result.ir.curves.find((c) => c.id === 'motion.state-change'), { id: 'motion.state-change', origin: 'design', type: 'cubic-bezier', value: [0, 0, 0.58, 1] }); + assert.equal(result.ir.policies.reducedMotion.strategy, 'substitute', 'interleaved yaml block is machine data'); + assert.doesNotMatch(result.ir.intent.sections.find((s) => s.heading === 'Reduced Motion').content, /strategy/); +}); + +test('token delay is added to the authored choreography offset; grouped tokens use dot paths', () => { + const offset = parseMotion(doc({ track: { timing: '{motion.surface-enter}', startMs: 60 } }), files()); + const track = offset.ir.timelines[0].tracks[0]; + assert.deepEqual([track.durationMs, track.startMs], [250, 100]); + + const grouped = parseMotion(doc({ track: { timing: '{motion.sm.tap}' } }), files()); + assert.equal(grouped.summary.errors, 0); + assert.deepEqual(grouped.ir.curves.find((c) => c.id === 'motion.sm.tap').value, [0.25, 0.1, 0.25, 1], 'CSS default timing function is ease'); +}); + +test('timing references fail when the token, the design file, or the binding is missing', () => { + assert.ok(rules(lintMotion(doc({ track: { timing: '{motion.nope}' } }), files())).includes('error:broken-ref')); + assert.ok(rules(lintMotion(doc(), { resolveFile: () => null })).includes('error:broken-ref')); + assert.ok(rules(lintMotion(doc({ root: { design: undefined } }), files())).includes('error:broken-ref')); + assert.ok(rules(lintMotion(doc())).includes('error:unresolved-design')); + assert.ok(rules(lintMotion(doc({ track: { timing: 'surface-enter' } }), files())).includes('error:timing-ref')); +}); + +test('timing and literal timing fields together are two sources of truth', () => { + const result = lintMotion(doc({ track: { timing: '{motion.surface-enter}', durationMs: 250, curve: 'standard' } }), files()); + assert.deepEqual(result.findings.filter((f) => f.rule === 'timing-conflict').map((f) => f.path), [ + '/timelines/reveal/tracks/0/durationMs', + '/timelines/reveal/tracks/0/curve', + ]); +}); + +test('literal values equal to a design token produce an info finding', () => { + const result = lintMotion(doc({ track: { durationMs: 250, curve: 'standard' } }), files()); + assert.deepEqual(rules(result), ['info:prefer-design-token']); +}); + +test('design path must stay inside the MOTION.md directory', () => { + for (const design of ['../DESIGN.md', '/DESIGN.md', 'design.json']) { + assert.ok(rules(lintMotion(doc({ root: { design } }), files())).includes('error:design-path'), design); + } +}); + +test('unsupported DESIGN.md timing functions are reported, not approximated', () => { + const design = DESIGN.replace('cubic-bezier(0.2, 0, 0, 1)', 'linear(0, 0.5 50%, 1)'); + assert.ok(rules(lintMotion(doc(), files({ 'DESIGN.md': design }))).includes('error:unsupported-timing-function')); +}); + +test('CSS easing keywords map to the curve model', () => { + assert.deepEqual(parseTimingFunction('linear'), { type: 'linear' }); + assert.deepEqual(parseTimingFunction('ease-in-out'), { type: 'cubic-bezier', value: [0.42, 0, 0.58, 1] }); + assert.deepEqual(parseTimingFunction('steps(4, jump-both)'), { type: 'steps', count: 4, jump: 'both' }); + assert.deepEqual(parseTimingFunction('step-start'), { type: 'steps', count: 1, jump: 'start' }); + assert.equal(parseTimingFunction('cubic-bezier(1.2, 0, 0, 1)'), null); + assert.equal(parseTimingFunction('steps(1, jump-none)'), null); +}); + +test('a DESIGN.md token change shows up in the semantic diff', () => { + const before = parseMotion(doc(), files()).ir; + const after = parseMotion(doc(), files({ 'DESIGN.md': DESIGN.replace('250ms', '300ms') })).ir; + const paths = diffMotion(before, after).changes.modified.map((change) => change.path); + assert.ok(paths.includes('/timelines/reveal/tracks/0/durationMs')); + assert.ok(paths.includes('/design/sourceHash')); +}); + +test('a top-level key may be defined once across front matter and yaml blocks', () => { + const body = '## Extra\n\n```yaml\nreducedMotion:\n strategy: instant\n```\n'; + assert.ok(rules(lintMotion(doc({ body }), files())).includes('error:duplicate-key')); +}); + +test('headings inside fenced code are not sections', () => { + const body = '## Notes\n\n```md\n## Motion Thesis\n```\n'; + const result = parseMotion(doc({ body }), files()); + assert.equal(result.summary.errors, 0); + assert.equal(result.sections.filter((s) => s.heading === 'Motion Thesis').length, 1); +}); + +test('external @-references follow DESIGN.md resolution and severity rules', () => { + const body = [ + '## References', + '', + 'Good `@DESIGN.md#motion--micro-interaction`, missing `@clips/open.mp4`, bad anchor `@DESIGN.md#nope`,', + 'html `@kit/sheet.html#detail-sheet`, source `@src/sheet.tsx#Sheet`, absolute `@/etc/x.md`, escaping `@../x.md`,', + 'not references: `@media`, `@scope/package`, @DESIGN.md.', + '', + '```text', + '`@inside/fence.md`', + '```', + '', + ].join('\n'); + const result = lintMotion(doc({ body }), files({ + 'kit/sheet.html': '
', + 'src/sheet.tsx': 'export function Sheet() {}', + })); + const refs = result.findings.filter((f) => f.rule === 'broken-ref').map((f) => `${f.severity}:${f.path.split('/references/')[1]}`); + assert.deepEqual(refs.sort(), [ + 'error:@../x.md', + 'error:@/etc/x.md', + 'info:@src/sheet.tsx#Sheet', + 'warning:@DESIGN.md#nope', + 'warning:@clips/open.mp4', + ]); +}); + +test('omitted sections suppress missing-section warnings and are themselves checked', () => { + const without = SECTIONS.filter((heading) => heading !== 'Hierarchy and Choreography'); + assert.ok(rules(lintMotion(doc({ sections: without }), files())).includes('warning:missing-section')); + + const omitted = [{ section: 'hierarchy-and-choreography', reason: 'Single-element surface.' }]; + assert.deepEqual(rules(lintMotion(doc({ sections: without, root: { omitted } }), files())), []); + + const noisy = lintMotion(doc({ root: { omitted: ['performance', 'choreography'] } }), files()); + assert.deepEqual(rules(noisy).sort(), ['warning:redundant-omission', 'warning:unknown-omission']); +}); diff --git a/tests/motion-ir.test.mjs b/tests/motion-ir.test.mjs index 99b3b14..640c9a3 100644 --- a/tests/motion-ir.test.mjs +++ b/tests/motion-ir.test.mjs @@ -4,7 +4,7 @@ import { diffMotion, normalizeMotion, stableStringify } from '../packages/motion function document(overrides = {}) { return { - version: '0.1', + version: '0.2', name: 'Example', posture: 'minimal', states: { diff --git a/tests/parser.test.mjs b/tests/parser.test.mjs index 975d0aa..a0cbb86 100644 --- a/tests/parser.test.mjs +++ b/tests/parser.test.mjs @@ -16,8 +16,8 @@ test('all four reference documents parse into Motion IR without findings', () => ]) { const result = parseMotion(read(path)); assert.deepEqual(result.summary, { errors: 0, info: 0, warnings: 0 }, path); - assert.equal(result.ir.irVersion, '0.1'); - assert.equal(result.ir.specification, 'motion.md/0.1'); + assert.equal(result.ir.irVersion, '0.2'); + assert.equal(result.ir.specification, 'motion.md/0.2'); } }); @@ -76,5 +76,5 @@ test('URL scalars in sequences are not misread as mappings', () => { test('prose-only documents remain readable but warn about incomplete machine semantics', () => { const result = lintMotion('## Motion Thesis\n\nStillness is deliberate.\n'); assert.equal(result.summary.errors, 0); - assert.ok(result.findings.some((finding) => finding.rule === 'missing-frontmatter')); + assert.ok(result.findings.some((finding) => finding.rule === 'missing-machine-data')); }); From 97323aaa96e07dd96d834c305a1e82323cc959c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:29:49 +0800 Subject: [PATCH 2/4] fix(parser): CommonMark fence openings and inline DESIGN.md motion tokens Addresses review: fences with info strings or up to three spaces of indentation are recognized; motion tokens written as inline JSON or in JSON front matter are read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XvGrrMtBAhmTdvPRgAnpxt --- packages/parser/src/design.mjs | 13 +++++++++++-- packages/parser/src/document.mjs | 13 ++++++++----- tests/design.test.mjs | 15 +++++++++++++++ 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/packages/parser/src/design.mjs b/packages/parser/src/design.mjs index 38eef93..602ab26 100644 --- a/packages/parser/src/design.mjs +++ b/packages/parser/src/design.mjs @@ -50,7 +50,7 @@ function parseDuration(value) { // its tree, and its other sections may use YAML outside the portable subset. function motionBlock(yaml) { const lines = yaml.replace(/\r\n?/g, '\n').split('\n'); - const start = lines.findIndex((line) => /^motion:\s*(#.*)?$/.test(line)); + const start = lines.findIndex((line) => /^motion:/.test(line)); if (start < 0) return null; let end = start + 1; while (end < lines.length && (lines[end].trim() === '' || /^\s/.test(lines[end]) || /^#/.test(lines[end]))) end += 1; @@ -78,7 +78,16 @@ export function loadDesignMotion(source, designPath) { const add = (rule, severity, path, message) => findings.push({ rule, severity, path, message }); const { yaml, markdown } = splitFrontmatter(source); const blocks = [yaml, ...extractYamlBlocks(markdown).map((block) => block.yaml)].filter((text) => text != null); - const motionSources = blocks.map(motionBlock).filter(Boolean); + // Prefer the whole block when it is portable (covers JSON front matter); otherwise read + // only the motion key so the rest of DESIGN.md may use any YAML. + const motionSources = blocks.map((text) => { + try { + const whole = parseYaml(text); + return whole && Object.hasOwn(whole, 'motion') ? `motion: ${JSON.stringify(whole.motion)}` : null; + } catch { + return motionBlock(text); + } + }).filter(Boolean); if (motionSources.length > 1) add('design-motion', 'error', '/design', `${designPath} defines the motion key more than once.`); if (motionSources.length === 1) { diff --git a/packages/parser/src/document.mjs b/packages/parser/src/document.mjs index e76bdc4..ad04d44 100644 --- a/packages/parser/src/document.mjs +++ b/packages/parser/src/document.mjs @@ -1,6 +1,8 @@ import { YamlLiteError } from './yaml-lite.mjs'; -const FENCE = /^(`{3,}|~{3,})\s*([A-Za-z0-9_-]*)\s*$/; +// CommonMark fences: up to three spaces of indentation; the info string's first word is the language. +const FENCE_OPEN = /^ {0,3}(`{3,}(?=[^`]*$)|~{3,})\s*(.*)$/; +const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})\s*$/; export function splitFrontmatter(source) { const normalized = source.replace(/^/, '').replace(/\r\n?/g, '\n'); @@ -22,9 +24,9 @@ function scan(markdown) { const out = []; let fence = null; for (const [index, line] of lines.entries()) { - const match = line.match(FENCE); if (fence) { - if (match && match[1][0] === fence.marker[0] && match[1].length >= fence.marker.length && !match[2]) { + const close = line.match(FENCE_CLOSE); + if (close && close[1][0] === fence.marker[0] && close[1].length >= fence.marker.length) { out.push({ index, line, kind: 'fence-close', fence }); fence = null; } else { @@ -33,8 +35,9 @@ function scan(markdown) { } continue; } - if (match) { - fence = { marker: match[1], info: match[2].toLowerCase(), lines: [], startIndex: index }; + const open = line.match(FENCE_OPEN); + if (open) { + fence = { marker: open[1], info: (open[2].trim().split(/\s+/)[0] ?? '').toLowerCase(), lines: [], startIndex: index }; out.push({ index, line, kind: 'fence-open', fence }); continue; } diff --git a/tests/design.test.mjs b/tests/design.test.mjs index a3d4a0e..9ef3d07 100644 --- a/tests/design.test.mjs +++ b/tests/design.test.mjs @@ -187,3 +187,18 @@ test('omitted sections suppress missing-section warnings and are themselves chec const noisy = lintMotion(doc({ root: { omitted: ['performance', 'choreography'] } }), files()); assert.deepEqual(rules(noisy).sort(), ['warning:redundant-omission', 'warning:unknown-omission']); }); + +test('fences with info strings or up to three spaces of indentation are code, not structure', () => { + const body = '## Notes\n\n```js title="demo"\n## Motion Thesis\n```\n\n ~~~\n## Motion Principles\n ~~~\n'; + const result = parseMotion(doc({ body }), files()); + assert.equal(result.summary.errors, 0, JSON.stringify(result.findings)); +}); + +test('inline and JSON motion tokens in DESIGN.md are read', () => { + const inline = '---\nname: Inline\nmotion: {"surface-enter": {"duration": "250ms"}}\n---\n'; + assert.equal(lintMotion(doc(), files({ 'DESIGN.md': inline })).summary.errors, 0); + const json = '---\n{"name": "Json", "motion": {"surface-enter": {"duration": "250ms"}}}\n---\n'; + assert.equal(lintMotion(doc(), files({ 'DESIGN.md': json })).summary.errors, 0); + const nonPortable = '---\nname: Odd\ndescription: >\n folded text\nmotion:\n surface-enter:\n duration: 250ms\n---\n'; + assert.equal(lintMotion(doc(), files({ 'DESIGN.md': nonPortable })).summary.errors, 0, 'other DESIGN.md YAML may be non-portable'); +}); From 1b01aae137763dddbd0b4e78507940cd6a680b07 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:38:43 +0800 Subject: [PATCH 3/4] fix: address review on token suggestions, path containment, easing parsing - prefer-design-token only suggests zero-delay tokens (a delay moves startMs) - CLI resolver follows symlinks before checking containment; allows ..name - Own-property easing lookups; reject empty cubic-bezier components - Malformed omitted entries are type errors; schema accepts unknown keys (linter warns) and documents that containment is a lint check - Release notes: CI runs on pushes to main and on PRs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XvGrrMtBAhmTdvPRgAnpxt --- docs/releases/v0.2.0.md | 4 ++-- docs/spec.md | 4 ++-- packages/cli/src/index.mjs | 17 +++++++++++------ packages/parser/src/design.mjs | 9 ++++++--- packages/parser/src/index.mjs | 3 ++- packages/parser/src/validate.mjs | 4 ++++ schemas/motion.schema.json | 9 +++------ tests/design.test.mjs | 8 +++++++- 8 files changed, 37 insertions(+), 21 deletions(-) diff --git a/docs/releases/v0.2.0.md b/docs/releases/v0.2.0.md index b8530bd..7a9416e 100644 --- a/docs/releases/v0.2.0.md +++ b/docs/releases/v0.2.0.md @@ -13,7 +13,7 @@ Google Labs' `DESIGN.md` gained a `## Motion & Micro-interaction` section and `m - Interleaved ` ```yaml ` blocks; duplicate top-level keys are errors. / 穿插 YAML 块;顶层键重复即错误。 - `omitted` for prose sections, with `unknown-omission` and `redundant-omission`. / 声明省略的正文章节。 - External `` `@path#fragment` `` references with `DESIGN.md` severities. / 外部引用,严重级别与 `DESIGN.md` 一致。 -- CI runs `npm run check` on every push and pull request. / CI 在每次 push 与 PR 上运行 `npm run check`。 +- CI runs `npm run check` on pushes to `main` and on pull requests. / CI 在推送到 `main` 和每个 PR 上运行 `npm run check`。 ## Changed / 变更 @@ -29,5 +29,5 @@ Google Labs' `DESIGN.md` gained a `## Motion & Micro-interaction` section and `m ## Migration / 迁移 1. Change `version: "0.1"` to `version: "0.2"`. / 把版本改成 `"0.2"`。 -2. If the project has a `DESIGN.md` with `motion` tokens, add `design: DESIGN.md` and replace each track's `durationMs` + `curve` that match a token with `timing: "{motion.}"`. `motionmd lint` lists candidates as `prefer-design-token`. / 若项目的 `DESIGN.md` 有 motion token,加上 `design`,并按 `prefer-design-token` 提示把对应字面值换成 `timing` 引用。 +2. If the project has a `DESIGN.md` with `motion` tokens, add `design: DESIGN.md` and replace each track's `durationMs` + `curve` that match a token with `timing: "{motion.}"`. `motionmd lint` lists candidates as `prefer-design-token`; it only suggests tokens with a zero delay, because a token delay is added to `startMs`. For a delayed token, lower the track's `startMs` by the delay when switching. / 若项目的 `DESIGN.md` 有 motion token,加上 `design`,并按 `prefer-design-token` 提示把对应字面值换成 `timing` 引用;该提示只针对 delay 为 0 的 token,因为 token delay 会叠加到 `startMs`,换用带 delay 的 token 时要相应减小 `startMs`。 3. Rename any tooling that matches `missing-frontmatter`. / 更新匹配旧规则名的工具。 diff --git a/docs/spec.md b/docs/spec.md index d91b88a..37a32eb 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -35,7 +35,7 @@ A fully authored document SHOULD include these `##` sections in this order: Unknown sections MUST be preserved. Duplicate second-level headings are invalid because they make stable section addressing ambiguous. A prose-only document is valid but produces a `missing-machine-data` warning and cannot yield a complete Motion IR. -A section that is deliberately absent is declared in `omitted`, either as a section key or as `{ section, reason }`. Section keys are the lower kebab-case headings: `motion-thesis`, `motion-principles`, `hierarchy-and-choreography`, `interruption`, `reduced-motion`, `performance`, `provenance`. A declared omission suppresses the `missing-section` warning. An unknown key produces `unknown-omission`; a key whose section is present produces `redundant-omission`. `omitted` covers prose only: required machine fields such as `reducedMotion` and `performance` cannot be omitted. +A section that is deliberately absent is declared in `omitted`, either as a section key or as `{ section, reason }`. Section keys are the lower kebab-case headings: `motion-thesis`, `motion-principles`, `hierarchy-and-choreography`, `interruption`, `reduced-motion`, `performance`, `provenance`. A declared omission suppresses the `missing-section` warning. An unknown key produces `unknown-omission` (a warning, so schema-valid); a key whose section is present produces `redundant-omission`. `omitted` covers prose only: required machine fields such as `reducedMotion` and `performance` cannot be omitted. ```yaml omitted: @@ -139,7 +139,7 @@ A referenced token resolves as follows: ### 7.4 Single source of truth -When a track declares a literal `durationMs` and a `curve` that together equal a bound token, the linter reports `prefer-design-token` (`info`) so the literal can be replaced with a reference. +When a track declares a literal `durationMs` and a `curve` that together equal a bound token whose delay is zero, the linter reports `prefer-design-token` (`info`) so the literal can be replaced with a reference. ## 8. Timelines and tracks diff --git a/packages/cli/src/index.mjs b/packages/cli/src/index.mjs index 0afdfcd..61f7994 100644 --- a/packages/cli/src/index.mjs +++ b/packages/cli/src/index.mjs @@ -1,6 +1,6 @@ -import { existsSync, readFileSync, statSync } from 'node:fs'; +import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { dirname, isAbsolute, relative, resolve } from 'node:path'; +import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'; import { diffMotion, stableStringify } from '../../motion-ir/src/index.mjs'; import { lintMotion, parseMotion } from '../../parser/src/index.mjs'; @@ -13,12 +13,17 @@ function readInput(path) { // Resolve references from the MOTION.md directory (cwd for stdin), never outside it. function resolverFor(path) { - const base = path === '-' ? process.cwd() : dirname(resolve(process.cwd(), path)); + const base = realpathSync(path === '-' ? process.cwd() : dirname(resolve(process.cwd(), path))); + const contained = (target) => { + const inside = relative(base, target); + return inside !== '' && inside !== '..' && !inside.startsWith(`..${sep}`) && !isAbsolute(inside); + }; return (relativePath) => { const target = resolve(base, relativePath); - const inside = relative(base, target); - if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) return null; - return existsSync(target) && statSync(target).isFile() ? readFileSync(target, 'utf8') : null; + if (!contained(target) || !existsSync(target)) return null; + // Follow symlinks before trusting containment. + const real = realpathSync(target); + return contained(real) && statSync(real).isFile() ? readFileSync(real, 'utf8') : null; }; } diff --git a/packages/parser/src/design.mjs b/packages/parser/src/design.mjs index 602ab26..867cd05 100644 --- a/packages/parser/src/design.mjs +++ b/packages/parser/src/design.mjs @@ -20,12 +20,14 @@ const JUMPS = { export function parseTimingFunction(input) { const value = String(input).trim(); if (value === 'linear') return { type: 'linear' }; - if (KEYWORDS[value]) return { type: 'cubic-bezier', value: KEYWORDS[value] }; + if (Object.hasOwn(KEYWORDS, value)) return { type: 'cubic-bezier', value: KEYWORDS[value] }; if (value === 'step-start') return { type: 'steps', count: 1, jump: 'start' }; if (value === 'step-end') return { type: 'steps', count: 1, jump: 'end' }; let match = value.match(/^cubic-bezier\(([^)]*)\)$/); if (match) { - const numbers = match[1].split(',').map((part) => Number(part.trim())); + const parts = match[1].split(',').map((part) => part.trim()); + if (parts.some((part) => !/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/.test(part))) return null; + const numbers = parts.map(Number); if (numbers.length !== 4 || numbers.some((n) => !Number.isFinite(n))) return null; if (numbers[0] < 0 || numbers[0] > 1 || numbers[2] < 0 || numbers[2] > 1) return null; return { type: 'cubic-bezier', value: numbers }; @@ -33,7 +35,8 @@ export function parseTimingFunction(input) { match = value.match(/^steps\(\s*(\d+)\s*(?:,\s*([a-z-]+)\s*)?\)$/); if (match) { const count = Number(match[1]); - const jump = JUMPS[match[2] ?? 'end']; + const keyword = match[2] ?? 'end'; + const jump = Object.hasOwn(JUMPS, keyword) ? JUMPS[keyword] : undefined; if (!jump || count < 1 || (jump === 'none' && count < 2)) return null; return { type: 'steps', count, jump }; } diff --git a/packages/parser/src/index.mjs b/packages/parser/src/index.mjs index 929515a..6a9955e 100644 --- a/packages/parser/src/index.mjs +++ b/packages/parser/src/index.mjs @@ -81,7 +81,8 @@ function bindDesign(frontmatter, resolveFile, findings) { const curve = frontmatter.curves?.[track.curve]; if (!curve) return; for (const [tokenPath, token] of loaded.tokens) { - if (token.durationMs === track.durationMs && stableStringify(token.curve) === stableStringify(curve)) { + // A delayed token would move the track's start, so only an exact equivalent is suggested. + if (token.delayMs === 0 && token.durationMs === track.durationMs && stableStringify(token.curve) === stableStringify(curve)) { add(findings, 'prefer-design-token', 'info', `/timelines/${id}/tracks/${index}`, `Duration and curve equal {${tokenPath}}; reference it with timing instead.`); break; } diff --git a/packages/parser/src/validate.mjs b/packages/parser/src/validate.mjs index 5de1419..09cd658 100644 --- a/packages/parser/src/validate.mjs +++ b/packages/parser/src/validate.mjs @@ -119,6 +119,10 @@ function validateOmitted(findings, omitted, headings) { omitted.forEach((entry, index) => { const path = `/omitted/${index}`; const section = typeof entry === 'string' ? entry : entry?.section; + if (typeof section !== 'string') { + add(findings, 'type', 'error', path, 'Omitted entries must be a section key or { section, reason }.'); + return; + } if (isObject(entry)) { unknownKeys(findings, entry, new Set(['section', 'reason']), path); if (entry.reason !== undefined) requireString(findings, entry.reason, `${path}/reason`); diff --git a/schemas/motion.schema.json b/schemas/motion.schema.json index cc03d54..fc84a19 100644 --- a/schemas/motion.schema.json +++ b/schemas/motion.schema.json @@ -12,18 +12,18 @@ "design": { "type": "string", "pattern": "^(?!/)(?![A-Za-z]:)[^\\s\\\\]*\\.md$", - "description": "Relative path to the DESIGN.md whose motion tokens this document references. Resolved from the MOTION.md directory; must not leave it." + "description": "Relative path to the DESIGN.md whose motion tokens this document references. Resolved from the MOTION.md directory; must not leave it. The pattern cannot express containment, so `..` escapes are rejected by the linter (design-path)." }, "omitted": { "type": "array", "items": { "anyOf": [ - { "$ref": "#/$defs/sectionKey" }, + { "type": "string", "minLength": 1 }, { "type": "object", "required": ["section"], "properties": { - "section": { "$ref": "#/$defs/sectionKey" }, + "section": { "type": "string", "minLength": 1 }, "reason": { "type": "string", "minLength": 1 } }, "additionalProperties": false @@ -70,9 +70,6 @@ "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, - "sectionKey": { - "enum": ["motion-thesis", "motion-principles", "hierarchy-and-choreography", "interruption", "reduced-motion", "performance", "provenance"] - }, "timingRef": { "type": "string", "pattern": "^\\{motion(\\.[a-z][a-z0-9-]*)+\\}$", diff --git a/tests/design.test.mjs b/tests/design.test.mjs index 9ef3d07..34fa64c 100644 --- a/tests/design.test.mjs +++ b/tests/design.test.mjs @@ -106,7 +106,7 @@ test('timing and literal timing fields together are two sources of truth', () => }); test('literal values equal to a design token produce an info finding', () => { - const result = lintMotion(doc({ track: { durationMs: 250, curve: 'standard' } }), files()); + const result = lintMotion(doc({ track: { durationMs: 250, curve: 'standard' } }), files({ 'DESIGN.md': DESIGN.replace('delay: 40ms', 'delay: 0ms') })); assert.deepEqual(rules(result), ['info:prefer-design-token']); }); @@ -202,3 +202,9 @@ test('inline and JSON motion tokens in DESIGN.md are read', () => { const nonPortable = '---\nname: Odd\ndescription: >\n folded text\nmotion:\n surface-enter:\n duration: 250ms\n---\n'; assert.equal(lintMotion(doc(), files({ 'DESIGN.md': nonPortable })).summary.errors, 0, 'other DESIGN.md YAML may be non-portable'); }); + +test('review hardening: delayed tokens are not suggested, malformed easing and omissions are rejected', () => { + assert.deepEqual(rules(lintMotion(doc({ track: { durationMs: 250, curve: 'standard' } }), files())), [], 'token delay 40ms would move the start'); + for (const value of ['constructor', 'cubic-bezier(, 0, , 1)', 'steps(2, constructor)']) assert.equal(parseTimingFunction(value), null, value); + assert.ok(rules(lintMotion(doc({ root: { omitted: [null] } }), files())).includes('error:type')); +}); From a9e5ff4a1812e7ad0394a6ba0db941e6735b2563 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 01:41:37 +0800 Subject: [PATCH 4/4] fix(parser): reject trailing-dot numbers and repeated motion keys Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XvGrrMtBAhmTdvPRgAnpxt --- packages/parser/src/design.mjs | 5 +++-- tests/design.test.mjs | 6 ++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/parser/src/design.mjs b/packages/parser/src/design.mjs index 867cd05..ab70a15 100644 --- a/packages/parser/src/design.mjs +++ b/packages/parser/src/design.mjs @@ -26,7 +26,7 @@ export function parseTimingFunction(input) { let match = value.match(/^cubic-bezier\(([^)]*)\)$/); if (match) { const parts = match[1].split(',').map((part) => part.trim()); - if (parts.some((part) => !/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/.test(part))) return null; + if (parts.some((part) => !/^[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?$/.test(part))) return null; const numbers = parts.map(Number); if (numbers.length !== 4 || numbers.some((n) => !Number.isFinite(n))) return null; if (numbers[0] < 0 || numbers[0] > 1 || numbers[2] < 0 || numbers[2] > 1) return null; @@ -92,7 +92,8 @@ export function loadDesignMotion(source, designPath) { } }).filter(Boolean); - if (motionSources.length > 1) add('design-motion', 'error', '/design', `${designPath} defines the motion key more than once.`); + const repeated = blocks.some((text) => text.replace(/\r\n?/g, '\n').split('\n').filter((line) => /^motion:/.test(line)).length > 1); + if (motionSources.length > 1 || repeated) add('design-motion', 'error', '/design', `${designPath} defines the motion key more than once.`); if (motionSources.length === 1) { let raw; try { diff --git a/tests/design.test.mjs b/tests/design.test.mjs index 34fa64c..d616fbd 100644 --- a/tests/design.test.mjs +++ b/tests/design.test.mjs @@ -208,3 +208,9 @@ test('review hardening: delayed tokens are not suggested, malformed easing and o for (const value of ['constructor', 'cubic-bezier(, 0, , 1)', 'steps(2, constructor)']) assert.equal(parseTimingFunction(value), null, value); assert.ok(rules(lintMotion(doc({ root: { omitted: [null] } }), files())).includes('error:type')); }); + +test('trailing-dot numbers and repeated motion keys in one block are rejected', () => { + assert.equal(parseTimingFunction('cubic-bezier(0, 1., 0, 1)'), null); + const repeated = '---\nname: Twice\nmotion:\n surface-enter:\n duration: 250ms\nmotion:\n other:\n duration: 1ms\n---\n'; + assert.ok(rules(lintMotion(doc(), files({ 'DESIGN.md': repeated }))).includes('error:design-motion')); +});