phation 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE.md +15 -0
  2. package/README.md +142 -2
  3. package/animate/core/feels.js +11 -0
  4. package/animate/core/recipes/index.js +84 -0
  5. package/animate/core/recipes/resolve.js +96 -0
  6. package/animate/detect.mjs +201 -0
  7. package/animate/index.mjs +266 -0
  8. package/animate/testset/eval.mjs +24 -0
  9. package/animate/testset/expected.json +23 -0
  10. package/animate/testset/holdout/commerce-delete-item-button.tsx +38 -0
  11. package/animate/testset/holdout/commerce-gallery.tsx +96 -0
  12. package/animate/testset/holdout/commerce-tile.tsx +50 -0
  13. package/animate/testset/holdout/shadcn-button-group-demo.tsx +114 -0
  14. package/animate/testset/holdout/shadcn-card-demo.tsx +63 -0
  15. package/animate/testset/holdout/shadcn-command-dialog.tsx +87 -0
  16. package/animate/testset/holdout/shadcn-drawer-dialog.tsx +90 -0
  17. package/animate/testset/holdout/shadcn-field-switch.tsx +24 -0
  18. package/animate/testset/holdout/shadcn-hover-card-demo.tsx +40 -0
  19. package/animate/testset/holdout/shadcn-mode-toggle.tsx +40 -0
  20. package/animate/testset/holdout/shadcn-toggle-group-demo.tsx +22 -0
  21. package/animate/testset/holdout.json +14 -0
  22. package/animate/testset/holdout2/chatbot-artifact-close-button.tsx +30 -0
  23. package/animate/testset/holdout2/chatbot-message-actions.tsx +211 -0
  24. package/animate/testset/holdout2/chatbot-sidebar-history-item.tsx +132 -0
  25. package/animate/testset/holdout2/chatbot-sidebar-toggle.tsx +35 -0
  26. package/animate/testset/holdout2/chatbot-suggested-actions.tsx +82 -0
  27. package/animate/testset/holdout2/chatbot-weather.tsx +434 -0
  28. package/animate/testset/holdout2/site-code-tabs.tsx +26 -0
  29. package/animate/testset/holdout2/site-copy-button.tsx +121 -0
  30. package/animate/testset/holdout2/site-github-link.tsx +38 -0
  31. package/animate/testset/holdout2/site-mobile-nav.tsx +220 -0
  32. package/animate/testset/holdout2/site-mode-switcher.tsx +97 -0
  33. package/animate/testset/holdout2/site-page-nav.tsx +15 -0
  34. package/animate/testset/holdout2.json +15 -0
  35. package/animate/testset/screens/commerce-cart-add-to-cart.tsx +94 -0
  36. package/animate/testset/screens/commerce-cart-modal.tsx +256 -0
  37. package/animate/testset/screens/commerce-navbar-mobile-menu.tsx +104 -0
  38. package/animate/testset/screens/commerce-product-variant-selector.tsx +106 -0
  39. package/animate/testset/screens/shadcn-accordion-demo.tsx +61 -0
  40. package/animate/testset/screens/shadcn-alert-dialog-demo.tsx +35 -0
  41. package/animate/testset/screens/shadcn-card-with-form.tsx +59 -0
  42. package/animate/testset/screens/shadcn-collapsible-demo.tsx +46 -0
  43. package/animate/testset/screens/shadcn-dialog-demo.tsx +50 -0
  44. package/animate/testset/screens/shadcn-drawer-demo.tsx +136 -0
  45. package/animate/testset/screens/shadcn-login-form.tsx +71 -0
  46. package/animate/testset/screens/shadcn-nav-main.tsx +73 -0
  47. package/animate/testset/screens/shadcn-section-cards.tsx +102 -0
  48. package/animate/testset/screens/shadcn-sheet-demo.tsx +47 -0
  49. package/animate/testset/screens/shadcn-switch-demo.tsx +11 -0
  50. package/animate/testset/screens/shadcn-tabs-demo.tsx +80 -0
  51. package/animate/testset/screens/taxonomy-main-nav.tsx +61 -0
  52. package/animate/testset/screens/taxonomy-post-item.tsx +42 -0
  53. package/animate/testset/screens/taxonomy-pricing.tsx +69 -0
  54. package/animate/testset/screens/taxonomy-user-account-nav.tsx +65 -0
  55. package/audit.mjs +456 -0
  56. package/bin/cli.mjs +113 -0
  57. package/bin/server.mjs +147 -0
  58. package/data/entries.json +864 -0
  59. package/data/standard/CORE.md +21 -0
  60. package/data/standard/STANDARD.md +185 -0
  61. package/data/standard/claude/CLAUDE.block.md +5 -0
  62. package/data/standard/claude/SKILL.md +26 -0
  63. package/data/standard/codex/AGENTS.block.md +25 -0
  64. package/data/standard/cursor/phation.mdc +27 -0
  65. package/data/standard/meta.json +4 -0
  66. package/data/standard/vscode/phation.instructions.md +25 -0
  67. package/data/standard/windsurf/phation.md +26 -0
  68. package/lib.mjs +214 -0
  69. package/package.json +41 -4
  70. package/share.mjs +72 -0
