@bun-native/renderer 0.0.0-stage → 0.33.0

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