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.
@@ -0,0 +1,266 @@
1
+ // Phation Animate — surface A (ANIMATE_SPEC.md §04): plan and apply recipes on a user's own JSX/TSX.
2
+ // animate(path, { feel, only, roles, apply, write }) → { text, files[], plan[] }
3
+ // plan: token-lean list (≈ 15 tokens a part) of role → recipe, with confidence and "⚠ check" under 0.6.
4
+ // apply: edits the file in place by offsets (never re-prints it): motion tags, one MOTION object, data-phation hooks for
5
+ // audit_motion. Writes <name>.animated.<ext> unless write: true. Returns the changed lines only.
6
+ import fs from 'fs'
7
+ import path from 'path'
8
+ import { detect, jsxName } from './detect.mjs'
9
+ import { RECIPES, recipesFor, resolve, DEFAULT_FEEL } from './core/recipes/index.js'
10
+ import { FEELS } from './core/feels.js'
11
+
12
+ const EXT = /\.(jsx|tsx)$/
13
+ const camel = id => id.replace(/-(\w)/g, (_, c) => c.toUpperCase())
14
+ const feelName = id => FEELS.find(f => f.id === id)?.name || id
15
+ // what each recipe can do automatically in code; the rest is planned and pointed at a library entry
16
+ const AUTO = new Set(['press', 'hover-lift', 'sheet-open', 'modal-open', 'accordion-open', 'list-enter', 'number-roll', 'toggle-knob', 'tab-pill'])
17
+
18
+ /** Pick the recipe for a part: the first recipe for its role, filtered by `only`. */
19
+ function pick(part, only) {
20
+ const list = recipesFor(part.role).filter(r => !only?.length || only.includes(r.id))
21
+ return list[0] || null
22
+ }
23
+
24
+ function files(target) {
25
+ const st = fs.statSync(target)
26
+ if (st.isFile()) return [target]
27
+ const out = []
28
+ const visit = d => { for (const f of fs.readdirSync(d, { withFileTypes: true })) {
29
+ if (f.name.startsWith('.') || f.name === 'node_modules' || f.name.includes('.animated.')) continue
30
+ const p = path.join(d, f.name)
31
+ if (f.isDirectory()) visit(p); else if (EXT.test(f.name)) out.push(p)
32
+ } }
33
+ visit(target)
34
+ return out
35
+ }
36
+
37
+ /** Plan one file: parts with their recipe and resolved values. `roles` = { "<line>": "<role>" } overrides. */
38
+ export function planFile(file, { feel = DEFAULT_FEEL, only, roles } = {}) {
39
+ const source = fs.readFileSync(file, 'utf8')
40
+ const d = detect(source, { file })
41
+ const items = []
42
+ for (const p of d.parts) {
43
+ const forced = roles?.[String(p.line)] || roles?.[p.name]
44
+ if (forced) { p.role = forced; p.confidence = 1; p.signal = 'you' }
45
+ const rc = pick(p, only)
46
+ if (!rc) continue
47
+ // a number shown by a component (<Price amount={…}/>) has no expression here to roll: point at its file instead
48
+ items.push({ ...p, recipe: rc, values: resolve(rc, feel), auto: AUTO.has(rc.id) && !(rc.id === 'number-roll' && p.kind !== 'expr') })
49
+ }
50
+ // one recipe per element: keep the strongest; a list item can also take hover-lift (different trigger)
51
+ const seen = new Map(), keep = []
52
+ for (const it of items.sort((a, b) => b.confidence - a.confidence)) {
53
+ const k = `${it.el.start}:${it.recipe.trigger}`
54
+ if (seen.has(k)) continue
55
+ seen.set(k, it); keep.push(it)
56
+ }
57
+ keep.sort((a, b) => a.line - b.line)
58
+ keep.forEach((it, i) => { it.n = i + 1 })
59
+ return { file, source, detected: d, items: keep, feel }
60
+ }
61
+
62
+ // one short line a part: "5 L126 <DeleteItemButton> icon-button .5 → press ⚠" (⚠ = a guess: confirm with roles)
63
+ function planLine(it) {
64
+ const v = it.values, extra = v.staggerMs ? ` ${v.staggerMs}ms` : ''
65
+ const warn = it.confidence < 0.6 ? ' ⚠' : ''
66
+ const manual = it.auto ? '' : it.recipe.entry ? ` · manual: add_motion ${it.recipe.entry}` : ' · manual'
67
+ const label = it.kind === 'expr' ? `{} in <${it.name}>` : `<${it.name}>`
68
+ return `${it.n} L${it.line} ${label} ${it.role} ${String(it.confidence.toFixed(1)).replace(/^0/, '')} → ${it.recipe.id}${extra}${manual}${warn}`
69
+ }
70
+
71
+ // ---------- apply ----------
72
+ const lit = v => typeof v === 'string' ? `'${v}'` : String(v)
73
+ const obj = o => `{ ${Object.entries(o).map(([k, v]) => `${k}: ${Array.isArray(v) ? `[${v.join(', ')}]` : typeof v === 'object' ? obj(v) : lit(v)}`).join(', ')} }`
74
+ const spring = s => ({ type: 'spring', stiffness: s.stiffness, damping: s.damping, mass: s.mass })
75
+
76
+ function motionEntry(rc, v) {
77
+ const e = {}
78
+ const st = rc.states || rc.content
79
+ if (st) { e.from = { ...st.from }; e.to = { ...st.to } }
80
+ if (rc.id === 'toggle-knob') { e.to = { x: 20 }; e.travel = 'track − knob − 2 × inset' }
81
+ e.spring = spring(v.spring)
82
+ if (v.exit) e.exit = v.exit.durationMs ? { durationMs: v.exit.durationMs, ease: v.exit.ease } : { spring: spring(v.exit.spring) }
83
+ if (v.staggerMs) { e.staggerMs = v.staggerMs; e.maxItems = v.staggerMaxItems }
84
+ return e
85
+ }
86
+
87
+ export function applyPlan(plan) {
88
+ const { source, detected, items } = plan
89
+ const ast = detected.ast, edits = [], notes = [], done = []
90
+ const M = /\bexport\s+const\s+MOTION\b|\bconst\s+MOTION\b/.test(source) ? 'PHATION_MOTION' : 'MOTION'
91
+ const creates = new Map() // component name → Motion alias
92
+ const used = new Map() // recipe id → entry
93
+ const edit = (start, end, text) => edits.push({ start, end, text })
94
+ const tagged = new Set()
95
+
96
+ const motionName = name => {
97
+ if (/^[a-z]/.test(name) && !name.includes('.')) return `motion.${name}`
98
+ const alias = 'Motion' + name.replace(/\./g, '')
99
+ creates.set(name, alias)
100
+ return alias
101
+ }
102
+ const retag = el => {
103
+ if (tagged.has(el)) return
104
+ tagged.add(el)
105
+ const name = jsxName(el.openingElement.name), to = motionName(name)
106
+ edit(el.openingElement.name.start, el.openingElement.name.end, to)
107
+ if (el.closingElement) edit(el.closingElement.name.start, el.closingElement.name.end, to)
108
+ }
109
+ const has = (el, n) => el.openingElement.attributes.some(a => a.type === 'JSXAttribute' && a.name?.name === n)
110
+ // props are collected per element and written once, so two recipes on one element never repeat an attribute
111
+ const pending = new Map() // el → { hooks: [], props: [] }
112
+ const props = (el, text, id) => { const p = pending.get(el) || { hooks: [], props: [] }; p.props.push(text); if (id) p.hooks.push(id); pending.set(el, p) }
113
+
114
+ for (const it of items) {
115
+ const rc = it.recipe, key = camel(rc.id), ref = `${M}.${key}`
116
+ if (!it.auto) { notes.push(`${it.n} ${rc.id}: not applied automatically${rc.entry ? `. add_motion ${rc.entry} for the full pattern` : ''}`); continue }
117
+ const el = it.el
118
+ const clash = ['whileTap', 'whileHover', 'initial', 'animate', 'layoutId'].find(p => has(el, p))
119
+ if (it.kind === 'element' && clash) { notes.push(`${it.n} ${rc.id}: <${it.name}> already has ${clash}; left as is`); continue }
120
+ const hook = '' // data-phation is written once per element below
121
+ // gestures carry their own spring inside the target, so they never fight an entrance transition on the same element
122
+ if (rc.id === 'press') { retag(el); props(el, `whileTap={{ ...${ref}.to, transition: ${ref}.spring }}`, rc.id) }
123
+ else if (rc.id === 'hover-lift') { retag(el); props(el, `whileHover={{ ...${ref}.to, transition: ${ref}.spring }}`, rc.id) }
124
+ else if (rc.id === 'sheet-open' || rc.id === 'modal-open') {
125
+ retag(el)
126
+ props(el, `initial={${ref}.from} animate={${ref}.to} exit={{ ...${ref}.from, transition: { duration: ${ref}.exit.durationMs / 1000, ease: ${ref}.exit.ease } }} transition={${ref}.spring}`, rc.id)
127
+ notes.push(`${it.n} ${rc.id}: the exit plays only inside <AnimatePresence> (Radix: add forceMount to the content)`)
128
+ } else if (rc.id === 'accordion-open') { retag(el); props(el, `initial={${ref}.from} animate={${ref}.to} transition={${ref}.spring}`, rc.id) }
129
+ else if (rc.id === 'list-enter') {
130
+ const fn = el.__phationMap
131
+ let idx = fn?.params[1]?.type === 'Identifier' ? fn.params[1].name : null
132
+ if (!idx && fn?.params.length === 1) {
133
+ idx = 'phationI'
134
+ const p = fn.params[0], wrapped = fn.start < p.start && source.slice(fn.start, p.start).includes('(')
135
+ if (wrapped) edit(p.end, p.end, ', phationI'); else edit(p.start, p.end, `(${source.slice(p.start, p.end)}, phationI)`)
136
+ }
137
+ retag(el)
138
+ props(el, idx
139
+ ? `initial={${ref}.from} animate={${ref}.to} transition={{ ...${ref}.spring, delay: Math.min(${idx}, ${ref}.maxItems - 1) * ${ref}.staggerMs / 1000 }}`
140
+ : `initial={${ref}.from} animate={${ref}.to} transition={${ref}.spring}`, rc.id)
141
+ } else if (rc.id === 'number-roll') {
142
+ const ex = it.expr, code = source.slice(ex.expression.start, ex.expression.end)
143
+ edit(ex.start, ex.end, `<motion.span key={String(${code})} data-phation="number-roll" initial={${ref}.from} animate={${ref}.to} transition={${ref}.spring} style={{ display: 'inline-block' }}>{${code}}</motion.span>`)
144
+ notes.push(`${it.n} number-roll: the whole value rolls in; add_motion digit-roll rolls each digit`)
145
+ } else if (rc.id === 'toggle-knob') {
146
+ const knob = el.children.find(c => c.type === 'JSXElement')
147
+ const state = el.openingElement.attributes.find(a => a.type === 'JSXAttribute' && ['checked', 'aria-checked'].includes(a.name?.name) && a.value?.type === 'JSXExpressionContainer')
148
+ if (!knob || !state) { notes.push(`${it.n} toggle-knob: no knob child with a checked state here; animate the thumb inside the switch component (add_motion day-night)`); continue }
149
+ const cond = source.slice(state.value.expression.start, state.value.expression.end)
150
+ retag(knob); props(knob, `initial={false} animate={{ x: ${cond} ? ${ref}.to.x : 0 }} transition={${ref}.spring}`, rc.id)
151
+ notes.push(`${it.n} toggle-knob: set ${M}.toggleKnob.to.x to the real travel (track − knob − 2 × inset)`)
152
+ } else if (rc.id === 'tab-pill') {
153
+ let pill = null
154
+ const visit = n => { if (!n || pill || typeof n !== 'object') return
155
+ if (n.type === 'LogicalExpression' && n.operator === '&&' && n.right?.type === 'JSXElement') { pill = n.right; return }
156
+ if (n.type === 'ConditionalExpression' && n.consequent?.type === 'JSXElement' && n.alternate?.type !== 'JSXElement') { pill = n.consequent; return }
157
+ for (const k in n) if (k !== 'loc' && !k.startsWith('__') && n[k] && typeof n[k] === 'object') Array.isArray(n[k]) ? n[k].forEach(visit) : visit(n[k]) }
158
+ visit(el)
159
+ if (!pill) { notes.push(`${it.n} tab-pill: no active-tab indicator found; render one inside the active tab and give it layoutId (add_motion model-picker)`); continue }
160
+ retag(pill); props(pill, `layoutId="phation-tab-pill" transition={${ref}.spring}`, rc.id)
161
+ }
162
+ used.set(rc.id, motionEntry(rc, it.values))
163
+ done.push(it.n)
164
+ }
165
+ // reduced motion (Standard §6): wrap each touched component's returned JSX once in <MotionConfig reducedMotion="user">,
166
+ // which drops transform and layout motion for users who ask for less and keeps opacity fades
167
+ const roots = new Set()
168
+ const visitRet = n => { if (!n || typeof n !== 'object') return
169
+ let arg = n.type === 'ReturnStatement' ? n.argument : n.type === 'ArrowFunctionExpression' && n.body?.type !== 'BlockStatement' ? n.body : null
170
+ while (arg?.type === 'ParenthesizedExpression') arg = arg.expression
171
+ if (arg && (arg.type === 'JSXElement' || arg.type === 'JSXFragment') && [...pending.keys(), ...items.filter(i => i.kind === 'expr').map(i => i.expr)].some(e => e.start >= arg.start && e.end <= arg.end)) {
172
+ if (![...roots].some(r => r.start <= arg.start && r.end >= arg.end)) { for (const r of [...roots]) if (arg.start <= r.start && arg.end >= r.end) roots.delete(r); roots.add(arg) }
173
+ }
174
+ for (const k in n) if (k !== 'loc' && !k.startsWith('__') && n[k] && typeof n[k] === 'object') Array.isArray(n[k]) ? n[k].forEach(visitRet) : visitRet(n[k]) }
175
+ visitRet(ast.program)
176
+ for (const r of roots) { edit(r.start, r.start, '<MotionConfig reducedMotion="user">'); edit(r.end, r.end, '</MotionConfig>') }
177
+ const needConfig = roots.size > 0
178
+
179
+ for (const [el, p] of pending) {
180
+ // an element with an entrance transition and a gesture keeps one transition prop (the entrance); gestures carry theirs
181
+ const text = (p.hooks.length ? `data-phation="${p.hooks.join(' ')}" ` : '') + p.props.join(' ')
182
+ edit(el.openingElement.name.end, el.openingElement.name.end, ' ' + text)
183
+ }
184
+ if (!done.length) return { source, changed: false, notes, done }
185
+
186
+ // imports + MOTION object (after the last import; after directives when there are none)
187
+ const body = ast.program.body
188
+ const imp = body.filter(s => s.type === 'ImportDeclaration')
189
+ const mImp = imp.find(s => s.source.value === 'motion/react' || s.source.value === 'framer-motion')
190
+ const head = []
191
+ const want = ['motion', ...(needConfig ? ['MotionConfig'] : [])]
192
+ if (!mImp) head.push(`import { ${want.join(', ')} } from 'motion/react'`)
193
+ else {
194
+ const missing = want.filter(n => !mImp.specifiers.some(s => s.local.name === n))
195
+ const first = mImp.specifiers.find(s => s.type === 'ImportSpecifier')
196
+ if (missing.length && first) edit(first.start, first.start, missing.join(', ') + ', ')
197
+ else if (missing.length) head.push(`import { ${missing.join(', ')} } from '${mImp.source.value}'`)
198
+ }
199
+ const at = imp.length ? imp[imp.length - 1].end : (ast.program.directives?.length ? ast.program.directives.at(-1).end : 0)
200
+ const motionObj = [`// Phation Animate · Feel: ${feelName(plan.feel)} · springs k/c/m, durations in ms. Reduced motion: <MotionConfig reducedMotion="user"> keeps fades, drops movement.`,
201
+ `export const ${M} = {`, ...[...used].map(([id, e]) => ` ${camel(id)}: ${obj(e)},`), `}`]
202
+ const createLines = [...creates].map(([name, alias]) => `const ${alias} = motion.create(${name})`)
203
+ const block = (head.length ? '\n' + head.join('\n') : '') + '\n\n' + motionObj.join('\n') + (createLines.length ? '\n' + createLines.join('\n') : '')
204
+ edit(at, at, at === 0 ? block.trimStart() + '\n' : block)
205
+ if (creates.size) notes.push(`motion.create(${[...creates.keys()].join(', ')}): these components must forward their ref to the DOM element (shadcn/Radix do)`)
206
+
207
+ let out = source
208
+ for (const e of edits.sort((a, b) => b.start - a.start || b.end - a.end)) out = out.slice(0, e.start) + e.text + out.slice(e.end)
209
+ return { source: out, changed: true, notes, done }
210
+ }
211
+
212
+ /** Changed lines only, as a compact unified-style list. */
213
+ export function lineDiff(a, b) {
214
+ const A = a.split('\n'), B = b.split('\n'), n = A.length, m = B.length
215
+ const L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1))
216
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = A[i] === B[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1])
217
+ const out = []
218
+ let i = 0, j = 0
219
+ while (i < n || j < m) {
220
+ if (i < n && j < m && A[i] === B[j]) { i++; j++ }
221
+ else if (j < m && (i >= n || L[i][j + 1] >= L[i + 1][j])) { out.push(`+${String(j + 1).padStart(4)} ${B[j]}`); j++ }
222
+ else { out.push(`-${String(i + 1).padStart(4)} ${A[i]}`); i++ }
223
+ }
224
+ return out.join('\n')
225
+ }
226
+
227
+ // audit actions that trigger each applied recipe (audit_motion `actions`)
228
+ const ACTION = {
229
+ press: '"hold:[data-phation~=press]:300"', 'hover-lift': '"hover:[data-phation~=hover-lift]"', 'tab-pill': 'click on another tab',
230
+ 'toggle-knob': 'click the switch', 'accordion-open': 'click its trigger', 'sheet-open': 'click its trigger', 'modal-open': 'click its trigger',
231
+ 'list-enter': 'page load (no action)', 'number-roll': 'change the value',
232
+ }
233
+
234
+ /** Plan (default) or apply across a file or folder. */
235
+ export function animate(target, { feel = DEFAULT_FEEL, only, roles, apply = false, write = false, projectRoot = process.cwd() } = {}) {
236
+ const abs = path.resolve(projectRoot, target)
237
+ if (!fs.existsSync(abs)) throw new Error(`No file or folder at ${target}`)
238
+ if (!FEELS.some(f => f.id === feel)) throw new Error(`Unknown feel "${feel}". Use one of: ${FEELS.map(f => f.id).join(', ')}`)
239
+ const list = files(abs)
240
+ if (!list.length) throw new Error(`No .jsx/.tsx files in ${target}`)
241
+ const lines = [], results = []
242
+ for (const f of list) {
243
+ let plan
244
+ try { plan = planFile(f, { feel, only, roles }) } catch (e) { lines.push(`${path.relative(projectRoot, f)} · parse error: ${e.message}`); continue }
245
+ if (!plan.items.length) continue
246
+ const rel = path.relative(projectRoot, f)
247
+ lines.push(`${rel} · Feel: ${feelName(feel)}`, ...plan.items.map(planLine))
248
+ if (apply) {
249
+ const r = applyPlan(plan)
250
+ if (r.changed) {
251
+ const out = write ? f : f.replace(EXT, '.animated.$1')
252
+ fs.writeFileSync(out, r.source)
253
+ lines.push(`→ wrote ${path.relative(projectRoot, out)} (${r.done.length} part${r.done.length > 1 ? 's' : ''})`, lineDiff(plan.source, r.source))
254
+ const acts = [...new Set(plan.items.filter(it => r.done.includes(it.n)).map(it => `${it.recipe.id}: ${ACTION[it.recipe.id]}`))]
255
+ lines.push(`check: audit_motion({ url, actions }) · ${acts.join(' · ')}`)
256
+ }
257
+ lines.push(...r.notes.map(n => ` · ${n}`))
258
+ results.push({ file: rel, ...r, source: undefined })
259
+ }
260
+ lines.push('')
261
+ results.push({ file: rel, parts: plan.items.map(it => ({ n: it.n, line: it.line, name: it.name, role: it.role, confidence: it.confidence, signal: it.signal, recipe: it.recipe.id, auto: it.auto })) })
262
+ }
263
+ if (!lines.length) return { text: `Nothing to animate in ${target}: no buttons, cards, sheets, dialogs, tabs, toggles, lists or numbers found.`, results }
264
+ if (!apply) lines.push(`⚠ = guess, fix with roles: { "<line>": "<role>" } · then apply: true`)
265
+ return { text: lines.join('\n').trim(), results }
266
+ }