package/LICENSE.md ADDED
@@ -0,0 +1,15 @@
1
+ # Phation license
2
+
3
+ Copyright © 2026 Phation (https://phation.app). All rights reserved.
4
+
5
+ **Free use.** You may install and run this package to browse the library, read the specs and MOTION values, and install the
6
+ Phation Standard rules into your projects. The standard's text may be used in your own projects.
7
+
8
+ **Pro content.** Component source code, `phation add`, the audit and `animate` require an active Phation Pro license
9
+ (https://phation.app/pricing). Code you add with a valid license may be used in your own and your clients' products,
10
+ commercial or not. You may not resell, redistribute or publish the components as a library, kit or template, or share
11
+ your license key.
12
+
13
+ Full terms: https://phation.app/license and https://phation.app/terms.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # phation
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Phation as an MCP server and a CLI. The data is the library itself: 35 React + Motion entries with their spec, source and media.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ # Claude Code
9
+ claude mcp add phation -- npx -y phation mcp
10
+ # Cursor / Windsurf / VS Code: { "command": "npx", "args": ["-y", "phation", "mcp"] }
11
+ # No agent
12
+ npx phation search "price counter"
13
+ ```
14
+
15
+ ## Free and Pro
16
+
17
+ | Free | Pro (https://phation.app/pricing) |
18
+ |---|---|
19
+ | `list`, `search`, `show`: every motion's spec and MOTION values | `add`: the component source written into your project |
20
+ | `standard`, `init`: the Phation Standard rules for your agent | `get_motion` with `code: true` |
21
+ | | `audit`, `animate` |
22
+
23
+ Pro uses the license key from your Polar receipt email:
24
+
25
+ ```bash
26
+ npx phation login <license-key> # saved to ~/.config/phation/license.json
27
+ # or, for CI / an agent config: PHATION_KEY=<license-key>
28
+ npx phation whoami
29
+ ```
30
+
31
+ The package ships no component source. With a key, `add` fetches it from phation.app/api/source and the demo media from phation.app.
32
+
33
+ ## Tools (MCP)
34
+
35
+ | Tool | What it does |
36
+ |---|---|
37
+ | `search_motions` | Find entries by what they should do or feel like ("calm bottom sheet", "make the price feel alive") |
38
+ | `list_motions` | Every entry, optionally for one category |
39
+ | `get_motion` | Spec, `MOTION` values, dependencies and media of one entry (~200 tokens). `code: true` adds the full source |
40
+ | `add_motion` | Copy the component (and its images) into the project. Never overwrites unless `force`. `from` = a Studio share link: its tuned values are written into the file's `MOTION` object |
41
+ | `animate_ui` | Animate the user's own screens: names each part of a .jsx/.tsx file or folder (button, card, sheet, modal, tabs, toggle, list, number…), maps it to a recipe under one Feel. Plan by default; `apply: true` writes `<file>.animated.tsx` (`write: true` in place) with one `MOTION` object, `data-phation` hooks and `<MotionConfig reducedMotion="user">`, then lists the `audit_motion` actions. CLI: `phation animate <path> [--feel] [--only] [--role 12=button] [--apply] [--write]` |
42
+
43
+ The server also sends instructions: search → `add_motion` (the file is written to disk, never retyped) → edit only `MOTION`, copy and styles → `audit_motion`.
44
+
45
+ ## Token budget
46
+
47
+ Everything the model reads or writes is kept small on purpose. Measured over the real server (chars ÷ 3.6), one task "add a rolling price to a cart" with Codex:
48
+
49
+ | | Before (2026-11-09) | Now |
50
+ |---|---|---|
51
+ | Rules loaded every session (AGENTS.md block) | 3.3k | 0.8k (core only; full standard in `.phation/STANDARD.md`, read by section) |
52
+ | Server instructions + tool schemas | 1.9k | 1.5k |
53
+ | `search_motions` | 0.7k | 0.2k (one line + one sentence per hit, 4 hits) |
54
+ | `get_motion` | 1.8k (full source) | 0.2k (spec + `MOTION`; `code: true` for the source) |
55
+ | `get_standard` (no section) | 3.2k (everything) | 0.6k (core; a section or `all` on request) |
56
+ | `audit_motion` | report + raw JSON | report only (`json: true` adds it) |
57
+ | `animate_ui` plan (new, 2026-11-18) | n/a | ~16 tokens a part (13-part cart screen: ~210); apply returns the changed lines only |
58
+ | Code the model types | ~1.5k (whole file) | ~0.1k (`add_motion` writes the file; only `MOTION` is edited) |
59
+ | **Task total** (without the extra `get_standard` call) | **~9.8k** | **~2.8k** |
60
+
61
+ Re-measure after changing outputs: the script lives in the session scratchpad (`tok.mjs`, MCP client over stdio); keep these numbers in sync with the landing's "Why" section.
62
+
63
+ ## Animate: detection accuracy
64
+
65
+ `node animate/testset/eval.mjs [--holdout|--holdout2]` scores the code detector on hand-labelled real screens (shadcn examples and blocks, vercel/commerce, shadcn/taxonomy, vercel/ai-chatbot, the shadcn site). Honest reading (2026-11-18): the first run on a set the rules had never seen (`--holdout2`) scored **40.7 %**; after general fixes all three sets score 91–98 %, but they were all tuned on, so the real blind test is still Huy's own projects (ANIMATE_SPEC §08.3). Unclear parts are marked ⚠ for the agent to confirm with `roles`.
66
+
67
+ ## Use it locally (before it is on npm)
68
+
69
+ ```bash
70
+ cd motion-library/mcp && npm install
71
+
72
+ # Claude Code
73
+ claude mcp add phation -- node "/Users/pnhathuy09_1/PNH/AI Test/Portfolio 2025_Frammer/motion-library/mcp/bin/server.mjs"
74
+
75
+ # Cursor / Windsurf / VS Code: same command in the tool's MCP config
76
+ # { "command": "node", "args": ["<absolute path>/mcp/bin/server.mjs"] }
77
+
78
+ # CLI
79
+ node bin/cli.mjs search tactile quantity stepper
80
+ node bin/cli.mjs add digit-roll # run from the target project
81
+ ```
82
+
83
+ Once published, the landing-page snippets work as written: `npx -y phation mcp` for the server, `npx phation add <slug>` for the CLI.
84
+
85
+ Studio share links: tune an entry in the Studio, press Share, then `npx phation add --from "<link>"` (the slug comes from the link). Only the changed values travel in the link (`?digit=s420_32_1&stagger=60`; codec in `share.mjs`, shared with the site). The file gets a `// tuned in Phation Studio: <link>` line above `MOTION`.
86
+
87
+ ## Keep it in sync with the library
88
+
89
+ ```bash
90
+ cd motion-library && npm run export:mcp # rewrites mcp/data from src/transitions
91
+ ```
92
+
93
+ Run it after adding or editing an entry. The landing only features entries that pass `npm run qc`.
94
+
95
+ ## Phation Standard (rules for your agent)
96
+
97
+ The library gives your agent examples; the standard gives it rules. Install it once per project and every animation the agent writes uses the same curves, springs, durations and accessibility handling.
98
+
99
+ ```bash
100
+ npx phation init claude # .claude/skills/phation/SKILL.md + a pointer block in CLAUDE.md
101
+ npx phation init cursor # .cursor/rules/phation.mdc
102
+ npx phation init codex # a marked section in AGENTS.md (your own content is kept)
103
+ npx phation init windsurf # .windsurf/rules/phation.md
104
+ npx phation init vscode # .github/instructions/phation.instructions.md
105
+ npx phation init all
106
+ npx phation standard springs # print one section
107
+ ```
108
+
109
+ Re-running `init` updates only Phation's own files and the block between the `phation:start` / `phation:end` markers.
110
+
111
+ Over MCP the same standard is available as:
112
+ - the tools `get_standard` (whole text or one section) and `install_standard`;
113
+ - the resource `phation://standard`;
114
+ - the prompt `motion_review`.
115
+
116
+ Source: `skill/STANDARD.md` in the library repo. Rebuild with `npm run build:skill`.
117
+
118
+ ## Motion audit (find and fix janky motion)
119
+
120
+ `audit` opens a page in headless Chrome, performs your actions, records every element frame by frame and scores the motion against the standard. It needs Google Chrome installed (or `CHROME_PATH`).
121
+
122
+ ```bash
123
+ npx phation audit http://localhost:3000/checkout --do click:#pay
124
+ npx phation audit http://localhost:3000 --do hover:.card --do scroll:800 --root main --mobile
125
+ npx phation audit http://localhost:3000 --json # machine-readable
126
+ ```
127
+
128
+ Actions, in order: `click:<sel>` · `hover:<sel>` · `focus:<sel>` · `scroll:<px>` · `drag:<sel>:dx,dy` · `hold:<sel>:ms` · `key:<Key>` · `type:<sel>:text` · `wait:<ms>`. With no actions, it records the page load and hovers a few controls (it never clicks on its own).
129
+
130
+ It runs the page three times (timing, trace, and again with `prefers-reduced-motion: reduce`) and reports, with the time, the element and the fix:
131
+
132
+ | Blockers | Warnings |
133
+ |---|---|
134
+ | linear movement · no response to the action · text under 3:1 · heavy frame drops · page errors | hard cuts · one-frame jumps · overshoot > 22 % · too slow / too abrupt · width/height/top/left animation (inline or CSS) · reduced motion ignored · weak contrast · tiny text · small targets · upscaled images |
135
+
136
+ PASS = score ≥ 85 and no blockers. Exit code 0 (pass or review), 2 (fail), 1 (page could not be opened).
137
+
138
+ Over MCP it is the `audit_motion` tool: the agent writes the motion, audits the page, fixes what it reports and audits again.
139
+
140
+
141
+ ## Audit: skipping a deliberate bad example
142
+
143
+ Mark a subtree with `data-audit="skip"` and the audit neither traces its motion nor checks its text/targets. The landing's before/after card uses it on the "before" pane.
@@ -0,0 +1,11 @@
1
+ // GENERATED from src/feels.js by scripts/sync-animate.mjs. Edit the source, not this copy.
2
+ // Named motion personalities, shared by the Studio (applies them to every value of an entry) and the landing.
3
+ // spring = every spring; ease / out = curves (out for exit-like ones); time = multiplier for durations, delays, staggers.
4
+ export const FEELS = [
5
+ { id: 'calm', name: 'Calm', hint: 'Slow, soft, no bounce', spring: { stiffness: 120, damping: 26, mass: 1 }, ease: [0.22, 1, 0.36, 1], out: [0.4, 0, 0.6, 1], time: 1.4 },
6
+ { id: 'fluid', name: 'Fluid', hint: 'Smooth glide', spring: { stiffness: 170, damping: 22, mass: 1 }, ease: [0.16, 1, 0.3, 1], out: [0.7, 0, 0.84, 0], time: 1.1 },
7
+ { id: 'snappy', name: 'Snappy', hint: 'Quick and crisp', spring: { stiffness: 420, damping: 32, mass: 1 }, ease: [0.2, 1, 0.4, 1], out: [0.5, 0, 0.75, 0], time: 0.7 },
8
+ { id: 'playful', name: 'Playful', hint: 'Bounces past, settles', spring: { stiffness: 400, damping: 16, mass: 1 }, ease: [0.34, 1.56, 0.64, 1], out: [0.36, 0, 0.66, -0.56], time: 1 },
9
+ { id: 'heavy', name: 'Heavy', hint: 'Slow start, real weight', spring: { stiffness: 200, damping: 34, mass: 2.4 }, ease: [0.7, 0, 0.2, 1], out: [0.8, 0, 0.9, 0.3], time: 1.5 },
10
+ { id: 'mechanical', name: 'Mechanical', hint: 'Even, precise, exact', spring: { stiffness: 800, damping: 60, mass: 1 }, ease: [0.45, 0, 0.55, 1], out: [0.45, 0, 0.55, 1], time: 0.85 },
11
+ ]
@@ -0,0 +1,84 @@
1
+ // GENERATED from src/recipes/index.js by scripts/sync-animate.mjs. Edit the source, not this copy.
2
+ // Phation Animate recipes: patterns applied to the user's own elements (a library entry is a full component; a recipe is not).
3
+ // Spec: ANIMATE_SPEC.md §02. Values come from resolve.js + a Feel; nothing here is tuned per Feel.
4
+ //
5
+ // Fields
6
+ // roles roles Detect can return that this recipe fits (first match = recommended)
7
+ // trigger press | hover | toggle | select | open | enter | value
8
+ // spring a CORE.md spring role (resolve.js › SPRING_ROLES)
9
+ // states from → to, transform and opacity only. Symbolic values are filled by the surface:
10
+ // 'travel' = track width − knob width − 2 × inset · '100%' = the element's own height
11
+ // layout true = the size change is a layout animation (Motion `layout` / `layoutId`), never width/height
12
+ // exit how it leaves: a spring role, or the Feel's exit curve for durationMs (capped at 250 ms)
13
+ // stagger { kind: letters | items | groups, ms } — clamped to the Standard's range per Feel
14
+ // reduced under prefers-reduced-motion: 'none' (no motion) or 'fade' (≤ 150 ms opacity only)
15
+ // figma full | approx | none — how well Figma Smart Animate can play it
16
+ // figmaTrigger Figma prototype trigger type
17
+ // entry closest library entry slug, for "see it in Phation"
18
+
19
+ export const ROLES = ['button', 'icon-button', 'toggle', 'tabs', 'card', 'list', 'modal', 'sheet', 'accordion', 'nav-link', 'input', 'number', 'image', 'unknown']
20
+
21
+ export const RECIPES = {
22
+ press: {
23
+ id: 'press', name: 'Press', roles: ['button', 'icon-button', 'card'], trigger: 'press', spring: 'snap',
24
+ states: { from: { scale: 1 }, to: { scale: 0.96 } },
25
+ reduced: 'none', figma: 'full', figmaTrigger: 'ON_PRESS', entry: 'buy-morph',
26
+ },
27
+ 'hover-lift': {
28
+ id: 'hover-lift', name: 'Hover lift', roles: ['card', 'image', 'button'], trigger: 'hover', spring: 'soft',
29
+ states: { from: { y: 0, scale: 1 }, to: { y: -4, scale: 1.01 } },
30
+ reduced: 'none', figma: 'full', figmaTrigger: 'ON_HOVER', entry: 'work-card-hover',
31
+ },
32
+ 'toggle-knob': {
33
+ id: 'toggle-knob', name: 'Toggle', roles: ['toggle'], trigger: 'toggle', spring: 'snap',
34
+ states: { from: { x: 0 }, to: { x: 'travel' } },
35
+ reduced: 'fade', figma: 'full', figmaTrigger: 'ON_CLICK', entry: 'day-night',
36
+ },
37
+ 'tab-pill': {
38
+ id: 'tab-pill', name: 'Tab pill', roles: ['tabs'], trigger: 'select', spring: 'snap',
39
+ layout: true, // the pill is one element shared across tabs (layoutId); in Figma, one layer moved between variants
40
+ reduced: 'fade', figma: 'full', figmaTrigger: 'ON_CLICK', entry: 'model-picker',
41
+ },
42
+ 'sheet-open': {
43
+ id: 'sheet-open', name: 'Sheet', roles: ['sheet'], trigger: 'open', spring: 'soft',
44
+ states: { from: { y: '100%' }, to: { y: 0 } }, backdrop: { from: { opacity: 0 }, to: { opacity: 1 } },
45
+ exit: { durationMs: 220 },
46
+ reduced: 'fade', figma: 'full', figmaTrigger: 'ON_CLICK',
47
+ },
48
+ 'modal-open': {
49
+ id: 'modal-open', name: 'Modal', roles: ['modal'], trigger: 'open', spring: 'soft', // a large surface: soft, not pop
50
+ states: { from: { opacity: 0, scale: 0.94 }, to: { opacity: 1, scale: 1 } }, backdrop: { from: { opacity: 0 }, to: { opacity: 1 } },
51
+ exit: { durationMs: 180 },
52
+ reduced: 'fade', figma: 'full', figmaTrigger: 'ON_CLICK',
53
+ },
54
+ 'accordion-open': {
55
+ id: 'accordion-open', name: 'Accordion', roles: ['accordion'], trigger: 'open', spring: 'soft',
56
+ layout: true, content: { from: { opacity: 0, y: -6 }, to: { opacity: 1, y: 0 } },
57
+ exit: { durationMs: 160 },
58
+ reduced: 'fade', figma: 'approx', figmaTrigger: 'ON_CLICK', entry: 'capabilities-accordion',
59
+ },
60
+ 'list-enter': {
61
+ id: 'list-enter', name: 'List enter', roles: ['list'], trigger: 'enter', spring: 'soft',
62
+ states: { from: { opacity: 0, y: 20 }, to: { opacity: 1, y: 0 } }, // fade + 18–24 px rise (Standard: never pop in)
63
+ stagger: { kind: 'items', ms: 50 },
64
+ reduced: 'fade', figma: 'approx', figmaTrigger: 'AFTER_TIMEOUT', // Figma: no real stagger, one shared transition
65
+ },
66
+ 'number-roll': {
67
+ id: 'number-roll', name: 'Number roll', roles: ['number'], trigger: 'value', spring: 'snap',
68
+ states: { from: { y: '100%', opacity: 0 }, to: { y: 0, opacity: 1 } }, // per digit; the old digit leaves to −100%
69
+ stagger: { kind: 'letters', ms: 30 },
70
+ reduced: 'fade', figma: 'none', entry: 'digit-roll',
71
+ },
72
+ 'nav-roll': {
73
+ id: 'nav-roll', name: 'Letter roll', roles: ['nav-link'], trigger: 'hover', spring: 'snap',
74
+ states: { from: { y: 0 }, to: { y: '-100%' } }, // per letter, a copy rolls in from below
75
+ stagger: { kind: 'letters', ms: 25 },
76
+ reduced: 'none', figma: 'none', entry: 'nav-letter-roll',
77
+ },
78
+ }
79
+
80
+ /** Recipes for a role, best first. */
81
+ export const recipesFor = role => Object.values(RECIPES).filter(r => r.roles.includes(role))
82
+ .sort((a, b) => a.roles.indexOf(role) - b.roles.indexOf(role))
83
+
84
+ export { resolve, figmaText, springFor, settleMs, DEFAULT_FEEL } from './resolve.js'
@@ -0,0 +1,96 @@
1
+ // GENERATED from src/recipes/resolve.js by scripts/sync-animate.mjs. Edit the source, not this copy.
2
+ // Phation Animate: turns a recipe + a Feel into exact motion values.
3
+ // One function shared by every surface (animate_ui, the Figma plugin, the site's previews), so a Feel looks the same everywhere.
4
+ //
5
+ // import { resolve } from './resolve.js'
6
+ // resolve(RECIPES.press, 'snappy') → { spring, settleMs, ease, durationMs, staggerMs, exit, figma }
7
+ //
8
+ // How a Feel bends a spring role (roles and base values from skill/CORE.md):
9
+ // tempo — the Feel's `time`, relative to Fluid's, scales the role's natural period: stiffness = k / t² (mass kept).
10
+ // Fluid (the default) gives back the CORE.md values exactly. A Feel's own mass (Heavy 2.4) is not carried over.
11
+ // bounce — the role's damping ratio ζ shifts by the Feel's distance from Fluid (the neutral Feel, the default).
12
+ // ζ is clamped to [0.45, 1.2]: 0.45 ≈ 20 % overshoot, under the Standard's 22 % cap.
13
+ // Durations and staggers scale by `time` and are clamped to the Standard's ranges. Exits use the Feel's `out` curve, ≤ 250 ms.
14
+
15
+ import { FEELS } from '../feels.js'
16
+
17
+ export const DEFAULT_FEEL = 'fluid'
18
+
19
+ // CORE.md springs (k / c / m). `bounce` (celebration) is left out on purpose: its overshoot is over the cap for UI recipes.
20
+ export const SPRING_ROLES = {
21
+ snap: { stiffness: 420, damping: 32, mass: 1 }, // controls, pills, rolls
22
+ pop: { stiffness: 400, damping: 20, mass: 1 }, // small things appearing
23
+ soft: { stiffness: 170, damping: 22, mass: 1 }, // large surfaces
24
+ follow: { stiffness: 420, damping: 34, mass: 0.6 }, // pointer-following
25
+ }
26
+
27
+ const ZETA_MIN = 0.45, ZETA_MAX = 1.2
28
+ const EXIT_MAX_MS = 250
29
+ const STAGGER = { letters: [25, 60], items: [35, 80], groups: [100, 300] }
30
+ const STAGGER_TOTAL_MAX = 400
31
+
32
+ const clamp = (v, a, b) => Math.min(b, Math.max(a, v))
33
+ const r = (v, n = 0) => +v.toFixed(n)
34
+ export const zetaOf = s => s.damping / (2 * Math.sqrt(s.stiffness * (s.mass ?? 1)))
35
+ /** Peak overshoot of an underdamped spring released from rest, as a fraction (0.2 = 20 %). */
36
+ export const overshootOf = s => { const z = zetaOf(s); return z >= 1 ? 0 : Math.exp((-Math.PI * z) / Math.sqrt(1 - z * z)) }
37
+
38
+ /** Time for a spring to settle within 2 % of its target, in ms. Used as Figma's `duration` and as a fallback length. */
39
+ export function settleMs(s) {
40
+ const m = s.mass ?? 1, w = Math.sqrt(s.stiffness / m), z = zetaOf(s)
41
+ const rate = z < 1 ? z * w : w * (z - Math.sqrt(z * z - 1)) // slowest decaying mode
42
+ return Math.round((Math.log(50) / rate) * 1000)
43
+ }
44
+
45
+ export const feelOf = id => FEELS.find(f => f.id === id) ?? FEELS.find(f => f.id === DEFAULT_FEEL)
46
+ const NEUTRAL_ZETA = zetaOf(feelOf(DEFAULT_FEEL).spring)
47
+ const NEUTRAL_TIME = feelOf(DEFAULT_FEEL).time
48
+
49
+ /** A spring role under a Feel. */
50
+ export function springFor(role, feelId = DEFAULT_FEEL) {
51
+ const base = SPRING_ROLES[role]
52
+ if (!base) throw new Error(`Unknown spring role "${role}". Use one of: ${Object.keys(SPRING_ROLES).join(', ')}`)
53
+ const f = feelOf(feelId)
54
+ const t = f.time / NEUTRAL_TIME // Fluid gives back the CORE values exactly
55
+ const m = base.mass, stiffness = r(base.stiffness / (t * t))
56
+ const z = clamp(zetaOf(base) + (zetaOf(f.spring) - NEUTRAL_ZETA), ZETA_MIN, ZETA_MAX)
57
+ return { stiffness, damping: r(z * 2 * Math.sqrt(stiffness * m), 1), mass: m }
58
+ }
59
+
60
+ /** Every value a surface needs to play or write one recipe under one Feel. */
61
+ export function resolve(recipe, feelId = DEFAULT_FEEL) {
62
+ const f = feelOf(feelId)
63
+ const spring = springFor(recipe.spring, f.id)
64
+ const out = { recipe: recipe.id, feel: f.id, spring, settleMs: settleMs(spring), ease: f.ease }
65
+
66
+ if (recipe.durationMs) out.durationMs = Math.round(recipe.durationMs * f.time)
67
+ if (recipe.stagger) {
68
+ const [lo, hi] = STAGGER[recipe.stagger.kind]
69
+ const each = clamp(Math.round(recipe.stagger.ms * f.time), lo, hi)
70
+ // keep the whole wave ≤ 400 ms: past that many items, the rest arrive together
71
+ out.staggerMs = each
72
+ out.staggerMaxItems = Math.floor(STAGGER_TOTAL_MAX / each) + 1
73
+ }
74
+ if (recipe.exit) {
75
+ const exitSpring = recipe.exit.spring ? springFor(recipe.exit.spring, f.id) : null
76
+ out.exit = exitSpring
77
+ ? { spring: exitSpring, settleMs: settleMs(exitSpring) }
78
+ : { ease: f.out, durationMs: Math.min(EXIT_MAX_MS, Math.round(recipe.exit.durationMs * f.time)) }
79
+ }
80
+ // Figma Smart Animate: custom spring + a duration (settle time). `approx` / `none` are reported, not hidden.
81
+ out.figma = recipe.figma === 'none' ? null : {
82
+ support: recipe.figma,
83
+ trigger: recipe.figmaTrigger,
84
+ // Figma's runtime rejects initialVelocity ("Unrecognized key", checked in a real file 2026-11-18) although the typings list it
85
+ easing: { type: 'CUSTOM_SPRING', easingFunctionSpring: { mass: spring.mass, stiffness: spring.stiffness, damping: spring.damping } },
86
+ durationMs: out.settleMs,
87
+ }
88
+ return out
89
+ }
90
+
91
+ /** Short text for "Copy values" / sticky notes, e.g. "Smart Animate · Spring · mass 1 · stiffness 420 · damping 32". */
92
+ export function figmaText(resolved) {
93
+ if (!resolved.figma) return `${resolved.recipe}: web only`
94
+ const s = resolved.spring
95
+ return `Smart Animate · Spring · mass ${s.mass} · stiffness ${s.stiffness} · damping ${s.damping} · ≈ ${resolved.settleMs} ms`
96
+ }
@@ -0,0 +1,201 @@
1
+ // Phation Animate — detection for code (ANIMATE_SPEC.md §03). Parses JSX/TSX with @babel/parser (no regex on code) and
2
+ // returns the parts of a screen with a role, a confidence and the signal that decided it.
3
+ //
4
+ // Confidence = strongest signal: semantic 1.0 · library 0.9 · state 0.7 · name 0.5. Below 0.6 the plan says "check".
5
+ // Every part keeps the AST nodes apply.mjs needs to edit the file in place (start/end offsets, never re-printing).
6
+ import { parse } from '@babel/parser'
7
+ import { ROLES } from './core/recipes/index.js'
8
+
9
+ const LIB_SOURCE = /(^|\/)(components\/ui|ui)(\/|$)|@radix-ui|@headlessui|@mui|@chakra-ui|@nextui-org|@heroui|@ark-ui|@base-ui|vaul|react-aria/
10
+
11
+ // component names that libraries (shadcn/Radix/Headless/MUI/Chakra/vaul) use, by role
12
+ const LIB_NAMES = [
13
+ ['modal', /^(Dialog|AlertDialog)\.?(Content|Panel)$|^(DialogContent|AlertDialogContent|DialogPanel|ModalContent|CommandDialog)$/],
14
+ ['sheet', /^(Sheet|Drawer)\.?Content$|^(SheetContent|DrawerContent|BottomSheet)$/],
15
+ ['toggle', /^(Switch|Switch\.Root|SwitchRoot|Toggle|Toggle\.Root|ToggleGroupItem|ToggleGroup\.Item)$/],
16
+ ['tabs', /^(Tabs\.List|TabsList|TabList|Tab\.List)$/],
17
+ ['accordion', /^(Accordion\.Content|AccordionContent|Collapsible\.Content|CollapsibleContent|Disclosure\.Panel|DisclosurePanel|AccordionDetails)$/],
18
+ ['icon-button', /^IconButton$/],
19
+ ['button', /Button$/],
20
+ ['card', /^Card$/],
21
+ ['nav-link', /^(NavigationMenu\.Link|NavigationMenuLink|NavLink)$/],
22
+ ['input', /^(\w*Input|Textarea|SelectTrigger|Slider|Checkbox|RadioGroup)$/],
23
+ ]
24
+ // weaker: names an author picked (layer names in Figma, component names here)
25
+ const NAME_HINTS = [
26
+ ['sheet', /sheet|drawer|bottom.?bar/i],
27
+ ['modal', /modal|dialog|popup|lightbox/i],
28
+ ['toggle', /toggle|switch/i],
29
+ ['tabs', /tabs|segmented|tab.?bar/i],
30
+ ['accordion', /accordion|collapse|faq.?item|disclosure/i],
31
+ ['number', /price|total|amount|counter|balance|subtotal/i],
32
+ ['nav-link', /nav.?link|menu.?link/i],
33
+ ['icon-button', /icon.?button|icon.?btn|(delete|remove|close|dismiss|edit\w*quantity|increment|decrement|plus|minus).*(button|btn)/i],
34
+ ['button', /button|btn|cta/i],
35
+ ['card', /card|tile/i],
36
+ ]
37
+ const ICON_SOURCE = /lucide|heroicons|react-icons|@tabler\/icons|@radix-ui\/react-icons|phosphor|iconoir|iconsax|@mui\/icons/
38
+ const isIconLike = (k, imports) => { const n = jsxName(k.openingElement.name), r = n.split('.')[0]; return n === 'svg' || /Icon$|Avatar|Logo|^Icons\./.test(n) || ICON_SOURCE.test(imports[r] || '') || /sr-only/.test(attrStr(k, 'className') || '') }
39
+ const SUB_PART = /[a-z](Content|Header|Footer|Title|Description|Trigger|Close|Overlay|Portal|Provider|Root|Group|Item|Label|Icon|Wrapper|Container|Body|Action|Cancel|Thumb|Indicator|Viewport)$/
40
+ const LIB_ROOTS = /^(Sheet|Dialog|AlertDialog|Drawer|Tabs|Accordion|Collapsible|Popover|DropdownMenu|NavigationMenu|Tooltip|HoverCard)$/
41
+ const NUMBERISH = /(^|[^a-z])(price|total|subtotal|amount|count|qty|quantity|balance|score|cost|sum)([^a-z]|$)/i
42
+ const FORMAT_CALL = /^(toFixed|toLocaleString|formatPrice|formatCurrency|formatMoney|formatNumber|currency)$/ // not format(): date-fns
43
+ const UNIT_TEXT = /^\s*(°[CF]?|%|\$|€|£|¥|₫|k|K|ms|s|kg|km|mi|pts?|x|×)/
44
+ const UNIT_BEFORE = /(\$|€|£|¥|₫)\s*$/
45
+
46
+ export function parseCode(source) {
47
+ return parse(source, { sourceType: 'module', plugins: ['jsx', 'typescript', 'decorators-legacy', 'importAttributes'], errorRecovery: true, ranges: false })
48
+ }
49
+
50
+ export const jsxName = n => !n ? '' : n.type === 'JSXIdentifier' ? n.name : n.type === 'JSXMemberExpression' ? `${jsxName(n.object)}.${jsxName(n.property)}` : n.type === 'JSXNamespacedName' ? `${n.namespace.name}:${n.name.name}` : ''
51
+ const attr = (el, name) => el.openingElement.attributes.find(a => a.type === 'JSXAttribute' && a.name?.name === name)
52
+ const attrStr = (el, name) => { const a = attr(el, name); return a?.value?.type === 'StringLiteral' ? a.value.value : a?.value?.expression?.type === 'StringLiteral' ? a.value.expression.value : null }
53
+ // the className as written (string or expression), for class-based signals
54
+ const classCode = (el, src) => { const a = attr(el, 'className'); return !a?.value ? '' : a.value.type === 'StringLiteral' ? a.value.value : src.slice(a.value.start, a.value.end) }
55
+ const isIntrinsic = name => /^[a-z]/.test(name) && !name.includes('.')
56
+ const lineOf = (src, pos) => src.slice(0, pos).split('\n').length
57
+
58
+ function walk(node, visit, parent = null, stack = []) {
59
+ if (!node || typeof node.type !== 'string') return
60
+ visit(node, parent, stack)
61
+ stack.push(node)
62
+ for (const k in node) {
63
+ if (k.startsWith('__') || k === 'loc' || k === 'start' || k === 'end' || k === 'extra' || k === 'leadingComments' || k === 'trailingComments' || k === 'innerComments') continue
64
+ const v = node[k]
65
+ if (Array.isArray(v)) { for (const c of v) if (c && typeof c.type === 'string') walk(c, visit, node, stack) }
66
+ else if (v && typeof v.type === 'string') walk(v, visit, node, stack)
67
+ }
68
+ stack.pop()
69
+ }
70
+
71
+ /** Map of local name → import source, e.g. { Button: '@/components/ui/button', motion: 'motion/react' }. */
72
+ function importsOf(ast) {
73
+ const m = {}
74
+ for (const s of ast.program.body) if (s.type === 'ImportDeclaration') for (const sp of s.specifiers) m[sp.local.name] = s.source.value
75
+ return m
76
+ }
77
+
78
+ /**
79
+ * detect(source, { file }) → { parts, imports, ast }
80
+ * part: { id, role, confidence, signal, name, line, el, kind: 'element' | 'expr', expr?, list? }
81
+ */
82
+ export function detect(source, { file = 'file.tsx' } = {}) {
83
+ const ast = parseCode(source), imports = importsOf(ast), importsAll = imports
84
+ const found = new Map() // element node → [{ role, confidence, signal }]
85
+ const exprParts = []
86
+ const add = (el, role, confidence, signal) => {
87
+ const list = found.get(el) || []
88
+ const same = list.find(x => x.role === role)
89
+ if (same) { if (confidence > same.confidence) Object.assign(same, { confidence, signal }); return }
90
+ list.push({ role, confidence, signal }); found.set(el, list)
91
+ }
92
+
93
+ // numeric state: const [goal, setGoal] = useState(350) → {goal} is a value that changes
94
+ const numericState = new Set()
95
+ walk(ast.program, node => {
96
+ if (node.type === 'VariableDeclarator' && node.id?.type === 'ArrayPattern' && node.init?.type === 'CallExpression' && /useState$/.test(source.slice(node.init.callee.start, node.init.callee.end))) {
97
+ const a0 = node.init.arguments[0]
98
+ if (a0?.type === 'NumericLiteral' && node.id.elements[0]?.type === 'Identifier') numericState.add(node.id.elements[0].name)
99
+ }
100
+ })
101
+ walk(ast.program, (node, parent, stack) => {
102
+ if (node.type === 'JSXElement') {
103
+ const name = jsxName(node.openingElement.name)
104
+ if (!name || name.startsWith('motion.') || /^Motion[A-Z]/.test(name)) return // already animated
105
+ if (stack.some(s => s.type === 'JSXElement' && jsxName(s.openingElement.name) === 'svg')) return
106
+ const root = name.split('.')[0], fromLib = LIB_SOURCE.test(imports[root] || '')
107
+ const role = attrStr(node, 'role')
108
+ // 1 · semantic
109
+ if (name === 'button') add(node, 'button', 1, '<button>') // icon-only is decided below, from the children
110
+ if (role === 'switch') add(node, 'toggle', 1, 'role="switch"')
111
+ if (role === 'tablist') add(node, 'tabs', 1, 'role="tablist"')
112
+ if (role === 'dialog' || role === 'alertdialog' || name === 'dialog') add(node, 'modal', 1, role ? `role="${role}"` : '<dialog>')
113
+ if (name === 'details') add(node, 'accordion', 1, '<details>')
114
+ if (['input', 'textarea', 'select'].includes(name)) add(node, 'input', 1, `<${name}>`)
115
+ if (/^(a|Link|NavLink)$/.test(name) && stack.some(s => s.type === 'JSXElement' && jsxName(s.openingElement.name) === 'nav')) add(node, 'nav-link', 0.9, `<${name}> in <nav>`)
116
+ const clsCode = classCode(node, source)
117
+ if (/\bbuttonVariants\(/.test(clsCode)) add(node, 'button', 0.9, 'buttonVariants()')
118
+ // 2 · library
119
+ // a library trigger without asChild renders its own <button> (AccordionTrigger, DropdownMenuTrigger…)
120
+ if (fromLib && /Trigger$/.test(name) && !/SubTrigger$/.test(name) && !/^(Select|Tabs)/.test(name) && !attr(node, 'asChild')) add(node, 'button', 0.9, `${name} renders a button`)
121
+ for (const [r, re] of LIB_NAMES) if (re.test(name)) {
122
+ if (r === 'button' && !fromLib && name !== 'Button') continue // a project's own *Button: let its name decide (DeleteItemButton → icon-button)
123
+ // a dialog panel pinned to a screen edge at full height (or full width at the bottom) is a sheet / drawer
124
+ const edge = r === 'modal' && /\bfixed\b/.test(clsCode) && ((/\b(left|right)-0\b/.test(clsCode) && /\btop-0\b/.test(clsCode) && /\bbottom-0\b/.test(clsCode)) || (/\bbottom-0\b/.test(clsCode) && /\binset-x-0\b|\bleft-0\b.*\bright-0\b/.test(clsCode) && !/\btop-0\b/.test(clsCode)))
125
+ add(node, edge ? 'sheet' : r, fromLib ? 0.9 : 0.6, (edge ? 'edge-pinned ' : '') + (fromLib ? `${name} (${imports[root]})` : name)); break
126
+ }
127
+ // 3 · state
128
+ if (!isIntrinsic(name) || name !== 'input') {
129
+ if ((attr(node, 'checked') || attr(node, 'aria-checked') || attr(node, 'onCheckedChange')) && !['input'].includes(name) && !found.get(node)?.some(x => x.role === 'toggle')) add(node, 'toggle', 0.7, 'checked prop')
130
+ }
131
+ // 4 · names: component name, then className words
132
+ // library roots (Sheet, Dialog, Tabs…) render no element of their own, and sub-parts (CardContent, SheetTrigger…) are
133
+ // not the moving surface: names alone never tag them
134
+ const subPart = SUB_PART.test(name) || (fromLib && LIB_ROOTS.test(name))
135
+ const inButton = stack.some(s => s.type === 'JSXElement' && found.get(s)?.some(x => /button/.test(x.role)))
136
+ if (!found.get(node) && !subPart && !inButton && !ICON_SOURCE.test(imports[root] || '') && !/Icon$/.test(name) && !(fromLib && !isIntrinsic(name))) {
137
+ const cls = attrStr(node, 'className') || ''
138
+ for (const [r, re] of NAME_HINTS) {
139
+ if (!isIntrinsic(name) && re.test(name)) { add(node, r, 0.5, `name ${name}`); break }
140
+ if (r === 'card' && cls.split(/\s+/).some(t => /^(card|[\w-]+-card|card-[\w-]+)$/i.test(t))) { add(node, 'card', 0.5, 'class "card"'); break }
141
+ }
142
+ }
143
+ }
144
+ if (node.type === 'JSXElement' && !found.get(node)) {
145
+ const name = jsxName(node.openingElement.name)
146
+ if (name && !name.startsWith('motion.') && !/^Motion[A-Z]/.test(name)) {
147
+ // 5 · behaviour: something clickable that nothing above named is a press target
148
+ // (not library parts such as menu items, and not links: an href navigates, the handler only closes a menu)
149
+ const libPart = LIB_SOURCE.test(imports[name.split('.')[0]] || '')
150
+ if (['onClick', 'formAction', 'onSelect', 'onPress'].some(h => attr(node, h)) && !libPart && !attr(node, 'href') && !['input', 'form', 'label', 'div', 'li', 'tr', 'td', 'span', 'img', 'a'].includes(name)) add(node, 'button', 0.5, 'click handler')
151
+ // a component's root surface with rounded corners and depth (shadow or border) reads as a card
152
+ else if (parent?.type === 'ReturnStatement' || (parent?.type === 'ParenthesizedExpression' && stack.at(-2)?.type === 'ReturnStatement') || parent?.type === 'ArrowFunctionExpression') {
153
+ const c = classCode(node, source)
154
+ if (/\brounded-(lg|xl|2xl|3xl)\b/.test(c) && /\b(shadow(-\w+)?|border)\b/.test(c) && /\bp-\d/.test(c)) add(node, 'card', 0.5, 'root surface: rounded + depth')
155
+ }
156
+ }
157
+ }
158
+ // list: xs.map(x => <Item/>) → the item element
159
+ if ((node.type === 'CallExpression' || node.type === 'OptionalCallExpression') && node.callee?.property?.name === 'map' && (parent?.type === 'JSXExpressionContainer' || stack.some(s => s.type === 'JSXExpressionContainer'))) {
160
+ const fn = node.arguments[0]
161
+ if (fn && /FunctionExpression|ArrowFunctionExpression/.test(fn.type)) {
162
+ let item = fn.body
163
+ if (item.type === 'BlockStatement') item = item.body.find(s => s.type === 'ReturnStatement')?.argument
164
+ while (item?.type === 'ParenthesizedExpression') item = item.expression
165
+ if (item?.type === 'JSXFragment') item = item.children.find(c => c.type === 'JSXElement')
166
+ if (item?.type === 'JSXElement' && !/^motion\.|^Motion[A-Z]/.test(jsxName(item.openingElement.name))) { add(item, 'list', 0.7, '.map() item'); item.__phationMap = fn }
167
+ }
168
+ }
169
+ // number: {total} / {price.toFixed(2)} / {format(amount)} as the content of an element
170
+ if (node.type === 'JSXExpressionContainer' && parent?.type === 'JSXElement' && node.expression.type !== 'JSXEmptyExpression') {
171
+ const code = source.slice(node.expression.start, node.expression.end)
172
+ const call = node.expression.type === 'CallExpression' ? (node.expression.callee.property?.name || node.expression.callee.name) : null
173
+ const stateNum = node.expression.type === 'Identifier' && numericState.has(node.expression.name)
174
+ const sib = parent.children, at = sib.indexOf(node), next = sib[at + 1], prev = sib[at - 1]
175
+ const unit = (next?.type === 'JSXText' && UNIT_TEXT.test(next.value)) || (prev?.type === 'JSXText' && UNIT_BEFORE.test(prev.value))
176
+ if (code.length < 80 && !/=>|<|\.map\(/.test(code) && (stateNum || unit || NUMBERISH.test(code) || (call && FORMAT_CALL.test(call)))) {
177
+ exprParts.push({ role: 'number', confidence: 0.7, signal: stateNum ? `{${code}} numeric state` : unit ? `{${code.length > 20 ? code.slice(0, 18) + '…' : code}} + unit` : `{${code.length > 28 ? code.slice(0, 26) + '…' : code}}`, el: parent, expr: node })
178
+ }
179
+ }
180
+ })
181
+
182
+ // a button that is only an icon (size="icon", or an icon + sr-only label) is an icon-button
183
+ for (const [el, roles] of found) for (const r of roles) if (r.role === 'button') {
184
+ const size = attrStr(el, 'size') || ''
185
+ const text = el.children.some(c => c.type === 'JSXText' && c.value.trim()) || el.children.some(c => c.type === 'JSXExpressionContainer' && c.expression.type !== 'JSXEmptyExpression')
186
+ const labelled = el.children.some(c => c.type === 'JSXElement' && /sr-only/.test(attrStr(c, 'className') || ''))
187
+ const kids = el.children.filter(c => c.type === 'JSXElement')
188
+ const iconLike = k => isIconLike(k, imports)
189
+ if (attr(el, 'asChild')) continue // the child carries the content
190
+ // aria-label + no text = the visible content is a glyph, unless that content is a picture (a thumbnail button)
191
+ const picture = kids.some(k => /^(img|picture|video)$|Image|Img|Photo|Thumbnail|Picture/.test(jsxName(k.openingElement.name)))
192
+ if (/^icon/.test(size) || (!text && kids.length && (kids.every(iconLike) || (attr(el, 'aria-label') && !picture)))) { r.role = 'icon-button'; r.signal += ' · icon only' }
193
+ }
194
+ const parts = []
195
+ for (const [el, roles] of found) for (const r of roles) parts.push({ ...r, el, kind: 'element', name: jsxName(el.openingElement.name), line: lineOf(source, el.start) })
196
+ for (const p of exprParts) parts.push({ ...p, kind: 'expr', name: jsxName(p.el.openingElement.name), line: lineOf(source, p.expr.start) })
197
+ // a library content element covers its own role; drop weaker duplicates on the same node, keep the strongest per element+trigger
198
+ parts.sort((a, b) => a.line - b.line || b.confidence - a.confidence)
199
+ parts.forEach((p, i) => { p.id = i + 1; if (!ROLES.includes(p.role)) p.role = 'unknown' })
200
+ return { parts, imports, ast, file }
201
+ }