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
//! Border rendering — styled-frame slice.
//!
//! Port of ink's `render-border.ts`, including the `stylePiece` SGR coloring
//! that the M1 char-only port dropped (M2-C restores it).
//!
//! # Design decisions
//!
//! ## Color (render-border.ts:7-20, 36-64)
//! `stylePiece` wraps each border piece: colorize fg (innermost) → colorize bg
//! → dim (outermost). Per-edge fg resolves `border{Edge}Color ?? borderColor`;
//! per-edge dim resolves `border{Edge}DimColor ?? borderDimColor`, read from
//! `Style` (these are style props that flow JS→core via Box's `...style` spread).
//! With no color and no dim, `style_piece` is the identity transform, so plain
//! borders stay byte-identical.
//!
//! ## Per-element wrapping (render-border.ts:74-131)
//! Each corner+run top/bottom row is wrapped once (one SGR pair per row), and
//! EACH vertical-bar cell is wrapped independently before the rows are joined
//! with `\n`. The styled-grid `write` path (grid.rs) tokenizes each line with no
//! carried SGR state, so a once-wrapped vertical strip would leave interior bars
//! unstyled — every bar must carry its own open/close pair.
//!
//! ## Per-edge suppression (render-border.ts:66-69 citation)
//! ```ts
//! const showTopBorder    = node.style.borderTop    !== false;
//! const showBottomBorder = node.style.borderBottom !== false;
//! const showLeftBorder   = node.style.borderLeft   !== false;
//! const showRightBorder  = node.style.borderRight  !== false;
//! ```
//! A missing/`true` value means "show"; only explicit `false` suppresses.
//! In Rust: `style.border_top == Some(false)` → hide; anything else → show.
//!
//! ## Corner handling when an edge is off (render-border.ts:74-79 citation)
//! ```ts
//! let topBorder = showTopBorder
//!   ? (showLeftBorder ? box.topLeft : '') +
//!     box.top.repeat(contentWidth) +
//!     (showRightBorder ? box.topRight : '')
//!   : undefined;
//! ```
//! Corners appear only when BOTH the edge they terminate AND the perpendicular
//! edge are shown. When the top edge is off the entire top row is omitted
//! (topBorder = undefined). When the left edge is off, topLeft corner is ''.
//! Same logic applies to bottom/right permutations.
//!
//! ## Vertical border height (render-border.ts:86-95 citation)
//! ```ts
//! let verticalBorderHeight = height;
//! if (showTopBorder)    verticalBorderHeight -= 1;
//! if (showBottomBorder) verticalBorderHeight -= 1;
//! ```
//! Left/right border strings span only the interior rows (total height minus
//! the rows consumed by top/bottom border lines).

use crate::dom::{BorderStyle, Style};
use crate::render::cli_boxes::{BoxChars, CustomChars, named as named_box};
use crate::render::colorize::{ColorLevel, Kind, colorize, dim as dim_modifier};
use crate::render::grid::Grid;

/// Style one border piece: colorize fg (innermost) → colorize bg → dim
/// (outermost), mirroring `stylePiece` (render-border.ts:7-20).
///
/// With `fg`/`bg` both `None`/empty and `dim` false this is the identity
/// transform (`colorize` passes through and dim is skipped), so plain borders
/// stay byte-identical to the char-only slice. `level` is the detected color
/// level (chalk's `chalk.level`): at [`ColorLevel::None`] every colorize/dim is a
/// no-op, so a colored border in a non-color terminal emits plain box chars.
fn style_piece(
    segment: &str,
    fg: Option<&str>,
    bg: Option<&str>,
    dim: bool,
    level: ColorLevel,
) -> String {
    let styled = colorize(segment, fg, Kind::Fg, level);
    let styled = colorize(&styled, bg, Kind::Bg, level);
    if dim {
        dim_modifier(&styled, level)
    } else {
        styled
    }
}

