@atom.io/spa 0.0.2 → 0.0.4

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 (94) hide show
  1. package/README.md +144 -47
  2. package/README.mdx +37 -11
  3. package/dist/astro-application.d.ts +1 -1
  4. package/dist/astro-application.js +2 -2
  5. package/dist/astro-application.js.map +1 -1
  6. package/dist/astro-client.d.ts +1 -1
  7. package/dist/astro-client.js +4 -4
  8. package/dist/astro-client.js.map +1 -1
  9. package/dist/{astro-shared-DyzbUi6c.d.ts → astro-shared-CYSRrRr8.d.ts} +2 -2
  10. package/dist/{astro-shared-DyzbUi6c.d.ts.map → astro-shared-CYSRrRr8.d.ts.map} +1 -1
  11. package/dist/astro.d.ts +1 -1
  12. package/dist/capabilities-BkQ2i0vV.js +63 -0
  13. package/dist/capabilities-BkQ2i0vV.js.map +1 -0
  14. package/dist/{capabilities-yC9TsHDI.d.ts → capabilities-D3HObAIy.d.ts} +66 -11
  15. package/dist/capabilities-D3HObAIy.d.ts.map +1 -0
  16. package/dist/client.min.js +1 -1
  17. package/dist/{capabilities-BuZUQpiD.js → core-Bl1Ec1hY.js} +42 -79
  18. package/dist/core-Bl1Ec1hY.js.map +1 -0
  19. package/dist/development/astro-application.js +2 -2
  20. package/dist/development/astro-application.js.map +1 -1
  21. package/dist/development/astro-client.js +4 -4
  22. package/dist/development/astro-client.js.map +1 -1
  23. package/dist/development/capabilities-BkQ2i0vV.js +63 -0
  24. package/dist/development/capabilities-BkQ2i0vV.js.map +1 -0
  25. package/dist/development/{capabilities-DhOJmeoJ.js → core-DZFaOyTO.js} +42 -79
  26. package/dist/development/core-DZFaOyTO.js.map +1 -0
  27. package/dist/development/{dom-BKc6V_Kz.js → dom-Dwa2SFTn.js} +16 -7
  28. package/dist/development/dom-Dwa2SFTn.js.map +1 -0
  29. package/dist/development/index.js +4 -4
  30. package/dist/development/konva.js +25 -3
  31. package/dist/development/konva.js.map +1 -1
  32. package/dist/development/motion.js +392 -8
  33. package/dist/development/motion.js.map +1 -1
  34. package/dist/development/renderer.js +23 -10
  35. package/dist/development/renderer.js.map +1 -1
  36. package/dist/development/server.js +2 -1
  37. package/dist/development/server.js.map +1 -1
  38. package/dist/development/{src-Dh-d6w4y.js → src-BUtG4BgX.js} +4 -4
  39. package/dist/development/src-BUtG4BgX.js.map +1 -0
  40. package/dist/development/three.js +24 -10
  41. package/dist/development/three.js.map +1 -1
  42. package/dist/{dom-B2rm8o2L.js → dom-Cfj3GtQK.js} +16 -7
  43. package/dist/dom-Cfj3GtQK.js.map +1 -0
  44. package/dist/{index-BdwxmSKg.d.ts → index-YRZ79lN5.d.ts} +3 -3
  45. package/dist/{index-BdwxmSKg.d.ts.map → index-YRZ79lN5.d.ts.map} +1 -1
  46. package/dist/index.d.ts +4 -4
  47. package/dist/index.js +4 -4
  48. package/dist/{jsx-runtime-CZU7F8Qz.d.ts → jsx-runtime-Q-UBV97Y.d.ts} +2 -2
  49. package/dist/{jsx-runtime-CZU7F8Qz.d.ts.map → jsx-runtime-Q-UBV97Y.d.ts.map} +1 -1
  50. package/dist/jsx-runtime.d.ts +1 -1
  51. package/dist/konva.d.ts +3 -3
  52. package/dist/konva.d.ts.map +1 -1
  53. package/dist/konva.js +25 -3
  54. package/dist/konva.js.map +1 -1
  55. package/dist/motion.d.ts +2 -1
  56. package/dist/motion.d.ts.map +1 -1
  57. package/dist/motion.js +392 -8
  58. package/dist/motion.js.map +1 -1
  59. package/dist/renderer.d.ts +3 -3
  60. package/dist/renderer.d.ts.map +1 -1
  61. package/dist/renderer.js +23 -10
  62. package/dist/renderer.js.map +1 -1
  63. package/dist/server.d.ts +1 -1
  64. package/dist/server.js +2 -1
  65. package/dist/server.js.map +1 -1
  66. package/dist/size.json +12 -12
  67. package/dist/{src-BZxX4xbU.js → src-DvkUMuNW.js} +4 -4
  68. package/dist/src-DvkUMuNW.js.map +1 -0
  69. package/dist/three.d.ts +3 -3
  70. package/dist/three.d.ts.map +1 -1
  71. package/dist/three.js +24 -10
  72. package/dist/three.js.map +1 -1
  73. package/package.json +9 -7
  74. package/src/astro-application.ts +2 -2
  75. package/src/astro-client.ts +3 -3
  76. package/src/capabilities.ts +21 -2
  77. package/src/core.ts +66 -41
  78. package/src/dom.ts +35 -4
  79. package/src/index.ts +2 -2
  80. package/src/konva.ts +41 -14
  81. package/src/motion-tween.ts +106 -0
  82. package/src/motion.ts +122 -9
  83. package/src/presence.ts +324 -0
  84. package/src/renderer.ts +51 -14
  85. package/src/three-events.ts +13 -1
  86. package/src/three.ts +38 -15
  87. package/src/use-loadable.ts +3 -3
  88. package/dist/capabilities-BuZUQpiD.js.map +0 -1
  89. package/dist/capabilities-yC9TsHDI.d.ts.map +0 -1
  90. package/dist/development/capabilities-DhOJmeoJ.js.map +0 -1
  91. package/dist/development/dom-BKc6V_Kz.js.map +0 -1
  92. package/dist/development/src-Dh-d6w4y.js.map +0 -1
  93. package/dist/dom-B2rm8o2L.js.map +0 -1
  94. package/dist/src-BZxX4xbU.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atom.io/spa",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "An atom.io-driven JSX renderer.",
