@bun-native/renderer 0.0.0-stage → 0.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/root.ts ADDED
@@ -0,0 +1,391 @@
1
+ import {
2
+ NativeStateError,
3
+ type DropTargetEvent,
4
+ type InputState,
5
+ type NativeBatch,
6
+ type NativeDropTarget,
7
+ type NativeNode,
8
+ type NativeUIEvent,
9
+ type NativeWindow,
10
+ type Style,
11
+ } from '@bun-native/core'
12
+ import {
13
+ invalidate,
14
+ Node,
15
+ setProperty,
16
+ snapshot,
17
+ visit,
18
+ type Owner,
19
+ type Snapshot,
20
+ } from './nodes.ts'
21
+ import { commitNativeTree, type Committed, type Counts } from './native-tree.ts'
22
+ import { observeInput } from './input-intent.ts'
23
+ import { watchWindow } from './window-lifetime.ts'
24
+ import {
25
+ eventProperties,
26
+ isEventProperty,
27
+ type EventListener,
28
+ type EventProperty,
29
+ } from './event-properties.ts'
30
+
31
+ type Registration = {
32
+ listener: EventListener
33
+ unsubscribe: () => void
34
+ }
35
+
36
+ /** Adapter behavior that is not a public render option. */
37
+ export interface RenderAdapter {
38
+ /**
39
+ * Run one native callback; React batches it as a discrete update. An
40
+ * adapter that supplies this keeps each handler's registration while the
41
+ * handler property stays defined (see `Owner.stableHandlers`).
42
+ */
43
+ dispatch(listener: EventListener, event: NativeUIEvent): void | Promise<void>
44
+ }
45
+
46
+ export interface RenderOptions {
47
+ /** Initial native style of this root's ownership container; omitted preserves intrinsic sizing. */
48
+ style?: Style
49
+ }
50
+
51
+ export interface RenderRoot {
52
+ /** Initial native acknowledgement. A synchronous JSX evaluation error rejects this promise. */
53
+ readonly ready: Promise<void>
54
+ /** Ends after unmount or OS close; asynchronous renderer failures reject it. */
55
+ readonly closed: Promise<void>
56
+ readonly diagnostics: Readonly<{
57
+ nodes: number
58
+ listeners: number
59
+ pending: boolean
60
+ commits: number
61
+ mutations: Readonly<Counts>
62
+ }>
63
+ /** Wait until all currently staged mutations have native acknowledgements. */
64
+ flush(): Promise<void>
65
+ /** Dispose the framework owner, revoke callbacks and remove only this root's subtree. */
66
+ dispose(): Promise<void>
67
+ }
68
+
69
+ export interface RenderContext {
70
+ readonly container: Node
71
+ /** Register one callable teardown while active, before evaluating user components. */
72
+ onCleanup(cleanup: () => void): void
73
+ /** Unrecovered asynchronous framework errors terminate only this render root. */
74
+ fail(cause: unknown): void
75
+ }
76
+
77
+ class Root implements RenderRoot, Owner {
78
+ readonly token = {}
79
+ readonly root = new Node('box')
80
+ readonly ready: Promise<void>
81
+ readonly closed: Promise<void>
82
+ private resolveClosed!: () => void
83
+ private rejectClosed!: (error: Error) => void
84
+ private disposeFramework: (() => void) | undefined
85
+ private unwatch: (() => void) | undefined
86
+ private committed = new Map<Node, Committed>()
87
+ private readonly registrations = new Map<Node, Map<EventProperty, Registration>>()
88
+ private operation: Promise<void> | undefined
89
+ private version = 0
90
+ private acknowledged = -1
91
+ private phase: 'active' | 'disposing' | 'closed' = 'active'
92
+ private windowEnded = false
93
+ private failure: Error | undefined
94
+ private commits = 0
95
+ private readonly mutations: Counts = { create: 0, set: 0, insert: 0, remove: 0 }
96
+
97
+ constructor(
98
+ private readonly window: NativeWindow,
99
+ initialize: (context: RenderContext) => void,
100
+ style: Style | undefined,
101
+ private readonly adapter: RenderAdapter | undefined
102
+ ) {
103
+ // Copy before initialization or asynchronous commits, without publishing an owner yet.
104
+ setProperty(this.root, 'style', style)
105
+ this.closed = new Promise((resolve, reject) => {
106
+ this.resolveClosed = resolve
107
+ this.rejectClosed = reject
108
+ })
109
+ void this.closed.catch(() => {})
110
+ this.root.owner = this
111
+ this.root.scope = this.token
112
+ this.unwatch = watchWindow(window, () => {
113
+ this.windowEnded = true
114
+ this.stop()
115
+ this.finish()
116
+ })
117
+ try {
118
+ initialize({
119
+ container: this.root,
120
+ onCleanup: (cleanup) => {
121
+ if (this.phase !== 'active')
122
+ throw new NativeStateError(
123
+ 'invalid_state',
124
+ 'Cannot register framework cleanup after disposal has started'
125
+ )
126
+ if (typeof cleanup !== 'function')
127
+ throw new TypeError('Framework cleanup must be a function')
128
+ if (this.disposeFramework)
129
+ throw new NativeStateError('invalid_state', 'Framework cleanup is already registered')
130
+ this.disposeFramework = cleanup
131
+ },
132
+ fail: (cause) => this.fail(cause),
133
+ })
134
+ } catch (cause) {
135
+ this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
136
+ this.stop()
137
+ }
138
+ this.start()
139
+ this.ready = this.flush().then(() => {
140
+ if (this.commits === 0)
141
+ throw new NativeStateError(
142
+ 'invalid_handle',
143
+ 'Render root closed before initial native acknowledgement'
144
+ )
145
+ })
146
+ void this.ready.catch(() => {})
147
+ }
148
+
149
+ get diagnostics() {
150
+ let listeners = 0
151
+ for (const registrations of this.registrations.values()) listeners += registrations.size
152
+ return Object.freeze({
153
+ nodes: this.committed.size,
154
+ listeners,
155
+ pending: this.operation !== undefined,
156
+ commits: this.commits,
157
+ mutations: Object.freeze({ ...this.mutations }),
158
+ })
159
+ }
160
+
161
+ get stableHandlers(): boolean {
162
+ return this.adapter !== undefined
163
+ }
164
+
165
+ changed(): void {
166
+ if (this.phase !== 'active') return
167
+ this.version += 1
168
+ this.start()
169
+ }
170
+
171
+ detached(node: Node): void {
172
+ visit(node, (child) => this.revoke(child))
173
+ }
174
+
175
+ private revoke(node: Node, property?: EventProperty): void {
176
+ const registrations = this.registrations.get(node)
177
+ if (!registrations) return
178
+ if (property) {
179
+ const registration = registrations.get(property)
180
+ registrations.delete(property)
181
+ if (!registrations.size) this.registrations.delete(node)
182
+ registration?.unsubscribe()
183
+ } else {
184
+ this.registrations.delete(node)
185
+ for (const registration of registrations.values()) registration.unsubscribe()
186
+ registrations.clear()
187
+ }
188
+ }
189
+
190
+ registerDropTarget(
191
+ node: Node,
192
+ listener: (event: DropTargetEvent) => void | Promise<void>
193
+ ): Promise<NativeDropTarget> {
194
+ const state = this.committed.get(node)
195
+ if (this.phase !== 'active' || !state)
196
+ return Promise.reject(
197
+ new NativeStateError('invalid_handle', 'Node is unmounted or not yet committed')
198
+ )
199
+ // The native target is revoked when a later commit removes this node.
200
+ return this.window.registerDropTarget(state.handle, listener)
201
+ }
202
+
203
+ input(node: Node): InputState {
204
+ const state = this.committed.get(node)
205
+ if (this.phase !== 'active' || !state || state.handle.kind !== 'input')
206
+ throw new NativeStateError(
207
+ 'invalid_handle',
208
+ 'Input is unmounted or has no committed native handle'
209
+ )
210
+ return this.window.input(state.handle as NativeNode<'input'>)
211
+ }
212
+
213
+ async request(node: Node, send: (batch: NativeBatch, handle: NativeNode) => void): Promise<void> {
214
+ await this.flush()
215
+ const state = this.committed.get(node)
216
+ if (this.phase !== 'active' || !state)
217
+ throw new NativeStateError('invalid_handle', 'Node is unmounted or has no committed handle')
218
+ await this.window.batch((batch) => send(batch, state.handle))
219
+ }
220
+
221
+ private start(): void {
222
+ if (this.operation || this.phase === 'closed') return
223
+ this.operation = Promise.resolve()
224
+ .then(async () => {
225
+ while (this.phase === 'active' && this.acknowledged !== this.version) {
226
+ const version = this.version
227
+ await this.commit(snapshot(this.root))
228
+ this.acknowledged = version
229
+ }
230
+ if (this.phase === 'disposing') await this.cleanup()
231
+ })
232
+ .catch(async (cause: unknown) => {
233
+ if (!this.windowEnded) {
234
+ this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
235
+ this.stop()
236
+ try {
237
+ await this.cleanup()
238
+ } catch (cleanupError) {
239
+ this.failure = new AggregateError(
240
+ [this.failure, cleanupError],
241
+ 'Native renderer cleanup failed'
242
+ )
243
+ this.finish()
244
+ }
245
+ }
246
+ })
247
+ .finally(() => {
248
+ this.operation = undefined
249
+ if (
250
+ this.phase === 'disposing' ||
251
+ (this.phase === 'active' && this.acknowledged !== this.version)
252
+ )
253
+ this.start()
254
+ })
255
+ }
256
+
257
+ async flush(): Promise<void> {
258
+ while (this.operation) await this.operation
259
+ if (this.failure) throw this.failure
260
+ }
261
+
262
+ async dispose(): Promise<void> {
263
+ this.stop()
264
+ this.start()
265
+ await this.flush()
266
+ await this.closed
267
+ }
268
+
269
+ private fail(cause: unknown): void {
270
+ if (this.phase !== 'active') return
271
+ this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
272
+ this.stop()
273
+ this.start()
274
+ }
275
+
276
+ private stop(): void {
277
+ if (this.phase === 'closed') return
278
+ this.phase = 'disposing'
279
+ const dispose = this.disposeFramework
280
+ this.disposeFramework = undefined
281
+ try {
282
+ dispose?.()
283
+ } catch (cause) {
284
+ this.failure ??= cause instanceof Error ? cause : new Error(String(cause))
285
+ }
286
+ for (const node of this.registrations.keys()) this.revoke(node)
287
+ visit(this.root, (node) => {
288
+ invalidate(node)
289
+ node.owner = undefined
290
+ for (const name of Object.keys(node.properties))
291
+ if (isEventProperty(name)) delete node.properties[name]
292
+ })
293
+ }
294
+
295
+ private finish(): void {
296
+ if (this.phase === 'closed') return
297
+ this.phase = 'closed'
298
+ this.unwatch?.()
299
+ this.unwatch = undefined
300
+ this.committed.clear()
301
+ this.root.children.length = 0
302
+ invalidate(this.root)
303
+ if (this.failure) this.rejectClosed(this.failure)
304
+ else this.resolveClosed()
305
+ }
306
+
307
+ private async cleanup(): Promise<void> {
308
+ const root = this.committed.get(this.root)
309
+ if (root && !this.windowEnded) {
310
+ await this.window.batch((batch) => batch.remove(root.handle))
311
+ this.mutations.remove += 1
312
+ this.commits += 1
313
+ }
314
+ this.finish()
315
+ }
316
+
317
+ private async commit(changes: ReadonlyMap<Node, Snapshot>): Promise<void> {
318
+ const { updates, removed, counts } = await commitNativeTree(
319
+ this.window,
320
+ this.root,
321
+ this.committed,
322
+ changes
323
+ )
324
+ if (this.windowEnded) return
325
+ // Publish in place only after acknowledgement; unchanged records stay shared.
326
+ for (const node of removed) this.committed.delete(node)
327
+ for (const [node, state] of updates) this.committed.set(node, state)
328
+ if (Object.values(counts).some((count) => count > 0)) this.commits += 1
329
+ for (const field of ['create', 'set', 'insert', 'remove'] as const)
330
+ this.mutations[field] += counts[field]
331
+ if (this.phase !== 'active') return
332
+ // Native snapshots own immutable transaction state, never live unsubscribe
333
+ // functions. A detach during acknowledgement revokes this separate registry,
334
+ // and every unchanged record's registrations were reconciled when it was
335
+ // published, so only removed and changed nodes need reconciliation.
336
+ for (const node of removed) this.revoke(node)
337
+ for (const [node, state] of updates) {
338
+ if (node.owner !== this) {
339
+ this.revoke(node)
340
+ continue
341
+ }
342
+ for (const [name, registration] of this.registrations.get(node) ?? [])
343
+ if (
344
+ this.adapter
345
+ ? state.events[name] === undefined
346
+ : state.events[name] !== registration.listener
347
+ )
348
+ this.revoke(node, name)
349
+ for (const [name, listener] of Object.entries(state.events)) {
350
+ if (!isEventProperty(name) || !listener || this.registrations.get(node)?.has(name)) continue
351
+ const binding = eventProperties[name]
352
+ const unsubscribe = this.window.on(
353
+ state.handle,
354
+ binding.type,
355
+ async (event) => {
356
+ if (node.owner !== this) return
357
+ const adapter = this.adapter
358
+ const current = node.properties[name]
359
+ // A replaced handler is not called before its replacement commits,
360
+ // unless the adapter keeps the registration and calls the latest.
361
+ if (adapter ? !current : current !== listener) return
362
+ if (event.type === 'input') observeInput(event)
363
+ await (adapter ? adapter.dispatch(current!, event) : listener(event))
364
+ await this.flush()
365
+ },
366
+ { capture: binding.capture }
367
+ )
368
+ let registrations = this.registrations.get(node)
369
+ if (!registrations) {
370
+ registrations = new Map()
371
+ this.registrations.set(node, registrations)
372
+ }
373
+ registrations.set(name, { listener, unsubscribe })
374
+ }
375
+ }
376
+ }
377
+ }
378
+
379
+ /** Own one framework's staged tree, atomic native commits and terminal cleanup. */
380
+ export function createRenderRoot(
381
+ window: NativeWindow,
382
+ initialize: (context: RenderContext) => void,
383
+ options: RenderOptions = {},
384
+ adapter?: RenderAdapter
385
+ ): RenderRoot {
386
+ if (!options || typeof options !== 'object' || Array.isArray(options))
387
+ throw new TypeError('Native render options must be an object')
388
+ for (const name of Object.keys(options))
389
+ if (name !== 'style') throw new TypeError('Unknown native render option: ' + name)
390
+ return new Root(window, initialize, options.style, adapter)
391
+ }
@@ -0,0 +1,42 @@
1
+ import { NativeStateError, type NativeWindow } from '@bun-native/core'
2
+
3
+ type Registration = { listener: (() => void) | undefined }
4
+ type Lifetime = { ended: boolean; listeners: Set<Registration> }
5
+ const lifetimes = new WeakMap<NativeWindow, Lifetime>()
6
+
7
+ /** Release ownership before invocation, even if user code throws or reenters. */
8
+ function consume(registration: Registration): (() => void) | undefined {
9
+ const listener = registration.listener
10
+ registration.listener = undefined
11
+ return listener
12
+ }
13
+
14
+ function lifetimeFor(window: NativeWindow): Lifetime {
15
+ let lifetime = lifetimes.get(window)
16
+ if (!lifetime) {
17
+ const created: Lifetime = { ended: false, listeners: new Set() }
18
+ lifetime = created
19
+ lifetimes.set(window, created)
20
+ // This scope never contains an individual root. Completion owns revocable
21
+ // registrations rather than keeping callback bindings in retained closures.
22
+ void window.closed.then(() => {
23
+ created.ended = true
24
+ const listeners = [...created.listeners].map(consume)
25
+ created.listeners.clear()
26
+ for (const notify of listeners) notify?.()
27
+ })
28
+ }
29
+ return lifetime
30
+ }
31
+
32
+ /** One completion observer per window; release clears the callback itself. */
33
+ export function watchWindow(window: NativeWindow, listener: () => void): () => void {
34
+ const lifetime = lifetimeFor(window)
35
+ if (lifetime.ended) throw new NativeStateError('invalid_handle', 'Window is already closed')
36
+ const registration: Registration = { listener }
37
+ lifetime.listeners.add(registration)
38
+ return () => {
39
+ lifetime.listeners.delete(registration)
40
+ registration.listener = undefined
41
+ }
42
+ }