inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! Op enum and `apply` — the in-Rust contract for DOM mutations.
//!
//! The flat byte-buffer FFI encoding is M3's surface, not this task.
//! See `dom/mod.rs` for the error-philosophy and Free-cascade rationale.

use super::arena::Arena;
use super::node::{AttrValue, Kind, Node, Style, TextStyle};

/// All mutations expressible over the arena.
#[derive(Debug, Clone, PartialEq)]
pub enum Op {
    Create {
        id: u32,
        kind: Kind,
    },
    AppendChild {
        parent: u32,
        child: u32,
    },
    InsertBefore {
        parent: u32,
        child: u32,
        before: u32,
    },
    RemoveChild {
        parent: u32,
        child: u32,
    },
    SetText {
        id: u32,
        text: String,
    },
    SetStyle {
        id: u32,
        style: Box<Style>,
    },
    SetAttribute {
        id: u32,
        key: String,
        value: AttrValue,
    },
    SetTransform {
        id: u32,
        has: bool,
    },
    /// Inline text styling (P5.1 SET_TEXT_STYLE).  The native render path reads
    /// this for the guarded-simple `<Text>` styling (P5.1b).
    SetTextStyle {
        id: u32,
        style: TextStyle,
    },
    /// Clear inline text styling (P6.2 CLEAR_TEXT_STYLE).  Resets the node's
    /// `text_styling` to `None` so a styled→plain in-place `<Text>` rerender
    /// stops rendering the stale native SGR.  The additive sibling of
    /// `SetTransform { has: false }` for the native text-style field.
    ClearTextStyle {
        id: u32,
    },
    SetStatic {
        id: u32,
        value: bool,
    },
    Hide {
        id: u32,
    },
    Unhide {
        id: u32,
    },
    Free {
        id: u32,
    },
}

/// Apply a slice of ops to the arena.
///
/// Total function: any op whose ids cannot be resolved is silently skipped.
/// This mirrors ink's own no-op guard in `removeChildNode` (dom.ts:178-182)
/// — JS would guard with `indexOf >= 0` rather than throw.
pub fn apply(arena: &mut Arena, ops: &[Op]) {
    for op in ops {
        apply_one(arena, op);
    }
}

