@atom.io/spa 0.0.1 → 0.0.2

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 (112) hide show
  1. package/README.md +201 -6
  2. package/README.mdx +62 -1
  3. package/dist/astro-application.d.ts +1 -1
  4. package/dist/astro-client.d.ts +1 -1
  5. package/dist/astro-client.js +6 -3
  6. package/dist/astro-client.js.map +1 -1
  7. package/dist/astro-server.js +2 -1
  8. package/dist/astro-server.js.map +1 -1
  9. package/dist/astro-shared-BT45auwR.js.map +1 -1
  10. package/dist/{astro-shared-DkZaqX7L.d.ts → astro-shared-DyzbUi6c.d.ts} +4 -2
  11. package/dist/astro-shared-DyzbUi6c.d.ts.map +1 -0
  12. package/dist/astro.d.ts +1 -1
  13. package/dist/astro.js +1 -1
  14. package/dist/{core-Dvqm7w2y.js → capabilities-BuZUQpiD.js} +64 -2
  15. package/dist/capabilities-BuZUQpiD.js.map +1 -0
  16. package/dist/{core-BhiA9fFi.d.ts → capabilities-yC9TsHDI.d.ts} +20 -2
  17. package/dist/capabilities-yC9TsHDI.d.ts.map +1 -0
  18. package/dist/client.min.js +1 -1
  19. package/dist/development/astro-client.js +6 -3
  20. package/dist/development/astro-client.js.map +1 -1
  21. package/dist/development/astro-server.js +2 -1
  22. package/dist/development/astro-server.js.map +1 -1
  23. package/dist/development/astro-shared-BT45auwR.js.map +1 -1
  24. package/dist/development/astro.js +1 -1
  25. package/dist/development/{core-DB3sQz4h.js → capabilities-DhOJmeoJ.js} +64 -2
  26. package/dist/development/capabilities-DhOJmeoJ.js.map +1 -0
  27. package/dist/development/{dom-D9cY6l1R.js → dom-BKc6V_Kz.js} +8 -3
  28. package/dist/development/dom-BKc6V_Kz.js.map +1 -0
  29. package/dist/development/index.js +3 -38
  30. package/dist/development/jsx-runtime.js.map +1 -1
  31. package/dist/development/konva.js +121 -0
  32. package/dist/development/konva.js.map +1 -0
  33. package/dist/development/motion.js +217 -0
  34. package/dist/development/motion.js.map +1 -0
  35. package/dist/development/renderer.js +177 -0
  36. package/dist/development/renderer.js.map +1 -0
  37. package/dist/development/server.js +3 -2
  38. package/dist/development/server.js.map +1 -1
  39. package/dist/development/src-Dh-d6w4y.js +38 -0
  40. package/dist/development/src-Dh-d6w4y.js.map +1 -0
  41. package/dist/development/three.js +438 -0
  42. package/dist/development/three.js.map +1 -0
  43. package/dist/development/vite-CSHoxzXU.js +240 -0
  44. package/dist/development/vite-CSHoxzXU.js.map +1 -0
  45. package/dist/development/vite.js +1 -1
  46. package/dist/{dom-BR9o9wZW.js → dom-B2rm8o2L.js} +8 -3
  47. package/dist/dom-B2rm8o2L.js.map +1 -0
  48. package/dist/index-BdwxmSKg.d.ts +24 -0
  49. package/dist/index-BdwxmSKg.d.ts.map +1 -0
  50. package/dist/index.d.ts +4 -24
  51. package/dist/index.js +3 -38
  52. package/dist/{jsx-runtime-BzGV18VO.d.ts → jsx-runtime-CZU7F8Qz.d.ts} +6 -4
  53. package/dist/jsx-runtime-CZU7F8Qz.d.ts.map +1 -0
  54. package/dist/jsx-runtime.d.ts +2 -2
  55. package/dist/jsx-runtime.js.map +1 -1
  56. package/dist/konva.d.ts +32 -0
  57. package/dist/konva.d.ts.map +1 -0
  58. package/dist/konva.js +121 -0
  59. package/dist/konva.js.map +1 -0
  60. package/dist/motion.d.ts +44 -0
  61. package/dist/motion.d.ts.map +1 -0
  62. package/dist/motion.js +217 -0
  63. package/dist/motion.js.map +1 -0
  64. package/dist/renderer.d.ts +24 -0
  65. package/dist/renderer.d.ts.map +1 -0
  66. package/dist/renderer.js +177 -0
  67. package/dist/renderer.js.map +1 -0
  68. package/dist/server.d.ts +1 -1
  69. package/dist/server.d.ts.map +1 -1
  70. package/dist/server.js +3 -2
  71. package/dist/server.js.map +1 -1
  72. package/dist/size.json +16 -16
  73. package/dist/src-BZxX4xbU.js +38 -0
  74. package/dist/src-BZxX4xbU.js.map +1 -0
  75. package/dist/three.d.ts +110 -0
  76. package/dist/three.d.ts.map +1 -0
  77. package/dist/three.js +438 -0
  78. package/dist/three.js.map +1 -0
  79. package/dist/vite-CSHoxzXU.js +240 -0
  80. package/dist/vite-CSHoxzXU.js.map +1 -0
  81. package/dist/vite.js +1 -1
  82. package/package.json +56 -11
  83. package/src/astro-client.ts +1 -0
  84. package/src/astro-server.ts +1 -0
  85. package/src/astro-shared.ts +3 -0
  86. package/src/capabilities.ts +88 -0
  87. package/src/compiler.ts +251 -178
  88. package/src/core.ts +11 -0
  89. package/src/dom.ts +4 -1
  90. package/src/index.ts +5 -0
  91. package/src/jsx-runtime.ts +4 -0
  92. package/src/jsx-types.d.ts +3 -1
  93. package/src/konva.ts +159 -0
  94. package/src/motion.ts +406 -0
  95. package/src/renderer.ts +241 -0
  96. package/src/server.ts +3 -0
  97. package/src/three-events.ts +330 -0
  98. package/src/three.ts +350 -0
  99. package/dist/astro-shared-DkZaqX7L.d.ts.map +0 -1
  100. package/dist/core-BhiA9fFi.d.ts.map +0 -1
  101. package/dist/core-Dvqm7w2y.js.map +0 -1
  102. package/dist/development/core-DB3sQz4h.js.map +0 -1
  103. package/dist/development/dom-D9cY6l1R.js.map +0 -1
  104. package/dist/development/index.js.map +0 -1
  105. package/dist/development/vite-CQchIQ_-.js +0 -126
  106. package/dist/development/vite-CQchIQ_-.js.map +0 -1
  107. package/dist/dom-BR9o9wZW.js.map +0 -1
  108. package/dist/index.d.ts.map +0 -1
  109. package/dist/index.js.map +0 -1
  110. package/dist/jsx-runtime-BzGV18VO.d.ts.map +0 -1
  111. package/dist/vite-CQchIQ_-.js +0 -126
  112. package/dist/vite-CQchIQ_-.js.map +0 -1
