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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! Text measurement: squash, measure, and wrap-aware Taffy closure builder.
//!
//! # Design decisions
//!
//! ## Squash / transform boundary (M3-B)
//! `squash-text-nodes.ts` concatenates children text AND applies
//! `internal_transform` during squash (squash-text-nodes.ts:34-39), so in ink
//! transforms run at **measure time** as well as render time. inkferro splits
//! these two squash sites by design:
//!   * **Render time** — [`squash_styled`] threads the per-node transform
//!     accessor and applies each nested child's `internal_transform` during the
//!     fold, exactly mirroring squash-text-nodes.ts:34-39. The styled-render
//!     entry (`render::render_styled`) uses it; `<Text color>` SGR and
//!     `<Transform>` callbacks flow through here.
//!   * **Measure time** — [`squash_text`] (this module) stays transform-FREE.
//!     `build_measure_fn_for` snapshots raw concatenated text for the taffy
//!     layout pass. Applying transforms here would mean dispatching JS callbacks
//!     during layout (the reentrancy hazard the M3 plan flags) and would risk the
//!     layout corpus.
//!
//! ## Deliberate divergence: measure does not see transforms
//! Because the measure path is transform-free, a transform that changes a line's
//! **displayed width** diverges from ink, which applies transforms in its
//! measure-time squash too. This covers any transform that inserts/removes
//! visible characters (a `<Transform>` like `s => s + "!"`, padding, a gradient
//! that adds glyphs) AND case- or script-mapping that alters width (e.g. `ß`→`SS`,
//! full-width folding): ink measures the post-transform width, inkferro the
//! pre-transform width. A transform that emits ONLY ANSI SGR escapes around the
//! same visible glyphs (`<Text>` color/bold/dim/inverse, the `colorize` path) is
//! width-neutral — `string_width` strips the SGR, so both sides measure the same
//! and layout is identical. The layout corpus cannot catch this (no block uses a
//! width-changing transform), so it is named here.
//!
//! ## sanitizeAnsi at squash boundary
//! `squash-text-nodes.ts:45` returns `sanitizeAnsi(text)` which strips
//! non-SGR/non-OSC control sequences (#129 port: `text::sanitize_ansi`).
//! Both squash entry points apply it at EVERY recursion level, exactly where
//! ink does — each `squashTextNodes` return is sanitized, so a nested text
//! child is sanitized BEFORE its transform applies and the transform's output
//! is re-sanitized by the parent level; the outermost node's OWN transform
//! (applied later at `write_styled`) is NOT sanitized, matching ink's
//! `output.write` site. For well-formed input, measurement is unchanged
//! (string_width strips all ANSI; height counts `\n`) — pinned below by
//! `measure_sgr_and_osc8_hyperlink_width_equals_visible_width`. For MALFORMED
//! input (e.g. an unterminated `\x1b[31` tail) sanitize drops the remainder
//! and measurement follows the oracle's sanitized text, not the raw bytes.
//!
//! ## textWrap home
//! `wrap-text.ts:3` types it as `Styles['textWrap']`; `dom.ts:242` reads
//! `node.style?.textWrap`. It lives on `dom::Style.text_wrap` (node.rs), not
//! a node attribute — smallest change, correct location per ink oracle.
//!
//! ## AvailableSpace ↔ widthMode mapping
//! ink's `measureTextNode` (dom.ts:222-246) takes `(node, width: number)`.
//! The two ink numeric guards:
//!   dom.ts:232: `if (dimensions.width <= width) return dimensions`
//!   dom.ts:238: `if (dimensions.width >= 1 && width > 0 && width < 1) return dimensions`
//! Taffy passes `(known_dimensions: Size<Option<f32>>, available: Size<AvailableSpace>)`:
//!   - `known.width = Some(w)` → Taffy has already resolved an exact width: use w.
//!   - `known.width = None, available.width = Definite(w)` → constrained to w: use w.
//!   - `known.width = None, available.width = MaxContent` → unconstrained: return intrinsic.
//!   - `known.width = None, available.width = MinContent` → minimal constraint:
//!     wrap at 1 (clamps to 1 via wrap_ansi); document — the conformance corpus
//!     does not exercise MinContent directly.
//!
//! The two ink numeric guards are applied before wrapping:
//! dom.ts:232 — if `intrinsic.width <= constraint` return intrinsic (text fits).
//! dom.ts:238 — if `intrinsic.width >= 1 && constraint > 0.0 && constraint < 1.0`
//! return intrinsic (Taffy asking "can you fit in sub-pixel space?" — tell it no).
//!
//! ## Cache decision
//! `measure-text.ts` caches by text string. M1 omits the cache; the
//! conformance corpus doesn't require it and a `HashMap<String, (f32,f32)>`
//! would need to live inside the closure (behind `RefCell` or as a module
//! static). Deferred to M2 performance pass.
//!
//! ## Closure invalidation contract
//! `build_measure_fn` snapshots the squashed text + wrap mode at call time.
//! The caller must rebuild the measure function (via `LayoutEngine::set_measure`)
//! on `SetText` and `SetStyle` ops. M1-6's harness exercises this contract.
//!
//! ## destroy lifecycle
//! `LayoutEngine::destroy(id)` added to complete the node lifecycle. Taffy 0.10's
//! `remove(node)` detaches the node from parent/children; orphaned children are
//! freed by their own subsequent `Free` ops per the Free-no-cascade contract.

use taffy::geometry::Size;
use taffy::style::AvailableSpace;

use crate::dom::{Arena, Kind, TextWrap};
use crate::layout::MeasureFn;
use crate::text::cli_truncate::{TruncateOptions, TruncatePosition, cli_truncate_with};
use crate::text::string_width::string_width;
use crate::text::wrap_ansi::{WrapOptions, wrap_ansi_with};

// ─── 1. Squash ───────────────────────────────────────────────────────────────

/// Concatenate the text content of a `Text` or `VirtualText` node's subtree.
///
/// Mirrors `squashTextNodes` (squash-text-nodes.ts:10-46).
///
/// ## Arena shape
/// The Rust arena folds `#text` nodeValue directly into `Node.text`
/// (dom/mod.rs — "Text storage" rationale).  `Text` / `VirtualText` nodes
/// whose `node.text` is `Some(s)` are the leaf text sources; their
/// `node.children` may contain further `VirtualText` sub-nodes (mirroring
/// `ink-virtual-text` children of `ink-text`), which are squashed recursively.
///
/// ## Transform omission (measure path — intentional)
/// `squash-text-nodes.ts:34-39` applies `internal_transform` during squash, so
/// in ink transforms run at measure time as well as render time. This function
/// is the **measure-time** squash and stays transform-FREE on purpose: it feeds
/// the taffy layout pass, where dispatching JS transform callbacks would be the
/// reentrancy hazard the M3 plan flags. The render-time squash that DOES apply
/// transforms is [`squash_styled`]. See the module-level "Squash / transform
/// boundary" and "Deliberate divergence" notes for the width consequence.
///
/// ## sanitizeAnsi
/// The JS oracle returns `sanitizeAnsi(text)` (squash-text-nodes.ts:45) at
/// every recursion level. Ported (#129): each nested Text/VirtualText child's
/// fold is sanitized on its own (see `squash_into`'s recursion through this
/// function), and the top-level result is sanitized here — byte-identical to
/// ink's per-call sanitize. For well-formed input measurement is unchanged
/// (string_width strips all ANSI); malformed tails now drop exactly as the
/// oracle drops them.
pub(crate) fn squash_text(arena: &Arena, id: u32) -> String {
    let mut buf = String::new();
    squash_into(arena, id, &mut buf);
    crate::text::sanitize_ansi::sanitize_ansi(buf)
}

