@bun-native/renderer 0.33.1 → 0.33.3

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/README.md CHANGED
@@ -2,4 +2,4 @@
2
2
 
3
3
  Native element tree and batching shared by Bun Native adapters.
4
4
 
5
- Part of [Bun Native](https://github.com/0xPlayerOne/bun-native), an experimental developer preview. Version 0.33.1 was built from [c56fdd675365](https://github.com/0xPlayerOne/bun-native/tree/c56fdd6753653a10144a4167c1d3dfb3c38a0647) and published from GitHub Actions with npm provenance. Use the Bun revision pinned in that commit's toolchain.json. Start with the [getting-started guide](https://github.com/0xPlayerOne/bun-native/blob/c56fdd6753653a10144a4167c1d3dfb3c38a0647/docs/getting-started.md); `bun-native host install` fetches the matching release host. The license notice is in LICENSE.
5
+ Part of [Bun Native](https://github.com/0xPlayerOne/bun-native), an experimental developer preview. Version 0.33.3 was built from [bf02b4420333](https://github.com/0xPlayerOne/bun-native/tree/bf02b44203336646cf156e369cd57b84496a3a7d) and published from GitHub Actions with npm provenance. Use the Bun revision pinned in that commit's toolchain.json. Start with the [getting-started guide](https://github.com/0xPlayerOne/bun-native/blob/bf02b44203336646cf156e369cd57b84496a3a7d/docs/getting-started.md); `bun-native host install` fetches the matching release host. The license notice is in LICENSE.
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "commit": "c56fdd6753653a10144a4167c1d3dfb3c38a0647",
4
- "tree": "c6e81b3f9d041e11dd0413b5fdd7a50910383854",
3
+ "commit": "bf02b44203336646cf156e369cd57b84496a3a7d",
4
+ "tree": "5943b16183fcc166a5694a7da25bd1d33a3788d4",
5
5
  "files": {
6
6
  "package.json": {
7
- "bytes": 2115,
8
- "sha256": "caf866d56f3cd7530d5735ecbf62512e9e22526bc44c75a4b48a18c26352c0b8"
7
+ "bytes": 2258,
8
+ "sha256": "52d4fbfcecc45b4c0da143af60977d68491559283dc78ee31ce720e51d001106"
9
9
  },
10
10
  "packages/renderer/package.json": {
11
11
  "bytes": 192,
@@ -24,16 +24,16 @@
24
24
  "sha256": "efe908fe1df1d14a7cbc1e3e30e8e76dc888fb865dca6b203bf91c18f3bb4d02"
25
25
  },
26
26
  "packages/renderer/src/native-tree.ts": {
27
- "bytes": 10353,
28
- "sha256": "a0ee9a365500bc3cd66dcda5410fcf396681494daa2bac78370426036184ed4e"
27
+ "bytes": 10947,
28
+ "sha256": "6e42f29c1405b4f728b6df0b9ef1f959ac403516a9a99582354c513d7e9e91ac"
29
29
  },
30
30
  "packages/renderer/src/nodes.ts": {
31
- "bytes": 26306,
32
- "sha256": "e24c747da4933cdfa2dda80bac54e602828a530c2f5920ce85119b7e78427548"
31
+ "bytes": 27579,
32
+ "sha256": "cb6acf41c522ee9512a43665db097a3ec17e8799699afefceba0c0e0b3bf8f62"
33
33
  },
34
34
  "packages/renderer/src/root.ts": {
35
- "bytes": 13196,
36
- "sha256": "20a18fb833f5f7a89180967c735efa875dc5a408826a17cee4fffc50fd2885d3"
35
+ "bytes": 13836,
36
+ "sha256": "0a58f9d95198386079663393bf71f30f28454578500135b313a6aea63e507553"
37
37
  },
38
38
  "packages/renderer/src/window-lifetime.ts": {
39
39
  "bytes": 1635,
@@ -49,7 +49,7 @@
49
49
  "sha256": "9f4d9362cb4cc38c0f4e705295789a0cbfec46ffdd007e0541b9441a7c3003a7"
50
50
  },
51
51
  "dependencyLock": {
52
- "bytes": 28357,
53
- "sha256": "65e3dbd01be4a1889367690faf1a9c3f08fb31d22dbd273d9bb9f39dd6baa6fb"
52
+ "bytes": 28430,
53
+ "sha256": "9d321f65b9224958ec99286628d652232a16e3242ea9536a396bceaf72892460"
54
54
  }
55
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bun-native/renderer",
3
- "version": "0.33.1",
3
+ "version": "0.33.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -15,7 +15,7 @@
15
15
  "exports": "./src/index.ts",
16
16
  "description": "Native element tree and batching shared by Bun Native adapters.",
17
17
  "dependencies": {
18
- "@bun-native/core": "0.33.1"
18
+ "@bun-native/core": "0.33.3"
19
19
  },
20
20
  "repository": {
21
21
  "type": "git",
@@ -11,15 +11,32 @@ import type { Node, Snapshot } from './nodes.ts'
11
11
  import { stableChildren } from '@bun-native/core/order'
12
12
 
13
13
  export type Counts = { create: number; set: number; insert: number; remove: number }
14
- export type Committed = Snapshot & { handle: NativeNode }
15
14
 
16
- // Unchanged nodes share one immutable element across commits; memoize its
17
- // serialization instead of restringifying the committed side every commit.
18
- const keys = new WeakMap<Element, string>()
19
- function key(element: Element): string {
20
- let value = keys.get(element)
21
- if (value === undefined) keys.set(element, (value = JSON.stringify(element)))
22
- return value
15
+ /**
16
+ * Whether two element values are equal as the wire sees them: plain data whose
17
+ * `undefined` properties are omitted. Elements hold only primitives and one
18
+ * level of style, so comparing in place is cheaper than serializing either.
19
+ */
20
+ function same(left: unknown, right: unknown): boolean {
21
+ if (left === right) return true
22
+ if (
23
+ left === null ||
24
+ right === null ||
25
+ typeof left !== 'object' ||
26
+ typeof right !== 'object' ||
27
+ Array.isArray(left) !== Array.isArray(right)
28
+ )
29
+ return false
30
+ const a = left as Record<string, unknown>
31
+ const b = right as Record<string, unknown>
32
+ let fields = 0
33
+ for (const name in a) {
34
+ if (a[name] === undefined) continue
35
+ if (!same(a[name], b[name])) return false
36
+ fields += 1
37
+ }
38
+ for (const name in b) if (b[name] !== undefined) fields -= 1
39
+ return fields === 0
23
40
  }
24
41
 
25
42
  const noChildren: readonly Node[] = Object.freeze([])
@@ -27,7 +44,8 @@ const noChildren: readonly Node[] = Object.freeze([])
27
44
  function updateInput(
28
45
  window: NativeWindow,
29
46
  batch: NativeBatch,
30
- old: Committed,
47
+ old: Snapshot,
48
+ handle: NativeNode<'input'>,
31
49
  state: Snapshot & { element: Extract<Element, { kind: 'input' }> }
32
50
  ): boolean {
33
51
  if (old.element.kind !== 'input')
@@ -37,7 +55,7 @@ function updateInput(
37
55
  const intent = state.inputIntent
38
56
  if (intent && intent !== old.inputIntent) {
39
57
  if (intent.observedNode) {
40
- if (intent.observedNode !== old.handle)
58
+ if (intent.observedNode !== handle)
41
59
  throw new NativeStateError(
42
60
  'invalid_handle',
43
61
  'Native input observation belongs to another node'
@@ -45,61 +63,60 @@ function updateInput(
45
63
  // Echo is an observation of a native edit, even if ingestion has advanced
46
64
  // again before its callback runs. Never emit it as a replacement command.
47
65
  } else {
48
- batch.set(old.handle as NativeNode<'input'>, state.element, intent.revision)
66
+ batch.set(handle, state.element, intent.revision)
49
67
  return true
50
68
  }
51
69
  }
52
- const appearance = (element: Extract<Element, { kind: 'input' }>) =>
53
- JSON.stringify({
54
- placeholder: element.placeholder ?? '',
55
- disabled: element.disabled === true,
56
- read_only: element.read_only === true,
57
- style: element.style ?? {},
58
- })
59
- if (appearance(old.element) === appearance(state.element)) return false
70
+ const before = old.element
71
+ const after = state.element
72
+ if (
73
+ (before.placeholder ?? '') === (after.placeholder ?? '') &&
74
+ (before.disabled === true) === (after.disabled === true) &&
75
+ (before.read_only === true) === (after.read_only === true) &&
76
+ same(before.style ?? {}, after.style ?? {})
77
+ )
78
+ return false
60
79
  // An appearance/state-only update preserves the current native value; this never upgrades
61
80
  // an older application value intent to a newer revision.
62
- const current = window.input(old.handle as NativeNode<'input'>)
63
- batch.set(
64
- old.handle as NativeNode<'input'>,
65
- { ...state.element, value: current.value },
66
- current.revision
67
- )
81
+ const current = window.input(handle)
82
+ batch.set(handle, { ...state.element, value: current.value }, current.revision)
68
83
  return true
69
84
  }
70
85
 
71
86
  export type Commit = {
72
- /** Committed records for every changed node, to publish over the previous ones. */
73
- updates: Map<Node, Committed>
87
+ /** Native handles of the nodes this batch created. */
88
+ created: Map<Node, NativeNode>
74
89
  /** Previously committed nodes that left the tree, including removed descendants. */
75
90
  removed: Node[]
76
91
  counts: Counts
77
92
  }
78
93
 
79
94
  /**
80
- * Framework-independent native diff from the changed captures alone. Publish
81
- * its records only after atomic acknowledgement; `previous` is read, never
82
- * mutated, so a rejected batch leaves committed state untouched.
95
+ * Framework-independent native diff from the changed captures alone. After
96
+ * atomic acknowledgement, the caller publishes every change as its committed
97
+ * record and each created handle; each node's `committed` and `handle` are
98
+ * read, never written, so a rejected batch leaves committed state untouched.
99
+ * A committed node's native handle never changes, so it is kept apart from
100
+ * its record.
83
101
  */
84
102
  export async function commitNativeTree(
85
103
  window: NativeWindow,
86
104
  root: Node,
87
- previous: ReadonlyMap<Node, Committed>,
88
105
  changes: ReadonlyMap<Node, Snapshot>
89
106
  ): Promise<Commit> {
90
107
  const counts: Counts = { create: 0, set: 0, insert: 0, remove: 0 }
91
- const [updates, removed] = await window.batch((batch) => {
108
+ const [created, removed] = await window.batch((batch) => {
92
109
  const removed: Node[] = []
93
- // Working state overlays `previous` and records only what this batch
110
+ // Working state overlays committed records and records only what this batch
94
111
  // changes, instead of copying every committed handle, parent and child list.
95
112
  const created = new Map<Node, NativeNode>()
96
113
  const parents = new Map<Node, Node>()
97
114
  const edited = new Map<Node, Node[]>()
98
- const handle = (node: Node) => created.get(node) ?? previous.get(node)!.handle
115
+ const handle = (node: Node) => created.get(node) ?? node.handle!
99
116
  const parentOf = (node: Node) =>
100
- parents.has(node) ? parents.get(node) : previous.get(node)?.parent
117
+ parents.has(node) ? parents.get(node) : node.committed?.parent
101
118
  const childrenOf = (node: Node): readonly Node[] =>
102
- edited.get(node) ?? previous.get(node)?.children ?? noChildren
119
+ edited.get(node) ?? node.committed?.children ?? noChildren
103
120
  const editChildren = (node: Node): Node[] => {
104
121
  let list = edited.get(node)
105
122
  if (!list) edited.set(node, (list = [...childrenOf(node)]))
@@ -133,14 +150,14 @@ export async function commitNativeTree(
133
150
  }
134
151
  const forget = (node: Node): void => {
135
152
  removed.push(node)
136
- for (const child of previous.get(node)!.children) if (!changes.has(child)) forget(child)
153
+ for (const child of node.committed!.children) if (!changes.has(child)) forget(child)
137
154
  }
138
155
  // Only a recaptured parent can have lost a committed child. A lost child
139
156
  // still in the tree was reinserted elsewhere and is therefore recaptured.
140
157
  // Lost children leave their working list in one pass per parent, so
141
158
  // clearing a keyed region costs O(children) rather than O(children²).
142
159
  for (const [parent, state] of changes) {
143
- const old = previous.get(parent)
160
+ const old = parent.committed
144
161
  if (!old?.children.length || old.children === state.children) continue
145
162
  // Children shared by both lists' ends are retained; only the middles
146
163
  // can differ, and keyed edits usually leave them short.
@@ -163,11 +180,15 @@ export async function commitNativeTree(
163
180
  if (kept === 0) continue
164
181
  const retained = new Set(after.slice(start, afterEnd))
165
182
  const lost = new Set<Node>()
166
- for (let index = start; index < end; index += 1) {
183
+ // A pure suffix can leave last-first, making each core/native removal a tail pop.
184
+ const tail = afterEnd === start && end === before.length
185
+ const stop = tail ? start - 1 : end
186
+ const step = tail ? -1 : 1
187
+ for (let index = tail ? end - 1 : start; index !== stop; index += step) {
167
188
  const node = before[index]!
168
189
  if (changes.has(node) || retained.has(node)) continue
169
190
  rescue(node)
170
- batch.remove(previous.get(node)!.handle)
191
+ batch.remove(node.handle!)
171
192
  counts.remove += 1
172
193
  lost.add(node)
173
194
  if (parent === root) unlisted += 1
@@ -180,9 +201,8 @@ export async function commitNativeTree(
180
201
  )
181
202
  if (parent === root) unlisted = 0
182
203
  }
183
- const updates = new Map<Node, Committed>()
184
204
  for (const [node, state] of changes) {
185
- const old = previous.get(node)
205
+ const old = node.committed
186
206
  if (!old) {
187
207
  if (state.inputIntent?.observedNode)
188
208
  throw new NativeStateError(
@@ -202,14 +222,15 @@ export async function commitNativeTree(
202
222
  batch.append(window.root, nativeNode)
203
223
  counts.insert += 1
204
224
  }
205
- updates.set(node, { ...state, handle: nativeNode })
206
225
  continue
207
226
  }
208
- updates.set(node, { ...state, handle: old.handle })
227
+ const nativeNode = node.handle!
209
228
  if (state.element.kind === 'input') {
210
- if (updateInput(window, batch, old, { ...state, element: state.element })) counts.set += 1
211
- } else if (key(old.element) !== key(state.element)) {
212
- batch.set(old.handle as NativeNode<Exclude<Element['kind'], 'input'>>, state.element)
229
+ const input = { ...state, element: state.element }
230
+ if (updateInput(window, batch, old, nativeNode as NativeNode<'input'>, input))
231
+ counts.set += 1
232
+ } else if (!same(old.element, state.element)) {
233
+ batch.set(nativeNode as NativeNode<Exclude<Element['kind'], 'input'>>, state.element)
213
234
  counts.set += 1
214
235
  }
215
236
  }
@@ -242,7 +263,7 @@ export async function commitNativeTree(
242
263
  before = at
243
264
  }
244
265
  }
245
- return [updates, removed] as const
266
+ return [created, removed] as const
246
267
  })
247
- return { updates, removed, counts }
268
+ return { created, removed, counts }
248
269
  }
package/src/nodes.ts CHANGED
@@ -73,10 +73,17 @@ export type PropertyName = keyof Properties
73
73
 
74
74
  const isContainer = (kind: Node['kind']) => kind === 'box' || kind === 'split' || kind === 'overlay'
75
75
 
76
- const nodes = new WeakSet<object>()
76
+ /** Whether `value` was made by this module's `Node` constructor. */
77
+ let isStaged: (value: object) => boolean
77
78
 
78
79
  export class Node implements RendererNode {
79
80
  declare readonly [identity]: true
81
+ /** Unforgeable brand: checked with `in`, it costs no lookup in a side table. */
82
+ readonly #brand = true
83
+ static {
84
+ // Reading the brand after `in` is what marks it used for the linter.
85
+ isStaged = (value) => #brand in value && (value as Node).#brand
86
+ }
80
87
  /**
81
88
  * Staged children, where a detached child leaves an `undefined` hole until
82
89
  * the list is next read: removing a child from a wide list then neither
@@ -97,9 +104,10 @@ export class Node implements RendererNode {
97
104
  captured: Snapshot | undefined
98
105
  /**
99
106
  * This node or a staged descendant lacks a current capture. Every dirty node
100
- * in a tree has dirty ancestors, so snapshot() walks only dirty paths.
107
+ * in a tree has dirty ancestors, so snapshot() walks only dirty paths. A new
108
+ * node has no capture yet.
101
109
  */
102
- dirty = false
110
+ dirty = true
103
111
  /**
104
112
  * Dirty children registered when they became dirty, so a parent whose own
105
113
  * capture is current visits only them. A recaptured parent scans all of its
@@ -110,10 +118,17 @@ export class Node implements RendererNode {
110
118
  index = 0
111
119
  /** Children before this position have current `index` hints. */
112
120
  indexed = 0
121
+ /**
122
+ * The owning render root's acknowledged record and native handle, kept on
123
+ * the node rather than in root-level maps. Only that root writes them: it
124
+ * publishes them after native acknowledgement and clears them when a commit
125
+ * removes the node or the root finishes, so nothing reachable from a
126
+ * removed or disposed node retains committed state.
127
+ */
128
+ committed: Snapshot | undefined
129
+ handle: NativeNode | undefined
113
130
 
114
- constructor(readonly kind: Element['kind'] | 'text-node') {
115
- nodes.add(this)
116
- }
131
+ constructor(readonly kind: Element['kind'] | 'text-node') {}
117
132
 
118
133
  /** The staged children in order; adapters may truncate this list directly. */
119
134
  get children(): Node[] {
@@ -123,7 +138,7 @@ export class Node implements RendererNode {
123
138
  }
124
139
 
125
140
  export function asNode(value: RendererNode): Node {
126
- if (!value || typeof value !== 'object' || !nodes.has(value))
141
+ if (!value || typeof value !== 'object' || !isStaged(value))
127
142
  throw new NativeStateError('invalid_handle', 'Expected an owned staged native node')
128
143
  return value as Node
129
144
  }
@@ -310,15 +325,18 @@ export function insertNode(parent: Node, node: Node, anchor?: Node): void {
310
325
  if (owner && node.owner !== owner) checkScope(node, owner.token)
311
326
  const previousOwner = node.owner
312
327
  // An owner only holds nodes attached under its root (removal and disposal
313
- // clear it), so this subtree moves without ever leaving the live tree.
314
- const moved = owner !== undefined && previousOwner === owner && node.parent !== undefined
328
+ // clear it), so this subtree moves without ever leaving the live tree. An
329
+ // unowned subtree that stays unowned holds no capture an owner committed:
330
+ // leaving an owner cleared them, and the next owner adopts it in full. An
331
+ // adapter that builds detached trees bottom-up thus walks each node once.
332
+ const moved = previousOwner === owner && (owner === undefined || node.parent !== undefined)
315
333
  if (previousOwner && previousOwner !== owner) previousOwner.detached(node)
316
334
  if (node.parent) detachChild(node.parent, node)
317
335
  invalidate(node.parent)
318
336
  invalidate(parent)
319
337
  node.parent = parent
320
338
  attachChild(parent, node, anchor ? childIndex(parent, anchor) : parent.staged.length)
321
- // Adapters may clear detached nodes directly, so a reinserted subtree is
339
+ // Adapters may clear detached nodes directly, so a subtree an owner takes is
322
340
  // always captured again from its current state. A moved subtree's captures
323
341
  // and dirty paths stay current below it: its root's capture names the old
324
342
  // parent, so snapshot() recaptures that node alone, and the diff moves it
@@ -493,7 +511,12 @@ export type Snapshot = Readonly<{
493
511
  inputIntent: InputIntent | undefined
494
512
  }>
495
513
 
496
- function leafStyle(style: Style): NonNullable<Extract<Element, { kind: 'text' }>['style']> {
514
+ type LeafStyle = NonNullable<Extract<Element, { kind: 'text' }>['style']>
515
+
516
+ function leafStyle(style: Style): LeafStyle {
517
+ // The stored style is the renderer's own copy and is replaced, never
518
+ // mutated, so a style without scrolling members is shared as it is.
519
+ if (!('overflow' in style) && !('scroll_anchor' in style)) return style as LeafStyle
497
520
  const { overflow, scroll_anchor, ...rest } = style
498
521
  if (
499
522
  scroll_anchor !== undefined ||
@@ -583,7 +606,7 @@ function build(node: Node, parent: Node | undefined): Snapshot {
583
606
  ...(props.accessibleSelected === undefined
584
607
  ? {}
585
608
  : { accessible_selected: props.accessibleSelected }),
586
- ...(props.style ? { style: { ...props.style } } : {}),
609
+ ...(props.style ? { style: props.style } : {}),
587
610
  } as Element
588
611
  else if (node.kind === 'split')
589
612
  // Core validation rejects gap and alignment on a split.
@@ -605,7 +628,7 @@ function build(node: Node, parent: Node | undefined): Snapshot {
605
628
  ...(props.navigation === undefined ? {} : { navigation: props.navigation }),
606
629
  ...(props.surface === undefined ? {} : { surface: props.surface }),
607
630
  ...(props.accessibleLabel === undefined ? {} : { accessible_label: props.accessibleLabel }),
608
- ...(props.style ? { style: { ...props.style } } : {}),
631
+ ...(props.style ? { style: props.style } : {}),
609
632
  } as Element
610
633
  else if (node.kind === 'input')
611
634
  element = {
package/src/root.ts CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  type Owner,
19
19
  type Snapshot,
20
20
  } from './nodes.ts'
21
- import { commitNativeTree, type Committed, type Counts } from './native-tree.ts'
21
+ import { commitNativeTree, type Counts } from './native-tree.ts'
22
22
  import { observeInput } from './input-intent.ts'
23
23
  import { watchWindow } from './window-lifetime.ts'
24
24
  import {
@@ -83,7 +83,8 @@ class Root implements RenderRoot, Owner {
83
83
  private rejectClosed!: (error: Error) => void
84
84
  private disposeFramework: (() => void) | undefined
85
85
  private unwatch: (() => void) | undefined
86
- private committed = new Map<Node, Committed>()
86
+ /** Committed nodes; each holds its own record and handle (see `Node.committed`). */
87
+ private nodes = 0
87
88
  private readonly registrations = new Map<Node, Map<EventProperty, Registration>>()
88
89
  private operation: Promise<void> | undefined
89
90
  private version = 0
@@ -150,7 +151,7 @@ class Root implements RenderRoot, Owner {
150
151
  let listeners = 0
151
152
  for (const registrations of this.registrations.values()) listeners += registrations.size
152
153
  return Object.freeze({
153
- nodes: this.committed.size,
154
+ nodes: this.nodes,
154
155
  listeners,
155
156
  pending: this.operation !== undefined,
156
157
  commits: this.commits,
@@ -191,31 +192,31 @@ class Root implements RenderRoot, Owner {
191
192
  node: Node,
192
193
  listener: (event: DropTargetEvent) => void | Promise<void>
193
194
  ): Promise<NativeDropTarget> {
194
- const state = this.committed.get(node)
195
- if (this.phase !== 'active' || !state)
195
+ const handle = node.handle
196
+ if (this.phase !== 'active' || !handle)
196
197
  return Promise.reject(
197
198
  new NativeStateError('invalid_handle', 'Node is unmounted or not yet committed')
198
199
  )
199
200
  // The native target is revoked when a later commit removes this node.
200
- return this.window.registerDropTarget(state.handle, listener)
201
+ return this.window.registerDropTarget(handle, listener)
201
202
  }
202
203
 
203
204
  input(node: Node): InputState {
204
- const state = this.committed.get(node)
205
- if (this.phase !== 'active' || !state || state.handle.kind !== 'input')
205
+ const handle = node.handle
206
+ if (this.phase !== 'active' || !handle || handle.kind !== 'input')
206
207
  throw new NativeStateError(
207
208
  'invalid_handle',
208
209
  'Input is unmounted or has no committed native handle'
209
210
  )
210
- return this.window.input(state.handle as NativeNode<'input'>)
211
+ return this.window.input(handle as NativeNode<'input'>)
211
212
  }
212
213
 
213
214
  async request(node: Node, send: (batch: NativeBatch, handle: NativeNode) => void): Promise<void> {
214
215
  await this.flush()
215
- const state = this.committed.get(node)
216
- if (this.phase !== 'active' || !state)
216
+ const handle = node.handle
217
+ if (this.phase !== 'active' || !handle)
217
218
  throw new NativeStateError('invalid_handle', 'Node is unmounted or has no committed handle')
218
- await this.window.batch((batch) => send(batch, state.handle))
219
+ await this.window.batch((batch) => send(batch, handle))
219
220
  }
220
221
 
221
222
  private start(): void {
@@ -297,7 +298,8 @@ class Root implements RenderRoot, Owner {
297
298
  this.phase = 'closed'
298
299
  this.unwatch?.()
299
300
  this.unwatch = undefined
300
- this.committed.clear()
301
+ release(this.root)
302
+ this.nodes = 0
301
303
  this.root.children.length = 0
302
304
  invalidate(this.root)
303
305
  if (this.failure) this.rejectClosed(this.failure)
@@ -305,9 +307,9 @@ class Root implements RenderRoot, Owner {
305
307
  }
306
308
 
307
309
  private async cleanup(): Promise<void> {
308
- const root = this.committed.get(this.root)
310
+ const root = this.root.handle
309
311
  if (root && !this.windowEnded) {
310
- await this.window.batch((batch) => batch.remove(root.handle))
312
+ await this.window.batch((batch) => batch.remove(root))
311
313
  this.mutations.remove += 1
312
314
  this.commits += 1
313
315
  }
@@ -315,16 +317,16 @@ class Root implements RenderRoot, Owner {
315
317
  }
316
318
 
317
319
  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
- )
320
+ const { created, removed, counts } = await commitNativeTree(this.window, this.root, changes)
324
321
  if (this.windowEnded) return
325
322
  // 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)
323
+ for (const node of removed) {
324
+ node.committed = undefined
325
+ node.handle = undefined
326
+ }
327
+ for (const [node, state] of changes) node.committed = state
328
+ for (const [node, handle] of created) node.handle = handle
329
+ this.nodes += created.size - removed.length
328
330
  if (Object.values(counts).some((count) => count > 0)) this.commits += 1
329
331
  for (const field of ['create', 'set', 'insert', 'remove'] as const)
330
332
  this.mutations[field] += counts[field]
@@ -334,23 +336,28 @@ class Root implements RenderRoot, Owner {
334
336
  // and every unchanged record's registrations were reconciled when it was
335
337
  // published, so only removed and changed nodes need reconciliation.
336
338
  for (const node of removed) this.revoke(node)
337
- for (const [node, state] of updates) {
339
+ for (const [node, state] of changes) {
338
340
  if (node.owner !== this) {
339
341
  this.revoke(node)
340
342
  continue
341
343
  }
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
344
+ const registrations = this.registrations.get(node)
345
+ if (registrations)
346
+ for (const [name, registration] of registrations)
347
+ if (
348
+ this.adapter
349
+ ? state.events[name] === undefined
350
+ : state.events[name] !== registration.listener
351
+ )
352
+ this.revoke(node, name)
353
+ // Most changed nodes have no handlers: iterating allocates nothing then.
354
+ for (const name in state.events) {
355
+ if (!isEventProperty(name)) continue
356
+ const listener = state.events[name]
357
+ if (!listener || this.registrations.get(node)?.has(name)) continue
351
358
  const binding = eventProperties[name]
352
359
  const unsubscribe = this.window.on(
353
- state.handle,
360
+ node.handle!,
354
361
  binding.type,
355
362
  async (event) => {
356
363
  if (node.owner !== this) return
@@ -376,6 +383,18 @@ class Root implements RenderRoot, Owner {
376
383
  }
377
384
  }
378
385
 
386
+ /**
387
+ * Drop the committed record and handle of `node` and of every node its
388
+ * committed record reaches: on finishing, the committed tree is exactly the
389
+ * set of nodes holding them.
390
+ */
391
+ function release(node: Node): void {
392
+ const record = node.committed
393
+ node.committed = undefined
394
+ node.handle = undefined
395
+ if (record) for (const child of record.children) release(child)
396
+ }
397
+
379
398
  /** Own one framework's staged tree, atomic native commits and terminal cleanup. */
380
399
  export function createRenderRoot(
381
400
  window: NativeWindow,