fn apply_one(arena: &mut Arena, op: &Op) {
    match op {
        Op::Create { id, kind } => {
            // dom.ts:95-112 — createNode allocates a fresh element.
            arena.insert(*id, Node::new(*kind));
        }

        Op::AppendChild { parent, child } => {
            // dom.ts:114-135 — appendChildNode:
            //   1. validate both ids first — in JS `node` is always a live
            //      object, so a missing parent is purely a Rust/FFI concern;
            //      we validate before detaching so an unknown parent never
            //      orphans the child (atomicity: resolve, then mutate).
            //   2. detach child from its current parent (move semantics)
            //   3. set child.parentNode = node
            //   4. push to node.childNodes
            if arena.get(*parent).is_none() || arena.get(*child).is_none() {
                return;
            }
            detach(arena, *child);
            if let Some(c) = arena.get_mut(*child) {
                c.parent = Some(*parent);
            }
            if let Some(p) = arena.get_mut(*parent) {
                p.children.push(*child);
            }
        }

        Op::InsertBefore {
            parent,
            child,
            before,
        } => {
            // dom.ts:137-168 — insertBeforeNode:
            //   1. validate both ids first (same atomicity rationale as AppendChild)
            //   2. detach child first (detach-before-indexOf avoids stale index
            //      when child and before share the same parent)
            //   3. set child.parentNode = node
            //   4. indexOf(before); splice at index if found, else push to end
            if arena.get(*parent).is_none() || arena.get(*child).is_none() {
                return;
            }
            detach(arena, *child);
            if let Some(c) = arena.get_mut(*child) {
                c.parent = Some(*parent);
            }
            let idx = arena
                .get(*parent)
                .and_then(|p| p.children.iter().position(|&c| c == *before));
            if let Some(p) = arena.get_mut(*parent) {
                match idx {
                    Some(i) => p.children.insert(i, *child),
                    // dom.ts:155 — if before not found, append to end
                    None => p.children.push(*child),
                }
            }
        }

        Op::RemoveChild { parent, child } => {
            // dom.ts:170-188 — removeChildNode:
            //   1. clear child.parentNode (unconditional)
            //   2. indexOf child in parent.childNodes; splice if >= 0
            if arena.get(*child).is_none() {
                return;
            }
            if let Some(c) = arena.get_mut(*child) {
                c.parent = None;
            }
            // guard: if child not found in parent's list, silently no-op
            // (dom.ts:178-182 guards with index >= 0)
            if let Some(p) = arena.get_mut(*parent)
                && let Some(i) = p.children.iter().position(|&c| c == *child)
            {
                p.children.remove(i);
            }
        }

        Op::SetText { id, text } => {
            // dom.ts:262-269 — setTextNodeValue sets nodeValue.
            // Ink applies `String(text)` coercion; here we receive a String.
            if let Some(node) = arena.get_mut(*id) {
                node.text = Some(text.clone());
            }
        }

        Op::SetStyle { id, style } => {
            // dom.ts:203-206 — setStyle: style is always an object.
            if let Some(node) = arena.get_mut(*id) {
                node.style = *style.clone();
            }
        }

        Op::SetAttribute { id, key, value } => {
            // dom.ts:200-201 — setAttribute stores into node.attributes.
            // dom.ts:195-198 (internal_accessibility special-case) is out of
            // M1-1 scope: it stores an object type incompatible with AttrValue.
            // `internal_transform` and `internal_static` are NOT routed here;
            // the reconciler handles them separately (reconciler.ts:231-245).
            if let Some(node) = arena.get_mut(*id) {
                if let Some(entry) = node.attributes.iter_mut().find(|(k, _)| k == key) {
                    entry.1 = value.clone();
                } else {
                    node.attributes.push((key.clone(), value.clone()));
                }
            }
        }

        Op::SetTransform { id, has } => {
            // reconciler.ts:231-235 — internal_transform presence flag. Mutual
            // exclusion with text_styling (P5.1b): a node taking the JS transform
            // path (has=true) must NOT retain stale native `text_styling` from a
            // prior simple-styled state, or `resolve_transform` (which prefers
            // text_styling) would render the stale style across an in-place
            // native→JS prop transition (e.g. bold → dimColor+bold). Clearing it
            // makes the walk fall through to the JS closure. has=false leaves
            // text_styling for a same-commit SetTextStyle to set.
            if let Some(node) = arena.get_mut(*id) {
                node.has_transform = *has;
                if *has {
                    node.text_styling = None;
                }
            }
        }

        Op::SetTextStyle { id, style } => {
            // P5.1(b) native Text-style render: `resolve_transform` reads this for
            // the guarded-simple path. Clear has_transform so a JS→native in-place
            // transition (e.g. dimColor+bold → bold) cannot leave a stale JS
            // dispatch shadowing the native style. Text.tsx emits exactly one of
            // SetTransform / SetTextStyle per node, so the clears are mutually safe.
            if let Some(node) = arena.get_mut(*id) {
                node.text_styling = Some(style.clone());
                node.has_transform = false;
            }
        }

        Op::ClearTextStyle { id } => {
            // reconciler.ts internal_text_style clear branch — a styled→plain
            // in-place `<Text>` rerender (e.g. `color={active ? 'red' : undefined}`
            // when `active` flips false). Without this the node retains its prior
            // `text_styling = Some(..)`, the diff sees zero changed lines, and the
            // terminal keeps the stale color where ink renders plain. Resetting to
            // `None` makes `resolve_transform` fall through to the (now absent) JS
            // transform → empty chain → plain render, matching ink. This is the
            // additive mirror of `SetTransform { has: false }` for the native
            // text-style field; it does NOT touch `has_transform` (a node never
            // carries both an active native style and a JS transform in one commit).
            if let Some(node) = arena.get_mut(*id) {
                node.text_styling = None;
            }
        }

        Op::SetStatic { id, value } => {
            // reconciler.ts:237-244 — internal_static flag.
            if let Some(node) = arena.get_mut(*id) {
                node.is_static = *value;
            }
        }

        Op::Hide { id } => {
            // reconciler.ts:269-271 — hideInstance sets yoga DISPLAY_NONE.
            // Actual yoga effect is JS-side; we record the flag.
            if let Some(node) = arena.get_mut(*id) {
                node.is_hidden = true;
            }
        }

        Op::Unhide { id } => {
            // reconciler.ts:272-274 — unhideInstance restores DISPLAY_FLEX.
            if let Some(node) = arena.get_mut(*id) {
                node.is_hidden = false;
            }
        }

        Op::Free { id } => {
            // See module docs: Free drops a single slot, no cascade.
            arena.free(*id);
        }
    }
}