/// Recursive inner helper — fills `buf` depth-first left-to-right.
///
/// Mirrors the `for` loop in squash-text-nodes.ts:13-43.
fn squash_into(arena: &Arena, id: u32, buf: &mut String) {
    let Some(node) = arena.get(id) else { return };

    // squash-text-nodes.ts:22-23: leaf text (mirrors `#text` nodeValue).
    // In our arena this is Node.text on any Kind that has it set.
    if let Some(ref t) = node.text {
        buf.push_str(t);
    }

    // squash-text-nodes.ts:24-39: recurse into ink-text / ink-virtual-text children.
    // Only Text and VirtualText children contribute — Box/Root children of a
    // text node don't arise in practice (reconciler forbids it), but we guard
    // on Kind to be safe, matching the `nodeName === 'ink-text' || 'ink-virtual-text'`
    // check in squash-text-nodes.ts:26-28.
    for &child_id in &node.children {
        let Some(child) = arena.get(child_id) else {
            continue;
        };
        if matches!(child.kind, Kind::Text | Kind::VirtualText) {
            // #129: recurse through `squash_text` (NOT `squash_into`) so each
            // nested child's fold is sanitized on its own, mirroring ink's
            // per-`squashTextNodes`-call sanitize (squash-text-nodes.ts:29,45).
            // Observable for malformed tails: a child ending in an unterminated
            // sequence drops only ITS remainder, not later siblings' text.
            buf.push_str(&squash_text(arena, child_id));
        }
    }
}

/// Squash the text subtree of `id`, applying each **nested** text child's own
/// transform during the fold — the render-time port of `squashTextNodes`
/// (squash-text-nodes.ts:34-39):
/// ```ts
/// if (childNode.nodeName === 'ink-text' || 'ink-virtual-text') {
///     nodeText = squashTextNodes(childNode);
/// }
/// if (nodeText.length > 0 && typeof childNode.internal_transform === 'function') {
///     nodeText = childNode.internal_transform(nodeText, index);
/// }
/// ```
///
/// `transform_of` is the same per-node own-transform seam the walk uses
/// ([`crate::render::walk::TransformAccessor`]). This is where **nested** styled
/// text composes: `<Text color="red">a<Text color="blue">b</Text></Text>` colors
/// only "b" blue because the inner child's transform is applied to *its own*
/// folded substring here, BEFORE concatenation — ink's behaviour, not a wrapper.
///
/// # Boundary with the walk (no double-application)
/// This applies a child's transform only to that **child's** folded string. The
/// node's OWN transform is NOT applied here — the walk applies the outermost
/// text node's own transform via `output.write` (render-node-to-output.ts:154).
/// Applying it in both places would double-wrap. So: nested = squash
/// (whole-string, child's sibling index); outermost own = write (per-line).
///
/// # Index nuance (documented divergence)
/// ink passes the child's positional index in the parent's `childNodes`
/// (squash-text-nodes.ts:38). The Rust arena folds a leaf `#text` into the
/// parent's `node.text` rather than keeping it as a `childNodes[0]` entry, so a
/// transformed `ink-text` child that follows folded leaf text sees a `children`
/// index one lower than ink's `childNodes` index. This is observable ONLY for a
/// `<Transform>` callback that BOTH reads its `index` arg AND is preceded by
/// sibling leaf text; every `<Text>`-style transform (colorize/bold/dim/…)
/// ignores `index`, so styled-text output is unaffected.
pub(crate) fn squash_styled(
    arena: &Arena,
    id: u32,
    transform_of: &crate::render::walk::TransformAccessor<'_>,
) -> String {
    let mut buf = String::new();
    squash_styled_into(arena, id, transform_of, &mut buf);
    // #129: sanitize at every squash return (squash-text-nodes.ts:45). Nested
    // children recurse through THIS function (squash_styled_into calls
    // squash_styled per child), so each level is sanitized BEFORE its
    // transform applies and the transform's output is re-sanitized by the
    // parent level — exactly ink's recursion. The node's OWN transform runs
    // later at `write_styled` and is NOT sanitized, matching ink's
    // `output.write` site (render-node-to-output.ts:154).
    crate::text::sanitize_ansi::sanitize_ansi(buf)
}

/// Recursive inner helper for [`squash_styled`] — mirrors squash-text-nodes.ts:13-43
/// including the per-child `internal_transform` application (lines 34-39).
fn squash_styled_into(
    arena: &Arena,
    id: u32,
    transform_of: &crate::render::walk::TransformAccessor<'_>,
    buf: &mut String,
) {
    let Some(node) = arena.get(id) else { return };

    // squash-text-nodes.ts:22-23: leaf `#text` nodeValue — NOT transformed
    // (the `if nodeName === '#text'` branch skips the transform block).
    if let Some(ref t) = node.text {
        buf.push_str(t);
    }

    // squash-text-nodes.ts:24-39: each ink-text / ink-virtual-text child is
    // squashed, then its OWN transform applied to its folded substring (when
    // non-empty) before concatenation. `index` is the child's position in
    // `children` (see the index nuance in [`squash_styled`]).
    for (index, &child_id) in node.children.iter().enumerate() {
        let Some(child) = arena.get(child_id) else {
            continue;
        };
        if !matches!(child.kind, Kind::Text | Kind::VirtualText) {
            continue;
        }
        // Fold the child's own subtree into a fresh buffer so its transform
        // wraps only its own text (squash-text-nodes.ts:29).
        let child_text = squash_styled(arena, child_id, transform_of);
        // squash-text-nodes.ts:34-39: apply the child's transform when present
        // and the folded text is non-empty.
        let transformed = match transform_of(child_id) {
            Some(t) if !child_text.is_empty() => t(&child_text, index),
            _ => child_text,
        };
        buf.push_str(&transformed);
    }
}

// ─── 2. Measure (intrinsic) ──────────────────────────────────────────────────