5
5
  "homepage": "https://atom.io.fyi/docs/spa",
6
6
  "repository": {
@@ -103,18 +103,18 @@
103
103
  "@types/three": "0.187.0",
104
104
  "@vitest/coverage-v8": "5.1.0",
105
105
  "astro": "7.4.5",
106
- "atom.io": "0.54.3",
107
- "breakage": "0.10.1",
106
+ "atom.io": "0.54.5",
107
+ "breakage": "0.10.2",
108
108
  "esbuild": "0.28.2",
109
109
  "eslint": "10.14.0",
110
110
  "happy-dom": "21.0.4",
111
111
  "konva": "10.9.1",
112
- "motion": "14.9.0",
112
+ "motion": "14.9.1",
113
113
  "playwright": "1.64.1",
114
114
  "preact": "11.1.1",
115
115
  "rolldown": "1.2.16",
116
116
  "three": "0.187.0",
117
- "tsdown": "0.23.4",
117
+ "tsdown": "0.23.5",
118
118
  "typescript": "7.0.2",
119
119
  "vite": "8.3.5",
120
120
  "vitest": "5.1.0"
@@ -122,7 +122,7 @@
122
122
  "peerDependencies": {
123
123
  "@types/three": "^0.187.0",
124
124
  "astro": "^7.4.2",
125
- "atom.io": "^0.54.1",
125
+ "atom.io": "^0.54.4",
126
126
  "konva": "^10.9.1",
127
127
  "motion": "^14.9.0",
128
128
  "three": "^0.187.0",
@@ -172,6 +172,8 @@
172
172
  "tonnage:check": "pnpm readme:check",
173
173
  "test:browser:graphics": "node scripts/graphics-browser-test.mjs",
174
174
  "test:optional-peers": "node scripts/optional-peers-check.mjs && node __tests__/fixtures/graphics-consumer/check.ts",
175
- "bench:compiler": "node scripts/compiler-benchmark.ts"
175
+ "bench:compiler": "node scripts/compiler-benchmark.ts",
176
+ "example:motion": "vite --config examples/motion/vite.config.ts",
177
+ "test:browser:motion": "node scripts/motion-browser-test.mjs"
176
178
  }
177
179
  }
