@atom.io/spa 0.0.4 → 0.0.6

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 (151) hide show
  1. package/README.md +224 -105
  2. package/README.mdx +87 -20
  3. package/dist/astro-application.d.ts +1 -1
  4. package/dist/astro-client.d.ts +3 -2
  5. package/dist/astro-client.d.ts.map +1 -1
  6. package/dist/astro-client.js +9 -8
  7. package/dist/astro-client.js.map +1 -1
  8. package/dist/astro-request-DRKvDjsO.js.map +1 -1
  9. package/dist/astro-resumability-client.d.ts +10 -0
  10. package/dist/astro-resumability-client.d.ts.map +1 -0
  11. package/dist/astro-resumability-client.js +29 -0
  12. package/dist/astro-resumability-client.js.map +1 -0
  13. package/dist/astro-resumability-server.d.ts +3 -0
  14. package/dist/astro-resumability-server.d.ts.map +1 -0
  15. package/dist/astro-resumability-server.js +7 -0
  16. package/dist/astro-resumability-server.js.map +1 -0
  17. package/dist/astro-server.d.ts +3 -2
  18. package/dist/astro-server.d.ts.map +1 -1
  19. package/dist/astro-server.js +28 -9
  20. package/dist/astro-server.js.map +1 -1
  21. package/dist/{astro-shared-BT45auwR.js → astro-shared-83hxw7-M.js} +4 -2
  22. package/dist/astro-shared-83hxw7-M.js.map +1 -0
  23. package/dist/{astro-shared-CYSRrRr8.d.ts → astro-shared-B9wvGIkk.d.ts} +2 -2
  24. package/dist/{astro-shared-CYSRrRr8.d.ts.map → astro-shared-B9wvGIkk.d.ts.map} +1 -1
  25. package/dist/astro.d.ts +1 -1
  26. package/dist/astro.js +6 -8
  27. package/dist/astro.js.map +1 -1
  28. package/dist/{capabilities-D3HObAIy.d.ts → capabilities-_zOwNJ-2.d.ts} +12 -7
  29. package/dist/capabilities-_zOwNJ-2.d.ts.map +1 -0
  30. package/dist/{capabilities-BkQ2i0vV.js → capabilities-nOIitQ-_.js} +6 -4
  31. package/dist/capabilities-nOIitQ-_.js.map +1 -0
  32. package/dist/client.min.js +1 -1
  33. package/dist/{core-Bl1Ec1hY.js → core-DjFJ0aIJ.js} +4 -2
  34. package/dist/core-DjFJ0aIJ.js.map +1 -0
  35. package/dist/development/astro-client.js +9 -8
  36. package/dist/development/astro-client.js.map +1 -1
  37. package/dist/development/astro-request-DRKvDjsO.js.map +1 -1
  38. package/dist/development/astro-resumability-client.js +29 -0
  39. package/dist/development/astro-resumability-client.js.map +1 -0
  40. package/dist/development/astro-resumability-server.js +7 -0
  41. package/dist/development/astro-resumability-server.js.map +1 -0
  42. package/dist/development/astro-server.js +28 -9
  43. package/dist/development/astro-server.js.map +1 -1
  44. package/dist/development/{astro-shared-BT45auwR.js → astro-shared-83hxw7-M.js} +4 -2
  45. package/dist/development/astro-shared-83hxw7-M.js.map +1 -0
  46. package/dist/development/astro.js +6 -8
  47. package/dist/development/astro.js.map +1 -1
  48. package/dist/development/{capabilities-BkQ2i0vV.js → capabilities-nOIitQ-_.js} +6 -4
  49. package/dist/development/capabilities-nOIitQ-_.js.map +1 -0
  50. package/dist/development/{core-DZFaOyTO.js → core-DxPiKryn.js} +4 -2
  51. package/dist/development/core-DxPiKryn.js.map +1 -0
  52. package/dist/development/{dom-Dwa2SFTn.js → dom-BWy4dDss.js} +53 -20
  53. package/dist/development/dom-BWy4dDss.js.map +1 -0
  54. package/dist/development/floating.js +148 -0
  55. package/dist/development/floating.js.map +1 -0
  56. package/dist/development/index.js +3 -3
  57. package/dist/development/jsx-runtime.js +2 -2
  58. package/dist/development/jsx-runtime.js.map +1 -1
  59. package/dist/development/konva.js +2 -2
  60. package/dist/development/konva.js.map +1 -1
  61. package/dist/development/motion.js +7 -2
  62. package/dist/development/motion.js.map +1 -1
  63. package/dist/development/renderer.js +2 -2
  64. package/dist/development/renderer.js.map +1 -1
  65. package/dist/development/server-renderer-C7lGVhpo.js +90 -0
  66. package/dist/development/server-renderer-C7lGVhpo.js.map +1 -0
  67. package/dist/development/server.js +2 -83
  68. package/dist/development/server.js.map +1 -1
  69. package/dist/development/{src-BUtG4BgX.js → src-WSHJxR9b.js} +2 -2
  70. package/dist/development/{src-BUtG4BgX.js.map → src-WSHJxR9b.js.map} +1 -1
  71. package/dist/development/three.js +12 -9
  72. package/dist/development/three.js.map +1 -1
  73. package/dist/{vite-CSHoxzXU.js → development/vite-Bmyb6P5w.js} +32 -7
  74. package/dist/development/vite-Bmyb6P5w.js.map +1 -0
  75. package/dist/development/vite.js +1 -1
  76. package/dist/{dom-Cfj3GtQK.js → dom-BrPrxO97.js} +53 -20
  77. package/dist/dom-BrPrxO97.js.map +1 -0
  78. package/dist/floating.d.ts +16 -0
  79. package/dist/floating.d.ts.map +1 -0
  80. package/dist/floating.js +148 -0
  81. package/dist/floating.js.map +1 -0
  82. package/dist/{index-YRZ79lN5.d.ts → index-BFIjI7gF.d.ts} +5 -5
  83. package/dist/{index-YRZ79lN5.d.ts.map → index-BFIjI7gF.d.ts.map} +1 -1
  84. package/dist/index.d.ts +4 -4
  85. package/dist/index.js +3 -3
  86. package/dist/{jsx-runtime-Q-UBV97Y.d.ts → jsx-runtime-BhiCZOYZ.d.ts} +7 -7
  87. package/dist/{jsx-runtime-Q-UBV97Y.d.ts.map → jsx-runtime-BhiCZOYZ.d.ts.map} +1 -1
  88. package/dist/jsx-runtime.d.ts +1 -1
  89. package/dist/jsx-runtime.js +2 -2
  90. package/dist/jsx-runtime.js.map +1 -1
  91. package/dist/konva.d.ts +16 -16
  92. package/dist/konva.js +2 -2
  93. package/dist/konva.js.map +1 -1
  94. package/dist/motion.d.ts +1 -1
  95. package/dist/motion.d.ts.map +1 -1
  96. package/dist/motion.js +7 -2
  97. package/dist/motion.js.map +1 -1
  98. package/dist/renderer.d.ts +4 -4
  99. package/dist/renderer.d.ts.map +1 -1
  100. package/dist/renderer.js +2 -2
  101. package/dist/renderer.js.map +1 -1
  102. package/dist/server-renderer-D-uRg04V.js +90 -0
  103. package/dist/server-renderer-D-uRg04V.js.map +1 -0
  104. package/dist/server.d.ts +2 -2
  105. package/dist/server.d.ts.map +1 -1
  106. package/dist/server.js +2 -83
  107. package/dist/server.js.map +1 -1
  108. package/dist/size.json +16 -16
  109. package/dist/{src-DvkUMuNW.js → src-DWIqXCiz.js} +2 -2
  110. package/dist/{src-DvkUMuNW.js.map → src-DWIqXCiz.js.map} +1 -1
  111. package/dist/three.d.ts +17 -17
  112. package/dist/three.js +12 -9
  113. package/dist/three.js.map +1 -1
  114. package/dist/{development/vite-CSHoxzXU.js → vite-Bmyb6P5w.js} +32 -7
  115. package/dist/vite-Bmyb6P5w.js.map +1 -0
  116. package/dist/vite.js +1 -1
  117. package/package.json +39 -11
  118. package/src/astro-client.ts +17 -4
  119. package/src/astro-request.ts +1 -1
  120. package/src/astro-resumability-client.ts +40 -0
  121. package/src/astro-resumability-server.ts +7 -0
  122. package/src/astro-server.ts +58 -19
  123. package/src/astro-shared.ts +5 -2
  124. package/src/astro.ts +11 -3
  125. package/src/capabilities.ts +9 -4
  126. package/src/compiler.ts +28 -9
  127. package/src/core.ts +15 -10
  128. package/src/dom.ts +85 -50
  129. package/src/floating.ts +234 -0
  130. package/src/index.ts +2 -2
  131. package/src/jsx-runtime.ts +11 -7
  132. package/src/jsx-types.d.ts +2 -2
  133. package/src/konva.ts +3 -3
  134. package/src/motion.ts +11 -1
  135. package/src/presence.ts +1 -1
  136. package/src/renderer.ts +24 -18
  137. package/src/server-renderer.ts +162 -0
  138. package/src/server.ts +4 -153
  139. package/src/three-events.ts +14 -10
  140. package/src/three.ts +4 -4
  141. package/dist/astro-shared-BT45auwR.js.map +0 -1
  142. package/dist/capabilities-BkQ2i0vV.js.map +0 -1
  143. package/dist/capabilities-D3HObAIy.d.ts.map +0 -1
  144. package/dist/core-Bl1Ec1hY.js.map +0 -1
  145. package/dist/development/astro-shared-BT45auwR.js.map +0 -1
  146. package/dist/development/capabilities-BkQ2i0vV.js.map +0 -1
  147. package/dist/development/core-DZFaOyTO.js.map +0 -1
  148. package/dist/development/dom-Dwa2SFTn.js.map +0 -1
  149. package/dist/development/vite-CSHoxzXU.js.map +0 -1
  150. package/dist/dom-Cfj3GtQK.js.map +0 -1
  151. package/dist/vite-CSHoxzXU.js.map +0 -1