/// Intrinsic dimensions of `text` without any wrapping.
///
/// Mirrors `measureText` (measure-text.ts:10-30):
///   width  = `widestLine(text)`  — max `string_width` across `\n`-split lines.
///   height = `text.split('\n').length` — line count (1 for no newline).
///
/// `widest-line` is `text.split('\n').map(stringWidth).max()` upstream.
/// Empty string → `{0, 0}` matching measure-text.ts:11-14.
///
/// No cache: deferred to M2 (measure-text.ts caches by text string; the
/// conformance corpus doesn't require it here).
pub(crate) fn measure_text(text: &str) -> (f32, f32) {
    // measure-text.ts:11-14: empty string short-circuit.
    if text.is_empty() {
        return (0.0, 0.0);
    }
    // measure-text.ts:24: widestLine — max string_width per \n-separated line.
    let width = text.split('\n').map(string_width).max().unwrap_or(0) as f32;
    // measure-text.ts:25: height = number of lines.
    let height = text.split('\n').count() as f32;
    (width, height)
}

// ─── 3. Wrap text ────────────────────────────────────────────────────────────

/// Apply the ink `textWrap` mode to `text` at `width` columns.
///
/// Mirrors `wrapText` (wrap-text.ts:7-53) exactly:
///
/// | textWrap         | wrap-ansi options             | source line |
/// |------------------|-------------------------------|-------------|
/// | `'wrap'`         | `{trim:false, hard:true}`     | wt:21-25    |
/// | `'hard'`         | `{trim:false, hard:true, word_wrap:false}` | wt:27-32 |
/// | `'truncate'`/`'truncate-end'` | cli_truncate End | wt:33-41 |
/// | `'truncate-middle'` | cli_truncate Middle        | wt:39      |
/// | `'truncate-start'`  | cli_truncate Start         | wt:43      |
///
/// Note: wrap-text.ts passes width as `number`; we receive it as `usize`.
pub(crate) fn wrap_text_with_mode(text: &str, width: usize, mode: TextWrap) -> String {
    match mode {
        // wrap-text.ts:21-25: wrapAnsi(text, maxWidth, {trim:false, hard:true})
        TextWrap::Wrap => wrap_ansi_with(
            text,
            width,
            WrapOptions {
                hard: true,
                word_wrap: true,
                trim: false,
            },
        ),
        // wrap-text.ts:27-32: wrapAnsi(text, maxWidth, {trim:false, hard:true, wordWrap:false})
        TextWrap::Hard => wrap_ansi_with(
            text,
            width,
            WrapOptions {
                hard: true,
                word_wrap: false,
                trim: false,
            },
        ),
        // wrap-text.ts:33-47: cliTruncate(text, maxWidth, {position})
        TextWrap::TruncateEnd => cli_truncate_with(
            text,
            width,
            &TruncateOptions {
                position: TruncatePosition::End,
                ..TruncateOptions::default()
            },
        ),
        TextWrap::TruncateMiddle => cli_truncate_with(
            text,
            width,
            &TruncateOptions {
                position: TruncatePosition::Middle,
                ..TruncateOptions::default()
            },
        ),
        TextWrap::TruncateStart => cli_truncate_with(
            text,
            width,
            &TruncateOptions {
                position: TruncatePosition::Start,
                ..TruncateOptions::default()
            },
        ),
    }
}

// ─── 4. Wrap-aware measure closure ───────────────────────────────────────────

/// Build a Taffy `MeasureFn` closure for a text node.
///
/// Snapshots `squashed_text` and `wrap_mode` at call time — the closure
/// captures owned data and borrows nothing from the arena.
///
/// ## Invalidation contract
/// The caller must call `LayoutEngine::set_measure` again (rebuild the closure)
/// whenever the node's text or style changes — i.e., on `Op::SetText` and
/// `Op::SetStyle`. M1-6's harness exercises this contract.
///
/// ## AvailableSpace → ink width mapping (named divergence surface)
/// See module-level doc for the full mapping.  Summary:
///   `known.width = Some(w)` or `available.width = Definite(w)` → constrained to w.
///   `MaxContent` → unconstrained → return intrinsic.
///   `MinContent` → minimal, clamp cols to 1.
///
/// The two ink numeric guards (dom.ts:232, dom.ts:238) are applied before
/// wrapping to match ink's early-return paths exactly.
pub fn build_measure_fn(squashed_text: String, wrap_mode: TextWrap) -> Box<MeasureFn> {
    Box::new(
        move |known: Size<Option<f32>>, available: Size<AvailableSpace>| {
            // Resolve the effective width constraint, mirroring dom.ts:222-246.
            let constraint: Option<f32> = match known.width {
                // known.width = Some(w): Taffy has already pinned width.
                // Maps to MEASURE_MODE_EXACTLY in yoga — dom.ts guard at :232.
                Some(w) => Some(w),
                None => match available.width {
                    // available.width = Definite(w): width is constrained but not fixed.
                    // Maps to MEASURE_MODE_AT_MOST in yoga — dom.ts guard at :232.
                    AvailableSpace::Definite(w) => Some(w),
                    // MaxContent: no width constraint — return intrinsic.
                    // Maps to MEASURE_MODE_UNDEFINED in yoga (unconstrained pass).
                    AvailableSpace::MaxContent => None,
                    // MinContent: minimal constraint; clamp cols to 1 (wrap_ansi clamps too).
                    AvailableSpace::MinContent => Some(1.0),
                },
            };

            let (iw, ih) = measure_text(&squashed_text);

            let effective_w = match constraint {
                // Unconstrained: return intrinsic dimensions (measure-text.ts path).
                None => {
                    return Size {
                        width: iw,
                        height: ih,
                    };
                }
                Some(w) => w,
            };

            // dom.ts:232 — text fits: no need to wrap.
            if iw <= effective_w {
                return Size {
                    width: iw,
                    height: ih,
                };
            }

            // dom.ts:238 — sub-pixel space guard: return intrinsic (tell layout "no").
            if iw >= 1.0 && effective_w > 0.0 && effective_w < 1.0 {
                return Size {
                    width: iw,
                    height: ih,
                };
            }

            // Wrap at the effective width.
            // usize cast: effective_w is a terminal column count; f32→usize truncation
            // is intentional (matches ink's floor-like behavior via integer indices).
            let cols = effective_w.max(1.0) as usize;
            let wrapped = wrap_text_with_mode(&squashed_text, cols, wrap_mode);
            let (ww, wh) = measure_text(&wrapped);
            Size {
                width: ww,
                height: wh,
            }
        },
    )
}

