@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/nodes.ts ADDED
@@ -0,0 +1,653 @@
1
+ import {
2
+ NativeStateError,
3
+ UnsupportedFeatureError,
4
+ type DropTargetEvent,
5
+ type Element,
6
+ type InputState,
7
+ type NativeBatch,
8
+ type NativeDropTarget,
9
+ type NativeNode,
10
+ type Style,
11
+ } from '@bun-native/core'
12
+ import { captureInput, type InputIntent } from './input-intent.ts'
13
+ import {
14
+ isEventProperty,
15
+ listeners,
16
+ type EventListener,
17
+ type EventListeners,
18
+ } from './event-properties.ts'
19
+
20
+ declare const identity: unique symbol
21
+
22
+ /** An adapter-owned JSX reference, not a DOM node or a native handle. */
23
+ export interface RendererNode {
24
+ readonly [identity]: true
25
+ }
26
+
27
+ export interface Owner {
28
+ readonly token: object
29
+ /**
30
+ * A handler property keeps its native registration while it stays defined:
31
+ * the registration calls the property's current value. Otherwise replacing
32
+ * a handler revokes the old registration once the replacement commits.
33
+ */
34
+ readonly stableHandlers: boolean
35
+ changed(): void
36
+ detached(node: Node): void
37
+ input(node: Node): InputState
38
+ /** Commit staged changes, then send one request batch for the committed handle. */
39
+ request(node: Node, send: (batch: NativeBatch, handle: NativeNode) => void): Promise<void>
40
+ registerDropTarget(
41
+ node: Node,
42
+ listener: (event: DropTargetEvent) => void | Promise<void>
43
+ ): Promise<NativeDropTarget>
44
+ }
45
+
46
+ type Properties = EventListeners & {
47
+ style?: Style
48
+ text?: string
49
+ value?: string | InputIntent
50
+ placeholder?: string
51
+ disabled?: boolean
52
+ ratio?: number
53
+ min_size?: number
54
+ anchor?: 'window' | 'parent'
55
+ modal?: boolean
56
+ autofocus?: boolean
57
+ navigation?: 'tab' | 'menu'
58
+ surface?: 'layer' | 'window'
59
+ readOnly?: boolean
60
+ accessibleLabel?: string
61
+ accessibleRole?: 'list' | 'list_item'
62
+ accessibleSetSize?: number
63
+ accessiblePosition?: number
64
+ accessibleSelected?: boolean
65
+ accessibleLive?: 'polite' | 'assertive'
66
+ }
67
+
68
+ /** Every native element tag the renderer accepts. */
69
+ export type ElementTag = Element['kind']
70
+
71
+ /** Every property name `setProperty` accepts: element props and event handlers. */
72
+ export type PropertyName = keyof Properties
73
+
74
+ const isContainer = (kind: Node['kind']) => kind === 'box' || kind === 'split' || kind === 'overlay'
75
+
76
+ const nodes = new WeakSet<object>()
77
+
78
+ export class Node implements RendererNode {
79
+ declare readonly [identity]: true
80
+ /**
81
+ * Staged children, where a detached child leaves an `undefined` hole until
82
+ * the list is next read: removing a child from a wide list then neither
83
+ * searches nor shifts it. Positions in this list are the `index` hints.
84
+ */
85
+ readonly staged: (Node | undefined)[] = []
86
+ /** Holes in `staged`, the first and last of them. */
87
+ holes = 0
88
+ firstHole = 0
89
+ lastHole = 0
90
+ /** Read-only to adapters: setProperty validates, stores and invalidates captures. */
91
+ readonly properties: Readonly<Properties> = {}
92
+ parent: Node | undefined
93
+ owner: Owner | undefined
94
+ scope: object | undefined
95
+ data = ''
96
+ /** Last immutable capture; cleared by every mutation that can change it. */
97
+ captured: Snapshot | undefined
98
+ /**
99
+ * 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.
101
+ */
102
+ dirty = false
103
+ /**
104
+ * Dirty children registered when they became dirty, so a parent whose own
105
+ * capture is current visits only them. A recaptured parent scans all of its
106
+ * children instead, which covers a child that arrived already dirty.
107
+ */
108
+ dirtyChildren: Set<Node> | undefined
109
+ /** Position hint in the parent's children; trusted only once verified. */
110
+ index = 0
111
+ /** Children before this position have current `index` hints. */
112
+ indexed = 0
113
+
114
+ constructor(readonly kind: Element['kind'] | 'text-node') {
115
+ nodes.add(this)
116
+ }
117
+
118
+ /** The staged children in order; adapters may truncate this list directly. */
119
+ get children(): Node[] {
120
+ if (this.holes) compact(this)
121
+ return this.staged as Node[]
122
+ }
123
+ }
124
+
125
+ export function asNode(value: RendererNode): Node {
126
+ if (!value || typeof value !== 'object' || !nodes.has(value))
127
+ throw new NativeStateError('invalid_handle', 'Expected an owned staged native node')
128
+ return value as Node
129
+ }
130
+
131
+ export function createElement(tag: ElementTag): Node {
132
+ if (
133
+ tag !== 'box' &&
134
+ tag !== 'text' &&
135
+ tag !== 'button' &&
136
+ tag !== 'input' &&
137
+ tag !== 'split' &&
138
+ tag !== 'overlay'
139
+ )
140
+ throw new UnsupportedFeatureError('native-element:' + tag)
141
+ return new Node(tag)
142
+ }
143
+
144
+ export function createTextNode(value: string): Node {
145
+ const node = new Node('text-node')
146
+ node.data = String(value)
147
+ return node
148
+ }
149
+
150
+ /** Discard a cached capture after changing this node's own snapshot inputs. */
151
+ export function invalidate(node: Node | undefined): void {
152
+ if (!node) return
153
+ node.captured = undefined
154
+ // An already dirty ancestor's own ancestors are dirty too.
155
+ for (let path: Node | undefined = node; path && !path.dirty; path = path.parent) {
156
+ path.dirty = true
157
+ if (path.parent) (path.parent.dirtyChildren ??= new Set()).add(path)
158
+ }
159
+ }
160
+
161
+ /** Gap of unverified siblings worth re-indexing to extend the valid prefix. */
162
+ const reindexLimit = 64
163
+
164
+ /**
165
+ * A child's position in its parent's `staged` list. Hints are verified before
166
+ * use, so a list an adapter truncated directly stays correct. A removal leaves
167
+ * every hint valid and an insertion only shortens the valid prefix to its
168
+ * position, so regions edited in order are found without a search.
169
+ */
170
+ function childIndex(parent: Node, child: Node): number {
171
+ const list = parent.staged
172
+ const hint = child.index
173
+ if (list[hint] === child) return hint
174
+ const last = list.length - 1
175
+ if (list[last] === child) return (child.index = last)
176
+ const start = Math.min(parent.indexed, list.length)
177
+ let found = list.indexOf(child, start)
178
+ if (found < 0) found = list.indexOf(child)
179
+ else if (found - start <= reindexLimit) {
180
+ for (let index = start; index < found; index += 1) {
181
+ const sibling = list[index]
182
+ if (sibling) sibling.index = index
183
+ }
184
+ parent.indexed = found + 1
185
+ }
186
+ if (found >= 0) child.index = found
187
+ return found
188
+ }
189
+
190
+ function contiguousHoles(parent: Node): boolean {
191
+ return parent.lastHole - parent.firstHole + 1 === parent.holes
192
+ }
193
+
194
+ /** Drop the holes in one pass, or one native splice when they are adjacent. */
195
+ function compact(parent: Node): void {
196
+ const list = parent.staged
197
+ const first = parent.firstHole
198
+ const adjacent = contiguousHoles(parent)
199
+ if (adjacent) list.splice(first, parent.holes)
200
+ else {
201
+ let write = first
202
+ for (let read = first; read < list.length; read += 1) {
203
+ const child = list[read]
204
+ if (!child) continue
205
+ child.index = write
206
+ list[write++] = child
207
+ }
208
+ list.length = write
209
+ }
210
+ // Hints from the first hole on moved, unless the pass above rewrote them.
211
+ if (parent.indexed >= first) parent.indexed = adjacent ? first : list.length
212
+ parent.holes = 0
213
+ }
214
+
215
+ function detachChild(parent: Node, child: Node): void {
216
+ parent.dirtyChildren?.delete(child)
217
+ const list = parent.staged
218
+ const index = childIndex(parent, child)
219
+ if (index < 0) return
220
+ // Shifting the remaining siblings would cost O(children) per removal.
221
+ // Never shift(): JavaScriptCore then keeps the list in a much slower mode.
222
+ if (index === list.length - 1) {
223
+ list.pop()
224
+ if (index < parent.indexed) parent.indexed = index
225
+ return
226
+ }
227
+ list[index] = undefined
228
+ if (!parent.holes) parent.firstHole = parent.lastHole = index
229
+ else if (index < parent.firstHole) parent.firstHole = index
230
+ else if (index > parent.lastHole) parent.lastHole = index
231
+ parent.holes += 1
232
+ // Bound the holes of a list that is edited but never read, such as one
233
+ // outside a render root; compacting at half keeps removals amortized O(1).
234
+ if (parent.holes * 2 > list.length) compact(parent)
235
+ }
236
+
237
+ function attachChild(parent: Node, child: Node, index: number): void {
238
+ const list = parent.staged
239
+ if (index === list.length) list.push(child)
240
+ else list.splice(index, 0, child)
241
+ if (parent.holes) {
242
+ if (index <= parent.firstHole) parent.firstHole += 1
243
+ if (index <= parent.lastHole) parent.lastHole += 1
244
+ }
245
+ if (index < parent.indexed) parent.indexed = index
246
+ child.index = index
247
+ if (parent.indexed === index) parent.indexed = index + 1
248
+ }
249
+
250
+ /** The first staged child, without compacting a run of leading holes. */
251
+ export function firstChild(node: Node): Node | undefined {
252
+ if (node.holes && node.firstHole === 0 && contiguousHoles(node))
253
+ return node.staged[node.lastHole + 1]
254
+ return node.children[0]
255
+ }
256
+
257
+ /** The staged sibling after `node`, for adapters that walk sibling chains. */
258
+ export function nextSibling(node: Node): Node | undefined {
259
+ const parent = node.parent
260
+ if (!parent) return undefined
261
+ const list = parent.staged
262
+ let index = childIndex(parent, node) + 1
263
+ if (parent.holes && index === parent.firstHole && contiguousHoles(parent))
264
+ index = parent.lastHole + 1
265
+ const start = index
266
+ while (index < list.length && !list[index]) index += 1
267
+ const sibling = list[index]
268
+ if (index - start > reindexLimit) compact(parent)
269
+ return sibling
270
+ }
271
+
272
+ export function visit(node: Node, fn: (node: Node) => void): void {
273
+ fn(node)
274
+ for (const child of node.children) visit(child, fn)
275
+ }
276
+
277
+ function checkScope(node: Node, token: object): void {
278
+ if (node.scope && node.scope !== token)
279
+ throw new NativeStateError('invalid_handle', 'Renderer nodes cannot move between render roots')
280
+ for (const child of node.children) checkScope(child, token)
281
+ }
282
+
283
+ /**
284
+ * Invalidate a subtree whose parent was just invalidated and hand it to
285
+ * `owner`, giving each node the owner's scope. Each node's parent already lacks
286
+ * a capture, so `snapshot()` scans all of its children and no node registers
287
+ * with its parent's `dirtyChildren`, which only a current capture reads.
288
+ */
289
+ function adopt(node: Node, owner: Owner | undefined): void {
290
+ node.captured = undefined
291
+ node.dirty = true
292
+ node.owner = owner
293
+ if (owner) node.scope = owner.token
294
+ for (const child of node.children) adopt(child, owner)
295
+ }
296
+
297
+ export function insertNode(parent: Node, node: Node, anchor?: Node): void {
298
+ if (parent.kind === 'input' || parent.kind === 'text-node')
299
+ throw new NativeStateError('invalid_state', 'This native element cannot have children')
300
+ if (!isContainer(parent.kind) && node.kind !== 'text-node')
301
+ throw new NativeStateError('invalid_state', 'Text and button children must be text')
302
+ if (anchor && anchor.parent !== parent)
303
+ throw new NativeStateError('invalid_handle', 'Insertion anchor belongs to another parent')
304
+ if (anchor === node) return
305
+ for (let ancestor: Node | undefined = parent; ancestor; ancestor = ancestor.parent)
306
+ if (ancestor === node) throw new NativeStateError('invalid_state', 'Native tree cycle')
307
+ const owner = parent.owner
308
+ // Every node an owner holds was given its scope with it (see adopt), so a
309
+ // subtree already owned by this root needs no check.
310
+ if (owner && node.owner !== owner) checkScope(node, owner.token)
311
+ const previousOwner = node.owner
312
+ // 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
315
+ if (previousOwner && previousOwner !== owner) previousOwner.detached(node)
316
+ if (node.parent) detachChild(node.parent, node)
317
+ invalidate(node.parent)
318
+ invalidate(parent)
319
+ node.parent = parent
320
+ attachChild(parent, node, anchor ? childIndex(parent, anchor) : parent.staged.length)
321
+ // Adapters may clear detached nodes directly, so a reinserted subtree is
322
+ // always captured again from its current state. A moved subtree's captures
323
+ // and dirty paths stay current below it: its root's capture names the old
324
+ // parent, so snapshot() recaptures that node alone, and the diff moves it
325
+ // natively while every descendant keeps its committed record.
326
+ if (!moved) adopt(node, owner)
327
+ previousOwner?.changed()
328
+ owner?.changed()
329
+ }
330
+
331
+ export function removeNode(parent: Node, node: Node): void {
332
+ if (node.parent !== parent)
333
+ throw new NativeStateError('invalid_handle', 'Removal target belongs to another parent')
334
+ const owner = parent.owner
335
+ owner?.detached(node)
336
+ detachChild(parent, node)
337
+ invalidate(parent)
338
+ node.parent = undefined
339
+ // A detached capture would otherwise retain listeners an adapter releases.
340
+ adopt(node, undefined)
341
+ owner?.changed()
342
+ }
343
+
344
+ export function replaceText(node: Node, value: string): void {
345
+ if (node.kind !== 'text-node')
346
+ throw new NativeStateError('invalid_state', 'Text replacement requires a text node')
347
+ if (node.data === value) return
348
+ node.data = value
349
+ invalidate(node)
350
+ // Text and button elements join their text-node children.
351
+ invalidate(node.parent)
352
+ node.owner?.changed()
353
+ }
354
+
355
+ export function setProperty(node: Node, name: PropertyName, value: unknown): void {
356
+ const props = node.properties as Properties
357
+ if (isEventProperty(name)) {
358
+ if (node.kind === 'text-node')
359
+ throw new TypeError('Text literals cannot own native event handlers')
360
+ const replaced = props[name] !== undefined
361
+ if (value === undefined) delete props[name]
362
+ else if (typeof value === 'function') props[name] = value as EventListener
363
+ else throw new TypeError(`Native ${name} must be a function`)
364
+ // Only a defined/undefined change reaches a stable registration.
365
+ if (replaced && value !== undefined && node.owner?.stableHandlers) return
366
+ invalidate(node)
367
+ node.owner?.changed()
368
+ return
369
+ }
370
+ switch (name) {
371
+ case 'style':
372
+ if (value === undefined) delete props.style
373
+ else if (value && typeof value === 'object' && !Array.isArray(value))
374
+ props.style = { ...value }
375
+ else throw new TypeError('Native style must be an object')
376
+ break
377
+ case 'text':
378
+ if (node.kind !== 'text' && node.kind !== 'button')
379
+ throw new TypeError('Only text and button elements accept text')
380
+ if (value === undefined) delete props.text
381
+ else if (typeof value === 'string') props.text = value
382
+ else throw new TypeError('Native text must be a string')
383
+ break
384
+ case 'value': {
385
+ if (node.kind !== 'input') throw new TypeError('Only inputs accept value')
386
+ const captured = captureInput(value)
387
+ if (captured === undefined) delete props.value
388
+ else props.value = captured
389
+ break
390
+ }
391
+ case 'placeholder':
392
+ if (node.kind !== 'input') throw new TypeError('Only inputs accept placeholder')
393
+ if (value === undefined) delete props.placeholder
394
+ else if (typeof value === 'string') props.placeholder = value
395
+ else throw new TypeError('Native input placeholder must be a string')
396
+ break
397
+ case 'disabled':
398
+ if (node.kind !== 'button' && node.kind !== 'input')
399
+ throw new TypeError('Only buttons and inputs accept disabled')
400
+ if (value === undefined) delete props.disabled
401
+ else if (typeof value === 'boolean') props.disabled = value
402
+ else throw new TypeError('Native disabled must be boolean')
403
+ break
404
+ case 'ratio':
405
+ case 'min_size':
406
+ if (node.kind !== 'split') throw new TypeError('Only splits accept ' + name)
407
+ if (value === undefined) delete props[name]
408
+ else if (typeof value === 'number') props[name] = value
409
+ else throw new TypeError(`Native split ${name} must be a number`)
410
+ break
411
+ case 'anchor':
412
+ if (node.kind !== 'overlay') throw new TypeError('Only overlays accept anchor')
413
+ if (value === undefined) delete props.anchor
414
+ else if (value === 'window' || value === 'parent') props.anchor = value
415
+ else throw new TypeError('Native overlay anchor must be window or parent')
416
+ break
417
+ case 'modal':
418
+ if (node.kind !== 'overlay') throw new TypeError('Only overlays accept modal')
419
+ if (value === undefined) delete props.modal
420
+ else if (typeof value === 'boolean') props.modal = value
421
+ else throw new TypeError('Native modal must be boolean')
422
+ break
423
+ case 'autofocus':
424
+ if (node.kind !== 'overlay') throw new TypeError('Only overlays accept autofocus')
425
+ if (value === undefined) delete props.autofocus
426
+ else if (typeof value === 'boolean') props.autofocus = value
427
+ else throw new TypeError('Native autofocus must be boolean')
428
+ break
429
+ case 'navigation':
430
+ if (node.kind !== 'overlay') throw new TypeError('Only overlays accept navigation')
431
+ if (value === undefined) delete props.navigation
432
+ else if (value === 'tab' || value === 'menu') props.navigation = value
433
+ else throw new TypeError('Native overlay navigation must be tab or menu')
434
+ break
435
+ case 'surface':
436
+ if (node.kind !== 'overlay') throw new TypeError('Only overlays accept surface')
437
+ if (value === undefined) delete props.surface
438
+ else if (value === 'layer' || value === 'window') props.surface = value
439
+ else throw new TypeError('Native overlay surface must be layer or window')
440
+ break
441
+ case 'accessibleLabel':
442
+ if (node.kind !== 'split' && node.kind !== 'overlay' && node.kind !== 'box')
443
+ throw new TypeError('Only boxes, splits and overlays accept accessibleLabel')
444
+ if (value === undefined) delete props.accessibleLabel
445
+ else if (typeof value === 'string') props.accessibleLabel = value
446
+ else throw new TypeError('Native accessibleLabel must be a string')
447
+ break
448
+ case 'accessibleRole':
449
+ if (node.kind !== 'box') throw new TypeError('Only boxes accept accessibleRole')
450
+ if (value === undefined) delete props.accessibleRole
451
+ else if (value === 'list' || value === 'list_item') props.accessibleRole = value
452
+ else throw new TypeError('Native accessibleRole must be list or list_item')
453
+ break
454
+ case 'accessibleSetSize':
455
+ case 'accessiblePosition':
456
+ if (node.kind !== 'box') throw new TypeError('Only boxes accept ' + name)
457
+ if (value === undefined) delete props[name]
458
+ else if (typeof value === 'number' && Number.isSafeInteger(value)) props[name] = value
459
+ else throw new TypeError(`Native ${name} must be an integer`)
460
+ break
461
+ case 'accessibleSelected':
462
+ if (node.kind !== 'box') throw new TypeError('Only boxes accept accessibleSelected')
463
+ if (value === undefined) delete props.accessibleSelected
464
+ else if (typeof value === 'boolean') props.accessibleSelected = value
465
+ else throw new TypeError('Native accessibleSelected must be boolean')
466
+ break
467
+ case 'accessibleLive':
468
+ if (node.kind !== 'text') throw new TypeError('Only text accepts accessibleLive')
469
+ if (value === undefined) delete props.accessibleLive
470
+ else if (value === 'polite' || value === 'assertive') props.accessibleLive = value
471
+ else throw new TypeError('Native accessibleLive must be polite or assertive')
472
+ break
473
+ case 'readOnly':
474
+ if (node.kind !== 'input') throw new TypeError('Only inputs accept readOnly')
475
+ if (value === undefined) delete props.readOnly
476
+ else if (typeof value === 'boolean') props.readOnly = value
477
+ else throw new TypeError('Native readOnly must be boolean')
478
+ break
479
+ default:
480
+ throw new UnsupportedFeatureError('native-property:' + name)
481
+ }
482
+ invalidate(node)
483
+ node.owner?.changed()
484
+ }
485
+
486
+ /** Immutable once captured: unchanged nodes share it across commits. */
487
+ export type Snapshot = Readonly<{
488
+ element: Element
489
+ children: readonly Node[]
490
+ parent: Node | undefined
491
+ events: Readonly<EventListeners>
492
+ initialValue: string | undefined
493
+ inputIntent: InputIntent | undefined
494
+ }>
495
+
496
+ function leafStyle(style: Style): NonNullable<Extract<Element, { kind: 'text' }>['style']> {
497
+ const { overflow, scroll_anchor, ...rest } = style
498
+ if (
499
+ scroll_anchor !== undefined ||
500
+ (overflow !== undefined && overflow !== 'visible' && overflow !== 'hidden')
501
+ )
502
+ throw new TypeError('Only native boxes and overlays support scrolling')
503
+ return { ...rest, ...(overflow === undefined ? {} : { overflow }) }
504
+ }
505
+
506
+ /**
507
+ * Capture values before awaiting the core queue; later effects form another batch.
508
+ *
509
+ * Returns only nodes captured anew: every other staged node keeps the immutable
510
+ * capture its acknowledged committed record already holds. The walk descends
511
+ * only dirty paths, so a clean subtree costs nothing. A node can leave its
512
+ * committed position only through a mutation that invalidates its old parent
513
+ * and leaves its own capture naming another parent (or none), so the diff
514
+ * finds removals and moves from the old and new child lists of recaptured
515
+ * nodes alone.
516
+ */
517
+ export function snapshot(root: Node): Map<Node, Snapshot> {
518
+ const result = new Map<Node, Snapshot>()
519
+ const current = (node: Node, parent: Node | undefined): boolean =>
520
+ !node.dirty && node.captured !== undefined && node.captured.parent === parent
521
+ const capture = (node: Node, parent: Node | undefined): void => {
522
+ node.dirty = false
523
+ const dirty = node.dirtyChildren
524
+ node.dirtyChildren = undefined
525
+ let captured = node.captured
526
+ if (!captured || captured.parent !== parent) {
527
+ captured = build(node, parent)
528
+ node.captured = captured
529
+ result.set(node, captured)
530
+ } else if (dirty && dirty.size * 8 < captured.children.length) {
531
+ // A current capture's children are this node's children, and each one
532
+ // that became dirty registered itself, so only those are visited, in
533
+ // child order: the diff emits native operations in snapshot order.
534
+ for (const child of inChildOrder(node, dirty)) if (!current(child, node)) capture(child, node)
535
+ return
536
+ }
537
+ for (const child of captured.children) if (!current(child, node)) capture(child, node)
538
+ }
539
+ if (!current(root, undefined)) capture(root, undefined)
540
+ return result
541
+ }
542
+
543
+ /** Registered children still under `parent`, in staged child order. */
544
+ function inChildOrder(parent: Node, children: ReadonlySet<Node>): Node[] {
545
+ const positioned: [number, Node][] = []
546
+ for (const child of children)
547
+ if (child.parent === parent) positioned.push([childIndex(parent, child), child])
548
+ if (positioned.length > 1) positioned.sort((left, right) => left[0] - right[0])
549
+ return positioned.map((entry) => entry[1])
550
+ }
551
+
552
+ /**
553
+ * The staged children as an immutable list, sharing the previous capture's
554
+ * list when they are unchanged (a moved node), so the diff skips it by identity.
555
+ */
556
+ function childList(node: Node): readonly Node[] {
557
+ const children = node.children
558
+ const previous = node.captured?.children
559
+ if (
560
+ previous?.length === children.length &&
561
+ previous.every((child, index) => child === children[index])
562
+ )
563
+ return previous
564
+ return [...children]
565
+ }
566
+
567
+ function build(node: Node, parent: Node | undefined): Snapshot {
568
+ const props = node.properties
569
+ const style = props.style && !isContainer(node.kind) ? { style: leafStyle(props.style) } : {}
570
+ let element: Element
571
+ if (node.kind === 'box')
572
+ // Core validation rejects members that do not fit the role.
573
+ element = {
574
+ kind: 'box',
575
+ ...(props.accessibleRole === undefined ? {} : { accessible_role: props.accessibleRole }),
576
+ ...(props.accessibleLabel === undefined ? {} : { accessible_label: props.accessibleLabel }),
577
+ ...(props.accessibleSetSize === undefined
578
+ ? {}
579
+ : { accessible_set_size: props.accessibleSetSize }),
580
+ ...(props.accessiblePosition === undefined
581
+ ? {}
582
+ : { accessible_position: props.accessiblePosition }),
583
+ ...(props.accessibleSelected === undefined
584
+ ? {}
585
+ : { accessible_selected: props.accessibleSelected }),
586
+ ...(props.style ? { style: { ...props.style } } : {}),
587
+ } as Element
588
+ else if (node.kind === 'split')
589
+ // Core validation rejects gap and alignment on a split.
590
+ element = {
591
+ kind: 'split',
592
+ ...(props.ratio === undefined ? {} : { ratio: props.ratio }),
593
+ ...(props.min_size === undefined ? {} : { min_size: props.min_size }),
594
+ ...(props.accessibleLabel === undefined ? {} : { accessible_label: props.accessibleLabel }),
595
+ ...(props.style ? { style: leafStyle(props.style) } : {}),
596
+ }
597
+ else if (node.kind === 'overlay')
598
+ // Core validation rejects a modal parent-anchored overlay and an
599
+ // unsized or window-anchored popup surface.
600
+ element = {
601
+ kind: 'overlay',
602
+ ...(props.anchor === undefined ? {} : { anchor: props.anchor }),
603
+ ...(props.modal === undefined ? {} : { modal: props.modal }),
604
+ ...(props.autofocus === undefined ? {} : { autofocus: props.autofocus }),
605
+ ...(props.navigation === undefined ? {} : { navigation: props.navigation }),
606
+ ...(props.surface === undefined ? {} : { surface: props.surface }),
607
+ ...(props.accessibleLabel === undefined ? {} : { accessible_label: props.accessibleLabel }),
608
+ ...(props.style ? { style: { ...props.style } } : {}),
609
+ } as Element
610
+ else if (node.kind === 'input')
611
+ element = {
612
+ kind: 'input',
613
+ value: typeof props.value === 'string' ? props.value : (props.value?.value ?? ''),
614
+ ...(props.placeholder === undefined ? {} : { placeholder: props.placeholder }),
615
+ ...(props.disabled ? { disabled: true } : {}),
616
+ ...(props.readOnly ? { read_only: true } : {}),
617
+ ...style,
618
+ }
619
+ else {
620
+ if (props.text !== undefined && node.children.length)
621
+ throw new TypeError('Choose text properties or text children, not both')
622
+ // Joined text-node children are part of this capture, not native nodes.
623
+ for (const child of node.children) child.dirty = false
624
+ const text =
625
+ node.kind === 'text-node'
626
+ ? node.data
627
+ : (props.text ?? node.children.map((child) => child.data).join(''))
628
+ element =
629
+ node.kind === 'button'
630
+ ? {
631
+ kind: 'button',
632
+ text,
633
+ ...(props.disabled === undefined ? {} : { disabled: props.disabled }),
634
+ ...style,
635
+ }
636
+ : {
637
+ kind: 'text',
638
+ text,
639
+ ...(props.accessibleLive === undefined
640
+ ? {}
641
+ : { accessible_live: props.accessibleLive }),
642
+ ...style,
643
+ }
644
+ }
645
+ return {
646
+ element,
647
+ children: isContainer(node.kind) ? childList(node) : [],
648
+ parent,
649
+ events: listeners(props),
650
+ initialValue: typeof props.value === 'string' ? props.value : undefined,
651
+ inputIntent: typeof props.value === 'object' ? props.value : undefined,
652
+ }
653
+ }