@@ -1,5 +1,5 @@
1
1
  import type { ReadableToken } from "atom.io"
2
- import { IMPLICIT, withdraw } from "atom.io/internal"
2
+ import { IMPLICIT, subscribeToStateSubject, withdraw } from "atom.io/internal"
3
3
 
4
4
  import { applicationContext } from "./astro-context.ts"
5
5
 
@@ -31,7 +31,7 @@ export function browserApplication(
31
31
  const state = withdraw(store, token)
32
32
  subscriptions.set(
33
33
  token.key,
34
- state.subject.subscribe(`spa:bootstrap`, changed),
34
+ subscribeToStateSubject(state, `spa:bootstrap`, changed),
35
35
  )
36
36
  }
37
37
  for (const state of [
@@ -12,7 +12,7 @@ import { browserApplication } from "./astro-application.ts"
12
12
  import { failPreparation, storeContext } from "./astro-context.ts"
13
13
  import type { Island } from "./astro-shared.ts"
14
14
  import { island, islandStore } from "./astro-shared.ts"
15
- import { onCleanup, useValue } from "./core.ts"
15
+ import { onCleanup, useGetter } from "./core.ts"
16
16
  import { hydrate, render } from "./dom.ts"
17
17
 
18
18
  type Props = Record<string, any>
@@ -101,8 +101,8 @@ export default (element: HTMLElement): Hydrator =>
101
101
  })
102
102
  const mount = () => {
103
103
  onCleanup(dispose)
104
- const value = useValue(state)
105
- return () => island(component, value().props, value().slots)
104
+ const getState = useGetter(state)
105
+ return () => island(component, getState().props, getState().slots)
106
106
  }
107
107
  if (replace) element.replaceChildren()