/// Resolve the effective `textWrap` mode that governs measuring node `id`.
///
/// ## Why an ancestor walk (the two-node measure boundary)
/// ink models `<Text wrap=…>foo</Text>` as an `ink-text` element carrying
/// `textWrap` whose string content is a SEPARATE `#text` child. The reconciler
/// reproduces this exactly: `createTextInstance` (reconciler.ts:369-388) emits a
/// styleless `#text` arena node (its own `style.text_wrap` is `None`) under the
/// `ink-text` node that holds the `textWrap`. At layout, Taffy 0.10 invokes the
/// measure closure ONLY on LEAF nodes; the `#text` child is the leaf, the
/// `ink-text` parent (having a child) is laid out by flexbox and its own measure
/// fn never fires. So the height-governing measure happens on the `#text` child —
/// which has no `text_wrap` and would default to `Wrap`, folding a truncate/hard
/// string to its multi-line WRAP height. The parent's mode would never govern.
///
/// ink measures only at the `ink-text` level (via `squashTextNodes` under the
/// parent's `textWrap`); to match that with the smallest change we let the
/// measured `#text` leaf INHERIT the wrap mode from its nearest ancestor
/// `ink-text` / `ink-virtual-text` when its own is absent.
///
/// ## Resolution order (own-takes-precedence — load-bearing)
/// 1. The node's OWN `style.text_wrap` if `Some` — covers every single-folded
///    `Text` node (`e10`, the layout corpus, `a1`/`a2`): own is set, the walk
///    never fires, behaviour is byte-identical to before.
/// 2. else the nearest ancestor `Text`/`VirtualText` node's `text_wrap` — the
///    two-node reconciler shape, where the wrap lives on the parent `ink-text`.
/// 3. else `TextWrap::default()` (`Wrap`, dom.ts:242 `?? 'wrap'`) — a `#text`
///    under a default `<Text>` (whose `ink-text` carries `textWrap='wrap'`)
///    resolves to `Wrap` either at step 2 or here, matching the prior
///    `None → unwrap_or_default()` Wrap.
///
/// The walk stops at the first non-text ancestor (a `Box`/`Root` parent never
/// carries `textWrap`), so it inherits ONLY through the text subtree — exactly the
/// scope `squashTextNodes` collapses.
fn effective_text_wrap(arena: &Arena, id: u32) -> TextWrap {
    // 1. The measured node's own mode wins outright.
    if let Some(w) = arena.get(id).and_then(|n| n.style.text_wrap) {
        return w;
    }

    // 2. Walk up through ancestor text nodes; the first non-text ancestor (Box/
    //    Root) ends the search. `parent` is populated by `apply(AppendChild/
    //    InsertBefore)` on the live reconciler/op path.
    let mut current = arena.get(id).and_then(|n| n.parent);
    while let Some(pid) = current {
        let Some(parent) = arena.get(pid) else { break };
        if !matches!(parent.kind, Kind::Text | Kind::VirtualText) {
            break;
        }
        if let Some(w) = parent.style.text_wrap {
            return w;
        }
        current = parent.parent;
    }

    // 3. Default (Wrap).
    TextWrap::default()
}