/// Detach `child` from its current parent, updating both the child's
/// `parent` field and the parent's `children` list.
///
/// Mirrors the detach-first step in `appendChildNode` (dom.ts:118-120) and
/// `insertBeforeNode` (dom.ts:142-144).  No-ops if `child` has no parent or
/// if any id is unknown.
fn detach(arena: &mut Arena, child: u32) {
    let parent_id = match arena.get(child) {
        Some(n) => n.parent,
        None => return,
    };
    let Some(pid) = parent_id else { return };

    if let Some(c) = arena.get_mut(child) {
        c.parent = None;
    }
    if let Some(p) = arena.get_mut(pid)
        && let Some(i) = p.children.iter().position(|&c| c == child)
    {
        p.children.remove(i);
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn arena_with(ops: &[Op]) -> Arena {
        let mut a = Arena::new();
        apply(&mut a, ops);
        a
    }

    fn create(id: u32, kind: Kind) -> Op {
        Op::Create { id, kind }
    }

    // ── 1. append ordering ───────────────────────────────────────────────────
    // dom.ts:114-135 — appendChildNode pushes to the end of childNodes.
    #[test]
    fn append_ordering() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            create(3, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 0,
                child: 2,
            },
            Op::AppendChild {
                parent: 0,
                child: 3,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![1, 2, 3]);
        assert_eq!(a.get(1).unwrap().parent, Some(0));
    }

    // ── 2. insertBefore ordering ─────────────────────────────────────────────
    // dom.ts:148-153 — splice at indexOf(before) when found.
    #[test]
    fn insert_before_ordering() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            create(3, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 0,
                child: 3,
            },
            // insert 2 before 3 → [1, 2, 3]
            Op::InsertBefore {
                parent: 0,
                child: 2,
                before: 3,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![1, 2, 3]);
        assert_eq!(a.get(2).unwrap().parent, Some(0));
    }

    // ── 3. insertBefore with unknown `before` appends to end ─────────────────
    // dom.ts:154-162 — if indexOf < 0, push to end (not a panic / throw).
    #[test]
    fn insert_before_unknown_appends_end() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            // `before` id 99 does not exist → append
            Op::InsertBefore {
                parent: 0,
                child: 2,
                before: 99,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![1, 2]);
    }

    // ── 4. reparent-move via AppendChild ─────────────────────────────────────
    // dom.ts:118-120 — if child already has a parent, remove it first.
    #[test]
    fn reparent_move_append() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Root),
            create(2, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 2,
            },
            // move node 2 from parent 0 → parent 1
            Op::AppendChild {
                parent: 1,
                child: 2,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![] as Vec<u32>);
        assert_eq!(a.get(1).unwrap().children, vec![2]);
        assert_eq!(a.get(2).unwrap().parent, Some(1));
    }

    // ── 5. reparent-move via InsertBefore ────────────────────────────────────
    // dom.ts:142-144 — detach before computing indexOf to avoid stale index.
    #[test]
    fn reparent_move_insert_before_same_parent() {
        // Move child 1 (currently before 2) to after 2 in same parent.
        // After detach: children = [2, 3].  InsertBefore(child=1, before=3)
        // → splice at idx=1 → [2, 1, 3].
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            create(3, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 0,
                child: 2,
            },
            Op::AppendChild {
                parent: 0,
                child: 3,
            },
            // move 1 to before 3 (should end up [2, 1, 3])
            Op::InsertBefore {
                parent: 0,
                child: 1,
                before: 3,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![2, 1, 3]);
    }

    // ── 6. removeChild clears parent and removes from list ───────────────────
    // dom.ts:170-188 — removeChildNode clears parentNode, splices if found.
    #[test]
    fn remove_child() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 0,
                child: 2,
            },
            Op::RemoveChild {
                parent: 0,
                child: 1,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![2]);
        assert_eq!(a.get(1).unwrap().parent, None);
    }

    // ── 7. Free drops node; children stay (no cascade) ───────────────────────
    // detachDeletedInstance is a no-op (reconciler.ts:298).  Free = single slot.
    #[test]
    fn free_no_cascade() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 1,
                child: 2,
            },
            // Remove 1 from root first (detach), then free 1.
            Op::RemoveChild {
                parent: 0,
                child: 1,
            },
            Op::Free { id: 1 },
        ]);
        // Node 1 dropped; node 2 still lives (children freed separately by reconciler).
        assert!(a.get(1).is_none());
        assert!(a.get(2).is_some());
        // live nodes: root(0) + child(2) = 2
        assert_eq!(a.live_count(), 2);
    }

    // ── 8. SetText / text mutation ───────────────────────────────────────────
    // dom.ts:262-269 — setTextNodeValue sets nodeValue.
    #[test]
    fn set_text() {
        let a = arena_with(&[
            create(10, Kind::Text),
            Op::SetText {
                id: 10,
                text: "hello".into(),
            },
        ]);
        assert_eq!(a.get(10).unwrap().text.as_deref(), Some("hello"));
    }

    // dom.ts:262-269 — subsequent SetText overwrites.
    #[test]
    fn set_text_overwrite() {
        let a = arena_with(&[
            create(10, Kind::VirtualText),
            Op::SetText {
                id: 10,
                text: "hello".into(),
            },
            Op::SetText {
                id: 10,
                text: "world".into(),
            },
        ]);
        assert_eq!(a.get(10).unwrap().text.as_deref(), Some("world"));
    }

    // ── 9. attribute mutation ─────────────────────────────────────────────────
    // dom.ts:190-201 — setAttribute stores key→value.
    #[test]
    fn set_attribute_insert_and_update() {
        let a = arena_with(&[
            create(5, Kind::Box),
            Op::SetAttribute {
                id: 5,
                key: "onClick".into(),
                value: AttrValue::Bool(true),
            },
            Op::SetAttribute {
                id: 5,
                key: "label".into(),
                value: AttrValue::Str("x".into()),
            },
            // update existing key
            Op::SetAttribute {
                id: 5,
                key: "label".into(),
                value: AttrValue::Str("y".into()),
            },
        ]);
        let attrs = &a.get(5).unwrap().attributes;
        assert_eq!(attrs.len(), 2);
        assert!(
            attrs
                .iter()
                .any(|(k, v)| k == "onClick" && *v == AttrValue::Bool(true))
        );
        assert!(
            attrs
                .iter()
                .any(|(k, v)| k == "label" && *v == AttrValue::Str("y".into()))
        );
    }

    // ── 10. flags: SetStatic, SetTransform, Hide/Unhide ──────────────────────
    // reconciler.ts:237-244 — internal_static flag.
    // reconciler.ts:231-235 — internal_transform presence.
    // reconciler.ts:269-274 — hide/unhide toggle is_hidden.
    #[test]
    fn flags() {
        let a = arena_with(&[
            create(7, Kind::Box),
            Op::SetStatic { id: 7, value: true },
            Op::SetTransform { id: 7, has: true },
            Op::Hide { id: 7 },
        ]);
        let n = a.get(7).unwrap();
        assert!(n.is_static);
        assert!(n.has_transform);
        assert!(n.is_hidden);
    }

    #[test]
    fn unhide_clears_flag() {
        let a = arena_with(&[
            create(7, Kind::Box),
            Op::Hide { id: 7 },
            Op::Unhide { id: 7 },
        ]);
        assert!(!a.get(7).unwrap().is_hidden);
    }

    // ── 10b. SetTransform / SetTextStyle mutually clear (P5.1b transition guard) ──
    // An in-place native↔JS style transition must not leave stale state that
    // `resolve_transform` (text_styling-first) would prefer. SetTransform{has:true}
    // clears text_styling; SetTextStyle clears has_transform. Without this, e.g.
    // bold→dimColor+bold would emit only SetTransform and keep the stale native
    // {bold}, rendering bold instead of the JS dim+bold.
    #[test]
    fn text_style_transform_mutual_clear() {
        let bold = || TextStyle {
            bold: true,
            ..Default::default()
        };

        // native (text_styling) → JS (SetTransform has=true): native state cleared.
        let a = arena_with(&[
            create(7, Kind::Box),
            Op::SetTextStyle {
                id: 7,
                style: bold(),
            },
            Op::SetTransform { id: 7, has: true },
        ]);
        let n = a.get(7).unwrap();
        assert!(n.has_transform);
        assert!(
            n.text_styling.is_none(),
            "SetTransform{{has:true}} must clear stale text_styling"
        );

        // JS (SetTransform has=true) → native (SetTextStyle): JS flag cleared.
        let b = arena_with(&[
            create(8, Kind::Box),
            Op::SetTransform { id: 8, has: true },
            Op::SetTextStyle {
                id: 8,
                style: bold(),
            },
        ]);
        let m = b.get(8).unwrap();
        assert!(m.text_styling.is_some());
        assert!(
            !m.has_transform,
            "SetTextStyle must clear stale has_transform"
        );

        // SetTransform{has:false} must NOT clear text_styling. Apply SetTextStyle
        // FIRST so the assertion fails if has=false wrongly cleared it (ordering
        // a later SetTextStyle would otherwise mask the bug by restoring it).
        let c = arena_with(&[
            create(9, Kind::Box),
            Op::SetTextStyle {
                id: 9,
                style: bold(),
            },
            Op::SetTransform { id: 9, has: false },
        ]);
        let p = c.get(9).unwrap();
        assert!(
            p.text_styling.is_some(),
            "SetTransform{{has:false}} must NOT clear text_styling"
        );
        assert!(!p.has_transform);
    }

    // ── 10c. ClearTextStyle resets text_styling to None (P6.2 styled→plain) ──
    // A styled→plain in-place `<Text>` rerender: the node was native-styled
    // (SetTextStyle), then the style is removed. ClearTextStyle must reset
    // text_styling to None so `resolve_transform` renders plain (matching ink).
    // Without it the node keeps Some(..) and the terminal shows the stale color.
    #[test]
    fn clear_text_style_resets_to_none() {
        let a = arena_with(&[
            create(7, Kind::Text),
            Op::SetTextStyle {
                id: 7,
                style: TextStyle {
                    color: Some("red".into()),
                    ..Default::default()
                },
            },
            Op::ClearTextStyle { id: 7 },
        ]);
        assert_eq!(
            a.get(7).unwrap().text_styling,
            None,
            "ClearTextStyle must reset text_styling to None"
        );
        // Mutation-discriminating control: WITHOUT the clear the style persists,
        // so the None assertion above is non-vacuous.
        let b = arena_with(&[
            create(8, Kind::Text),
            Op::SetTextStyle {
                id: 8,
                style: TextStyle {
                    color: Some("red".into()),
                    ..Default::default()
                },
            },
        ]);
        assert!(
            b.get(8).unwrap().text_styling.is_some(),
            "control: without ClearTextStyle the native style persists"
        );
    }

    // ── 10d. styled → plain → styled-AGAIN: the clear is NON-DESTRUCTIVE ──────
    // A toggle like `color={active ? 'red' : undefined}` flips BOTH ways: after a
    // ClearTextStyle wipes the field, a later SetTextStyle must be able to re-style
    // the SAME node. ClearTextStyle only resets the value to None; it must not wedge
    // the node into a permanently-plain state. This pins the full round trip:
    // SetTextStyle(red) → Some, ClearTextStyle → None, SetTextStyle(blue) → Some(blue).
    #[test]
    fn set_text_style_after_clear_restyles_node() {
        let a = arena_with(&[
            create(7, Kind::Text),
            Op::SetTextStyle {
                id: 7,
                style: TextStyle {
                    color: Some("red".into()),
                    ..Default::default()
                },
            },
        ]);
        // Styled: the native style is present (discriminates a never-styled node).
        assert_eq!(
            a.get(7).unwrap().text_styling,
            Some(TextStyle {
                color: Some("red".into()),
                ..Default::default()
            }),
            "after SetTextStyle the node carries the red native style"
        );

        // Clear: text_styling resets to None (the styled→plain leg).
        let b = arena_with(&[
            create(7, Kind::Text),
            Op::SetTextStyle {
                id: 7,
                style: TextStyle {
                    color: Some("red".into()),
                    ..Default::default()
                },
            },
            Op::ClearTextStyle { id: 7 },
        ]);
        assert_eq!(
            b.get(7).unwrap().text_styling,
            None,
            "ClearTextStyle resets text_styling to None"
        );

        // Re-style AGAIN after the clear: a fresh SetTextStyle must take hold with
        // the NEW color (proves the clear did not destroy the field's capacity to be
        // set, and that the prior red did not bleed through).
        let c = arena_with(&[
            create(7, Kind::Text),
            Op::SetTextStyle {
                id: 7,
                style: TextStyle {
                    color: Some("red".into()),
                    ..Default::default()
                },
            },
            Op::ClearTextStyle { id: 7 },
            Op::SetTextStyle {
                id: 7,
                style: TextStyle {
                    color: Some("blue".into()),
                    ..Default::default()
                },
            },
        ]);
        let n = c.get(7).unwrap();
        assert!(
            n.text_styling.is_some(),
            "re-style after clear must take hold (clear is non-destructive)"
        );
        assert_eq!(
            n.text_styling.as_ref().unwrap().color.as_deref(),
            Some("blue"),
            "the re-styled node carries the NEW color (blue), not the cleared red"
        );
    }

    // ── 11. malformed ops do NOT panic ───────────────────────────────────────
    // dom.ts guards: indexOf >= 0 before splice (dom.ts:178-182 and 149-163).
    // ink's JS would silently no-op or guard; we match that.
    #[test]
    fn malformed_op_no_panic() {
        let mut a = Arena::new();
        // All these reference ids that do not exist — must not panic.
        apply(
            &mut a,
            &[
                Op::AppendChild {
                    parent: 99,
                    child: 42,
                },
                Op::InsertBefore {
                    parent: 99,
                    child: 42,
                    before: 1,
                },
                Op::RemoveChild {
                    parent: 99,
                    child: 42,
                },
                Op::SetText {
                    id: 99,
                    text: "x".into(),
                },
                Op::SetStyle {
                    id: 99,
                    style: Box::new(Style::default()),
                },
                Op::SetAttribute {
                    id: 99,
                    key: "k".into(),
                    value: AttrValue::Bool(false),
                },
                Op::SetTransform { id: 99, has: true },
                Op::ClearTextStyle { id: 99 },
                Op::SetStatic {
                    id: 99,
                    value: true,
                },
                Op::Hide { id: 99 },
                Op::Unhide { id: 99 },
                Op::Free { id: 99 },
            ],
        );
        // Nothing was created — arena stays empty.
        assert_eq!(a.live_count(), 0);
    }

    // ── 11b. AppendChild with unknown parent does NOT orphan the child ──────────
    // Codex review finding: detaching before validation would orphan the child
    // even though the op is supposed to be a no-op.  Fix: validate both ids
    // before calling detach (atomic resolve-then-mutate).
    #[test]
    fn append_child_unknown_parent_does_not_orphan() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            // parent 99 doesn't exist — child 1 must stay under parent 0
            Op::AppendChild {
                parent: 99,
                child: 1,
            },
        ]);
        assert_eq!(a.get(1).unwrap().parent, Some(0));
        assert!(a.get(0).unwrap().children.contains(&1));
    }

    // ── 11c. InsertBefore with unknown parent does NOT orphan the child ──────────
    #[test]
    fn insert_before_unknown_parent_does_not_orphan() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 0,
                child: 2,
            },
            // parent 99 doesn't exist — child 1 must stay under parent 0
            Op::InsertBefore {
                parent: 99,
                child: 1,
                before: 2,
            },
        ]);
        assert_eq!(a.get(1).unwrap().parent, Some(0));
        assert!(a.get(0).unwrap().children.contains(&1));
    }

    // ── 12. AppendChild-move is idempotent for child already at end ───────────
    // dom.ts:118-123 — detach then append; re-appending the same child is safe.
    #[test]
    fn append_existing_child_moves_to_end() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Box),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 0,
                child: 2,
            },
            // Re-append child 1 → detaches then appends → [2, 1]
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![2, 1]);
    }

    // ── 13. SetStyle stores style placeholder ────────────────────────────────
    #[test]
    fn set_style() {
        let a = arena_with(&[
            create(3, Kind::Box),
            Op::SetStyle {
                id: 3,
                style: Box::new(Style::default()),
            },
        ]);
        assert_eq!(a.get(3).unwrap().style, Style::default());
    }

    // ── 14. Create on occupied slot is a no-op ───────────────────────────────
    // Arena doc: React allocates each id once; double-create is a protocol error.
    #[test]
    fn create_occupied_slot_noop() {
        let mut a = Arena::new();
        apply(&mut a, &[create(0, Kind::Root)]);
        // Give node 0 a child so we can detect if it was overwritten.
        apply(
            &mut a,
            &[
                create(1, Kind::Box),
                Op::AppendChild {
                    parent: 0,
                    child: 1,
                },
            ],
        );
        // Second Create on id=0 with a different kind — should be ignored.
        apply(&mut a, &[create(0, Kind::Box)]);
        assert_eq!(a.get(0).unwrap().kind, Kind::Root);
        assert_eq!(a.get(0).unwrap().children, vec![1]);
    }

    // ── 15. Realistic tree in one apply() batch ──────────────────────────────
    // Cross-op integration: the reconciler sends one op buffer per commit, so a
    // whole mount arrives as a single batch. Pins ordering across op kinds that
    // the per-op unit tests each miss.
    #[test]
    fn build_realistic_tree_in_one_batch() {
        let a = arena_with(&[
            create(0, Kind::Root),
            create(1, Kind::Box),
            create(2, Kind::Text),
            Op::AppendChild {
                parent: 0,
                child: 1,
            },
            Op::AppendChild {
                parent: 1,
                child: 2,
            },
            Op::SetText {
                id: 2,
                text: "hi".into(),
            },
            Op::SetAttribute {
                id: 1,
                key: "flexDirection".into(),
                value: AttrValue::Str("row".into()),
            },
        ]);
        assert_eq!(a.get(0).unwrap().children, vec![1]);
        assert_eq!(a.get(1).unwrap().children, vec![2]);
        assert_eq!(a.get(2).unwrap().parent, Some(1));
        assert_eq!(a.get(2).unwrap().text.as_deref(), Some("hi"));
        assert_eq!(
            a.get(1).unwrap().attributes,
            vec![("flexDirection".to_owned(), AttrValue::Str("row".into()))]
        );
        assert_eq!(a.live_count(), 3);
    }
}