108
108
  const root = (replace ? render : hydrate)(mount, element, {
@@ -1,19 +1,24 @@
1
- import type { Cleanup, Scope } from "./core.ts"
1
+ import type { Cleanup, Root, Scope } from "./core.ts"
2
+ import type { ExitHandle, PresenceCoordinator } from "./presence.ts"
2
3
 
3
4
  /** Native renderers expose property access without importing capability engines. */
4
5
  export interface CapabilityTarget {
5
6
  kind: string
6
7
  node: unknown
8
+ suspend?(): Cleanup
7
9
  read?(key: string): unknown
8
10
  write?(key: string, value: unknown): void
9
11
  listen?(event: string, listener: () => void): Cleanup
10
12
  }
11
13
  export interface CapabilityBinding {
14
+ exit?(props: Record<string, unknown>): ExitHandle | undefined
15
+ resume?(): void
12
16
  update(props: Record<string, unknown>): void
13
17
  dispose(): void
14
18
  }
15
19
  export interface Capability {
16
20
  namespace: string
21
+ presence?(root: Root): PresenceCoordinator
17
22
  scheduleFrame?(callback: (time: number) => void): Cleanup
18
23
  attach(target: CapabilityTarget): CapabilityBinding
19
24
  }
@@ -41,8 +46,11 @@ export function validateCapabilities(
41
46
  export function capabilityProps(
42
47
  scope: Scope,
43
48
  target: CapabilityTarget,
49
+ read?: () => Record<string, any>,
44
50
  ): (props: Record<string, any>) => Record<string, any> {
45
51
  const bindings = new Map<string, CapabilityBinding>()
52
+
53
+ scope._root._presence?.target(scope, target)
46
54
  const cleanup: Cleanup = () => {
47
55
  const errors: unknown[] = []
48
56
  for (const binding of [...bindings.values()].reverse()) {
@@ -63,7 +71,11 @@ export function capabilityProps(
63
71
  for (const key of Object.keys(props)) {
64
72
  const namespace = capabilityNamespace(key)
65
73
  if (!namespace) {
66
- native[key] = props[key]
74
+ const value = props[key]
75
+ native[key] =
76
+ key.startsWith(`on`) && typeof value === `function`
77
+ ? (scope._root._presence?.event(scope, value) ?? value)
78
+ : value
67
79
  continue
68
80
  }
69
81
  const group = groups.get(namespace) ?? {}
@@ -75,12 +87,19 @@ export function capabilityProps(
75
87
  if (!binding) {
76
88
  binding = scope._root._capabilities.get(namespace)!.attach(target)
77
89
  bindings.set(namespace, binding)
90
+ scope._root._presence?.bind(
91
+ scope,
92
+ binding,
93
+ read ?? (() => props),
94
+ namespace,
95
+ )
78
96
  }
79
97
  binding.update(values)
80
98
  }
81
99
  for (const [namespace, binding] of bindings)
82
100
  if (!groups.has(namespace)) {
83
101
  bindings.delete(namespace)
102
+ scope._root._presence?.unbind(binding)
84
103
  binding.dispose()
85
104
  }
86
105
  return native
package/src/core.ts CHANGED
@@ -22,15 +22,20 @@ import {
22
22
  getFromStore,
23
23
  getTimelineTransactionAtHead,
24
24
  IMPLICIT,
25
- inspectTimelineInStore,
26
25
  setIntoStore,
27
26
  subscribeToState,
28
27
  subscribeToTimeline,
29
28
  timeTravel,
30
29
  timeTravelTransactionGroupInStore,
30
+ withdraw,
31
31
  } from "atom.io/internal"
32
32
 
33
33
  import type { Capability } from "./capabilities.ts"
34
+ import type {
35
+ ExitParticipant,
36
+ PresenceCoordinator,
37
+ PresenceTarget,
38
+ } from "./presence.ts"
34
39
 
35
40
  export type Cleanup = () => void
36
41
  // A callable interface permits the recursive Child union. A type alias does not.
@@ -61,6 +66,9 @@ export interface RootOptions {
61
66
  onError?: (error: unknown) => void
62
67
  }
63
68
  export interface Scope {
69
+ _exiting?: boolean
70
+ _exits?: Set<ExitParticipant>
71
+ _targets?: Set<PresenceTarget>
64
72
  _root: Root
65
73
  _parent?: Scope | undefined
66
74
  _cleanups: Set<Cleanup | Scope>
@@ -68,6 +76,7 @@ export interface Scope {
68
76
  _dead: boolean
69
77
  }
70
78
  export interface Root extends Scope {
79
+ _presence?: PresenceCoordinator
71
80
  _capabilities: Map<string, Capability>
72
81
  _store: RootStore
73
82
  _prefix: string
@@ -124,6 +133,11 @@ export function dispose(scope: Scope): void {
124
133
  if (scope._dead) return
125
134
  scope._dead = true
126
135
  const errors: unknown[] = []
136
+ try {
137
+ scope._root._presence?.forget(scope)
138
+ } catch (error) {
139
+ errors.push(error)
140
+ }
127
141
  for (const cleanup of [...scope._cleanups].reverse()) {
128
142
  try {
129
143
  typeof cleanup === `function` ? cleanup() : dispose(cleanup)
@@ -142,7 +156,7 @@ export function invalidate(scope: Scope): void {
142
156
  if (typeof child !== `function`) invalidate(child)
143
157
  }
144
158
  function enqueue(scope: Scope, run: Cleanup): void {
145
- if (scope._dead) return
159
+ if (!isPresent(scope)) return
146
160
  const root = scope._root
147
161
  if (!root._queue.size)
148
162
  queueMicrotask(() => {
@@ -176,6 +190,11 @@ export function createRoot(options: RootOptions = {}, server = false): Root {
176
190
  ((error) => {
177
191
  throw error
178
192
  })
193
+ for (const capability of capabilities.values())
194
+ if (capability.presence) {
195
+ if (root._presence) throw new Error(`spa: multiple presence coordinators`)
196
+ root._presence = capability.presence(root)
197
+ }
179
198
  root.flush = () => {
180
199
  try {
181
200
  let passes = 0
@@ -219,7 +238,7 @@ export function observe<T>(
219
238
  ): void {
220
239
  const subscriptions = new Map<Subscribe, Cleanup>()
221
240
  const run = () => {
222
- if (scope._dead) return
241
+ if (!isPresent(scope)) return
223
242
  const used = new Set<Subscribe>()
224
243
  const previous = tracking
225
244
  tracking = (subscribe) => {
@@ -262,14 +281,14 @@ export function resolveStateToken(token: any, key?: Canonical): any {
262
281
  }
263
282
 
264
283
  /** Capture a token for this instance. Change the component key to change its token. */
265
- export function useValue<T, E = never>(
284
+ export function useGetter<T, E = never>(
266
285
  token: ReadableToken<T, any, E>,
267
286
  ): Accessor<ViewOf<T | E>>
268
- export function useValue<T, K extends Canonical, E = never>(
287
+ export function useGetter<T, K extends Canonical, E = never>(
269
288
  family: ReadableFamilyToken<T, K, E>,
270
289
  key: NoInfer<K>,
271
290
  ): Accessor<ViewOf<T | E>>
272
- export function useValue(token: any, key?: Canonical): Accessor<any> {
291
+ export function useGetter(token: any, key?: Canonical): Accessor<any> {
273
292
  token = resolveStateToken(token, key)
274
293
  const store = owner!._root._store
275
294
  const subscribe: Subscribe = (notify) =>
@@ -330,58 +349,58 @@ export function useRef<E extends Element>(
330
349
  }
331
350
  }
332
351
  }
333
- export interface TimelineValue {
334
- at: number
335
- length: number
352
+ export interface TimelineControls {
353
+ getCursor(): number
354
+ getLength(): number
336
355
  undo(): void
337
356
  redo(): void
338
357
  clear(): void
339
- undoTransaction?: Cleanup
340
- redoTransaction?: Cleanup
358
+ getTransaction(): { undo?: Cleanup; redo?: Cleanup }
341
359
  }
342
360
  export function useTimeline<M extends TimelineManageable>(
343
361
  token: TimelineToken<M>,
344
- ): Accessor<TimelineValue>
362
+ ): TimelineControls
345
363
  export function useTimeline<K extends Canonical, M extends TimelineManageable>(
346
364
  family: TimelineFamilyToken<K, M>,
347
365
  key: NoInfer<K>,
348
- ): Accessor<TimelineValue>
349
- export function useTimeline(
350
- token: any,
351
- key?: Canonical,
352
- ): Accessor<TimelineValue> {
366
+ ): TimelineControls
367
+ export function useTimeline(token: any, key?: Canonical): TimelineControls {
353
368
  const store = owner!._root._store
354
- if (token.type === `timeline_family`)
355
- token = findTimelineInStore(store, token, key!)
369
+ const selected: TimelineToken<any> =
370
+ token.type === `timeline_family`
371
+ ? findTimelineInStore(store, token, key!)
372
+ : token
356
373
  const subscribe: Subscribe = (notify) =>
357
- subscribeToTimeline(store, token, `spa:${serial++}`, notify)
358
- const controls = {
374
+ subscribeToTimeline(store, selected, `spa:${serial++}`, notify)
375
+ const read = () => {
376
+ const timeline = withdraw(store, selected)
377
+ tracking?.(subscribe)
378
+ return timeline
379
+ }
380
+ return {
381
+ getCursor: () => read().at,
382
+ getLength: () => read().history.length,
359
383
  undo: () => {
360
- timeTravel(store, `undo`, token)
384
+ timeTravel(store, `undo`, selected)
361
385
  },
362
386
  redo: () => {
363
- timeTravel(store, `redo`, token)
387
+ timeTravel(store, `redo`, selected)
364
388
  },
365
389
  clear: () => {
366
- clearTimelineInStore(store, token)
390
+ clearTimelineInStore(store, selected)
391
+ },
392
+ getTransaction: () => {
393
+ const timeline = read()
394
+ const controls: ReturnType<TimelineControls[`getTransaction`]> = {}
395
+ for (const direction of [`undo`, `redo`] as const) {
396
+ const group = getTimelineTransactionAtHead(timeline, direction)
397
+ if (group)
398
+ controls[direction] = () => {
399
+ timeTravelTransactionGroupInStore(store, direction, group)
400
+ }
401
+ }
402
+ return controls
367
403
  },
368
- }
369
- return () => {
370
- const value: TimelineValue = {
371
- ...inspectTimelineInStore(store, token),
372
- ...controls,
373
- }
374
- tracking?.(subscribe)
375
- for (const direction of [`undo`, `redo`] as const) {
376
- const group = getTimelineTransactionAtHead(
377
- store.timelines.get(token.key)!,
378
- direction,
379
- )
380
- if (group)
381
- value[`${direction}Transaction`] = () =>
382
- timeTravelTransactionGroupInStore(store, direction, group)
383
- }
384
- return value
385
404
  }
386
405
  }
387
406
 
@@ -394,3 +413,9 @@ export function plain(value: Child): string {
394
413
  // oxlint-disable-next-line typescript/no-base-to-string -- Valid text children are primitives here; development rejects malformed object children.
395
414
  return String(value)
396
415
  }
416
+
417
+ export function isPresent(scope: Scope): boolean {
418
+ for (let at: Scope | undefined = scope; at; at = at._parent)
419
+ if (at._dead || at._exiting) return false
420
+ return true
421
+ }
package/src/dom.ts CHANGED
@@ -129,6 +129,21 @@ function mount(
129
129
  comment(`{`, parent, before, owner, cursor)
130
130
  let end: Node | null = null
131
131
  let records = new Map<unknown, RecordNode>()
132
+ const presence = owner._root._presence?.collection<RecordNode, Child>(
133
+ (record) => record._scope,
134
+ (record, child) =>
135
+ typeof record._value === typeof child &&
136
+ (record._value as VNode | null)?.type === (child as VNode | null)?.type,
137
+ )
138
+ const retire = (
139
+ record: RecordNode,
140
+ key: unknown,
141
+ eligible: boolean,
142
+ index: number,
143
+ ) => {
144
+ if (presence) presence.remove(record, key, eligible, index, () => {})
145
+ else dispose(record._scope)
146
+ }
132
147
  let initial = cursor
133
148
  observe(
134
149
  owner,
@@ -150,9 +165,15 @@ function mount(
150
165
  (typeof record._value !== typeof child ||
151
166
  (record._value as VNode | null)?.type !== vnode?.type)
152
167
  ) {
153
- dispose(record._scope)
168
+ retire(
169
+ record,
170
+ key,
171
+ child == null || typeof child === `boolean`,
172
+ [...records.keys()].indexOf(key),
173
+ )
154
174
  record = undefined
155
175
  }
176
+ record ??= presence?.take(key, child)
156
177
  if (!record) {
157
178
  const childOwner = createScope(owner)
158
179
  record = {
@@ -180,15 +201,20 @@ function mount(
180
201
  )
181
202
  } else {
182
203
  record._value = child
204
+ owner._root._presence?.resume(record._scope)
183
205
  invalidate(record._scope)
184
206
  }
185
207
  kept.set(key, record)
186
208
  }
187
209
  for (const [key, record] of records)
188
- if (!kept.has(key)) dispose(record._scope)
210
+ if (!kept.has(key))
211
+ retire(record, key, true, [...records.keys()].indexOf(key))
189
212
  if (!initial) {
190
213
  let at = end ?? before
191
- for (const record of [...kept.values()].reverse()) {
214
+ const rendered = presence?.merge([...kept.values()]) ?? [
215
+ ...kept.values(),
216
+ ]
217
+ for (const record of rendered.reverse()) {
192
218
  if (record._end.nextSibling !== at) {
193
219
  const range = parent.ownerDocument!.createRange()
194
220
  range.setStartBefore(record._start)
@@ -199,6 +225,7 @@ function mount(
199
225
  }
200
226
  if (
201
227
  focus?.isConnected &&
228
+ !focus.closest(`[inert]`) &&
202
229
  focus !== parent.ownerDocument!.activeElement
203
230
  )
204
231
  focus.focus({ preventScroll: true })
@@ -291,7 +318,11 @@ function mount(
291
318
  import.meta.env.DEV ? `spa: hydration mismatch` : undefined,
292
319
  )
293
320
  }
294
- const nativeProps = capabilityProps(owner, { kind: `dom`, node: element })
321
+ const nativeProps = capabilityProps(
322
+ owner,
323
+ { kind: `dom`, node: element },
324
+ () => ({ ...props }),
325
+ )
295
326
  let previous: Record<string, any> = {}
296
327
  owner._cleanups.add(() => {
297
328
  for (const key in previous)
package/src/index.ts CHANGED
@@ -8,19 +8,19 @@ export type {
8
8
  Child,
9
9
  Component,
10
10
  RootOptions,
11
- TimelineValue,
11
+ TimelineControls,
12
12
  VNode,
13
13
  } from "./core.ts"
14
14
  export {
15
15
  onCleanup,
16
16
  onMount,
17
+ useGetter,
17
18
  useId,
18
19
  useRef,
19
20
  useSetter,
20
21
  useStore,
21
22
  useTimeline,
22
23
  useTransaction,
23
- useValue,
24
24
  } from "./core.ts"
25
25
  export type { SpaRoot } from "./dom.ts"
26
26
  export { hydrate, render } from "./dom.ts"
package/src/konva.ts CHANGED
@@ -30,6 +30,17 @@ const constructors = {
30
30
  Star: Konva.Star,
31
31
  Transformer: Konva.Transformer,
32
32
  }
33
+ function suspendNode(node: Konva.Node): () => void {
34
+ const listening = node.listening()
35
+ const draggable = node.draggable()
36
+ node.listening(false)
37
+ // The public setter clears both pending and active native drag records.
38
+ node.draggable(false)
39
+ return () => {
40
+ node.listening(listening)
41
+ node.draggable(draggable)
42
+ }
43
+ }
33
44
  function updateNode(
34
45
  node: Konva.Node,
35
46
  props: Record<string, any>,
@@ -50,6 +61,9 @@ const renderer = createSceneRenderer<Konva.Node>({
50
61
  return {
51
62
  kind: `konva`,
52
63
  node,
64
+ suspend() {
65
+ return suspendNode(node)
66
+ },
53
67
  read: (key) => node.getAttr(key),
54
68
  write: (key, value) => {
55
69
  node.setAttr(key, value)
@@ -95,8 +109,14 @@ export function Stage(
95
109
  ): VNode {
96
110
  let container: HTMLDivElement | null = null
97
111
  onMount(() => {
112
+ // Konva clears its container; preserve SPA's markers in the outer element.
113
+ const surface = container!.ownerDocument.createElement(`div`)
114
+ container!.append(surface)
115
+ onCleanup(() => {
116
+ surface.remove()
117
+ })
98
118
  const stage = new Konva.Stage({
99
- container: container!,
119
+ container: surface,
100
120
  width: props.width ?? 300,
101
121
  height: props.height ?? 150,
102
122
  })
@@ -104,20 +124,27 @@ export function Stage(
104
124
  stage.off()
105
125
  stage.destroy()
106
126
  })
107
- const nativeProps = capabilityProps(owner!, {
108
- kind: `konva`,
109
- node: stage,
110
- listen(event, listener) {
111
- stage.on(event, listener)
112
- return () => {
113
- stage.off(event, listener)
114
- }
115
- },
116
- read: (key) => stage.getAttr(key),
117
- write: (key, value) => {
118
- stage.setAttr(key, value)
127
+ const nativeProps = capabilityProps(
128
+ owner!,
129
+ {
130
+ kind: `konva`,
131
+ node: stage,
132
+ suspend() {
133
+ return suspendNode(stage)
134
+ },
135
+ listen(event, listener) {
136
+ stage.on(event, listener)
137
+ return () => {
138
+ stage.off(event, listener)
139
+ }
140
+ },
141
+ read: (key) => stage.getAttr(key),
142
+ write: (key, value) => {
143
+ stage.setAttr(key, value)
144
+ },
119
145
  },
120
- })
146
+ () => ({ ...props }),
147
+ )
121
148
  let previous: Record<string, any> = {}
122
149
  bindScene(
123
150
  () => ({ ...props }),
@@ -0,0 +1,106 @@
1
+ import type { MotionValue, ValueAnimationTransition } from "motion"
2
+ import { animate, keyframes } from "motion"
3
+
4
+ import type { MotionScalar } from "./motion.ts"
5
+
6
+ const trajectories = new WeakMap<
7
+ MotionValue<MotionScalar>,
8
+ () => { position: number; velocity: number }
9
+ >()
10
+ const scalar = /^(-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)([a-z%]*)$/i
11
+ const brake = (progress: number) => progress * (2 - progress)
12
+ const returnToTarget = (progress: number) =>
13
+ progress * progress * (3 - 2 * progress)
14
+
15
+ /** Retarget a moving tween without changing its position or velocity at the join. */
16
+ export function animateTween(
17
+ value: MotionValue<MotionScalar>,
18
+ goal: MotionScalar,
19
+ transition: ValueAnimationTransition,
20
+ interrupted: boolean,
21
+ ): ReturnType<typeof animate> {
22
+ if (interrupted) value.stop()
23
+ const current = value.get()
24
+ const from =
25
+ typeof current === `number` ? [``, current, ``] : scalar.exec(current)
26
+ const to = typeof goal === `number` ? [``, goal, ``] : scalar.exec(goal)
27
+ const previous = trajectories.get(value)?.()
28
+ const velocity =
29
+ previous && from && Math.abs(previous.position - Number(from[1])) < 0.001
30
+ ? previous.velocity
31
+ : value.getVelocity()
32
+ trajectories.delete(value)
33
+ const duration = transition.duration ?? 0.3
34
+ // A duration/ease without an explicit type is also a Motion tween. Springs keep
35
+ // Motion's own velocity-aware integration; discrete values keep native mixing.
36
+ const tween =
37
+ transition.type === `tween` ||
38
+ (transition.type === undefined &&
39
+ (transition.duration !== undefined || transition.ease !== undefined))
40
+ const moving =
41
+ interrupted &&
42
+ tween &&
43
+ from &&
44
+ to &&
45
+ from[2] === to[2] &&
46
+ Number.isFinite(velocity) &&
47
+ velocity !== 0 &&
48
+ duration > 0
49
+ const braking = 0.2
50
+ const turn = from ? Number(from[1]) + (velocity * duration * braking) / 2 : 0
51
+ const waypoint = typeof current === `number` ? turn : `${turn}${from?.[2]}`
52
+ const frames = moving ? [current, waypoint, goal] : [current, goal]
53
+ // Constant deceleration: dx/dt at t=0 is v, and at the waypoint is zero.
54
+ // The return starts and ends at rest. Keyframes also handle goal === current.
55
+ const next = moving
56
+ ? {
57
+ ...transition,
58
+ type: `tween` as const,
59
+ duration,
60
+ delay: 0,
61
+ times: [0, braking, 1],
62
+ ease: [brake, returnToTarget],
63
+ }
64
+ : transition
65
+ // Values are already resolved. Synchronous numeric tweens also keep cancelled,
66
+ // not-yet-started resolver work from being revived by a timeline read.
67
+ const controls = animate(
68
+ value,
69
+ frames,
70
+ tween && (moving || current !== goal) ? { ...next, isSync: true } : next,
71
+ )
72
+ if (
73
+ tween &&
74
+ (moving || current !== goal) &&
75
+ from &&
76
+ to &&
77
+ from[2] === to[2] &&
78
+ duration > 0
79
+ ) {
80
+ const curve = keyframes({
81
+ keyframes: moving
82
+ ? [Number(from[1]), turn, Number(to[1])]
83
+ : [Number(from[1]), Number(to[1])],
84
+ duration: duration * 1000,
85
+ times: moving ? [0, braking, 1] : [0, 1],
86
+ ease: next.ease ?? `easeOut`,
87
+ })
88
+ const sample = (at: number) => curve.next(at * 1000).value
89
+
90
+ // Use the tween's own timeline. Frame-estimated MotionValue velocity becomes
91
+ // noisy when stop/resume happen several times within the same render frame.
92
+ trajectories.set(value, () => {
93
+ const at = Math.max(0, Math.min(duration, controls.time))
94
+ const before = Math.max(0, at - 0.0001),
95
+ after = Math.min(duration, at + 0.0001)
96
+ return {
97
+ position: sample(at),
98
+ velocity:
99
+ at <= 0 || at >= duration
100
+ ? 0
101
+ : (sample(after) - sample(before)) / (after - before),
102
+ }
103
+ })
104
+ }
105
+ return controls
106
+ }