/// Convenience: squash the arena subtree rooted at `id`, then build the closure.
///
/// Equivalent to `build_measure_fn(squash_text(arena, id), wrap_mode)`.
/// Use this when `set_measure` is called on a node that just had `SetText`.
///
/// `wrap_mode` is resolved by [`effective_text_wrap`]: the node's own mode, else
/// inherited from its nearest ancestor text node, else `Wrap`. The inheritance
/// fixes the two-node `<Text wrap=…>` boundary (the measured `#text` leaf has no
/// own wrap) without disturbing single-folded text nodes (own mode always wins).
pub fn build_measure_fn_for(arena: &Arena, id: u32) -> Box<MeasureFn> {
    let text = squash_text(arena, id);
    let wrap_mode = effective_text_wrap(arena, id);
    build_measure_fn(text, wrap_mode)
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dom::{Arena, Kind, Node, apply};
    use crate::layout::{LayoutEngine, TaffyEngine};

    // ── helpers ──────────────────────────────────────────────────────────────

    fn text_node(text: &str) -> Node {
        let mut n = Node::new(Kind::Text);
        n.text = Some(text.to_owned());
        n
    }

    fn vtext_node(text: &str) -> Node {
        let mut n = Node::new(Kind::VirtualText);
        n.text = Some(text.to_owned());
        n
    }

    // Build an arena with a single Text node (id=1) whose text is `text`.
    fn arena_single(text: &str) -> Arena {
        let mut a = Arena::new();
        a.insert(1, text_node(text));
        a
    }

    // ── Squash tests (pinned to squash-text-nodes.ts) ─────────────────────────

    // squash-text-nodes.ts:22-23: leaf with direct text.
    // A single Text node with text "hello" → "hello".
    #[test]
    fn squash_single_text_node() {
        let a = arena_single("hello");
        assert_eq!(squash_text(&a, 1), "hello");
    }

    // squash-text-nodes.ts:13-43: three sibling VirtualText children under a Text.
    // Mirrors <Text>hello{' '}world</Text> → three #text nodes concatenated.
    // node: squashTextNodes({nodeName:'ink-text', childNodes:[{nodeName:'#text',nodeValue:'hello'},{nodeName:'#text',nodeValue:' '},{nodeName:'#text',nodeValue:'world'}]}) === 'hello world'
    #[test]
    fn squash_three_virtual_children() {
        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Text));
        a.insert(1, vtext_node("hello"));
        a.insert(2, vtext_node(" "));
        a.insert(3, vtext_node("world"));
        // Parent text is None; children are the text sources.
        let parent = a.get_mut(0).unwrap();
        parent.children = vec![1, 2, 3];
        assert_eq!(squash_text(&a, 0), "hello world");
    }

    // squash-text-nodes.ts:24-39: nested virtual-text recursion.
    // Outer Text → VirtualText → nested VirtualText leaf.
    // node: squashTextNodes({nodeName:'ink-text', childNodes:[{nodeName:'ink-virtual-text', childNodes:[{nodeName:'#text',nodeValue:'deep'}]}]}) === 'deep'
    #[test]
    fn squash_nested_virtual_text() {
        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Text)); // root text
        a.insert(1, Node::new(Kind::VirtualText)); // intermediate virtual-text
        a.insert(2, vtext_node("deep")); // leaf

        a.get_mut(0).unwrap().children = vec![1];
        a.get_mut(1).unwrap().children = vec![2];

        assert_eq!(squash_text(&a, 0), "deep");
    }

    // squash-text-nodes.ts:26-28: Box children of a Text node are skipped
    // (they are not ink-text or ink-virtual-text).
    #[test]
    fn squash_skips_box_children() {
        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Text));
        a.insert(1, Node::new(Kind::Box)); // should be ignored

        a.get_mut(0).unwrap().children = vec![1];
        // No text on either node — result is empty.
        assert_eq!(squash_text(&a, 0), "");
    }

    // Transform is JS-side; M1 concatenates raw text.
    // Documented: node has has_transform=true but fn is absent → raw text returned.
    #[test]
    fn squash_transform_flag_does_not_affect_output() {
        let mut a = Arena::new();
        let mut n = text_node("raw");
        n.has_transform = true;
        a.insert(1, n);
        // squash-text-nodes.ts:34-39 applies transform JS-side; Rust skips (fn absent).
        assert_eq!(squash_text(&a, 1), "raw");
    }

    // ── #129: sanitizeAnsi at the squash boundary (squash-text-nodes.ts:45) ──

    // Oracle: sanitizeAnsi('A\x1b[2JB') === 'AB' (live-build probe /tmp/t129).
    // MUTATION (verified): removing the sanitize_ansi call in squash_text
    // returns 'A\x1b[2JB' → fails.
    #[test]
    fn squash_strips_embedded_clear_screen() {
        let a = arena_single("A\x1b[2JB");
        assert_eq!(squash_text(&a, 1), "AB");
    }

    // SGR survival control: sanitize keeps SGR byte-verbatim, so the squash
    // boundary must NOT touch styling escapes (chalk/colorize passthrough).
    #[test]
    fn squash_keeps_sgr_verbatim() {
        let a = arena_single("A\x1b[31mR\x1b[39mB");
        assert_eq!(squash_text(&a, 1), "A\x1b[31mR\x1b[39mB");
    }

    // Per-LEVEL sanitize (ink sanitizes every squashTextNodes return): a
    // nested child ending in an unterminated sequence drops only ITS
    // remainder; the following sibling's text survives. A single top-level
    // sanitize of the concatenation would see 'A\x1b]xB' (unterminated OSC)
    // and drop 'B' too — oracle keeps it: child → 'A', concat → 'AB'.
    // MUTATION (verified): recursing via squash_into (top-only sanitize)
    // yields 'A' → fails.
    #[test]
    fn squash_sanitizes_each_nested_level_like_ink() {
        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Text));
        a.insert(1, vtext_node("A\x1b]x")); // unterminated OSC → child folds to "A"
        a.insert(2, vtext_node("B"));
        a.get_mut(0).unwrap().children = vec![1, 2];
        assert_eq!(squash_text(&a, 0), "AB");
    }

    // squash_styled (render-time squash) sanitizes identically: same strip,
    // same SGR passthrough, through the no-transform accessor.
    #[test]
    fn squash_styled_strips_and_keeps_like_squash_text() {
        let a = arena_single("A\x1b[2J\x1b[31mR\x1b[39mB");
        assert_eq!(squash_styled(&a, 1, &|_| None), "A\x1b[31mR\x1b[39mB");
    }

    // ── #130: nested-transform re-sanitize (squash-text-nodes.ts:28 + :33) ────
    //
    // A NESTED <Text>/<Transform> child's `internal_transform` runs at the
    // CHILD's concatenation site (squash-text-nodes.ts:28) — its output is then
    // re-sanitized by the PARENT level's `sanitizeAnsi(text)` return (line 33).
    // So a child transform that RE-INTRODUCES a non-SGR CSI (e.g. \x1b[2J)
    // after the child's own squash sanitized it is stripped AGAIN by the parent.
    // Contrast the OUTERMOST node's OWN transform: applied later at
    // `write_styled` (render-node-to-output.ts:154) and NOT sanitized — hence
    // these pins use a NESTED child transform, never the outermost.
    //
    // Oracle (live-build probe /tmp/t130, driving build/squash-text-nodes.js):
    //   child internal_transform = (s,i) => `X\x1b[2JY`, sibling "Z"
    //     → squashTextNodes(parent) === "XYZ"   (non-SGR CSI STRIPPED by parent)
    //   child internal_transform = (s,i) => `\x1b[31m${s}\x1b[39m`, sibling "B"
    //     → squashTextNodes(parent) === "\x1b[31mR\x1b[39mB"  (SGR SURVIVES)

    // Build: parent Text (id=0) → nested Text child (id=1, leaf "s") + sibling
    // VirtualText (id=2, "Z"). The accessor mints a transform for the child id
    // whose OUTPUT carries a non-SGR CSI (\x1b[2J) — re-introduced AFTER the
    // child's own squash sanitized. The parent's squash_styled return
    // (mod.rs:212) must strip it: oracle → "XYZ".
    #[test]
    fn squash_styled_nested_transform_nonsgr_restripped_by_parent() {
        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Text));
        a.insert(1, vtext_node("s")); // nested child, leaf text "s"
        a.insert(2, vtext_node("Z")); // sibling
        a.get_mut(0).unwrap().children = vec![1, 2];
        // Accessor: child id=1 → transform emitting "X\x1b[2JY" (ignores input).
        let accessor = |id: u32| -> Option<crate::render::walk::LineTransform<'_>> {
            (id == 1).then(|| {
                Box::new(|_s: &str, _i: usize| "X\x1b[2JY".to_owned())
                    as crate::render::walk::LineTransform<'_>
            })
        };
        // Parent re-sanitizes the concatenation → \x1b[2J gone, "XYZ".
        assert_eq!(squash_styled(&a, 0, &accessor), "XYZ");
    }

    // Styling-passthrough control: an SGR-emitting nested transform SURVIVES the
    // parent re-sanitize (sanitize keeps SGR byte-verbatim). Same arena shape;
    // child id=1 → transform "\x1b[31m{s}\x1b[39m". Oracle → "\x1b[31mR\x1b[39mB".
    #[test]
    fn squash_styled_nested_transform_sgr_survives_parent() {
        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Text));
        a.insert(1, vtext_node("R")); // nested child, leaf text "R"
        a.insert(2, vtext_node("B")); // sibling
        a.get_mut(0).unwrap().children = vec![1, 2];
        let accessor = |id: u32| -> Option<crate::render::walk::LineTransform<'_>> {
            (id == 1).then(|| {
                Box::new(|s: &str, _i: usize| format!("\x1b[31m{s}\x1b[39m"))
                    as crate::render::walk::LineTransform<'_>
            })
        };
        assert_eq!(squash_styled(&a, 0, &accessor), "\x1b[31mR\x1b[39mB");
    }

    // ── Measure tests (pinned to measure-text.ts) ─────────────────────────────

    // measure-text.ts:11-14: empty string.
    // node: measureText('') === {width:0, height:0}
    #[test]
    fn measure_empty() {
        assert_eq!(measure_text(""), (0.0, 0.0));
    }

    // measure-text.ts:24-25: single line.
    // node: measureText('hello') === {width:5, height:1}
    #[test]
    fn measure_single_line() {
        assert_eq!(measure_text("hello"), (5.0, 1.0));
    }

    // measure-text.ts:24-25: multi-line.
    // node: measureText('hello\nworld foo') → {width:9, height:2}
    // widestLine: max(5, 9) = 9; split('\n').length = 2.
    #[test]
    fn measure_multi_line() {
        assert_eq!(measure_text("hello\nworld foo"), (9.0, 2.0));
    }

    // ANSI-styled text: '\x1b[31mred\x1b[39m' → visible width 3.
    // measure-text.ts delegates to widestLine which uses string-width (strips ANSI).
    // node: measureText('\x1b[31mred\x1b[39m') === {width:3, height:1}
    #[test]
    fn measure_ansi_styled_width_3() {
        assert_eq!(measure_text("\x1b[31mred\x1b[39m"), (3.0, 1.0));
    }

    // Wide characters (CJK): each = 2 columns.
    // node: measureText('中文') === {width:4, height:1}
    #[test]
    fn measure_cjk_wide_chars() {
        assert_eq!(measure_text("中文"), (4.0, 1.0));
    }

    // Emoji: U+1F600 GRINNING FACE = width 2.
    // node: measureText('\u{1F600}') === {width:2, height:1}
    #[test]
    fn measure_emoji_width_2() {
        assert_eq!(measure_text("\u{1F600}"), (2.0, 1.0));
    }

    // Multi-line with widest line != first line.
    // node: measureText('hi\nhello world') → {width:11, height:2}
    #[test]
    fn measure_widest_not_first_line() {
        assert_eq!(measure_text("hi\nhello world"), (11.0, 2.0));
    }

    // ── Wrap-aware measure closure tests ─────────────────────────────────────

    // Unconstrained (MaxContent) → intrinsic dimensions returned.
    // node: measureTextNode at unconstrained width → {width:5, height:1} for "hello"
    #[test]
    fn closure_unconstrained_returns_intrinsic() {
        let f = build_measure_fn("hello".to_owned(), TextWrap::Wrap);
        let mut f = f;
        let size = f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::MaxContent,
                height: AvailableSpace::MaxContent,
            },
        );
        assert_eq!(
            size,
            Size {
                width: 5.0,
                height: 1.0
            }
        );
    }

    // Constrained (Definite) — text fits: return intrinsic (dom.ts:232).
    // dom.ts:232: if (dimensions.width <= width) return dimensions
    #[test]
    fn closure_constrained_fits_returns_intrinsic() {
        let f = build_measure_fn("hi".to_owned(), TextWrap::Wrap);
        let mut f = f;
        let size = f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::Definite(10.0),
                height: AvailableSpace::MaxContent,
            },
        );
        // "hi" width=2 <= 10 → intrinsic {2, 1}
        assert_eq!(
            size,
            Size {
                width: 2.0,
                height: 1.0
            }
        );
    }

    // Sub-pixel guard (dom.ts:238): width > 0 && width < 1 → return intrinsic.
    // dom.ts:238: if (dimensions.width >= 1 && width > 0 && width < 1) return dimensions
    #[test]
    fn closure_sub_pixel_guard_returns_intrinsic() {
        let f = build_measure_fn("hello".to_owned(), TextWrap::Wrap);
        let mut f = f;
        let size = f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::Definite(0.5),
                height: AvailableSpace::MaxContent,
            },
        );
        // intrinsic width=5 >= 1 && 0.5 > 0 && 0.5 < 1 → return {5, 1}
        assert_eq!(
            size,
            Size {
                width: 5.0,
                height: 1.0
            }
        );
    }

    // Constrained with wrap needed (TextWrap::Wrap = hard:true, trim:false, word_wrap:true).
    // "hello world" at width=5, {hard:true,trim:false}:
    // Traced against the M0-proven wrap_ansi oracle (text/wrap_ansi.rs):
    //   trim:false means a new row is started when row fills, then a space is
    //   prepended (row_length > 0 || !trim = true) even when row_length=0.
    //   Result: ["hello", " ", "world"] → "hello\n \nworld" → 3 lines.
    //   widest line: max(string_width("hello")=5, string_width(" ")=1, 5) = 5.
    // node (verified with wrap_ansi@10 trim:false,hard:true):
    //   wrapAnsi("hello world", 5, {hard:true,trim:false}) === "hello\n \nworld"
    #[test]
    fn closure_wrap_mode_wraps_text() {
        let f = build_measure_fn("hello world".to_owned(), TextWrap::Wrap);
        let mut f = f;
        let size = f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::Definite(5.0),
                height: AvailableSpace::MaxContent,
            },
        );
        // "hello\n \nworld" → height=3, width=5
        assert_eq!(size.height, 3.0, "wrap:true,trim:false produces 3 lines");
        assert_eq!(size.width, 5.0);
    }

    // known.width takes precedence over available.width.
    // Same oracle derivation: "hello world" at 5 cols → 3 lines.
    #[test]
    fn closure_known_width_takes_precedence() {
        let f = build_measure_fn("hello world".to_owned(), TextWrap::Wrap);
        let mut f = f;
        let size = f(
            Size {
                width: Some(5.0),
                height: None,
            },
            // Even if available says MaxContent, known.width=Some wins
            Size {
                width: AvailableSpace::MaxContent,
                height: AvailableSpace::MaxContent,
            },
        );
        // "hello\n \nworld" → height=3 (same oracle as closure_wrap_mode_wraps_text)
        assert_eq!(size.height, 3.0);
    }

    // ── End-to-end through TaffyEngine ────────────────────────────────────────

    // E2E-1: text node under a width-constrained box → wrapped height.
    //
    // Setup: root (80×24), box (width=10, flex-dir=column), text "hello world".
    // textWrap=Wrap → wrap_ansi({hard:true,trim:false}) at width=10.
    // wrap_ansi("hello world", 10, {hard:true,trim:false}):
    //   Verified against M0 oracle (wrap_ansi in text/wrap_ansi.rs is M0-proven).
    //   With hard:true, trim:false, cols=10: "hello world" (11 chars, 11 width)
    //   > 10 cols → wraps to "hello \nworld" (trim:false keeps trailing space).
    //   After measure_text: height=2, width=max(string_width("hello "),string_width("world"))=max(6,5)=6.
    //   The box constrains to 10; width 6 < 10 → width=6, height=2.
    #[test]
    fn e2e_constrained_wrapped_height() {
        use crate::dom::Dim;

        let mut a = Arena::new();
        a.insert(0, Node::new(Kind::Root));
        a.insert(1, Node::new(Kind::Box));
        a.insert(2, {
            let mut n = Node::new(Kind::Text);
            n.text = Some("hello world".to_owned());
            n
        });
        a.get_mut(1).unwrap().children = vec![2];
        a.get_mut(0).unwrap().children = vec![1];
        a.get_mut(2).unwrap().parent = Some(1);
        a.get_mut(1).unwrap().parent = Some(0);

        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        e.create(1).unwrap();
        e.create(2).unwrap();
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(1, 2, 0).unwrap();

        // Root: 80×24
        let root_style = crate::dom::Style {
            width: Some(Dim::Points(80.0)),
            height: Some(Dim::Points(24.0)),
            ..Default::default()
        };
        // Box: width=10, flex-direction=column, align-items=flex-start
        let box_style = crate::dom::Style {
            width: Some(Dim::Points(10.0)),
            align_items: Some(crate::dom::Align::FlexStart),
            ..Default::default()
        };
        e.apply_style(0, &root_style).unwrap();
        e.apply_style(1, &box_style).unwrap();

        // Wire the text measure function.
        e.set_measure(2, build_measure_fn_for(&a, 2));

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        let text_rect = e.computed(2).unwrap();
        // "hello world" at 10 cols with Wrap mode → height=2.
        assert_eq!(text_rect.height, 2, "wrapped height should be 2");
    }

    // E2E-2: unconstrained text node → intrinsic width returned.
    //
    // Root with no explicit children → text node with "hello" → intrinsic {5, 1}.
    #[test]
    fn e2e_unconstrained_intrinsic_width() {
        let mut a = Arena::new();
        a.insert(0, {
            let mut n = Node::new(Kind::Root);
            n.children = vec![1];
            n
        });
        a.insert(1, {
            let mut n = Node::new(Kind::Text);
            n.text = Some("hello".to_owned());
            n.parent = Some(0);
            n
        });

        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        e.create(1).unwrap();
        e.insert_child(0, 1, 0).unwrap();

        let root_style = crate::dom::Style {
            width: Some(crate::dom::Dim::Points(80.0)),
            height: Some(crate::dom::Dim::Points(24.0)),
            align_items: Some(crate::dom::Align::FlexStart),
            ..Default::default()
        };
        e.apply_style(0, &root_style).unwrap();
        e.set_measure(1, build_measure_fn_for(&a, 1));

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        let r = e.computed(1).unwrap();
        // "hello" intrinsic width=5, height=1.
        assert_eq!(r.width, 5, "intrinsic width should be 5");
        assert_eq!(r.height, 1, "intrinsic height should be 1");
    }

    // ── wrap_text_with_mode: Hard, TruncateEnd, TruncateMiddle, TruncateStart ──
    // These tests pin the four modes that were absent from the original suite.
    // Each test asserts against BOTH a derivation call (catching a mode→options
    // regression) AND a concrete literal (catching a wrap_ansi/cli_truncate
    // regression). Both layers must agree for the test to pass.

    // wrap-text.ts:27-32: wrapAnsi(text, w, {trim:false, hard:true, wordWrap:false})
    // Derivation: wrap_ansi_with("hello world", 8, WrapOptions{hard:true,word_wrap:false,trim:false})
    // node (wrap-ansi@10 oracle, M0-proven): "hello wo\nrld"
    // Distinguishing from Wrap: Wrap@8 breaks at word boundary ("hello \nworld");
    // Hard breaks mid-word because word_wrap:false disables word-boundary logic.
    #[test]
    fn wrap_mode_hard_pins_mid_word_break() {
        let derived = wrap_ansi_with(
            "hello world",
            8,
            WrapOptions {
                hard: true,
                word_wrap: false,
                trim: false,
            },
        );
        let got = wrap_text_with_mode("hello world", 8, TextWrap::Hard);
        // Layer-1 pin: mode→options mapping must produce the derivation.
        assert_eq!(got, derived, "Hard mode must use word_wrap:false");
        // Layer-2 pin: concrete literal from M0 wrap-ansi oracle.
        assert_eq!(got, "hello wo\nrld");
    }

    // wrap-text.ts:33-47: cliTruncate(text, w, {position:'end'})
    // Derivation: cli_truncate_with("hello world", 8, &TruncateOptions{position:End,..})
    // node (cli-truncate@6, pinned by cli_truncate.rs::end_plain): "hello w…"
    #[test]
    fn wrap_mode_truncate_end_pins_literal() {
        let derived = cli_truncate_with(
            "hello world",
            8,
            &TruncateOptions {
                position: TruncatePosition::End,
                ..TruncateOptions::default()
            },
        );
        let got = wrap_text_with_mode("hello world", 8, TextWrap::TruncateEnd);
        // Layer-1 pin: mode→options mapping.
        assert_eq!(got, derived, "TruncateEnd must use position:End");
        // Layer-2 pin: concrete literal (corroborated by cli_truncate.rs::end_plain).
        assert_eq!(got, "hello w\u{2026}");
    }

    // wrap-text.ts:39: cliTruncate(text, w, {position:'middle'})
    // Derivation: cli_truncate_with("hello world", 8, &TruncateOptions{position:Middle,..})
    // node (cli-truncate@6, pinned by cli_truncate.rs::middle_plain): "hell…rld"
    #[test]
    fn wrap_mode_truncate_middle_pins_literal() {
        let derived = cli_truncate_with(
            "hello world",
            8,
            &TruncateOptions {
                position: TruncatePosition::Middle,
                ..TruncateOptions::default()
            },
        );
        let got = wrap_text_with_mode("hello world", 8, TextWrap::TruncateMiddle);
        // Layer-1 pin: mode→options mapping.
        assert_eq!(got, derived, "TruncateMiddle must use position:Middle");
        // Layer-2 pin: concrete literal (corroborated by cli_truncate.rs::middle_plain).
        assert_eq!(got, "hell\u{2026}rld");
    }

    // wrap-text.ts:43: cliTruncate(text, w, {position:'start'})
    // Derivation: cli_truncate_with("hello world", 8, &TruncateOptions{position:Start,..})
    // node (cli-truncate@6, pinned by cli_truncate.rs::start_plain): "…o world"
    #[test]
    fn wrap_mode_truncate_start_pins_literal() {
        let derived = cli_truncate_with(
            "hello world",
            8,
            &TruncateOptions {
                position: TruncatePosition::Start,
                ..TruncateOptions::default()
            },
        );
        let got = wrap_text_with_mode("hello world", 8, TextWrap::TruncateStart);
        // Layer-1 pin: mode→options mapping.
        assert_eq!(got, derived, "TruncateStart must use position:Start");
        // Layer-2 pin: concrete literal (corroborated by cli_truncate.rs::start_plain).
        assert_eq!(got, "\u{2026}o world");
    }

    // ── Measure-with-mode end-to-end (truncate never wraps) ──────────────────

    // A truncated result must have height=1 and width<=w.
    // "hello world" (intrinsic width=11) > 8 → closure hits the truncate path.
    // TruncateEnd result "hello w…" has visible width=8, one line → height=1.
    // Pins both numbers so a future wrap-fallback regression is immediately visible.
    #[test]
    fn measure_truncate_end_height_1_width_le_w() {
        let f = build_measure_fn("hello world".to_owned(), TextWrap::TruncateEnd);
        let mut f = f;
        let size = f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::Definite(8.0),
                height: AvailableSpace::MaxContent,
            },
        );
        // "hello w…" → height=1 (truncate never wraps), width=8 (≤ constraint).
        assert_eq!(size.height, 1.0, "truncate must not wrap: height must be 1");
        assert_eq!(size.width, 8.0, "truncated width must equal 8");
    }

    // ── sanitizeAnsi / control-char pin (mod.rs:14-19 claim) ─────────────────

    // mod.rs:14-19 claims sanitizeAnsi is a measurement no-op: string_width
    // already strips all ANSI (including OSC 8 hyperlinks), and height counts \n
    // which is unaffected by sanitization.
    //
    // This test pins one case with an embedded SGR sequence AND an OSC 8
    // hyperlink so that a future sanitize port cannot silently change measurement.
    //
    // Input: SGR red open + "hi" + SGR reset + OSC8 hyperlink wrapping "ok" + reset.
    // Visible text: "hi" (width 2) + "ok" (width 2) = 4 columns, 1 line.
    //
    // string_width strips ANSI via ansi-regex@6.2.2 (OSC branch: \x1b\]...\x07).
    // Pinned by string_width.rs::ansi_osc8_hyperlink (proves OSC 8 stripping).
    // measure_text delegates width to string_width → width=4, height=1.
    #[test]
    fn measure_sgr_and_osc8_hyperlink_width_equals_visible_width() {
        // SGR: \x1b[31m ... \x1b[39m = red foreground open/close.
        // OSC 8: \x1b]8;;https://example.com\x07 ... \x1b]8;;\x07 = hyperlink.
        let s = "\x1b[31mhi\x1b[39m\x1b]8;;https://example.com\x07ok\x1b]8;;\x07";
        // string_width strips all ANSI: visible = "hi" + "ok" = 4 columns.
        assert_eq!(string_width(s), 4, "string_width must strip SGR and OSC 8");
        // measure_text uses string_width for width and \n-count for height.
        let (w, h) = measure_text(s);
        assert_eq!(w, 4.0, "measured width must equal visible width 4");
        assert_eq!(h, 1.0, "no newline → height 1");
    }

    // ── build_measure_fn_for reads text_wrap from the node's Style ───────────

    // Pins the style read in build_measure_fn_for: a mutant hardcoding
    // TextWrap::Wrap would wrap "hello world"@8 to 2 lines (height 2);
    // the node's TruncateEnd style must produce the 1-line truncate path.
    #[test]
    fn build_measure_fn_for_reads_text_wrap_style() {
        let mut a = arena_single("hello world");
        a.get_mut(1).unwrap().style.text_wrap = Some(TextWrap::TruncateEnd);
        let mut f = build_measure_fn_for(&a, 1);
        let size = f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::Definite(8.0),
                height: AvailableSpace::MaxContent,
            },
        );
        // TruncateEnd: "hello w…" → height 1, width 8 (Wrap would give height 2).
        assert_eq!(size.height, 1.0, "style read must select the truncate path");
        assert_eq!(size.width, 8.0);
    }

    // ── Two-node `<Text wrap=…>` boundary: child inherits the parent's mode ───
    //
    // Reproduces the #45/#70 reconciler topology: an `ink-text` node carrying the
    // `textWrap` whose string content is a SEPARATE `#text` child (created by
    // `createTextInstance`, styleless → own `text_wrap` is None). Taffy measures
    // only the leaf `#text` child, so it must inherit the parent's wrap mode, or it
    // folds the string in the default Wrap mode (the bug: multi-line height instead
    // of the truncated single line). `parent` is set via `apply(Op::AppendChild)`,
    // exactly the live reconciler path.
    fn two_node_text_arena(parent_wrap: Option<TextWrap>, text: &str) -> Arena {
        use crate::dom::Op;
        let mut a = Arena::new();
        // 1 = ink-text parent (carries textWrap, no own text).
        let mut parent = Node::new(Kind::Text);
        parent.style.text_wrap = parent_wrap;
        a.insert(1, parent);
        // 2 = styleless #text child (its own text_wrap is None).
        a.insert(2, text_node(text));
        // Wire via apply so `child.parent` is populated (op.rs:93).
        apply(
            &mut a,
            &[Op::AppendChild {
                parent: 1,
                child: 2,
            }],
        );
        a
    }

    fn measure_at(a: &Arena, id: u32, width: f32) -> Size<f32> {
        let mut f = build_measure_fn_for(a, id);
        f(
            Size {
                width: None,
                height: None,
            },
            Size {
                width: AvailableSpace::Definite(width),
                height: AvailableSpace::MaxContent,
            },
        )
    }

    // The #70 fix: the measured `#text` LEAF inherits `truncate` from its
    // `ink-text` parent → ONE line (height 1), not the Wrap-folded height. Without
    // inheritance the 11-char string at width 8 folds to 2 lines (height 2).
    #[test]
    fn child_text_inherits_truncate_from_parent_ink_text() {
        let a = two_node_text_arena(Some(TextWrap::TruncateEnd), "hello world");
        let size = measure_at(&a, 2, 8.0);
        assert_eq!(
            size.height, 1.0,
            "the #text child must inherit truncate from its ink-text parent (height 1, not the Wrap-folded 2)"
        );
        assert_eq!(size.width, 8.0, "truncated width equals the constraint");
    }

    // Inheritance is mode-general, not truncate-special: `Hard` (word_wrap:false)
    // on the parent must reach the leaf and break mid-word — distinct from Wrap's
    // word-boundary break. Pins that the fix threads the actual parent mode through,
    // not a truncate→height-1 shortcut.
    #[test]
    fn child_text_inherits_hard_from_parent_ink_text() {
        let a = two_node_text_arena(Some(TextWrap::Hard), "hello world");
        // Hard@8 → "hello wo\nrld" (mid-word) → height 2, widest line width 8.
        // Wrap@8 would break at the word boundary → "hello \nworld" → widest 6.
        let size = measure_at(&a, 2, 8.0);
        assert_eq!(size.height, 2.0, "Hard mode reaches the leaf (2 lines)");
        assert_eq!(
            size.width, 8.0,
            "Hard breaks mid-word → widest line is the full 8 cols (Wrap would give 6)"
        );
    }

    // Regression guard for the default `<Text>` path: a parent in Wrap mode (ink's
    // Text.tsx default `textWrap='wrap'`) keeps the child wrapping exactly as
    // before the fix — the inherited Wrap is identical to the prior
    // `None → unwrap_or_default()` Wrap, so this byte-for-byte matches the legacy
    // behaviour the goldens depend on.
    #[test]
    fn child_text_inherits_wrap_from_parent_is_unchanged() {
        let a = two_node_text_arena(Some(TextWrap::Wrap), "hello world");
        // Wrap@8 word-boundary break → "hello \nworld" → height 2, widest 6.
        let size = measure_at(&a, 2, 8.0);
        assert_eq!(
            size.height, 2.0,
            "Wrap parent still wraps the child (height 2)"
        );
        assert_eq!(size.width, 6.0, "Wrap word-boundary widest line is 6");
    }

    // A `#text` whose parent ALSO has no wrap (or no text parent at all — e.g. the
    // single-folded layout-corpus nodes whose parent is a Box) falls to the default
    // Wrap. This is what keeps the layout corpus and zero-flicker goldens
    // byte-identical: the walk finds no ancestor wrap and resolves to Wrap, exactly
    // the legacy `unwrap_or_default()`.
    #[test]
    fn child_text_with_no_ancestor_wrap_defaults_to_wrap() {
        let a = two_node_text_arena(None, "hello world");
        let size = measure_at(&a, 2, 8.0);
        // Same as the Wrap case above (the default).
        assert_eq!(
            size.height, 2.0,
            "absent ancestor wrap → default Wrap (height 2)"
        );
        assert_eq!(size.width, 6.0);
    }

    // Own mode wins over the ancestor: a `#text` child that DOES carry its own
    // `text_wrap` is governed by it, never by the parent. (Defensive — the
    // reconciler does not style `#text` children today, but the resolution order
    // must be own-first so single-folded nodes are never overridden.)
    #[test]
    fn child_text_own_wrap_overrides_parent() {
        // Parent says truncate, child says Wrap → child's Wrap governs (height 2).
        let mut a = two_node_text_arena(Some(TextWrap::TruncateEnd), "hello world");
        a.get_mut(2).unwrap().style.text_wrap = Some(TextWrap::Wrap);
        let size = measure_at(&a, 2, 8.0);
        assert_eq!(
            size.height, 2.0,
            "the child's own Wrap must win over the parent's truncate"
        );
        assert_eq!(size.width, 6.0);
    }
}