@atom.io/spa 0.0.8 → 0.0.10

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 (185) hide show
  1. package/README.md +194 -30
  2. package/README.mdx +78 -20
  3. package/dist/BrandMarkScene-CBYk-RJ2.js +140 -0
  4. package/dist/BrandMarkScene-CBYk-RJ2.js.map +1 -0
  5. package/dist/astro-application.d.ts +1 -1
  6. package/dist/astro-client.d.ts +1 -1
  7. package/dist/astro-client.d.ts.map +1 -1
  8. package/dist/astro-client.js +5 -4
  9. package/dist/astro-client.js.map +1 -1
  10. package/dist/astro-resumability-client.d.ts +1 -1
  11. package/dist/astro-server.js +4 -4
  12. package/dist/astro-server.js.map +1 -1
  13. package/dist/{astro-shared-83hxw7-M.js → astro-shared-DBwINQav.js} +2 -2
  14. package/dist/{astro-shared-83hxw7-M.js.map → astro-shared-DBwINQav.js.map} +1 -1
  15. package/dist/{astro-shared-DZp1x8RQ.d.ts → astro-shared-KxK9OUSj.d.ts} +2 -2
  16. package/dist/{astro-shared-DZp1x8RQ.d.ts.map → astro-shared-KxK9OUSj.d.ts.map} +1 -1
  17. package/dist/astro.d.ts +1 -1
  18. package/dist/astro.js +1 -1
  19. package/dist/brand-css.d.ts +2 -0
  20. package/dist/brand-model.d.ts +32 -0
  21. package/dist/brand-model.d.ts.map +1 -0
  22. package/dist/brand-model.js +120 -0
  23. package/dist/brand-model.js.map +1 -0
  24. package/dist/brand.css +37 -0
  25. package/dist/brand.d.ts +13 -0
  26. package/dist/brand.d.ts.map +1 -0
  27. package/dist/brand.js +94 -0
  28. package/dist/brand.js.map +1 -0
  29. package/dist/{capabilities-DNcnGRv_.d.ts → capabilities-ChgSs6bp.d.ts} +34 -6
  30. package/dist/capabilities-ChgSs6bp.d.ts.map +1 -0
  31. package/dist/client.min.js +1 -1
  32. package/dist/core-DD2giR6E.js +451 -0
  33. package/dist/core-DD2giR6E.js.map +1 -0
  34. package/dist/development/BrandMarkScene-BDdC7K5M.js +140 -0
  35. package/dist/development/BrandMarkScene-BDdC7K5M.js.map +1 -0
  36. package/dist/development/astro-client.js +5 -4
  37. package/dist/development/astro-client.js.map +1 -1
  38. package/dist/development/astro-server.js +4 -4
  39. package/dist/development/astro-server.js.map +1 -1
  40. package/dist/development/{astro-shared-83hxw7-M.js → astro-shared-DBwINQav.js} +2 -2
  41. package/dist/development/{astro-shared-83hxw7-M.js.map → astro-shared-DBwINQav.js.map} +1 -1
  42. package/dist/development/astro.js +1 -1
  43. package/dist/development/brand-model.js +120 -0
  44. package/dist/development/brand-model.js.map +1 -0
  45. package/dist/development/brand.css +37 -0
  46. package/dist/development/brand.js +94 -0
  47. package/dist/development/brand.js.map +1 -0
  48. package/dist/development/core-DrUd8x25.js +465 -0
  49. package/dist/development/core-DrUd8x25.js.map +1 -0
  50. package/dist/development/{dom-DQ0M3rLL.js → dom-CEVtlaav.js} +152 -36
  51. package/dist/development/dom-CEVtlaav.js.map +1 -0
  52. package/dist/development/floating.js +2 -6
  53. package/dist/development/floating.js.map +1 -1
  54. package/dist/development/hot.js +164 -0
  55. package/dist/development/hot.js.map +1 -0
  56. package/dist/development/identity-B8wTFkyW.js +121 -0
  57. package/dist/development/identity-B8wTFkyW.js.map +1 -0
  58. package/dist/development/index.js +5 -5
  59. package/dist/development/jsx-runtime-BGDPK50B.js +49 -0
  60. package/dist/development/jsx-runtime-BGDPK50B.js.map +1 -0
  61. package/dist/development/jsx-runtime.js +1 -25
  62. package/dist/development/konva.js +12 -5
  63. package/dist/development/konva.js.map +1 -1
  64. package/dist/development/motion.js +41 -39
  65. package/dist/development/motion.js.map +1 -1
  66. package/dist/development/renderer.js +41 -40
  67. package/dist/development/renderer.js.map +1 -1
  68. package/dist/development/{server-renderer-DCLoMdOX.js → server-renderer-zAqEL1g1.js} +8 -18
  69. package/dist/development/server-renderer-zAqEL1g1.js.map +1 -0
  70. package/dist/development/server.js +1 -1
  71. package/dist/{src-Bme1kz2b.js → development/src-CB7ruwRs.js} +3 -3
  72. package/dist/development/src-CB7ruwRs.js.map +1 -0
  73. package/dist/development/three-CsZ6Od1C.js +527 -0
  74. package/dist/development/three-CsZ6Od1C.js.map +1 -0
  75. package/dist/development/three.js +1 -508
  76. package/dist/development/vite-WUiz1ju6.js +545 -0
  77. package/dist/development/vite-WUiz1ju6.js.map +1 -0
  78. package/dist/development/vite.js +1 -1
  79. package/dist/{dom-D8g3roX9.js → dom-DUpa3Sj2.js} +141 -33
  80. package/dist/dom-DUpa3Sj2.js.map +1 -0
  81. package/dist/floating.d.ts +1 -1
  82. package/dist/floating.d.ts.map +1 -1
  83. package/dist/floating.js +2 -6
  84. package/dist/floating.js.map +1 -1
  85. package/dist/hot.d.ts +15 -0
  86. package/dist/hot.d.ts.map +1 -0
  87. package/dist/hot.js +19 -0
  88. package/dist/hot.js.map +1 -0
  89. package/dist/identity-ByJswZtF.js +121 -0
  90. package/dist/identity-ByJswZtF.js.map +1 -0
  91. package/dist/{index-BFnXIfOj.d.ts → index-DdA39aMv.d.ts} +4 -4
  92. package/dist/{index-BFnXIfOj.d.ts.map → index-DdA39aMv.d.ts.map} +1 -1
  93. package/dist/index.d.ts +4 -4
  94. package/dist/index.js +5 -5
  95. package/dist/jsx-runtime-BGDPK50B.js +49 -0
  96. package/dist/jsx-runtime-BGDPK50B.js.map +1 -0
  97. package/dist/{jsx-runtime-DQnpyT_g.d.ts → jsx-runtime-CCvcEosg.d.ts} +14 -9
  98. package/dist/jsx-runtime-CCvcEosg.d.ts.map +1 -0
  99. package/dist/jsx-runtime.d.ts +1 -1
  100. package/dist/jsx-runtime.js +1 -25
  101. package/dist/konva.d.ts +46 -9
  102. package/dist/konva.d.ts.map +1 -1
  103. package/dist/konva.js +12 -5
  104. package/dist/konva.js.map +1 -1
  105. package/dist/motion.d.ts +3 -1
  106. package/dist/motion.d.ts.map +1 -1
  107. package/dist/motion.js +41 -39
  108. package/dist/motion.js.map +1 -1
  109. package/dist/renderer.d.ts +1 -1
  110. package/dist/renderer.d.ts.map +1 -1
  111. package/dist/renderer.js +39 -40
  112. package/dist/renderer.js.map +1 -1
  113. package/dist/{server-renderer-D0rsFL_-.js → server-renderer-D7CdyOMo.js} +8 -18
  114. package/dist/server-renderer-D7CdyOMo.js.map +1 -0
  115. package/dist/server.d.ts +1 -1
  116. package/dist/server.js +1 -1
  117. package/dist/size.json +12 -12
  118. package/dist/{development/src-DoQgCX-O.js → src-B2W_TA_X.js} +3 -3
  119. package/dist/src-B2W_TA_X.js.map +1 -0
  120. package/dist/three-DcYxRXPW.js +527 -0
  121. package/dist/three-DcYxRXPW.js.map +1 -0
  122. package/dist/three.d.ts +24 -3
  123. package/dist/three.d.ts.map +1 -1
  124. package/dist/three.js +1 -508
  125. package/dist/vite-WUiz1ju6.js +545 -0
  126. package/dist/vite-WUiz1ju6.js.map +1 -0
  127. package/dist/vite.d.ts.map +1 -1
  128. package/dist/vite.js +1 -1
  129. package/package.json +45 -18
  130. package/src/BrandMark.module.css +25 -0
  131. package/src/BrandMark.tsx +106 -0
  132. package/src/BrandMarkScene.module.css +10 -0
  133. package/src/BrandMarkScene.tsx +116 -0
  134. package/src/astro-client.ts +3 -2
  135. package/src/astro-server.ts +2 -2
  136. package/src/brand-css.d.ts +2 -0
  137. package/src/brand-model.ts +177 -0
  138. package/src/brand.ts +3 -0
  139. package/src/capabilities.ts +48 -21
  140. package/src/compiler-hmr.ts +297 -0
  141. package/src/compiler.ts +127 -25
  142. package/src/core.ts +282 -33
  143. package/src/dom-forms.ts +127 -0
  144. package/src/dom.ts +124 -53
  145. package/src/floating.ts +2 -6
  146. package/src/hot.ts +191 -0
  147. package/src/identity.ts +39 -0
  148. package/src/index.ts +2 -0
  149. package/src/jsx-runtime.ts +6 -26
  150. package/src/jsx-types.d.ts +8 -3
  151. package/src/konva.ts +66 -10
  152. package/src/lasertag.d.ts +1 -0
  153. package/src/motion-layout.ts +55 -26
  154. package/src/motion.ts +3 -0
  155. package/src/presence.ts +11 -23
  156. package/src/props.ts +55 -0
  157. package/src/renderer.ts +91 -71
  158. package/src/server-renderer.ts +18 -13
  159. package/src/three.ts +92 -46
  160. package/src/use-loadable.ts +2 -2
  161. package/src/vite.ts +44 -4
  162. package/dist/capabilities-DNcnGRv_.d.ts.map +0 -1
  163. package/dist/capabilities-nOIitQ-_.js +0 -65
  164. package/dist/capabilities-nOIitQ-_.js.map +0 -1
  165. package/dist/core-B4rJ0xdc.js +0 -268
  166. package/dist/core-B4rJ0xdc.js.map +0 -1
  167. package/dist/development/capabilities-nOIitQ-_.js +0 -65
  168. package/dist/development/capabilities-nOIitQ-_.js.map +0 -1
  169. package/dist/development/core-BHA7I1nf.js +0 -271
  170. package/dist/development/core-BHA7I1nf.js.map +0 -1
  171. package/dist/development/dom-DQ0M3rLL.js.map +0 -1
  172. package/dist/development/jsx-runtime.js.map +0 -1
  173. package/dist/development/server-renderer-DCLoMdOX.js.map +0 -1
  174. package/dist/development/src-DoQgCX-O.js.map +0 -1
  175. package/dist/development/three.js.map +0 -1
  176. package/dist/development/vite-Bmyb6P5w.js +0 -265
  177. package/dist/development/vite-Bmyb6P5w.js.map +0 -1
  178. package/dist/dom-D8g3roX9.js.map +0 -1
  179. package/dist/jsx-runtime-DQnpyT_g.d.ts.map +0 -1
  180. package/dist/jsx-runtime.js.map +0 -1
  181. package/dist/server-renderer-D0rsFL_-.js.map +0 -1
  182. package/dist/src-Bme1kz2b.js.map +0 -1
  183. package/dist/three.js.map +0 -1
  184. package/dist/vite-Bmyb6P5w.js +0 -265
  185. package/dist/vite-Bmyb6P5w.js.map +0 -1
