phation 0.0.0-stage → 0.1.1

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.
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,111 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/pnhathuy09/phation/main/media/before-after.gif" alt="The same prompt, run by a default agent (41/100) and by an agent with Phation (100/100)" width="860">
3
+ </p>
2
4
 
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.
5
+ <h1 align="center">Phation</h1>
6
+ <p align="center"><b>Give your AI taste in motion.</b><br>
7
+ Ready-made interactions and motion rules for your coding agent, so the motion it writes is right the first time, not the fifth.</p>
8
+ <p align="center"><a href="https://phation.app">phation.app</a> · <a href="https://github.com/pnhathuy09/phation">GitHub</a> · <a href="#mcp-tools">MCP tools</a> · <a href="#the-phation-standard">Standard</a></p>
9
+
10
+ <p align="center"><a href="https://glama.ai/mcp/servers/pnhathuy09/phation"><img src="https://glama.ai/mcp/servers/pnhathuy09/phation/badges/score.svg" alt="pnhathuy09/phation MCP server"></a></p>
11
+
12
+ ---
13
+
14
+ Ask an agent to "animate the add-to-cart flow" and you usually get hard cuts, linear easing, numbers that swap instead of roll, and nothing for reduced motion. Phation gives the agent two things:
15
+
16
+ - **The Phation Standard**: a short set of motion rules (springs, curves, durations, stagger, accessibility) that the agent loads in every session.
17
+ - **A library of real interactions** it can search, read and drop into your project: React + Motion components with their exact spring and timing values.
18
+
19
+ It runs as an **MCP server** for Claude Code, Cursor, Codex, Windsurf and VS Code, and as a **CLI**.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ # Claude Code
25
+ claude mcp add phation -- npx -y phation mcp
26
+
27
+ # Cursor · Windsurf · VS Code (MCP config)
28
+ { "command": "npx", "args": ["-y", "phation", "mcp"] }
29
+
30
+ # Without an agent
31
+ npx phation search "price counter"
32
+ ```
33
+
34
+ Node 18 or newer.
35
+
36
+ ## The Phation Standard
37
+
38
+ Install the rules once per project. Every animation your agent writes then uses the same curves, springs, durations and accessibility handling.
39
+
40
+ ```bash
41
+ npx phation init claude # .claude/skills/phation/SKILL.md + a pointer block in CLAUDE.md
42
+ npx phation init cursor # .cursor/rules/phation.mdc
43
+ npx phation init codex # a marked section in AGENTS.md (your own content is kept)
44
+ npx phation init windsurf # .windsurf/rules/phation.md
45
+ npx phation init vscode # .github/instructions/phation.instructions.md
46
+ npx phation init all
47
+
48
+ npx phation standard springs # print one section
49
+ ```
50
+
51
+ Re-running `init` updates only Phation's own files and the block between the `phation:start` / `phation:end` markers. The rules are in [`data/standard`](https://github.com/pnhathuy09/phation/tree/main/data/standard).
52
+
53
+ A taste of what is inside: one spring family for the whole product.
54
+
55
+ | Spring | Stiffness · damping | Use for |
56
+ |---|---|---|
57
+ | snap | 420 · 32 | Controls |
58
+ | pop | 400 · 20 | Things appearing |
59
+ | soft | 170 · 22 | Surfaces |
60
+ | follow | 420 · 34 | The pointer |
61
+ | bounce | 160 · 14 | Celebrations |
62
+
63
+ ## MCP tools
64
+
65
+ | Tool | What it does |
66
+ |---|---|
67
+ | `get_standard` | The Phation Standard: the core rules, or one section |
68
+ | `install_standard` | Writes the rules into the project for the agent you use |
69
+ | `search_motions` | Finds interactions by what they should do or feel like ("calm bottom sheet", "make the price feel alive") |
70
+ | `list_motions` | Every interaction, optionally for one category |
71
+ | `get_motion` | Spec, `MOTION` values, dependencies and media of one interaction (about 200 tokens) |
72
+ | `add_motion` | Writes the component into your project · Pro |
73
+ | `animate_ui` | Animates your own screens: maps each part of a .jsx/.tsx file to a motion recipe under one Feel · Pro |
74
+ | `audit_motion` | Records a page frame by frame and scores its motion: layout jumps, low contrast, missing reduced motion · Pro |
75
+
76
+ Outputs are kept small on purpose: a typical "add a rolling price to the cart" task costs about 2.8k tokens end to end.
77
+
78
+ ## CLI
79
+
80
+ ```bash
81
+ npx phation list [category] # browse
82
+ npx phation search <words> # find by intent
83
+ npx phation show <slug> # spec + MOTION values
84
+ npx phation init <agent> # install the Standard
85
+ npx phation add <slug> # Pro: write the component into src/motion
86
+ npx phation add --from "<studio link>" # Pro: with the values you tuned in the Studio
87
+ npx phation audit <url> [--do click:#buy] # Pro: score the motion of a page
88
+ npx phation animate <file|folder> # Pro: plan motion for your own screens
89
+ ```
90
+
91
+ ## Free and Pro
92
+
93
+ | Free | Pro |
94
+ |---|---|
95
+ | The Phation Standard and `init` for every agent | `add`: component source written into your project |
96
+ | `list`, `search`, `show`: specs and `MOTION` values | `audit` and `animate` |
97
+ | Explore and tune every interaction live at [phation.app](https://phation.app) | |
98
+
99
+ This repository contains the CLI, the MCP server and the Standard. **It ships no component source**: with a license, `add` fetches it from phation.app. Plans are at [phation.app/pricing](https://phation.app/pricing).
100
+
101
+ ```bash
102
+ npx phation login <license-key> # saved to ~/.config/phation/license.json
103
+ # or, for CI and agent configs: PHATION_KEY=<license-key>
104
+ npx phation whoami
105
+ ```
106
+
107
+ ## License
108
+
109
+ The CLI, the MCP server and the Phation Standard may be installed and used freely; the Standard's text may be used in your own projects. Component source is covered by the Pro license. See [LICENSE.md](https://github.com/pnhathuy09/phation/blob/main/LICENSE.md), [phation.app/license](https://phation.app/license) and [phation.app/terms](https://phation.app/terms).
110
+
111
+ Made by [Pham Huy](https://phamhuyds.com).
@@ -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
+ }