/// Resolve a `BorderStyle` to its `BoxChars`.
///
/// Named styles return `Cow::Borrowed` (zero-copy). Custom styles return
/// `Cow::Owned` (no leaking — freed when the `BoxChars` is dropped).
///
/// **Unknown name fallback:** an unrecognised `Named` style silently falls
/// back to `"single"`.  Ink's JS equivalent throws a `TypeError`
/// (`cliBoxes[name]` is `undefined`, so `box.topLeft` access crashes); Rust
/// never panics — the caller always gets a valid frame.
///
/// Mirrors render-border.ts:32-34:
/// ```ts
/// const box = typeof node.style.borderStyle === 'string'
///   ? cliBoxes[node.style.borderStyle]
///   : node.style.borderStyle;
/// ```
fn resolve_box(style: &BorderStyle) -> BoxChars {
    match style {
        BorderStyle::Named(name) => named_box(name).unwrap_or_else(|| {
            // Unknown named style: fall back to "single" so the renderer
            // never panics. Document: unknown names behave like "single".
            named_box("single").unwrap()
        }),
        BorderStyle::Custom {
            top_left,
            top,
            top_right,
            right,
            bottom_right,
            bottom,
            bottom_left,
            left,
        } => BoxChars::from_custom(CustomChars {
            top_left: top_left.clone(),
            top: top.clone(),
            top_right: top_right.clone(),
            right: right.clone(),
            bottom_right: bottom_right.clone(),
            bottom: bottom.clone(),
            bottom_left: bottom_left.clone(),
            left: left.clone(),
        }),
    }
}