@@ -0,0 +1,234 @@
1
+ import type {
2
+ AutoUpdateOptions,
3
+ Middleware,
4
+ Placement,
5
+ ReferenceElement,
6
+ Strategy,
7
+ } from "@floating-ui/dom"
8
+ import { autoUpdate, computePosition } from "@floating-ui/dom"
9
+
10
+ import type {
11
+ Capability,
12
+ CapabilityBinding,
13
+ CapabilityTarget,
14
+ } from "./capabilities.ts"
15
+ import type { Scope } from "./core.ts"
16
+ import { fail, onMount, within } from "./core.ts"
17
+
18
+ export interface FloatingAttributes<Kind extends string = `dom`> {
19
+ [`floating:reference`]?: Kind extends `dom` ? ReferenceElement | null : never
20
+ [`floating:placement`]?: Kind extends `dom` ? Placement : never
21
+ [`floating:strategy`]?: Kind extends `dom` ? Strategy : never
22
+ [`floating:middleware`]?: Kind extends `dom` ? readonly Middleware[] : never
23
+ [`floating:enabled`]?: Kind extends `dom` ? boolean : never
24
+ [`floating:autoUpdate`]?: Kind extends `dom`
25
+ ? boolean | AutoUpdateOptions
26
+ : never
27
+ }
28
+
29
+ // eslint-disable-next-line quotes -- TypeScript module augmentation requires a string literal.
30
+ declare module "@atom.io/spa/jsx-runtime" {
31
+ // oxlint-disable-next-line typescript/no-empty-interface -- Declaration merging supplies optional floating attributes.
32
+ interface CapabilityAttributes<
33
+ Kind extends string,
34
+ > extends FloatingAttributes<Kind> {}
35
+ }
36
+
37
+ interface FloatingProps {
38
+ reference?: ReferenceElement | null
39
+ placement?: Placement
40
+ strategy?: Strategy
41
+ middleware?: readonly Middleware[]
42
+ enabled?: boolean
43
+ autoUpdate?: boolean | AutoUpdateOptions
44
+ }
45
+ const allowed = new Set([
46
+ `reference`,
47
+ `placement`,
48
+ `strategy`,
49
+ `middleware`,
50
+ `enabled`,
51
+ `autoUpdate`,
52
+ ])
53
+ const observerKeys = [
54
+ `ancestorScroll`,
55
+ `ancestorResize`,
56
+ `elementResize`,
57
+ `layoutShift`,
58
+ `animationFrame`,
59
+ ] as const
60
+ const ownedStyles = [
61
+ `position`,
62
+ `left`,
63
+ `top`,
64
+ `translate`,
65
+ `visibility`,
66
+ ] as const
67
+
68
+ function attach(target: CapabilityTarget, scope?: Scope): CapabilityBinding {
69
+ const element = target.node as HTMLElement
70
+ if (
71
+ target.kind !== `dom` ||
72
+ element?.namespaceURI !== `http://www.w3.org/1999/xhtml`
73
+ )
74
+ throw new Error(`spa/floating: floating elements must be HTML elements`)
75
+ let props: FloatingProps = {}
76
+ let dead = false
77
+ let mounted = false
78
+ let generation = 0
79
+ let request = 0
80
+ let stop: (() => void) | undefined
81
+ let reference: ReferenceElement | undefined
82
+ let observing: boolean | AutoUpdateOptions | undefined
83
+ let original: Map<string, { value: string; priority: string }> | undefined
84
+ let positioned = false
85
+ let translation = ``
86
+
87
+ const restore = () => {
88
+ if (!original) return
89
+ for (const [key, style] of original) {
90
+ if (style.value)
91
+ element.style.setProperty(key, style.value, style.priority)
92
+ else element.style.removeProperty(key)
93
+ }
94
+ original = undefined
95
+ positioned = false
96
+ translation = ``
97
+ }
98
+ const disconnect = () => {
99
+ ++generation
100
+ stop?.()
101
+ stop = undefined
102
+ reference = undefined
103
+ }
104
+ const report = (error: unknown) => {
105
+ if (!scope) {
106
+ queueMicrotask(() => {
107
+ throw error
108
+ })
109
+ return
110
+ }
111
+ try {
112
+ fail(scope._root, error)
113
+ } catch (failure) {
114
+ scope._root.error(failure)
115
+ }
116
+ }
117
+ const updatePosition = () => {
118
+ const anchor = reference
119
+ if (dead || !anchor) return
120
+ const currentGeneration = generation
121
+ const currentRequest = ++request
122
+ void computePosition(anchor, element, {
123
+ placement: props.placement ?? `bottom`,
124
+ strategy: props.strategy ?? `absolute`,
125
+ middleware: props.middleware ? [...props.middleware] : [],
126
+ }).then(
127
+ ({ x, y }) => {
128
+ if (
129
+ dead ||
130
+ generation !== currentGeneration ||
131
+ currentRequest !== request
132
+ )
133
+ return
134
+ translation = `${x}px ${y}px`
135
+ element.style.setProperty(`translate`, translation)
136
+ if (!positioned) {
137
+ positioned = true
138
+ const visibility = original!.get(`visibility`)!
139
+ if (visibility.value)
140
+ element.style.setProperty(
141
+ `visibility`,
142
+ visibility.value,
143
+ visibility.priority,
144
+ )
145
+ else element.style.removeProperty(`visibility`)
146
+ }
147
+ },
148
+ (error: unknown) => {
149
+ if (
150
+ !dead &&
151
+ generation === currentGeneration &&
152
+ currentRequest === request
153
+ )
154
+ report(error)
155
+ },
156
+ )
157
+ }
158
+ const connect = () => {
159
+ if (dead || !mounted) return
160
+ const nextReference =
161
+ props.enabled === false ? undefined : (props.reference ?? undefined)
162
+ const nextObserving = props.autoUpdate ?? true
163
+ const optionsChanged =
164
+ typeof nextObserving !== typeof observing ||
165
+ (typeof nextObserving === `object` && typeof observing === `object`
166
+ ? observerKeys.some(
167
+ (key) =>
168
+ nextObserving[key] !== (observing as AutoUpdateOptions)[key],
169
+ )
170
+ : nextObserving !== observing)
171
+ const reconnect = nextReference !== reference || optionsChanged
172
+ if (reconnect) disconnect()
173
+ if (!nextReference) {
174
+ restore()
175
+ return
176
+ }
177
+ original ??= new Map(
178
+ ownedStyles.map((key) => [
179
+ key,
180
+ {
181
+ value: element.style.getPropertyValue(key),
182
+ priority: element.style.getPropertyPriority(key),
183
+ },
184
+ ]),
185
+ )
186
+ element.style.setProperty(`position`, props.strategy ?? `absolute`)
187
+ element.style.setProperty(`left`, `0px`)
188
+ element.style.setProperty(`top`, `0px`)
189
+ if (positioned) element.style.setProperty(`translate`, translation)
190
+ else element.style.setProperty(`visibility`, `hidden`, `important`)
191
+ reference = nextReference
192
+ observing =
193
+ typeof nextObserving === `object` ? { ...nextObserving } : nextObserving
194
+ if (reconnect && nextObserving !== false) {
195
+ stop = autoUpdate(
196
+ nextReference,
197
+ element,
198
+ updatePosition,
199
+ typeof nextObserving === `object` ? nextObserving : undefined,
200
+ )
201
+ } else updatePosition()
202
+ }
203
+ const mount = () => {
204
+ if (dead) return
205
+ mounted = true
206
+ connect()
207
+ }
208
+ if (scope)
209
+ within(scope, () => {
210
+ onMount(mount)
211
+ })
212
+ else queueMicrotask(mount)
213
+ return {
214
+ update(next) {
215
+ if (dead) return
216
+ for (const key of Object.keys(next))
217
+ if (!allowed.has(key))
218
+ throw new Error(`spa/floating: unknown property floating:${key}`)
219
+ props = next
220
+ connect()
221
+ },
222
+ dispose() {
223
+ if (dead) return
224
+ dead = true
225
+ disconnect()
226
+ restore()
227
+ },
228
+ }
229
+ }
230
+
231
+ /** Position HTML overlays using CSS translate, leaving transform available to Motion. */
232
+ export function floatingCapability(): Capability {
233
+ return { namespace: `floating`, attach }
234
+ }
package/src/index.ts CHANGED
@@ -5,11 +5,11 @@ export type {
5
5
  } from "./capabilities.ts"