package/src/motion.ts ADDED
@@ -0,0 +1,406 @@
1
+ import type { MotionValue, ValueAnimationTransition } from "motion"
2
+ import {
3
+ animate,
4
+ cancelFrame,
5
+ frame,
6
+ hover,
7
+ motionValue,
8
+ press,
9
+ readStyleValue,
10
+ styleEffect,
11
+ } from "motion"
12
+
13
+ import type {
14
+ Capability,
15
+ CapabilityBinding,
16
+ CapabilityTarget,
17
+ } from "./capabilities.ts"
18
+
19
+ export type MotionScalar = number | string
20
+ export type MotionDOMTarget = Partial<
21
+ Record<
22
+ | keyof CSSStyleDeclaration
23
+ | `x`
24
+ | `y`
25
+ | `z`
26
+ | `scale`
27
+ | `scaleX`
28
+ | `scaleY`
29
+ | `rotate`
30
+ | `rotateX`
31
+ | `rotateY`
32
+ | `rotateZ`
33
+ | `skewX`
34
+ | `skewY`
35
+ | `--${string}`,
36
+ MotionScalar
37
+ >
38
+ >
39
+ export interface MotionThreeTarget {
40
+ position?: readonly [number, number, number]
41
+ rotation?: readonly [number, number, number]
42
+ scale?: number | readonly [number, number, number]
43
+ opacity?: number
44
+ intensity?: number
45
+ color?: string
46
+ }
47
+ export type MotionTarget<Kind extends string> = Kind extends `dom`
48
+ ? MotionDOMTarget
49
+ : Kind extends `three`
50
+ ? MotionThreeTarget
51
+ : Record<string, MotionScalar>
52
+ /** Supported transition options; keep public declarations independent of optional peer types. */
53
+ export interface MotionTransition {
54
+ type?: `spring` | `tween`
55
+ stiffness?: number
56
+ damping?: number
57
+ mass?: number
58
+ velocity?: number
59
+ restSpeed?: number
60
+ restDelta?: number
61
+ bounce?: number
62
+ visualDuration?: number
63
+ duration?: number
64
+ delay?: number
65
+ ease?:
66
+ | `linear`
67
+ | `easeIn`
68
+ | `easeOut`
69
+ | `easeInOut`
70
+ | `circIn`
71
+ | `circOut`
72
+ | `circInOut`
73
+ | `backIn`
74
+ | `backOut`
75
+ | `backInOut`
76
+ | readonly [number, number, number, number]
77
+ }
78
+ export interface MotionAttributes<Kind extends string = `dom`> {
79
+ [`motion:initial`]?: MotionTarget<Kind> | false
80
+ [`motion:animate`]?: MotionTarget<Kind>
81
+ [`motion:transition`]?: MotionTransition
82
+ [`motion:whileHover`]?: MotionTarget<Kind>
83
+ [`motion:whileTap`]?: MotionTarget<Kind>
84
+ }
85
+
86
+ // eslint-disable-next-line quotes -- TypeScript module augmentation requires a string literal.
87
+ declare module "@atom.io/spa/jsx-runtime" {
88
+ // oxlint-disable-next-line typescript/no-empty-interface -- Declaration merging adds optional motion attributes.
89
+ interface CapabilityAttributes<
90
+ Kind extends string,
91
+ > extends MotionAttributes<Kind> {}
92
+ }
93
+
94
+ export interface MotionCapabilityOptions {
95
+ /** Respect the user's reduced-motion preference by default. */
96
+ reducedMotion?: `user` | `always` | `never`
97
+ }
98
+ type TargetValues = Record<string, MotionScalar | readonly number[]>
99
+ interface AnimatedProperty {
100
+ values: MotionValue<MotionScalar>[]
101
+ base: MotionScalar | readonly number[]
102
+ rest: MotionScalar | readonly number[]
103
+ target: MotionScalar | readonly number[]
104
+ release(): void
105
+ }
106
+ const transform =
107
+ /^(x|y|z|translate.*|scale.*|rotate.*|skew.*|transformPerspective)$/
108
+ const allowed = new Set([
109
+ `initial`,
110
+ `animate`,
111
+ `transition`,
112
+ `whileHover`,
113
+ `whileTap`,
114
+ ])
115
+ function equal(a: unknown, b: unknown): boolean {
116
+ return (
117
+ Object.is(a, b) ||
118
+ (Array.isArray(a) &&
119
+ Array.isArray(b) &&
120
+ a.length === b.length &&
121
+ a.every((value, index) => Object.is(value, b[index])))
122
+ )
123
+ }
124
+
125
+ function attach(
126
+ target: CapabilityTarget,
127
+ options: MotionCapabilityOptions,
128
+ ): CapabilityBinding {
129
+ if (target.kind !== `dom` && (!target.read || !target.write))
130
+ throw new Error(
131
+ `spa/motion: renderer ${target.kind} does not support motion`,
132
+ )
133
+ const element =
134
+ target.kind === `dom` ? (target.node as HTMLElement | SVGElement) : undefined
135
+ const properties = new Map<string, AnimatedProperty>()
136
+ const originalStyles = new Map<string, { value: string; priority: string }>()
137
+ let styles: (() => void) | undefined
138
+ let props: Record<string, unknown> = {}
139
+ let hovered = false
140
+ let tapped = false
141
+ let started = false
142
+ let dead = false
143
+ let gestures: (() => void)[] = []
144
+ const preference =
145
+ options.reducedMotion !== `never` && typeof matchMedia === `function`
146
+ ? matchMedia(`(prefers-reduced-motion: reduce)`)
147
+ : undefined
148
+ const reduced = () =>
149
+ options.reducedMotion === `always` ||
150
+ (options.reducedMotion !== `never` && preference?.matches)
151
+ const read = (key: string, fallback: unknown): any => {
152
+ const value = element ? readStyleValue(element, key) : target.read!(key)
153
+ return value === undefined || value === ``
154
+ ? typeof fallback === `number`
155
+ ? key.startsWith(`scale`) || key === `opacity`
156
+ ? 1
157
+ : 0
158
+ : fallback
159
+ : value
160
+ }
161
+ const bindStyles = () => {
162
+ styles?.()
163
+ if (element)
164
+ styles = styleEffect(
165
+ [element],
166
+ Object.fromEntries(
167
+ [...properties].map(([key, property]) => [key, property.values[0]]),
168
+ ) as any,
169
+ )
170
+ }
171
+ const ensure = (
172
+ key: string,
173
+ goal: MotionScalar | readonly number[],
174
+ initial: TargetValues | false,
175
+ ): AnimatedProperty => {
176
+ const existing = properties.get(key)
177
+ if (existing) {
178
+ if (existing.values.length !== (Array.isArray(goal) ? goal.length : 1))
179
+ throw new Error(`spa/motion: cannot change the shape of ${key}`)
180
+ return existing
181
+ }
182
+ const base = read(key, goal) as MotionScalar | readonly number[]
183
+ const rest = !Array.isArray(goal) && Array.isArray(base) ? base[0]! : base
184
+ let start = initial === false ? goal : (initial[key] ?? rest)
185
+ if (!Array.isArray(goal) && Array.isArray(start)) start = start[0]!
186
+ if (
187
+ Array.isArray(goal) &&
188
+ (!Array.isArray(start) || start.length !== goal.length)
189
+ )
190
+ throw new Error(`spa/motion: ${key} requires matching numeric tuples`)
191
+ const values = (Array.isArray(start) ? start : [start]).map((value) =>
192
+ motionValue(value),
193
+ ) as MotionValue<MotionScalar>[]
194
+ const unsubscribers: (() => void)[] = []
195
+ if (element) {
196
+ if (Array.isArray(goal))
197
+ throw new Error(
198
+ `spa/motion: DOM targets must be scalar styles or transforms`,
199
+ )
200
+ const cssKey = transform.test(key)
201
+ ? `transform`
202
+ : key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)
203
+ if (!originalStyles.has(cssKey))
204
+ originalStyles.set(cssKey, {
205
+ value: element.style.getPropertyValue(cssKey),
206
+ priority: element.style.getPropertyPriority(cssKey),
207
+ })
208
+ } else {
209
+ const write = () => {
210
+ target.write!(
211
+ key,
212
+ Array.isArray(goal)
213
+ ? values.map((value) => value.get())
214
+ : values[0].get(),
215
+ )
216
+ }
217
+ for (const value of values) unsubscribers.push(value.on(`change`, write))
218
+ write()
219
+ }
220
+ const property: AnimatedProperty = {
221
+ values,
222
+ base,
223
+ rest,
224
+ target: start,
225
+ release() {
226
+ for (const release of unsubscribers) release()
227
+ for (const value of values) value.destroy()
228
+ },
229
+ }
230
+ properties.set(key, property)
231
+ return property
232
+ }
233
+ const refresh = () => {
234
+ if (dead) return
235
+ const initial = (props[`initial`] ?? {}) as TargetValues | false
236
+ const animateTo = (props[`animate`] ?? {}) as TargetValues
237
+ const hoverTo = (props[`whileHover`] ?? {}) as TargetValues
238
+ const tapTo = (props[`whileTap`] ?? {}) as TargetValues
239
+ const goals = {
240
+ ...animateTo,
241
+ ...(hovered ? hoverTo : {}),
242
+ ...(tapped ? tapTo : {}),
243
+ }
244
+ const keys = new Set([
245
+ ...Object.keys(initial || {}),
246
+ ...Object.keys(animateTo),
247
+ ...Object.keys(hoverTo),
248
+ ...Object.keys(tapTo),
249
+ ])
250
+ let added = false
251
+ for (const key of keys) {
252
+ const sample =
253
+ goals[key] ??
254
+ (initial === false ? undefined : initial[key]) ??
255
+ hoverTo[key] ??
256
+ tapTo[key]
257
+ if (sample === undefined) continue
258
+ const had = properties.has(key)
259
+ ensure(key, sample, started ? {} : initial)
260
+ if (!had) added = true
261
+ }
262
+ if (added) bindStyles()
263
+ const transition = (props[`transition`] ?? {
264
+ type: `spring`,
265
+ }) as ValueAnimationTransition
266
+ for (const [key, property] of properties) {
267
+ const goal =
268
+ goals[key] ??
269
+ (initial === false ? undefined : initial[key]) ??
270
+ property.rest
271
+ if (equal(property.target, goal)) continue
272
+ property.target = Array.isArray(goal) ? [...goal] : goal
273
+ const next = Array.isArray(goal) ? goal : [goal]
274
+ if (next.length !== property.values.length)
275
+ throw new Error(`spa/motion: cannot change the shape of ${key}`)
276
+ property.values.forEach((value, index) => {
277
+ if (reduced() || (!started && initial === false)) value.jump(next[index])
278
+ else animate(value, next[index], transition)
279
+ })
280
+ }
281
+ started = true
282
+ }
283
+ const clearGestures = () => {
284
+ for (const release of gestures) release()
285
+ gestures = []
286
+ }
287
+ const installGestures = () => {
288
+ clearGestures()
289
+ if (element) {
290
+ if (props[`whileHover`])
291
+ gestures.push(
292
+ hover([element], () => {
293
+ hovered = true
294
+ refresh()
295
+ return () => {
296
+ hovered = false
297
+ refresh()
298
+ }
299
+ }),
300
+ )
301
+ if (props[`whileTap`])
302
+ gestures.push(
303
+ press([element], () => {
304
+ tapped = true
305
+ refresh()
306
+ return () => {
307
+ tapped = false
308
+ refresh()
309
+ }
310
+ }),
311
+ )
312
+ } else if (props[`whileHover`] || props[`whileTap`]) {
313
+ if (!target.listen)
314
+ throw new Error(
315
+ `spa/motion: ${target.kind} gestures require a renderer event adapter`,
316
+ )
317
+ const listen = (event: string, run: () => void) =>
318
+ gestures.push(target.listen!(event, run))
319
+ listen(`pointerenter`, () => {
320
+ hovered = true
321
+ refresh()
322
+ })
323
+ listen(`pointerleave`, () => {
324
+ hovered = false
325
+ tapped = false
326
+ refresh()
327
+ })
328
+ listen(`pointerdown`, () => {
329
+ tapped = true
330
+ refresh()
331
+ })
332
+ listen(`pointerup`, () => {
333
+ tapped = false
334
+ refresh()
335
+ })
336
+ listen(`pointercancel`, () => {
337
+ tapped = false
338
+ refresh()
339
+ })
340
+ }
341
+ }
342
+ const preferenceChanged = () => {
343
+ if (reduced()) {
344
+ for (const property of properties.values()) {
345
+ const goal = Array.isArray(property.target)
346
+ ? property.target
347
+ : [property.target]
348
+ property.values.forEach((value, i) => {
349
+ value.jump(goal[i])
350
+ })
351
+ }
352
+ }
353
+ }
354
+ preference?.addEventListener(`change`, preferenceChanged)
355
+ return {
356
+ update(next) {
357
+ if (dead) return
358
+ for (const key of Object.keys(next))
359
+ if (!allowed.has(key))
360
+ throw new Error(`spa/motion: unknown property motion:${key}`)
361
+ const gestureChange =
362
+ !started ||
363
+ Boolean(next[`whileHover`]) !== Boolean(props[`whileHover`]) ||
364
+ Boolean(next[`whileTap`]) !== Boolean(props[`whileTap`])
365
+ props = next
366
+ if (gestureChange) installGestures()
367
+ refresh()
368
+ },
369
+ dispose() {
370
+ if (dead) return
371
+ dead = true
372
+ clearGestures()
373
+ preference?.removeEventListener(`change`, preferenceChanged)
374
+ styles?.()
375
+ for (const [key, property] of properties) {
376
+ property.release()
377
+ if (!element) target.write!(key, property.base)
378
+ }
379
+ for (const [key, value] of originalStyles) {
380
+ if (value.value)
381
+ element!.style.setProperty(key, value.value, value.priority)
382
+ else element!.style.removeProperty(key)
383
+ }
384
+ properties.clear()
385
+ },
386
+ }
387
+ }
388
+
389
+ /** Explicit, root-scoped motion:* integration. Importing it never registers globally. */
390
+ export function motionCapability(
391
+ options: MotionCapabilityOptions = {},
392
+ ): Capability {
393
+ return {
394
+ namespace: `motion`,
395
+ attach: (target) => attach(target, options),
396
+ scheduleFrame(callback) {
397
+ const run = ({ timestamp }: { timestamp: number }) => {
398
+ callback(timestamp)
399
+ }
400
+ frame.render(run, true)
401
+ return () => {
402
+ cancelFrame(run)
403
+ }
404
+ },
405
+ }
406
+ }
@@ -0,0 +1,241 @@
1
+ import type { CapabilityTarget } from "./capabilities.ts"
2
+ import { capabilityProps } from "./capabilities.ts"
3
+ import type { Child, Component, RootOptions, Scope, VNode } from "./core.ts"
4
+ import {
5
+ createRoot,
6
+ createScope,
7
+ dispose,
8
+ fail,
9
+ invalidate,
10
+ observe,
11
+ owner,
12
+ untrack,
13
+ within,
14
+ } from "./core.ts"
15
+ import { Fragment, merge } from "./jsx-runtime.ts"
16
+
17
+ export interface SceneHost<N> {
18
+ target?(node: N): CapabilityTarget
19
+ create(type: string, props: Record<string, any>): N
20
+ update(
21
+ node: N,
22
+ props: Record<string, any>,
23
+ previous: Record<string, any>,
24
+ ): void
25
+ children(parent: N, children: N[]): void
26
+ destroy(node: N): void
27
+ }
28
+ interface Entry<N> {
29
+ scope: Scope
30
+ value: Child
31
+ nodes: () => N[]
32
+ }
33
+
34
+ export interface SceneRenderer<N> {
35
+ mount(setup: () => Child, parent: N): void
36
+ render(
37
+ setup: () => Child,
38
+ parent: N,
39
+ options?: RootOptions,
40
+ ): { flush(): void; dispose(): void }
41
+ }
42
+
43
+ /** A scene renderer shares SPA's owner, store, scheduler, and component lifecycle. */
44
+ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
45
+ function mount(
46
+ source: () => Child,
47
+ scope: Scope,
48
+ changed: () => void,
49
+ ): () => N[] {
50
+ let entries: Entry<N>[] = []
51
+ observe(scope, source, (next) => {
52
+ const values = (
53
+ Array.isArray(next) ? next.flat(Infinity) : [next]
54
+ ) as Child[]
55
+ const old = new Map(
56
+ entries.map((entry, i) => [key(entry.value, i), entry]),
57
+ )
58
+ const seen = new Set<string>()
59
+ entries = values.map((value, i) => {
60
+ const id = key(value, i)
61
+ if (seen.has(id)) throw new Error(`spa: duplicate scene key`)
62
+ seen.add(id)
63
+ let entry = old.get(id)
64
+ old.delete(id)
65
+ if (entry && !same(entry.value, value)) {
66
+ dispose(entry.scope)
67
+ entry = undefined
68
+ }
69
+ if (entry) {
70
+ entry.value = value
71
+ invalidate(entry.scope)
72
+ return entry
73
+ }
74
+ const childScope = createScope(scope)
75
+ const created: Entry<N> = { scope: childScope, value, nodes: null! }
76
+ created.nodes = build(() => created.value, childScope, changed)
77
+ return created
78
+ })
79
+ for (const entry of old.values()) dispose(entry.scope)
80
+ changed()
81
+ })
82
+ return () => entries.flatMap((entry) => entry.nodes())
83
+ }
84
+ function key(value: Child, i: number): string {
85
+ const explicit = (value as VNode | null)?.props?.[`key`]
86
+ return explicit == null ? `index:${i}` : `key:${explicit}`
87
+ }
88
+ function same(a: Child, b: Child): boolean {
89
+ return (
90
+ typeof a === typeof b &&
91
+ (a as VNode | null)?.type === (b as VNode | null)?.type
92
+ )
93
+ }
94
+ function build(
95
+ source: () => Child,
96
+ scope: Scope,
97
+ changed: () => void,
98
+ ): () => N[] {
99
+ const value = untrack(source)
100
+ if (typeof value === `function`)
101
+ return mount(() => (source() as () => Child)(), scope, changed)
102
+ if (value == null || typeof value === `boolean`) return () => []
103
+ if (typeof value !== `object`)
104
+ throw new Error(`spa: scene children must be nodes`)
105
+ if (!(`type` in value) || !(`props` in value))
106
+ throw new Error(`spa: invalid scene child`)
107
+ const vnode = value
108
+ const props = merge(() => (source() as VNode).props)
109
+ if (!vnode.type || vnode.type === Fragment)
110
+ return mount(() => props[`children`], scope, changed)
111
+ if (typeof vnode.type === `function`) {
112
+ const output = within(scope, () =>
113
+ untrack(() => (vnode.type as Component)(props)),
114
+ )
115
+ return mount(() => output, scope, changed)
116
+ }
117
+ const node = host.create(
118
+ vnode.type,
119
+ untrack(() => props),
120
+ )
121
+ scope._cleanups.add(() => {
122
+ host.destroy(node)
123
+ })
124
+ const nativeProps = capabilityProps(
125
+ scope,
126
+ host.target?.(node) ?? { kind: `scene`, node },
127
+ )
128
+ let previous: Record<string, any> = {}
129
+ observe(
130
+ scope,
131
+ () => ({ ...props }),
132
+ (all) => {
133
+ const next = nativeProps(all)
134
+ host.update(node, next, previous)
135
+ previous = next
136
+ },
137
+ )
138
+ let children: () => N[] = () => []
139
+ const sync = () => {
140
+ host.children(node, children())
141
+ }
142
+ children = mount(() => props[`children`], scope, sync)
143
+ sync()
144
+ const ref = untrack(() => props[`ref`])
145
+ if (ref)
146
+ scope._root._mounts!.unshift(() => {
147
+ if (!scope._dead) {
148
+ scope._cleanups.add(() => ref(null))
149
+ ref(node)
150
+ }
151
+ })
152
+ return () => [node]
153
+ }
154
+ function attach(setup: () => Child, parent: N, scope: Scope) {
155
+ let nodes: () => N[] = () => []
156
+ const sync = () => {
157
+ host.children(parent, nodes())
158
+ }
159
+ nodes = mount(() => untrack(setup), scope, sync)
160
+ sync()
161
+ scope._cleanups.add(() => {
162
+ host.children(parent, [])
163
+ })
164
+ }
165
+ return {
166
+ /** Attach beneath the current component; disposal follows its lifetime. */
167
+ mount(setup: () => Child, parent: N): void {
168
+ if (!owner) throw new Error(`spa: scene mount requires an owner`)
169
+ const scope = createScope(owner)
170
+ try {
171
+ attach(setup, parent, scope)
172
+ } catch (error) {
173
+ fail(scope, error)
174
+ }
175
+ },
176
+ render(setup: () => Child, parent: N, options: RootOptions = {}) {
177
+ const root = createRoot(options)
178
+ try {
179
+ within(root, () => {
180
+ attach(setup, parent, root)
181
+ })
182
+ root.flush()
183
+ } catch (error) {
184
+ fail(root, error)
185
+ }
186
+ return {
187
+ flush: root.flush,
188
+ dispose: () => {
189
+ dispose(root)
190
+ },
191
+ }
192
+ },
193
+ }
194
+ }
195
+
196
+ /** Define a typed scene component without introducing another JSX runtime. */
197
+ export function sceneComponent<P>(type: string): (props: P) => VNode {
198
+ return (props) => ({ type, props: props as Record<string, any> })
199
+ }
200
+
201
+ /** Bind imperative scene work to the current owner and its reactive dependencies. */
202
+ export function bindScene<T>(read: () => T, apply: (value: T) => void): void {
203
+ observe(owner!, read, apply)
204
+ }
205
+
206
+ /** Scene drawing follows an installed capability clock, or the browser clock. */
207
+ export function onSceneFrame(callback: (time: number) => void): void {
208
+ const scope = owner!
209
+ const clocks = [...scope._root._capabilities.values()].filter(
210
+ (capability) => capability.scheduleFrame,
211
+ )
212
+ if (clocks.length > 1)
213
+ throw new Error(`spa: multiple frame clock capabilities`)
214
+ const draw = (time: number) => {
215
+ if (scope._dead) return
216
+ try {
217
+ callback(time)
218
+ } catch (error) {
219
+ try {
220
+ fail(scope._root, error)
221
+ } catch (failure) {
222
+ scope._root.error(failure)
223
+ }
224
+ }
225
+ }
226
+ let stop: () => void
227
+ if (clocks[0]) stop = clocks[0].scheduleFrame!(draw)
228
+ else {
229
+ let frame = 0
230
+ const tick = (time: number) => {
231
+ if (scope._dead) return
232
+ draw(time)
233
+ if (!scope._dead) frame = requestAnimationFrame(tick)
234
+ }
235
+ frame = requestAnimationFrame(tick)
236
+ stop = () => {
237
+ cancelAnimationFrame(frame)
238
+ }
239
+ }
240
+ scope._cleanups.add(stop)
241
+ }
package/src/server.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { capabilityNamespace, validateCapabilities } from "./capabilities.ts"
1
2
  import type { Child, RootOptions, Scope, VNode } from "./core.ts"
2
3
  import {
3
4
  createRoot,
@@ -73,10 +74,12 @@ function stringify(
73
74
  if (type === `astro-slot`)
74
75
  return `<astro-slot${props[`name`] ? ` name="${escape(props[`name`])}"` : ``}>${props[`innerHTML`] ?? ``}</astro-slot>`
75
76
  const ns = type === `svg` ? `svg` : namespace
77
+ validateCapabilities(owner, props)
76
78
  let attrs = ``
77
79
  let textValue: string | number | undefined
78
80
  for (let key of Object.keys(props)) {
79
81
  if (
82
+ capabilityNamespace(key) !== undefined ||
80
83
  key === `children` ||
81
84
  key === `ref` ||
82
85
  key === `key` ||