/// Draw the border of a box node into `grid`.
///
/// `(x, y)` is the top-left corner of the box (absolute grid coordinates).
/// `width` / `height` are the full computed dimensions including border cells.
///
/// Mirrors `renderBorder` in render-border.ts:22-155, including `stylePiece`.
pub fn render_border(
    x: i32,
    y: i32,
    width: u16,
    height: u16,
    style: &Style,
    grid: &mut Grid,
    level: ColorLevel,
) {
    let Some(ref border_style) = style.border_style else {
        return; // render-border.ts:28: early return if no borderStyle.
    };

    let bx = resolve_box(border_style);

    // render-border.ts:36-42: per-edge fg color — border{Edge}Color ?? borderColor.
    let top_color = style
        .border_top_color
        .as_deref()
        .or(style.border_color.as_deref());
    let bottom_color = style
        .border_bottom_color
        .as_deref()
        .or(style.border_color.as_deref());
    let left_color = style
        .border_left_color
        .as_deref()
        .or(style.border_color.as_deref());
    let right_color = style
        .border_right_color
        .as_deref()
        .or(style.border_color.as_deref());

    // render-border.ts:54-64: per-edge dim — border{Edge}DimColor ?? borderDimColor.
    // Read from Style (these are style props, threaded JS→core via Box's `...style`).
    let dim_top = style
        .border_top_dim_color
        .or(style.border_dim_color)
        .unwrap_or(false);
    let dim_bottom = style
        .border_bottom_dim_color
        .or(style.border_dim_color)
        .unwrap_or(false);
    let dim_left = style
        .border_left_dim_color
        .or(style.border_dim_color)
        .unwrap_or(false);
    let dim_right = style
        .border_right_dim_color
        .or(style.border_dim_color)
        .unwrap_or(false);

    // render-border.ts:44-52: per-edge bg — border{Edge}BackgroundColor ?? borderBackgroundColor.
    let top_bg = style
        .border_top_background_color
        .as_deref()
        .or(style.border_background_color.as_deref());
    let bottom_bg = style
        .border_bottom_background_color
        .as_deref()
        .or(style.border_background_color.as_deref());
    let left_bg = style
        .border_left_background_color
        .as_deref()
        .or(style.border_background_color.as_deref());
    let right_bg = style
        .border_right_background_color
        .as_deref()
        .or(style.border_background_color.as_deref());

    // render-border.ts:66-69: edge visibility.
    let show_top = style.border_top != Some(false);
    let show_bottom = style.border_bottom != Some(false);
    let show_left = style.border_left != Some(false);
    let show_right = style.border_right != Some(false);

    let w = width as i32;
    let h = height as i32;

    // render-border.ts:71-72: contentWidth = width − left_border − right_border.
    let content_width = w - if show_left { 1 } else { 0 } - if show_right { 1 } else { 0 };

    // render-border.ts:74-79: top border row.
    // Top corners appear only when both the top AND the respective side are shown.
    if show_top {
        let mut top_str = String::new();
        if show_left {
            top_str.push_str(&bx.top_left);
        }
        for _ in 0..content_width.max(0) {
            top_str.push_str(&bx.top);
        }
        if show_right {
            top_str.push_str(&bx.top_right);
        }
        // render-border.ts:80-85: wrap the whole top row once (single line).
        let top_str = style_piece(&top_str, top_color, top_bg, dim_top, level);
        grid.write(x, y, &top_str);
    }

    // render-border.ts:86-95: vertical border height = total height minus
    // the rows used by top and bottom borders.
    let mut vert_height = h;
    if show_top {
        vert_height -= 1;
    }
    if show_bottom {
        vert_height -= 1;
    }

    // render-border.ts:97-108: left border — one char per interior row.
    // Written as a single multi-line string with \n separators.
    // Borrow as &str so repeat clones cheap pointer+len, not the Cow itself.
    if show_left && vert_height > 0 {
        // render-border.ts:99-107: style ONE cell, then repeat — each line carries
        // its own SGR pair so the per-line tokenizer styles every bar.
        let one = style_piece(&bx.left, left_color, left_bg, dim_left, level);
        let left_str = std::iter::repeat_n(one.as_str(), vert_height as usize)
            .collect::<Vec<_>>()
            .join("\n");
        let offset_y = if show_top { 1 } else { 0 };
        grid.write(x, y + offset_y, &left_str);
    }

    // render-border.ts:109-119: right border.
    if show_right && vert_height > 0 {
        // render-border.ts:111-118: style ONE cell, then repeat (see left edge).
        let one = style_piece(&bx.right, right_color, right_bg, dim_right, level);
        let right_str = std::iter::repeat_n(one.as_str(), vert_height as usize)
            .collect::<Vec<_>>()
            .join("\n");
        let offset_y = if show_top { 1 } else { 0 };
        // render-border.ts:143-146: x + width - 1.
        grid.write(x + w - 1, y + offset_y, &right_str);
    }

    // render-border.ts:121-131: bottom border row.
    if show_bottom {
        let mut bot_str = String::new();
        if show_left {
            bot_str.push_str(&bx.bottom_left);
        }
        for _ in 0..content_width.max(0) {
            bot_str.push_str(&bx.bottom);
        }
        if show_right {
            bot_str.push_str(&bx.bottom_right);
        }
        // render-border.ts:126-131: wrap the whole bottom row once (single line).
        let bot_str = style_piece(&bot_str, bottom_color, bottom_bg, dim_bottom, level);
        // render-border.ts:148-151: y + height - 1.
        grid.write(x, y + h - 1, &bot_str);
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dom::Style;
    use crate::render::grid::Grid;

    fn style_with_border(name: &str) -> Style {
        Style {
            border_style: Some(BorderStyle::Named(name.to_owned())),
            ..Style::default()
        }
    }

    fn render_to_string(rows: usize, cols: usize, style: &Style, w: u16, h: u16) -> String {
        let mut g = Grid::new(rows, cols);
        // Truecolor (level 3) keeps these char-only border literals identical to
        // the pre-#77 behavior (no color → identity transform either way).
        render_border(0, 0, w, h, style, &mut g, ColorLevel::Truecolor);
        g.get().0
    }

    // ── Named styles (pin exact frame literals from ink oracle) ──────────────

    // ink: renderToString(<Box borderStyle="single" width={10} height={3}/>) ===
    // "┌────────┐\n│        │\n└────────┘"
    #[test]
    fn single_border_10x3() {
        let s = style_with_border("single");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "┌────────┐\n│        │\n└────────┘");
    }

    // ink: renderToString(<Box borderStyle="double" width={10} height={3}/>) ===
    // "╔════════╗\n║        ║\n╚════════╝"
    #[test]
    fn double_border_10x3() {
        let s = style_with_border("double");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "╔════════╗\n║        ║\n╚════════╝");
    }

    // ink: renderToString(<Box borderStyle="round" width={10} height={3}/>) ===
    // "╭────────╮\n│        │\n╰────────╯"
    #[test]
    fn round_border_10x3() {
        let s = style_with_border("round");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "╭────────╮\n│        │\n╰────────╯");
    }

    // ink: renderToString(<Box borderStyle="bold" width={10} height={3}/>) ===
    // "┏━━━━━━━━┓\n┃        ┃\n┗━━━━━━━━┛"
    #[test]
    fn bold_border_10x3() {
        let s = style_with_border("bold");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "┏━━━━━━━━┓\n┃        ┃\n┗━━━━━━━━┛");
    }

    // ink: renderToString(<Box borderStyle="classic" width={10} height={3}/>) ===
    // "+--------+\n|        |\n+--------+"
    #[test]
    fn classic_border_10x3() {
        let s = style_with_border("classic");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "+--------+\n|        |\n+--------+");
    }

    // ink: renderToString(<Box borderStyle="singleDouble" width={10} height={3}/>) ===
    // "╓────────╖\n║        ║\n╙────────╜"
    #[test]
    fn single_double_border_10x3() {
        let s = style_with_border("singleDouble");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "╓────────╖\n║        ║\n╙────────╜");
    }

    // ink: renderToString(<Box borderStyle="doubleSingle" width={10} height={3}/>) ===
    // "╒════════╕\n│        │\n╘════════╛"
    #[test]
    fn double_single_border_10x3() {
        let s = style_with_border("doubleSingle");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "╒════════╕\n│        │\n╘════════╛");
    }

    // ink: renderToString(<Box borderStyle="arrow" width={10} height={3}/>) ===
    // "↘↓↓↓↓↓↓↓↓↙\n→        ←\n↗↑↑↑↑↑↑↑↑↖"
    #[test]
    fn arrow_border_10x3() {
        let s = style_with_border("arrow");
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "↘↓↓↓↓↓↓↓↓↙\n→        ←\n↗↑↑↑↑↑↑↑↑↖");
    }

    // ── Partial edges ────────────────────────────────────────────────────────

    // ink: renderToString(<Box borderStyle="single" borderTop={false} width={10} height={3}/>) ===
    // "│        │\n│        │\n└────────┘"
    #[test]
    fn single_no_top_10x3() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_top: Some(false),
            ..Style::default()
        };
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "│        │\n│        │\n└────────┘");
    }

    // ink: renderToString(<Box borderStyle="single" borderLeft={false} width={10} height={3}/>) ===
    // "─────────┐\n         │\n─────────┘"
    #[test]
    fn single_no_left_10x3() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_left: Some(false),
            ..Style::default()
        };
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "─────────┐\n\n─────────┘");
    }

    // ink: renderToString(<Box borderStyle="single" borderRight={false} width={10} height={3}/>) ===
    // "┌─────────\n│\n└─────────"
    #[test]
    fn single_no_right_10x3() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_right: Some(false),
            ..Style::default()
        };
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "┌─────────\n\n└─────────");
    }

    // ink: renderToString(<Box borderStyle="single" borderBottom={false} width={10} height={3}/>) ===
    // "┌────────┐\n│        │\n│        │"
    #[test]
    fn single_no_bottom_10x3() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_bottom: Some(false),
            ..Style::default()
        };
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "┌────────┐\n│        │\n│        │");
    }

    // No borderStyle → render_border is a no-op → grid stays all spaces.
    #[test]
    fn no_border_style_noop() {
        let s = Style::default();
        let out = render_to_string(3, 10, &s, 10, 3);
        // All spaces trimmed → three empty lines joined by \n.
        assert_eq!(out, "\n\n");
    }

    // Unknown named style falls back to "single" (ink throws TypeError; we never panic).
    // "singel" is a deliberate misspelling — pins the fallback path.
    // Expected frame matches the oracle for single at 10×3.
    #[test]
    fn unknown_named_falls_back_to_single() {
        let s = style_with_border("singel"); // typo — not a known style
        let out = render_to_string(3, 10, &s, 10, 3);
        assert_eq!(out, "┌────────┐\n│        │\n└────────┘");
    }

    // ── M2-C: stylePiece SGR coloring ────────────────────────────────────────

    fn render_styled(rows: usize, cols: usize, style: &Style, w: u16, h: u16) -> String {
        let mut g = Grid::new(rows, cols);
        // Level 3: the M2-C stylePiece SGR pins are all chalk@5 level-3 bytes.
        render_border(0, 0, w, h, style, &mut g, ColorLevel::Truecolor);
        g.get().0
    }

    // No color and no dim → style_piece is identity → plain frame is
    // BYTE-IDENTICAL to the char-only slice (the ~37 plain tests must not move).
    #[test]
    fn plain_border_identity_no_sgr() {
        let s = style_with_border("single");
        let out = render_styled(3, 10, &s, 10, 3);
        assert_eq!(out, "┌────────┐\n│        │\n└────────┘");
        assert!(!out.contains('\x1b'), "plain border must emit no SGR bytes");
    }

    // #77: a hex-colored border honors the detected ColorLevel.
    //  - None (0): NO SGR — plain box chars (matches ink in a non-color terminal).
    //  - Basic (1): rgb→ansi16 downgrade (#ff8800 → 93 brightYellow).
    //  - Ansi256 (2): rgb→ansi256 downgrade (#ff8800 → 214).
    //  - Truecolor (3): 38;2 truecolor verbatim.
    // Bytes are chalk@5/ansi-styles ground truth (oracle-pinned in colorize tests).
    fn render_border_at(level: ColorLevel) -> String {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_color: Some("#ff8800".to_owned()),
            ..Style::default()
        };
        let mut g = Grid::new(3, 10);
        render_border(0, 0, 10, 3, &s, &mut g, level);
        g.get().0
    }

    #[test]
    fn hex_border_level_none_emits_no_sgr() {
        let out = render_border_at(ColorLevel::None);
        assert_eq!(out, "┌────────┐\n│        │\n└────────┘");
        assert!(
            !out.contains('\x1b'),
            "level 0: a hex-colored border must emit NO SGR (plain chars)"
        );
    }

    #[test]
    fn hex_border_level_basic_downgrades_to_16() {
        let out = render_border_at(ColorLevel::Basic);
        // Top row, each bar, bottom row wrapped in 93/39 (brightYellow).
        assert_eq!(
            out,
            "\x1b[93m┌────────┐\x1b[39m\n\x1b[93m│\x1b[39m        \x1b[93m│\x1b[39m\n\x1b[93m└────────┘\x1b[39m"
        );
    }

    #[test]
    fn hex_border_level_ansi256_downgrades_to_256() {
        let out = render_border_at(ColorLevel::Ansi256);
        assert_eq!(
            out,
            "\x1b[38;5;214m┌────────┐\x1b[39m\n\x1b[38;5;214m│\x1b[39m        \x1b[38;5;214m│\x1b[39m\n\x1b[38;5;214m└────────┘\x1b[39m"
        );
    }

    #[test]
    fn hex_border_level_truecolor_verbatim() {
        let out = render_border_at(ColorLevel::Truecolor);
        assert_eq!(
            out,
            "\x1b[38;2;255;136;0m┌────────┐\x1b[39m\n\x1b[38;2;255;136;0m│\x1b[39m        \x1b[38;2;255;136;0m│\x1b[39m\n\x1b[38;2;255;136;0m└────────┘\x1b[39m"
        );
    }

    // Per-edge fg color resolution cascade: border_top_color wins over
    // border_color for the top; other edges fall back to border_color.
    #[test]
    fn per_edge_color_resolution_cascade() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_color: Some("red".to_owned()),       // base
            border_top_color: Some("green".to_owned()), // top override
            ..Style::default()
        };
        let out = render_styled(3, 10, &s, 10, 3);
        // Top row green (32/39); each vertical bar and the bottom row red (31/39).
        assert_eq!(
            out,
            "\x1b[32m┌────────┐\x1b[39m\n\x1b[31m│\x1b[39m        \x1b[31m│\x1b[39m\n\x1b[31m└────────┘\x1b[39m"
        );
    }

    // Per-edge bg color resolution cascade: border_top_background_color wins over
    // border_background_color for the top; other edges fall back to the general
    // border_background_color. Mirrors the fg cascade (render-border.ts:44-52).
    // No fg set → colorize-fg is passthrough → only the bg SGR wraps each piece.
    // chalk level-3 named bg: blue → bgBlue = 44/49; red → bgRed = 41/49.
    #[test]
    fn per_edge_background_resolution_cascade() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_background_color: Some("red".to_owned()), // base
            border_top_background_color: Some("blue".to_owned()), // top override
            ..Style::default()
        };
        let out = render_styled(3, 10, &s, 10, 3);
        // Top row blue bg (44/49); each vertical bar and the bottom row red bg (41/49).
        assert_eq!(
            out,
            "\x1b[44m┌────────┐\x1b[49m\n\x1b[41m│\x1b[49m        \x1b[41m│\x1b[49m\n\x1b[41m└────────┘\x1b[49m"
        );
    }

    // Each vertical bar carries its OWN SGR pair — wrapping the strip once would
    // leave the interior bar unstyled after the per-line tokenizer split.
    #[test]
    fn each_vertical_bar_wrapped_independently() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_left_color: Some("green".to_owned()),
            ..Style::default()
        };
        // height 4 → 2 interior rows on the left edge.
        let out = render_styled(4, 10, &s, 10, 4);
        assert_eq!(
            out,
            "┌────────┐\n\x1b[32m│\x1b[39m        │\n\x1b[32m│\x1b[39m        │\n└────────┘"
        );
    }

    // Dim + color composition order: colorize fg (innermost) then dim (outermost).
    // Bytes: \x1b[2m (dim open) \x1b[32m (green open) … \x1b[39m (green close)
    // \x1b[22m (dim close) — color closes 39, dim closes 22, never crossed.
    #[test]
    fn dim_and_color_composition_order_bytes() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_top_color: Some("green".to_owned()),
            border_top_dim_color: Some(true),
            ..Style::default()
        };
        let out = render_styled(3, 10, &s, 10, 3);
        let top = out.lines().next().unwrap();
        assert_eq!(top, "\x1b[2m\x1b[32m┌────────┐\x1b[39m\x1b[22m");
    }

    // Per-edge dim falls back to general borderDimColor (the ?? cascade), read
    // from Style. General borderDimColor → every edge dims.
    #[test]
    fn dim_cascade_general_applies_to_all_edges() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_dim_color: Some(true),
            ..Style::default()
        };
        let out = render_styled(3, 10, &s, 10, 3);
        assert_eq!(
            out,
            "\x1b[2m┌────────┐\x1b[22m\n\x1b[2m│\x1b[22m        \x1b[2m│\x1b[22m\n\x1b[2m└────────┘\x1b[22m"
        );
    }

    // Style dim cascade: per-edge border{Edge}DimColor wins over the general
    // borderDimColor; general applies to every edge that has no per-edge value;
    // a None/false edge with no general falls through to no-dim. Mirrors the
    // `border{Edge}DimColor ?? borderDimColor` resolution (render-border.ts:54-64),
    // now sourced from Style (the style props flow JS→core via Box's `...style`).
    #[test]
    fn dim_cascade_resolution_style_based() {
        // Per-edge true on TOP only, no general → only the top row dims; the
        // bottom row and the vertical bars stay plain (no SGR).
        let per_edge = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_top_dim_color: Some(true),
            ..Style::default()
        };
        let out = render_styled(3, 10, &per_edge, 10, 3);
        assert_eq!(out, "\x1b[2m┌────────┐\x1b[22m\n│        │\n└────────┘");

        // Per-edge wins over general: TOP explicitly false suppresses dim on the
        // top even though the general borderDimColor is true; all other edges
        // dim from the general fallback.
        let per_edge_wins = Style {
            border_style: Some(BorderStyle::Named("single".to_owned())),
            border_dim_color: Some(true),
            border_top_dim_color: Some(false),
            ..Style::default()
        };
        let out = render_styled(3, 10, &per_edge_wins, 10, 3);
        assert_eq!(
            out,
            "┌────────┐\n\x1b[2m│\x1b[22m        \x1b[2m│\x1b[22m\n\x1b[2m└────────┘\x1b[22m"
        );
    }
}