6
6
  export type {
7
7
  Accessor,
8
- Child,
8
+ Children,
9
9
  Component,
10
10
  RootOptions,
11
+ SpaElement,
11
12
  TimelineControls,
12
- VNode,
13
13
  } from "./core.ts"
14
14
  export {
15
15
  onCleanup,
@@ -1,4 +1,4 @@
1
- import type { Child, Component, VNode } from "./core.ts"
1
+ import type { Children, Component, SpaElement } from "./core.ts"
2
2
  import type { HTMLAttributes, NativeElements } from "./jsx-types.d.ts"
3
3
 
4
4
  export type {
@@ -16,12 +16,13 @@ export type {
16
16
  // oxlint-disable-next-line typescript/no-empty-interface -- Optional integrations augment this declaration.
17
17
  export interface CapabilityAttributes<Kind extends string = string> {}
18
18
 
19
- export const Fragment = (props: { children?: Child }): Child => props.children
19
+ export const Fragment = (props: { children?: Children }): Children =>
20
+ props.children
20
21
  export function jsx(
21
- type: VNode[`type`],
22
- props: VNode[`props`] | null,
22
+ type: SpaElement[`type`],
23
+ props: SpaElement[`props`] | null,
23
24
  key?: unknown,
24
- ): VNode {
25
+ ): SpaElement {
25
26
  return {
26
27
  type,
27
28
  props: key === undefined ? (props ?? {}) : merge(props ?? {}, { key }),
@@ -46,13 +47,16 @@ export function merge(
46
47
  .reverse()
47
48
  .find((source) => Object.hasOwn(source, key))?.[key],
48
49
  ownKeys: () => [...new Set(values().flatMap(Object.keys))],
49
- getOwnPropertyDescriptor: () => ({ enumerable: true, configurable: true }),
50
+ getOwnPropertyDescriptor: (_, key) =>
51
+ values().some((source) => Object.hasOwn(source, key))
52
+ ? { enumerable: true, configurable: true }
53
+ : undefined,
50
54
  },
51
55
  )
52
56
  }
53
57
 
54
58
  export namespace JSX {
55
- export type Element = VNode
59
+ export type Element = SpaElement
56
60
  export type ElementType = keyof IntrinsicElements | Component
57
61
  export interface ElementChildrenAttribute {
58
62
  children: {}
@@ -1,4 +1,4 @@
1
- import type { Child } from "./core.ts"
1
+ import type { Children } from "./core.ts"
2
2
  import type { CapabilityAttributes } from "./jsx-runtime.ts"
3
3
 
4
4
  /** Native events retain their target; only currentTarget is the attached element. */
@@ -200,7 +200,7 @@ export type DOMAttributes<E extends Element> = CapabilityAttributes<`dom`> &
200
200
  EventAttributes<E> &
201
201
  AriaAttributes &
202
202
  Attributes<{
203
- children: Child
203
+ children: Children
204
204
  key: string | number
205
205
  ref: Ref<E>
206
206
  id: string
package/src/konva.ts CHANGED
@@ -2,7 +2,7 @@ import Konva from "konva"
2
2
 
3
3
  import { capabilityProps } from "./capabilities.ts"
4
4
  import { owner } from "./core.ts"
5
- import type { Child, VNode } from "./index.ts"
5
+ import type { Children, SpaElement } from "./index.ts"
6
6
  import { onCleanup, onMount } from "./index.ts"
7
7
  import type { CapabilityAttributes } from "./jsx-runtime.ts"
8
8
  import { jsx } from "./jsx-runtime.ts"
@@ -10,7 +10,7 @@ import { bindScene, createSceneRenderer, sceneComponent } from "./renderer.ts"
10
10
 
11
11
  type Props<C, N> = C &
12
12
  CapabilityAttributes<`konva`> & {
13
- children?: Child
13
+ children?: Children
14
14
  ref?: (node: N | null) => void
15
15
  onClick?: (event: Konva.KonvaEventObject<MouseEvent>) => void
16
16
  onPointerDown?: (event: Konva.KonvaEventObject<PointerEvent>) => void
@@ -106,7 +106,7 @@ export function Stage(
106
106
  width?: number
107
107
  height?: number
108
108
  },
109
- ): VNode {
109
+ ): SpaElement {
110
110
  let container: HTMLDivElement | null = null
111
111
  onMount(() => {
112
112
  // Konva clears its container; preserve SPA's markers in the outer element.
package/src/motion.ts CHANGED
@@ -464,7 +464,7 @@ function attach(
464
464
  installGestures()
465
465
  refresh(true)
466
466
  },
467
- update(next) {
467
+ update(next, previousStyle) {
468
468
  if (dead) return
469
469
  for (const key of Object.keys(next))
470
470
  if (!allowed.has(key))
@@ -475,6 +475,16 @@ function attach(
475
475
  Boolean(next[`whileTap`]) !== Boolean(props[`whileTap`])
476
476
  props = next
477
477
  if (gestureChange && !exiting) installGestures()
478
+ if (previousStyle !== undefined && started && element) {
479
+ const snapshot = element.ownerDocument.createElement(`div`).style
480
+ snapshot.cssText = previousStyle
481
+ for (const key of originalStyles.keys())
482
+ element.style.setProperty(
483
+ key,
484
+ snapshot.getPropertyValue(key),
485
+ snapshot.getPropertyPriority(key),
486
+ )
487
+ }
478
488
  refresh()
479
489
  },
480
490
  dispose() {
package/src/presence.ts CHANGED
@@ -15,7 +15,7 @@ export interface PresenceTarget {
15
15
  node: unknown
16
16
  suspend?(): Cleanup
17
17
  }
18
- export interface PresenceCollection<T, V> {
18
+ interface PresenceCollection<T, V> {
19
19
  take(key: unknown, value: V): T | undefined
20
20
  remove(
21
21
  record: T,
package/src/renderer.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import type { CapabilityTarget } from "./capabilities.ts"
2
2
  import { capabilityProps } from "./capabilities.ts"
3
- import type { Child, Component, RootOptions, Scope, VNode } from "./core.ts"
3
+ import type {
4
+ Children,
5
+ Component,
6
+ RootOptions,
7
+ Scope,
8
+ SpaElement,
9
+ } from "./core.ts"
4
10
  import {
5
11
  createRoot,
6
12
  createScope,
@@ -30,14 +36,14 @@ type SceneNodes<N> = (activeOnly?: boolean) => N[]
30
36
 
31
37
  interface Entry<N> {
32
38
  scope: Scope
33
- value: Child
39
+ value: Children
34
40
  nodes: SceneNodes<N>
35
41
  }
36
42
 
37
43
  export interface SceneRenderer<N> {
38
- mount(setup: () => Child, parent: N): void
44
+ mount(setup: () => Children, parent: N): void
39
45
  render(
40
- setup: () => Child,
46
+ setup: () => Children,
41
47
  parent: N,
42
48
  options?: RootOptions,
43
49
  ): { flush(): void; dispose(): void }
@@ -46,12 +52,12 @@ export interface SceneRenderer<N> {
46
52
  /** A scene renderer shares SPA's owner, store, scheduler, and component lifecycle. */
47
53
  export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
48
54
  function mount(
49
- source: () => Child,
55
+ source: () => Children,
50
56
  scope: Scope,
51
57
  changed: () => void,
52
58
  ): SceneNodes<N> {
53
59
  let entries: Entry<N>[] = []
54
- const presence = scope._root._presence?.collection<Entry<N>, Child>(
60
+ const presence = scope._root._presence?.collection<Entry<N>, Children>(
55
61
  (entry) => entry.scope,
56
62
  (entry, value) => same(entry.value, value),
57
63
  )
@@ -70,7 +76,7 @@ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
70
76
  observe(scope, source, (next) => {
71
77
  const values = (
72
78
  Array.isArray(next) ? next.flat(Infinity) : [next]
73
- ) as Child[]
79
+ ) as Children[]
74
80
  const previous = entries
75
81
  const old = new Map(
76
82
  entries.map((entry, i) => [key(entry.value, i), entry]),
@@ -114,31 +120,31 @@ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
114
120
  return rendered.flatMap((entry) => entry.nodes(activeOnly))
115
121
  }
116
122
  }
117
- function key(value: Child, i: number): string {
118
- const explicit = (value as VNode | null)?.props?.[`key`]
123
+ function key(value: Children, i: number): string {
124
+ const explicit = (value as SpaElement | null)?.props?.[`key`]
119
125
  return explicit == null ? `index:${i}` : `key:${explicit}`
120
126
  }
121
- function same(a: Child, b: Child): boolean {
127
+ function same(a: Children, b: Children): boolean {
122
128
  return (
123
129
  typeof a === typeof b &&
124
- (a as VNode | null)?.type === (b as VNode | null)?.type
130
+ (a as SpaElement | null)?.type === (b as SpaElement | null)?.type
125
131
  )
126
132
  }
127
133
  function build(
128
- source: () => Child,
134
+ source: () => Children,
129
135
  scope: Scope,
130
136
  changed: () => void,
131
137
  ): SceneNodes<N> {
132
138
  const value = untrack(source)
133
139
  if (typeof value === `function`)
134
- return mount(() => (source() as () => Child)(), scope, changed)
140
+ return mount(() => (source() as () => Children)(), scope, changed)
135
141
  if (value == null || typeof value === `boolean`) return () => []
136
142
  if (typeof value !== `object`)
137
143
  throw new Error(`spa: scene children must be nodes`)
138
144
  if (!(`type` in value) || !(`props` in value))
139
145
  throw new Error(`spa: invalid scene child`)
140
146
  const vnode = value
141
- const props = merge(() => (source() as VNode).props)
147
+ const props = merge(() => (source() as SpaElement).props)
142
148
  if (!vnode.type || vnode.type === Fragment)
143
149
  return mount(() => props[`children`], scope, changed)
144
150
  if (typeof vnode.type === `function`) {
@@ -185,7 +191,7 @@ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
185
191
  })
186
192
  return () => [node]
187
193
  }
188
- function attach(setup: () => Child, parent: N, scope: Scope) {
194
+ function attach(setup: () => Children, parent: N, scope: Scope) {
189
195
  let nodes: SceneNodes<N> = () => []
190
196
  const sync = () => {
191
197
  host.children(parent, nodes(), nodes(true))
@@ -198,7 +204,7 @@ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
198
204
  }
199
205
  return {
200
206
  /** Attach beneath the current component; disposal follows its lifetime. */
201
- mount(setup: () => Child, parent: N): void {
207
+ mount(setup: () => Children, parent: N): void {
202
208
  if (!owner) throw new Error(`spa: scene mount requires an owner`)
203
209
  const scope = createScope(owner)
204
210
  try {
@@ -207,7 +213,7 @@ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
207
213
  fail(scope, error)
208
214
  }
209
215
  },
210
- render(setup: () => Child, parent: N, options: RootOptions = {}) {
216
+ render(setup: () => Children, parent: N, options: RootOptions = {}) {
211
217
  const root = createRoot(options)
212
218
  try {
213
219
  within(root, () => {
@@ -228,7 +234,7 @@ export function createSceneRenderer<N>(host: SceneHost<N>): SceneRenderer<N> {
228
234
  }
229
235
 
230
236
  /** Define a typed scene component without introducing another JSX runtime. */
231
- export function sceneComponent<P>(type: string): (props: P) => VNode {
237
+ export function sceneComponent<P>(type: string): (props: P) => SpaElement {
232
238
  return (props) => ({ type, props: props as Record<string, any> })
233
239
  }
234
240
 
@@ -0,0 +1,162 @@
1
+ import type { ReadableToken } from "atom.io"
2
+
3
+ import { capabilityNamespace, validateCapabilities } from "./capabilities.ts"
4
+ import type { Children, RootOptions, Scope, SpaElement } from "./core.ts"
5
+ import {
6
+ createRoot,
7
+ createScope,
8
+ dispose,
9
+ plain,
10
+ untrack,
11
+ within,
12
+ } from "./core.ts"
13
+ import { Fragment } from "./jsx-runtime.ts"
14
+
15
+ const escape = (value: unknown): string =>
16
+ String(value).replace(
17
+ /[&<>"']/g,
18
+ (char) =>
19
+ ({ "&": `&amp;`, "<": `&lt;`, ">": `&gt;`, '"': `&quot;`, "'": `&#39;` })[
20
+ char
21
+ ]!,
22
+ )
23
+ const voidTags =
24
+ /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/
25
+ const booleans = new Set(
26
+ `allowfullscreen async autofocus autoplay checked controls credentialless default defer disabled disablepictureinpicture disableremoteplayback formnovalidate inert ismap itemscope loop multiple muted nomodule novalidate open playsinline readonly required reversed selected shadowrootclonable shadowrootdelegatesfocus shadowrootserializable`.split(
27
+ ` `,
28
+ ),
29
+ )
30
+ function stringify(
31
+ value: Children,
32
+ owner: Scope,
33
+ namespace = `html`,
34
+ selectValue?: string | number,
35
+ ): string {
36
+ if (typeof value === `function`) {
37
+ const values = ([untrack(value)] as unknown[]).flat(Infinity) as Children[]
38
+ const keys = new Set<unknown>()
39
+ return (
40
+ `<!--{-->` +
41
+ values
42
+ .map((child, index) => {
43
+ const explicit = (child as SpaElement | null)?.props?.[`key`]
44
+ const key = explicit == null ? index : String(explicit)
45
+ if (keys.has(key)) throw new Error(`spa: duplicate key`)
46
+ keys.add(key)
47
+ return `<!--[-->${within(owner, () => stringify(child, createScope(owner), namespace, selectValue))}<!--]-->`
48
+ })
49
+ .join(``) +
50
+ `<!--}-->`
51
+ )
52
+ }
53
+ if (Array.isArray(value))
54
+ return value
55
+ .map((child) => stringify(child, owner, namespace, selectValue))
56
+ .join(``)
57
+ if (value == null || typeof value === `boolean`) return ``
58
+ if (typeof value !== `object`) return `<!--t-->${escape(value)}`
59
+ if (!(`type` in value) || !(`props` in value))
60
+ throw new TypeError(`spa: invalid child`)
61
+ const { type, props } = value
62
+ if (!type || type === Fragment)
63
+ return stringify(() => props[`children`], owner, namespace, selectValue)
64
+ if (typeof type === `function`) {
65
+ const childOwner = createScope(owner)
66
+ return within(childOwner, () =>
67
+ stringify(
68
+ untrack(() => type(props)),
69
+ childOwner,
70
+ namespace,
71
+ selectValue,
72
+ ),
73
+ )
74
+ }
75
+ if (!/^[A-Za-z][\w.:-]*$/.test(type)) throw new Error(`spa: invalid tag`)
76
+ if (type === `astro-slot`)
77
+ return `<astro-slot${props[`name`] ? ` name="${escape(props[`name`])}"` : ``}>${props[`innerHTML`] ?? ``}</astro-slot>`
78
+ const ns = type === `svg` ? `svg` : namespace
79
+ validateCapabilities(owner, props)
80
+ let attrs = ``
81
+ let textValue: string | number | undefined
82
+ for (let key of Object.keys(props)) {
83
+ if (
84
+ capabilityNamespace(key) !== undefined ||
85
+ key === `children` ||
86
+ key === `ref` ||
87
+ key === `key` ||
88
+ key.startsWith(`on`)
89
+ )
90
+ continue
91
+ if (
92
+ /^(innerHTML|outerHTML|textContent|innerText|dangerouslySetInnerHTML)$/.test(
93
+ key,
94
+ )
95
+ )
96
+ throw new Error(`spa: owned content`)
97
+ let attribute = props[key]
98
+ if (ns === `html`) {
99
+ if (key === `defaultValue` && (type === `input` || type === `textarea`)) {
100
+ if (props[`value`] != null) continue
101
+ key = `value`
102
+ } else if (key === `defaultChecked` && type === `input`) {
103
+ if (props[`checked`] != null) continue
104
+ key = `checked`
105
+ }
106
+ }
107
+ if (key === `className`) key = `class`
108
+ if (key === `htmlFor`) key = `for`
109
+ if (!/^[^\s"'<>/=]+$/.test(key)) throw new Error(`spa: invalid attribute`)
110
+ if (key === `value` && (type === `select` || type === `textarea`)) {
111
+ textValue = attribute ?? textValue
112
+ continue
113
+ }
114
+ if (key === `style` && attribute != null && typeof attribute !== `string`)
115
+ throw new TypeError(`spa: CSS string required`)
116
+ const boolean =
117
+ ns === `html` &&
118
+ (booleans.has(key.toLowerCase()) ||
119
+ (/^(capture|download|hidden)$/.test(key) &&
120
+ typeof attribute === `boolean`))
121
+ if (attribute == null || (boolean && !attribute)) continue
122
+ attrs += boolean ? ` ${key}=""` : ` ${key}="${escape(attribute)}"`
123
+ }
124
+ if (
125
+ type === `option` &&
126
+ selectValue !== undefined &&
127
+ String(props[`value`]) === String(selectValue)
128
+ )
129
+ attrs += ` selected=""`
130
+ if (ns === `html` && voidTags.test(type)) return `<${type}${attrs}>`
131
+ if (ns === `html` && /^(textarea|title|style|script)$/.test(type)) {
132
+ let text = plain(
133
+ type === `textarea` ? (textValue ?? props[`children`]) : props[`children`],
134
+ )
135
+ if (type === `textarea` && text.startsWith(`\n`)) text = `\n${text}`
136
+ if (/^(script|style)$/.test(type) && new RegExp(`</${type}`, `i`).test(text))
137
+ throw new Error(`spa: unsafe raw text`)
138
+ return `<${type}${attrs}>${/^(script|style)$/.test(type) ? text : escape(text)}</${type}>`
139
+ }
140
+ const children = stringify(
141
+ () => props[`children`],
142
+ owner,
143
+ type === `foreignObject` ? `html` : ns,
144
+ type === `select` ? textValue : selectValue,
145
+ )
146
+ return `<${type}${attrs}>${children}</${type}>`
147
+ }
148
+
149
+ export function renderToStringWithReads(
150
+ setup: () => Children,
151
+ options: RootOptions = {},
152
+ onRead?: (value: unknown, token: ReadableToken<unknown>) => void,
153
+ ): string {
154
+ const root = createRoot(options, true)
155
+ root._onRead = onRead
156
+ if (/--|[<>]/.test(root._prefix)) throw new Error(`spa: invalid idPrefix`)
157
+ try {
158
+ return `<!--w:${root._prefix}-->${within(root, () => stringify(untrack(setup), root))}<!--/w-->`
159
+ } finally {
160
+ dispose(root)
161
+ }
162
+ }