package/src/compiler.ts CHANGED
@@ -11,6 +11,16 @@ import type {
11
11
  import { parseSync, visitorKeys } from "oxc-parser"
12
12
 
13
13
  type Part = string | Node
14
+ type FunctionNode = Extract<
15
+ Node,
16
+ {
17
+ type:
18
+ | `FunctionDeclaration`
19
+ | `FunctionExpression`
20
+ | `ArrowFunctionExpression`
21
+ }
22
+ >
23
+ type JSXNode = JSXElement | JSXFragment
14
24
 
15
25
  const decodeJsx = (value: string): string =>
16
26
  decode(value, { level: `html4`, scope: `strict` })
@@ -42,6 +52,26 @@ function eager(node: Node, allowJsx = false): boolean {
42
52
  )
43
53
  }
44
54
 
55
+ function containsSuspension(node: Node): boolean {
56
+ if (isFunction(node)) return false
57
+ if (node.type === `AwaitExpression` || node.type === `YieldExpression`)
58
+ return true
59
+ return visitorKeys[node.type].some((key) => {
60
+ const value = (node as unknown as Record<string, unknown>)[key]
61
+ return Array.isArray(value)
62
+ ? value.some((child) => child && containsSuspension(child))
63
+ : Boolean(value && containsSuspension(value as Node))
64
+ })
65
+ }
66
+
67
+ function isFunction(node: Node): node is FunctionNode {
68
+ return (
69
+ node.type === `FunctionDeclaration` ||
70
+ node.type === `FunctionExpression` ||
71
+ node.type === `ArrowFunctionExpression`
72
+ )
73
+ }
74
+
45
75
  export function compile(
46
76
  code: string,
47
77
  filename: string,
@@ -61,7 +91,8 @@ export function compile(
61
91
  const output = new MagicString(code)
62
92
  const parents = new WeakMap<Node, Node>()
63
93
  const identifiers = new Set<string>()
64
- const elements: (JSXElement | JSXFragment)[] = []
94
+ const elements: JSXNode[] = []
95
+ const receivers: Node[] = []
65
96
  const functions = new Set<Node>()
66
97
  function walk(node: Node, parent?: Node, outerFunction?: Node): void {
67
98
  if (parent) parents.set(node, parent)
@@ -69,13 +100,15 @@ export function compile(
69
100
  output.addSourcemapLocation(node.end)
70
101
  if (node.type === `Identifier` || node.type === `JSXIdentifier`)
71
102
  identifiers.add(node.name)
103
+ if (!outerFunction && isFunction(node)) outerFunction = node
72
104
  if (
73
- !outerFunction &&
74
- (node.type === `FunctionDeclaration` ||
75
- node.type === `FunctionExpression` ||
76
- node.type === `ArrowFunctionExpression`)
105
+ node.type === `ThisExpression` ||
106
+ (node.type === `JSXIdentifier` &&
107
+ node.name === `this` &&
108
+ ((parent?.type === `JSXMemberExpression` && parent.object === node) ||
109
+ (parent?.type === `JSXOpeningElement` && parent.name === node)))
77
110
  )
78
- outerFunction = node
111
+ receivers.push(node)
79
112
  if (node.type === `JSXElement` || node.type === `JSXFragment`) {
80
113
  elements.push(node)
81
114
  if (outerFunction) functions.add(outerFunction)
@@ -97,6 +130,43 @@ export function compile(
97
130
  }
98
131
  const create = uid(`spa`)
99
132
  const merge = uid(`props`)
133
+ const captures = new Map<
134
+ Node,
135
+ {
136
+ name: string
137
+ scope: FunctionNode | undefined
138
+ root: JSXNode
139
+ }
140
+ >()
141
+ const tagReceivers = new WeakMap<Node, string>()
142
+ for (const reference of receivers) {
143
+ let root: JSXNode | undefined
144
+ let ancestor = parents.get(reference)
145
+ // Arrows inside a JSX tree share its receiver. A normal function starts
146
+ // a separate receiver scope for any JSX it contains.
147
+ while (
148
+ ancestor &&
149
+ (!isFunction(ancestor) || ancestor.type === `ArrowFunctionExpression`)
150
+ ) {
151
+ if (ancestor.type === `JSXElement` || ancestor.type === `JSXFragment`)
152
+ root = ancestor
153
+ ancestor = parents.get(ancestor)
154
+ }
155
+ if (!root) continue
156
+ let scope = parents.get(root)
157
+ while (scope && !isFunction(scope)) scope = parents.get(scope)
158
+ // Default parameters run before declarations in the function body.
159
+ if (scope && root.start < scope.body.start) scope = undefined
160
+ const enclosing = scope ?? root
161
+ let capture = captures.get(enclosing)
162
+ if (!capture) {
163
+ capture = { name: uid(`self$`), scope, root }
164
+ captures.set(enclosing, capture)
165
+ }
166
+ if (reference.type === `ThisExpression`)
167
+ output.update(reference.start, reference.end, capture.name)
168
+ else tagReceivers.set(reference, capture.name)
169
+ }
100
170
  const join = (parts: Part[][], separator: string): Part[] =>
101
171
  parts.flatMap((part, i) => (i ? [separator, ...part] : part))
102
172
  const expression = (node: Expression): Part[] =>
@@ -104,12 +174,24 @@ export function compile(
104
174
  function tag(node: JSXElementName): string {
105
175
  if (node.type === `JSXNamespacedName`)
106
176
  return JSON.stringify(`${node.namespace.name}:${node.name.name}`)
107
- if (node.type === `JSXMemberExpression`)
108
- return code.slice(node.start, node.end)
177
+ if (node.type === `JSXMemberExpression`) {
178
+ let root = node.object
179
+ while (root.type === `JSXMemberExpression`) root = root.object
180
+ return (
181
+ (tagReceivers.get(root) ?? root.name) + code.slice(root.end, node.end)
182
+ )
183
+ }
184
+ if (tagReceivers.has(node)) return tagReceivers.get(node)!
109
185
  return /^[a-z]/.test(node.name) || node.name.includes(`-`)
110
186
  ? JSON.stringify(node.name)
111
187
  : node.name
112
188
  }
189
+ function checkAttribute(node: Node, name: string): void {
190
+ if (containsSuspension(node))
191
+ throw new SyntaxError(
192
+ `${filename}: JSX attribute ${JSON.stringify(name)} cannot contain await or yield outside a nested function`,
193
+ )
194
+ }
113
195
  /** Rewrite syntax around untouched expression spans, including nested JSX. */
114
196
  function rewrite(node: JSXElement | JSXFragment, parts: Part[]): void {
115
197
  let cursor = node.start
@@ -137,15 +219,16 @@ export function compile(
137
219
  if (node.type === `JSXElement`) {
138
220
  for (const attribute of node.openingElement.attributes) {
139
221
  if (attribute.type === `JSXSpreadAttribute`) {
222
+ checkAttribute(attribute.argument, `spread`)
140
223
  flush()
141
224
  chunks.push([`() => (`, attribute.argument, `)`])
142
225
  continue
143
226
  }
144
- const key = JSON.stringify(
227
+ const attributeName =
145
228
  attribute.name.type === `JSXNamespacedName`
146
229
  ? `${attribute.name.namespace.name}:${attribute.name.name.name}`
147
- : attribute.name.name,
148
- )
230
+ : attribute.name.name
231
+ const key = JSON.stringify(attributeName)
149
232
  const value = attribute.value
150
233
  if (!value) properties.push([`${key}: true`])
151
234
  else if (value.type === `Literal`)
@@ -153,8 +236,9 @@ export function compile(
153
236
  else {
154
237
  const expr =
155
238
  value.type === `JSXExpressionContainer` ? value.expression : value
239
+ checkAttribute(expr, attributeName)
156
240
  properties.push(
157
- key === `"key"` || eager(expr)
241
+ eager(expr)
158
242
  ? [`${key}: (`, expr, `)`]
159
243
  : [`get ${key}(){ return (`, expr, `); }`],
160
244
  )
@@ -174,6 +258,7 @@ export function compile(
174
258
  children.push([child])
175
259
  else if (child.type === `JSXExpressionContainer`) {
176
260
  if (child.expression.type !== `JSXEmptyExpression`) {
261
+ checkAttribute(child.expression, `children`)
177
262
  if (component) {
178
263
  // Component props expose their declared values, including callbacks.
179
264
  children.push([`(`, child.expression, `)`])
@@ -186,19 +271,11 @@ export function compile(
186
271
  if (children.length) {
187
272
  const value =
188
273
  children.length === 1 ? children[0] : [`[`, ...join(children, `, `), `]`]
189
- if (lazyChildren) {
190
- // Capture the computation outside the getter's method scope.
191
- const read = uid(`children`)
192
- properties.push([`get children(){ return ${read}(); }`])
193
- chunks.push([
194
- `((${read}) => ({`,
195
- ...join(properties, `, `),
196
- `}))(() => (`,
197
- ...value,
198
- `))`,
199
- ])
200
- properties = []
201
- } else properties.push([`children: `, ...value])
274
+ properties.push(
275
+ lazyChildren
276
+ ? [`get children(){ return (`, ...value, `); }`]
277
+ : [`children: `, ...value],
278
+ )
202
279
  }
203
280
  flush()
204
281
  const spreads =
@@ -209,12 +286,37 @@ export function compile(
209
286
  const props = spreads
210
287
  ? [`${merge}(`, ...join(chunks, `, `), `)`]
211
288
  : (chunks[0] ?? [`{}`])
289
+ const capture = captures.get(node)
212
290
  rewrite(node, [
291
+ capture ? `(() => { const ${capture.name} = this; return ` : ``,
213
292
  `${create}(${node.type === `JSXElement` ? tag(node.openingElement.name) : `null`}, `,
214
293
  ...props,
215
294
  `)`,
295
+ capture ? `; })()` : ``,
216
296
  ])
217
297
  }
298
+ for (const { name, scope, root } of captures.values()) {
299
+ if (!scope) continue
300
+ const body = scope.body
301
+ if (body.type !== `BlockStatement`) {
302
+ output.prependLeft(body.start, `{ const ${name} = this; return `)
303
+ output.appendLeft(body.end, `; }`)
304
+ continue
305
+ }
306
+ let position = body.start + 1
307
+ if (parents.get(scope)?.type === `MethodDefinition`) {
308
+ let statement: Node = root
309
+ while (parents.get(statement) !== body) statement = parents.get(statement)!
310
+ position = statement.start
311
+ } else {
312
+ for (const statement of body.body) {
313
+ if (statement.type !== `ExpressionStatement` || !statement.directive)
314
+ break
315
+ position = statement.end
316
+ }
317
+ }
318
+ output.prependLeft(position, `\nconst ${name} = this;\n`)
319
+ }
218
320
  const components = new Set<string>()
219
321
  for (const fn of functions) {
220
322
  let node = fn
package/src/core.ts CHANGED
@@ -69,39 +69,87 @@ export interface RootOptions {
69
69
  idPrefix?: string
70
70
  onError?: (error: unknown) => void
71
71
  }
72
+ interface BoundaryOptions extends Omit<RootOptions, `capabilities`> {
73
+ _capabilities?: Map<string, Capability>
74
+ }
72
75
  export interface Scope {
73
76
  _exiting?: boolean
74
77
  _exits?: Set<ExitParticipant>
75
78
  _targets?: Set<PresenceTarget>
76
79
  _root: Root
77
80
  _parent?: Scope | undefined
81
+ _options?: BoundaryOptions | undefined
82
+ _setupOrder: number
78
83
  _cleanups: Set<Cleanup | Scope>
79
84
  _updates: Cleanup[]
80
85
  _dead: boolean
81
86
  }
82
87
  export interface Root extends Scope {
83
- _onRead?: ((value: unknown, token: ReadableToken<unknown>) => void) | undefined
88
+ _onRead?:
89
+ | ((value: unknown, token: ReadableToken<unknown>, store: RootStore) => void)
90
+ | undefined
84
91
  _presence?: PresenceCoordinator
92
+ _presenceFactory?: Capability[`presence`]
85
93
  _capabilities: Map<string, Capability>
94
+ _boundaryCapabilities?: Map<Capability, number>
95
+ _prepareCapability?: ((capability: Capability) => void) | undefined
96
+ _failure?: { error: unknown; report: Root[`error`] } | undefined
86
97
  _store: RootStore
87
98
  _prefix: string
88
99
  _id: number
89
100
  _queue: Set<Cleanup>
101
+ _enqueueCount?: number
90
102
  _mounts: Cleanup[] | undefined
103
+ _commits?: Set<CommitJob>
104
+ _flushing?: boolean
105
+ _forms?: Set<() => boolean>
106
+ _host?: Element
91
107
  flush: Cleanup
92
108
  error: (error: unknown) => void
93
109
  }
94
110
 
111
+ interface CommitJob {
112
+ scope: Scope
113
+ order: number
114
+ run: Cleanup
115
+ loopError: Error | undefined
116
+ }
117
+ interface CommitGroup {
118
+ order: number
119
+ children: CommitGroup[]
120
+ jobs: CommitJob[]
121
+ }
122
+
95
123
  export let owner: Scope | undefined
96
124
  type Subscribe = (notify: Cleanup) => Cleanup
97
125
  let tracking: ((subscribe: Subscribe) => void) | undefined
98
126
  let serial = 0
127
+ let setupOrder = 0
99
128
 
129
+ function scopedErrorHandler(
130
+ scope: Scope,
131
+ error: unknown,
132
+ ): Root[`error`] | undefined {
133
+ const failure = scope._root._failure
134
+ return failure && Object.is(failure.error, error)
135
+ ? failure.report
136
+ : scope._options?.onError
137
+ }
138
+ function throwScopedError(
139
+ scope: Scope,
140
+ error: unknown,
141
+ report = scopedErrorHandler(scope, error),
142
+ ): never {
143
+ if (report) scope._root._failure = { error, report }
144
+ throw error
145
+ }
100
146
  export function within<T>(scope: Scope, run: () => T): T {
101
147
  const previous = owner
102
148
  owner = scope
103
149
  try {
104
150
  return run()
151
+ } catch (error) {
152
+ throwScopedError(scope, error)
105
153
  } finally {
106
154
  owner = previous
107
155
  }
@@ -119,6 +167,8 @@ export function createScope(parent?: Scope): Scope {
119
167
  const child: Scope = {
120
168
  _root: parent?._root as Root,
121
169
  _parent: parent,
170
+ _options: parent?._options,
171
+ _setupOrder: setupOrder++,
122
172
  _cleanups: new Set(),
123
173
  _updates: [],
124
174
  _dead: false,
@@ -127,10 +177,11 @@ export function createScope(parent?: Scope): Scope {
127
177
  return child
128
178
  }
129
179
  export function fail(scope: Scope, error: unknown): never {
180
+ const report = scopedErrorHandler(scope, error)
130
181
  try {
131
182
  dispose(scope)
132
183
  } catch (cleanup) {
133
- throw new AggregateError([error, cleanup])
184
+ throwScopedError(scope, new AggregateError([error, cleanup]), report)
134
185
  }
135
186
  throw error
136
187
  }
@@ -138,48 +189,153 @@ export function dispose(scope: Scope): void {
138
189
  if (scope._dead) return
139
190
  scope._dead = true
140
191
  const errors: unknown[] = []
192
+ let report: Root[`error`] | undefined
193
+ const record = (error: unknown) => {
194
+ errors.push(error)
195
+ // Keep the first boundary handler as nested disposal wraps its errors.
196
+ report ??= scopedErrorHandler(scope, error)
197
+ }
141
198
  try {
142
199
  scope._root._presence?.forget(scope)
143
200
  } catch (error) {
144
- errors.push(error)
201
+ record(error)
145
202
  }
146
203
  for (const cleanup of [...scope._cleanups].reverse()) {
147
204
  try {
148
205
  typeof cleanup === `function` ? cleanup() : dispose(cleanup)
149
206
  } catch (error) {
150
- errors.push(error)
207
+ record(error)
151
208
  }
152
209
  }
153
210
  scope._parent?._cleanups.delete(scope)
154
211
  scope._cleanups.clear()
212
+ scope._targets?.clear()
155
213
  scope._updates.length = 0
156
- if (errors.length) throw new AggregateError(errors)
214
+ if (errors.length) throwScopedError(scope, new AggregateError(errors), report)
157
215
  }
158
216
  export function invalidate(scope: Scope): void {
159
217
  for (const run of scope._updates) enqueue(scope, run)
160
218
  for (const child of scope._cleanups)
161
219
  if (typeof child !== `function`) invalidate(child)
162
220
  }
163
- function enqueue(scope: Scope, run: Cleanup): void {
221
+ export function enqueue(scope: Scope, run: Cleanup): void {
164
222
  if (!isPresent(scope)) return
165
223
  const root = scope._root
166
- if (!root._queue.size)
224
+ if (!root._queue.size && !root._flushing)
167
225
  queueMicrotask(() => {
168
226
  try {
169
227
  root.flush()
170
228
  } catch (error) {
171
- root.error(error)
229
+ const report = scopedErrorHandler(root, error) ?? root.error
230
+ root._failure = undefined
231
+ report(error)
172
232
  }
173
233
  })
234
+ // A write can invalidate an observer that is already pending.
235
+ if (import.meta.env.DEV) root._enqueueCount = (root._enqueueCount ?? 0) + 1
174
236
  root._queue.add(run)
175
237
  }
176
- export function createRoot(options: RootOptions = {}, server = false): Root {
238
+
239
+ function runCommits(root: Root, pending: Set<CommitJob>): CommitJob | undefined {
240
+ const top: CommitGroup = { order: root._setupOrder, children: [], jobs: [] }
241
+ const groups = new Map<Scope, CommitGroup>([[root, top]])
242
+ // Keep only branches with pending work. Visit siblings in setup order.
243
+ const groupFor = (scope: Scope): CommitGroup => {
244
+ let group = groups.get(scope)
245
+ if (!group) {
246
+ group = { order: scope._setupOrder, children: [], jobs: [] }
247
+ groups.set(scope, group)
248
+ groupFor(scope._parent!).children.push(group)
249
+ }
250
+ return group
251
+ }
252
+ for (const job of [...pending].sort((a, b) => a.order - b.order))
253
+ groupFor(job.scope).jobs.push(job)
254
+ let last: CommitJob | undefined
255
+ const visit = (group: CommitGroup) => {
256
+ for (const child of group.children.sort((a, b) => a.order - b.order))
257
+ visit(child)
258
+ for (const job of group.jobs) {
259
+ if (pending.delete(job) && isPresent(job.scope)) {
260
+ const enqueueCount = import.meta.env.DEV ? root._enqueueCount : undefined
261
+ job.run()
262
+ if (import.meta.env.DEV && root._enqueueCount !== enqueueCount)
263
+ last = job
264
+ }
265
+ }
266
+ }
267
+ visit(top)
268
+ return last
269
+ }
270
+
271
+ function capabilityMap(list: readonly Capability[] | undefined) {
177
272
  const capabilities = new Map<string, Capability>()
178
- for (const capability of options.capabilities ?? []) {
273
+ for (const capability of list ?? []) {
179
274
  if (capabilities.has(capability.namespace))
180
275
  throw new Error(`spa: duplicate capability ${capability.namespace}`)
181
276
  capabilities.set(capability.namespace, capability)
182
277
  }
278
+ return capabilities
279
+ }
280
+ function registerPresence(
281
+ root: Root,
282
+ capability: Capability,
283
+ shared = false,
284
+ ): void {
285
+ const create = capability.presence
286
+ if (!create) return
287
+ if (root._presence) {
288
+ if (!shared || root._presenceFactory !== create)
289
+ throw new Error(`spa: multiple presence coordinators`)
290
+ } else {
291
+ root._presence = create(root)
292
+ root._presenceFactory = create
293
+ }
294
+ }
295
+ export function scopeCapabilities(scope: Scope): Map<string, Capability> {
296
+ return scope._options?._capabilities ?? scope._root._capabilities
297
+ }
298
+ export function reportScopeError(scope: Scope, error: unknown): void {
299
+ const report = scopedErrorHandler(scope, error) ?? scope._root.error
300
+ try {
301
+ fail(scope._root, error)
302
+ } catch (failure) {
303
+ scope._root._failure = undefined
304
+ report(failure)
305
+ }
306
+ }
307
+
308
+ /** Override root options for these children while sharing their parent's ownership. */
309
+ export function RootBoundary(
310
+ props: RootOptions & { children?: Children },
311
+ ): Children {
312
+ const scope = owner!
313
+ const { store, idPrefix, onError, capabilities } = props
314
+ const options = { ...scope._options }
315
+ if (store !== undefined) options.store = store
316
+ if (idPrefix !== undefined) options.idPrefix = idPrefix
317
+ if (onError !== undefined) options.onError = onError
318
+ if (capabilities !== undefined) {
319
+ options._capabilities = capabilityMap(capabilities)
320
+ const root = scope._root
321
+ const active = (root._boundaryCapabilities ??= new Map())
322
+ for (const capability of options._capabilities.values()) {
323
+ registerPresence(root, capability, true)
324
+ active.set(capability, (active.get(capability) ?? 0) + 1)
325
+ scope._cleanups.add(() => {
326
+ const remaining = active.get(capability)! - 1
327
+ if (remaining) active.set(capability, remaining)
328
+ else active.delete(capability)
329
+ })
330
+ root._prepareCapability?.(capability)
331
+ }
332
+ }
333
+ scope._options = options
334
+ return () => props.children
335
+ }
336
+
337
+ export function createRoot(options: RootOptions = {}, server = false): Root {
338
+ const capabilities = capabilityMap(options.capabilities)
183
339
  const root = {
184
340
  _capabilities: capabilities,
185
341
  _store: options.store ?? IMPLICIT.STORE,
@@ -196,36 +352,78 @@ export function createRoot(options: RootOptions = {}, server = false): Root {
196
352
  throw error
197
353
  })
198
354
  for (const capability of capabilities.values())
199
- if (capability.presence) {
200
- if (root._presence) throw new Error(`spa: multiple presence coordinators`)
201
- root._presence = capability.presence(root)
202
- }
355
+ registerPresence(root, capability)
356
+ const hasWrites = () => root._queue.size || root._mounts!.length
357
+ const hasWork = () => hasWrites() || root._commits?.size
358
+ let flushPendingWrites: Cleanup | undefined
203
359
  root.flush = () => {
204
- if (!root._queue.size && !root._mounts!.length) return
360
+ const nested = root._flushing
361
+ if (!(nested ? hasWrites() : hasWork()) && !root._forms?.size) return
362
+ root._flushing = true
205
363
  try {
206
- const commits = [...capabilities.values()].map((capability) =>
207
- capability.beforeUpdate?.(root),
208
- )
209
- try {
210
- let passes = 0
211
- while (root._queue.size || root._mounts!.length) {
212
- if (import.meta.env.DEV && ++passes > 100)
213
- throw new Error(`spa: update loop`)
214
- for (const run of [...root._queue]) if (root._queue.delete(run)) run()
215
- for (const run of root._mounts!.splice(0)) run()
364
+ if (nested) {
365
+ // The outer flush owns commit dispatch. Mount callbacks can drain writes.
366
+ flushPendingWrites?.()
367
+ return
368
+ }
369
+ root._failure = undefined
370
+ let passes = 0
371
+ let lastCommit: CommitJob | undefined
372
+ const checkLoop = () => {
373
+ if (import.meta.env.DEV && ++passes > 100)
374
+ throw lastCommit?.loopError ?? new Error(`spa: update loop`)
375
+ }
376
+ const runWriteBatch = () => {
377
+ const commits = new Map<Capability, Cleanup | undefined>()
378
+ const prepare = (capability: Capability) => {
379
+ if (!commits.has(capability))
380
+ commits.set(capability, capability.beforeUpdate?.(root))
216
381
  }
217
- } finally {
218
- for (const commit of commits) commit?.()
382
+ const previous = root._prepareCapability
383
+ root._prepareCapability = prepare
384
+ let formsReady = true
385
+ try {
386
+ for (const capability of capabilities.values()) prepare(capability)
387
+ for (const capability of root._boundaryCapabilities?.keys() ?? [])
388
+ prepare(capability)
389
+ while (hasWrites()) {
390
+ checkLoop()
391
+ for (const run of [...root._queue])
392
+ if (root._queue.delete(run)) run()
393
+ for (const run of root._mounts!.splice(0)) run()
394
+ }
395
+ for (const restore of root._forms ?? [])
396
+ if (!untrack(restore)) formsReady = false
397
+ } finally {
398
+ root._prepareCapability = previous
399
+ for (const commit of commits.values()) commit?.()
400
+ }
401
+ return formsReady
219
402
  }
403
+ do {
404
+ flushPendingWrites = runWriteBatch
405
+ const formsReady = runWriteBatch()
406
+ flushPendingWrites = undefined
407
+ if (!hasWrites()) {
408
+ // Form event completion schedules a flush to restore the controls.
409
+ if (!formsReady || !root._commits?.size) break
410
+ checkLoop()
411
+ lastCommit = runCommits(root, root._commits) ?? lastCommit
412
+ }
413
+ } while (hasWork())
414
+ root._failure = undefined
220
415
  } catch (error) {
416
+ flushPendingWrites = undefined
221
417
  fail(root, error)
418
+ } finally {
419
+ if (!nested) root._flushing = false
222
420
  }
223
421
  }
224
422
  return root
225
423
  }
226
- /** Return the atom.io store selected by the current root. */
424
+ /** Return the atom.io store selected by the current owner. */
227
425
  export function useStore(): RootStore {
228
- return owner!._root._store
426
+ return owner!._options?.store ?? owner!._root._store
229
427
  }
230
428
  /** Return atom.io disposal bound to the current root's store. */
231
429
  export function useDisposal(): typeof disposeState {
@@ -243,9 +441,58 @@ export function onMount(run: Cleanup): void {
243
441
  })
244
442
  })
245
443
  }
444
+ /** Observe state during setup and apply changes after the root's writes. */
445
+ export function onCommit<T>(
446
+ read: Accessor<T>,
447
+ apply: (value: T, previous: T | undefined) => void | Cleanup,
448
+ ): void {
449
+ const scope = owner!
450
+ const root = scope._root
451
+ if (!root._mounts) return
452
+ const pending = (root._commits ??= new Set())
453
+ let ran = false
454
+ let next: T
455
+ let previous: T | undefined
456
+ let cleanup: Cleanup | void
457
+ const clear = () => {
458
+ const release = cleanup
459
+ cleanup = undefined
460
+ if (release) untrack(release)
461
+ }
462
+ const job: CommitJob = {
463
+ scope,
464
+ order: setupOrder++,
465
+ // The registration stack identifies the component in a feedback loop.
466
+ loopError: import.meta.env.DEV
467
+ ? new Error(`spa: onCommit update loop`)
468
+ : undefined,
469
+ run() {
470
+ within(scope, () => {
471
+ untrack(() => {
472
+ clear()
473
+ if (!isPresent(scope)) return
474
+ const old = previous
475
+ previous = next
476
+ ran = true
477
+ cleanup = apply(next, old)
478
+ if (scope._dead) clear()
479
+ })
480
+ })
481
+ },
482
+ }
483
+ scope._cleanups.add(() => {
484
+ pending.delete(job)
485
+ clear()
486
+ })
487
+ observe(scope, read, (value) => {
488
+ next = value
489
+ if (!ran || !Object.is(value, previous)) pending.add(job)
490
+ else pending.delete(job)
491
+ })
492
+ }
246
493
  export function useId(): string {
247
494
  const root = owner!._root
248
- return `${root._prefix}-${root._id++}`
495
+ return `${owner!._options?.idPrefix ?? root._prefix}-${root._id++}`
249
496
  }
250
497
 
251
498
  export function observe<T>(
@@ -279,8 +526,10 @@ export function observe<T>(
279
526
  subscriptions.delete(subscribe)
280
527
  }
281
528
  }
282
- untrack(() => {
283
- apply(value)
529
+ within(scope, () => {
530
+ untrack(() => {
531
+ apply(value)
532
+ })
284
533
  })
285
534
  }
286
535
  scope._updates.push(run)
@@ -313,7 +562,7 @@ export function useGetter(token: any, key?: Canonical): Accessor<any> {
313
562
  subscribeToState(store, token, `spa:${serial++}`, notify)
314
563
  return () => {
315
564
  const value = getFromStore(store, token)
316
- root._onRead?.(value, token)
565
+ root._onRead?.(value, token, store)
317
566
  tracking?.(subscribe)
318
567
  return value
319
568
  }