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
//! Tree walk — plain-frame render pass.
//!
//! Port of ink's `render-node-to-output.ts` — **plain-frame slice only**:
//! no transformers, no background rendering, no static-node output.
//!
//! # Design decisions
//!
//! ## Absolute positions
//! render-node-to-output.ts:129-130:
//! ```ts
//! const x = offsetX + yogaNode.getComputedLeft();
//! const y = offsetY + yogaNode.getComputedTop();
//! ```
//! Computed rects are parent-relative; the walk accumulates absolute offsets.
//!
//! ## display:none skip (render-node-to-output.ts:123-125)
//! ```ts
//! if (yogaNode.getDisplay() === Yoga.DISPLAY_NONE) { return; }
//! ```
//! In Rust: if `layout.width == 0 && layout.height == 0` for a node whose
//! `style.display == Some(Display::None)` the node is skipped. Taffy sets both
//! width and height to zero for display:none nodes (same as yoga), so we use
//! `node.style.display == Some(Display::None)` as the skip gate, matching ink
//! exactly and avoiding an accidental skip for intentionally zero-sized boxes.
//!
//! ## Static nodes skipped (render-node-to-output.ts:117-119)
//! ```ts
//! if (skipStaticElements && node.internal_static) { return; }
//! ```
//! `skipStaticElements=true` is the normal-frame path ([`walk`]): the static
//! subtree (ink's `<Static>`) is omitted from the live region. The SECOND pass
//! ([`walk_static`]) renders that same static subtree with `skipStaticElements
//! =false`, so the static entry node itself is NOT skipped — its descendants are
//! not static, so they render normally. This mirrors renderer.ts:42-57, where the
//! main `Output` is filled with `skipStaticElements:true` and a separate
//! `staticOutput` `Output` is filled from `node.staticNode` with
//! `skipStaticElements:false`. The `skip_static` flag is threaded through
//! `walk_node` exactly as ink threads `skipStaticElements` through its recursion.
//!
//! ## Text wrap at render time (render-node-to-output.ts:141-156)
//! ```ts
//! const currentWidth = widestLine(text);
//! const maxWidth = getMaxWidth(yogaNode);
//! if (currentWidth > maxWidth) {
//!   const textWrap = node.style.textWrap ?? 'wrap';
//!   text = wrapText(text, maxWidth, textWrap);
//! }
//! ```
//! Ink wraps at **render time** (not just at measure time) because the
//! layout may have assigned a narrower width than the text's intrinsic width.
//! We mirror this exactly: squash, check intrinsic width against computed
//! width, wrap if needed, then write.
//!
//! ## Overflow:hidden clip (render-node-to-output.ts:162-195)
//! X and Y clipping are independent. Each axis checks `overflowX === 'hidden'`
//! or `overflow === 'hidden'` (the shorthand was already resolved JS-side;
//! in Rust the `overflow` shorthand is stored on `overflow_x`/`overflow_y`).
//! The clip rect accounts for border cells (output.ts uses yogaNode.getComputedBorder).
//! In Rust: border widths come from `Style::border_edges()` — the shared helper
//! used by both the taffy layout reservation and this clip inset, so they can
//! never disagree.

use crate::dom::{Arena, Display, Kind, Overflow, TextStyle};
use crate::layout::Rect;
use crate::render::background::render_background;
use crate::render::border::render_border;
use crate::render::colorize::{ColorLevel, Kind as ColorKind, colorize, dim};
use crate::render::grid::{Clip, Grid, Transformer};
use crate::text::string_width::string_width;
use crate::text_measure::{squash_styled, wrap_text_with_mode};

/// Per-node transformer accessor — the seam that maps a dom id to the node's
/// **own** output transform (ink's `internal_transform`,
/// render-node-to-output.ts:136).
///
/// Returns `None` when the node has no own transform (the chain is left
/// untouched, exactly as ink's `typeof node.internal_transform === 'function'`
/// guard, render-node-to-output.ts:136-138). When `Some`, the returned closure
/// is an **owned** `Box<dyn Fn(&str, usize) -> String + 'a>`: the boxed transform
/// is minted *per id* and lives in the `walk_node` stack frame, where its
/// `.as_ref()` is pushed onto the local transformer chain as a borrowed
/// [`Transformer<'a>`].
///
/// # Why owned, non-`'static`
/// The plain path passes a no-op accessor (`&|_| None`) so the chain stays empty
/// at every node — `render_to_string` therefore produces byte-identical output.
/// The styled path's real consumer is `inkferro-napi` (M3-E), whose accessor
/// must **mint** a closure that captures the node `id` and dispatches to a JS
/// `internal_transform` via a borrowed `FunctionRef`:
/// ```ignore
/// |id| has_transform(id).then(|| {
///     Box::new(move |s, i| dispatch(&fref, id, s, i)) as Box<dyn Fn(&str, usize) -> String + '_>
/// })
/// ```
/// A *borrowed* return (`Option<Transformer<'a>>`) could not hold that
/// per-id closure (no place to own it), and a `'static` bound would forbid
/// borrowing the `FunctionRef`. The lifetime `'a` ties the boxed transform to
/// the accessor's captured state, nesting naturally with the recursion.
/// `<Text color>` SGR is *not* a separate branch: in ink it lives **inside**
/// `internal_transform` (Text.tsx:94-130 calls `colorize`), so it flows through
/// this same accessor — a core caller wires `colorize`, napi dispatches to JS.
/// An owned per-output-line text transform: the boxed closure a
/// [`TransformAccessor`] yields for one node (`(line, index) -> styled line`).
pub type LineTransform<'a> = Box<dyn Fn(&str, usize) -> String + 'a>;

pub type TransformAccessor<'a> = dyn Fn(u32) -> Option<LineTransform<'a>> + 'a;

/// Build the NATIVE `<Text>`-style output transform for `style` at `level` —
/// the in-Rust replacement for the JS `chalk`/`colorize` `internal_transform`
/// (P5.1(b)). The composition order is EXACTLY Text.tsx:105-143:
/// `dimColor → color(fg) → backgroundColor → bold → italic → underline →
/// strikethrough → inverse`, with each step routed through the oracle-frozen
/// [`colorize`]/[`dim`] (modifiers resolve via `colorize`'s named-style branch,
/// they are in `STYLE_NAMES`). The chalk-parity corpus
/// (`colorize_chalk_parity_tests.rs`) pins this exact composition BYTE-IDENTICAL
/// to chalk@5 for every styling combination EXCEPT `dimColor && bold` (the shared
/// close-code `22` re-open chalk does and the native chain does not) — so the
/// CALLER must guard `!(dim_color && bold)` before using this and fall back to the
/// JS `internal_transform` for that one case. `style.background_color` already
/// carries the JS-resolved `effectiveBackgroundColor` (own `backgroundColor` ??
/// the inherited `<Box>` background, baked in Text.tsx via `backgroundContext`),
/// so the inherited-bg golden cases compose through this self-contained transform
/// just as the JS closure did.
///
/// The returned closure is `'static` (it OWNS clones of the color strings + the
/// bool flags), so it satisfies any `'a` the [`TransformAccessor`] return demands.
/// `index` is ignored: every `<Text>`-style transform is line-position-invariant.
fn native_text_style_transform(style: &TextStyle, level: ColorLevel) -> LineTransform<'static> {
    // Own the data the per-line closure needs (no borrow of the arena node).
    let color = style.color.clone();
    let bg_color = style.background_color.clone();
    let dim_color = style.dim_color;
    let bold = style.bold;
    let italic = style.italic;
    let underline = style.underline;
    let strikethrough = style.strikethrough;
    let inverse = style.inverse;

    Box::new(move |s: &str, _index: usize| -> String {
        // Text.tsx:107-109 — dimColor first (innermost).
        let mut out = if dim_color {
            dim(s, level)
        } else {
            s.to_owned()
        };
        // Text.tsx:111-113 — foreground color.
        if let Some(ref c) = color {
            out = colorize(&out, Some(c), ColorKind::Fg, level);
        }
        // Text.tsx:118-120 — (effective) background color.
        if let Some(ref bg) = bg_color {
            out = colorize(&out, Some(bg), ColorKind::Bg, level);
        }
        // Text.tsx:122-140 — modifiers in fixed order (each via the named-style
        // branch of `colorize`, reproducing chalk's `(open, close)` pair).
        if bold {
            out = colorize(&out, Some("bold"), ColorKind::Fg, level);
        }
        if italic {
            out = colorize(&out, Some("italic"), ColorKind::Fg, level);
        }
        if underline {
            out = colorize(&out, Some("underline"), ColorKind::Fg, level);
        }
        if strikethrough {
            out = colorize(&out, Some("strikethrough"), ColorKind::Fg, level);
        }
        if inverse {
            out = colorize(&out, Some("inverse"), ColorKind::Fg, level);
        }
        out
    })
}

/// `true` when `style` is the ONE combination the native chain does NOT reproduce
/// byte-for-byte (`dimColor && bold` share close code `22`; chalk re-opens `bold`
/// after the inner `dim` close, the native chain does not — pinned by
/// `colorize_chalk_parity_tests::dim_bold_composition_DIVERGES_from_chalk`). When
/// this holds, the resolver MUST defer to the JS `internal_transform` (the JS side
/// keeps emitting `setTransform` for exactly this case).
fn text_style_diverges_from_chalk(style: &TextStyle) -> bool {
    style.dim_color && style.bold
}

/// Wrap the JS-dispatch `transform_of` accessor into a NATIVE-AWARE resolver: for
/// a node carrying `text_styling = Some(style)` whose styling is provably simple
/// (NOT `dim && bold`), it returns the native [`native_text_style_transform`]
/// INSTEAD of dispatching the JS `internal_transform`; otherwise it falls through
/// to `transform_of(id)` unchanged (plain nodes, `<Transform>` wrappers, the
/// `dim && bold` case the JS side still owns).
///
/// Threading this resolver in place of `transform_of` makes BOTH the walk's
/// own-transform site (`output.write`) AND `squash_styled`'s nested-child fold
/// resolve native styling through the SAME seam — so nested styled `<Text>` and
/// inherited dim/bg compose exactly as they did when the transform was JS-side,
/// with no change to `walk_node`/`squash_styled` bodies.
fn resolve_transform<'a>(
    arena: &'a Arena,
    id: u32,
    transform_of: &'a TransformAccessor<'a>,
    level: ColorLevel,
) -> Option<LineTransform<'a>> {
    if let Some(node) = arena.get(id)
        && let Some(style) = node.text_styling.as_ref()
        && !text_style_diverges_from_chalk(style)
    {
        // Native path: the guarded flip. The `'static` box coerces to `'a`.
        return Some(native_text_style_transform(style, level));
    }
    // JS path: unchanged (plain, <Transform>, or dim&&bold).
    transform_of(id)
}

/// Walk the arena tree rooted at `root_id`, writing each node into `grid`.
///
/// `rects` maps dom id → computed `Rect` (absolute from root, accumulated
/// during the walk: `x = parent_offset_x + rect.x`).
///
/// `transform_of` is the per-node own-transform seam (see [`TransformAccessor`]).
/// Pass `&|_| None` for the plain path (no SGR/transform), which keeps the
/// transformer chain empty at every node and yields byte-identical output to
/// the pre-seam walk.
///
/// Mirrors `renderNodeToOutput` (render-node-to-output.ts:100-212). The root is
/// seeded with an empty transformer chain (render-node-to-output.ts:113
/// `transformers = []`).
pub fn walk<'a>(
    arena: &'a Arena,
    root_id: u32,
    rects: &dyn Fn(u32) -> Option<Rect>,
    transform_of: &'a TransformAccessor<'a>,
    grid: &mut Grid,
    level: ColorLevel,
) {
    // skip_static = true: the live-region path (render-node-to-output.ts:117 with
    // `skipStaticElements: true`). Static subtrees are omitted here. `level` is the
    // detected color level, threaded to render_background/render_border (the
    // core-colorize call sites); see [`ColorLevel`].
    //
    // The accessor threaded into `walk_node`/`squash_styled` is the NATIVE-AWARE
    // resolver (P5.1(b)): a node with simple `text_styling` resolves to a native
    // SGR transform, every other node falls through to `transform_of` (JS) — see
    // [`resolve_transform`]. The plain path's `&|_| None` accessor still resolves
    // to `None` for every node (no `text_styling`, no JS transform), so colorless
    // output stays byte-identical.
    let resolver = |id: u32| resolve_transform(arena, id, transform_of, level);
    walk_node(
        arena,
        root_id,
        0,
        0,
        &[],
        true,
        rects,
        &resolver,
        grid,
        level,
    );
}

/// Walk the **static** subtree rooted at `static_id`, writing each node into
/// `grid` with `skipStaticElements=false`.
///
/// This is ink's SECOND render pass (renderer.ts:48-57): `node.staticNode` is
/// the `<Static>` element (itself `internal_static`), rendered into its OWN-sized
/// `Output` at offset 0. Passing `skip_static=false` bypasses the top-level
/// `is_static` skip at the static entry node, so the static subtree renders;
/// the entry's own computed left/top become the first write position, exactly as
/// `renderNodeToOutput(node.staticNode, output, {offsetX:0, offsetY:0, …})`.
pub fn walk_static<'a>(
    arena: &'a Arena,
    static_id: u32,
    rects: &dyn Fn(u32) -> Option<Rect>,
    transform_of: &'a TransformAccessor<'a>,
    grid: &mut Grid,
    level: ColorLevel,
) {
    // Same native-aware resolver as the live walk (see [`walk`]): a `<Static>`
    // subtree's styled `<Text>` resolves to the native transform too.
    let resolver = |id: u32| resolve_transform(arena, id, transform_of, level);
    walk_node(
        arena,
        static_id,
        0,
        0,
        &[],
        false,
        rects,
        &resolver,
        grid,
        level,
    );
}

// renderNodeToOutput's recursion threads exactly these inputs: the tree
// (`arena`/`id`), the accumulated absolute offset (`offset_x`/`offset_y`,
// render-node-to-output.ts:129-130), the inherited transformer chain
// (`transformers`, :134), and the two read accessors (`rects`, `transform_of`)
// plus the `grid` sink. Bundling them into a context struct would obscure the
// 1:1 mapping to the ink source without removing any real parameter.
#[allow(clippy::too_many_arguments)]
fn walk_node(
    arena: &Arena,
    id: u32,
    offset_x: i32,
    offset_y: i32,
    transformers: &[Transformer<'_>],
    skip_static: bool,
    rects: &dyn Fn(u32) -> Option<Rect>,
    transform_of: &TransformAccessor<'_>,
    grid: &mut Grid,
    level: ColorLevel,
) {
    let Some(node) = arena.get(id) else { return };

    // render-node-to-output.ts:117-119: `if (skipStaticElements && node.internal_static) return;`
    // The live-region walk ([`walk`]) passes `skip_static=true`, so static
    // subtrees are omitted. The static walk ([`walk_static`]) passes
    // `skip_static=false`, so the static entry node is rendered and the same flag
    // propagates to its children — none of which are static in practice.
    if skip_static && node.is_static {
        return;
    }

    let Some(rect) = rects(id) else { return };

    // render-node-to-output.ts:123-125: skip display:none nodes.
    // ink uses yogaNode.getDisplay() === Yoga.DISPLAY_NONE; we mirror with
    // the dom style field (taffy also produces width=0/height=0 for none,
    // but the style check is the canonical gate matching ink's intent).
    if node.style.display == Some(Display::None) {
        return;
    }

    // render-node-to-output.ts:129-130: absolute position = parent offset + computed.
    let x = offset_x + rect.x;
    let y = offset_y + rect.y;

    // render-node-to-output.ts:132-138: build this node's transformer chain.
    // ```ts
    // let newTransformers = transformers;
    // if (typeof node.internal_transform === 'function') {
    //   newTransformers = [node.internal_transform, ...transformers];
    // }
    // ```
    // The node's OWN transform is PREPENDED (innermost-first): `write_styled`
    // applies the chain front-to-back, so the own transform runs before any
    // inherited one — `colorize` then an ancestor `<Transform>`, oracle-pinned.
    // `own` (the boxed transform) must outlive the recursive calls below, so it
    // lives in THIS frame and we hand its borrow down via `chain`.
    let own = transform_of(id);
    let chain: Vec<Transformer<'_>> = match own.as_deref() {
        Some(own_ref) => {
            let mut v = Vec::with_capacity(transformers.len() + 1);
            v.push(own_ref as Transformer<'_>);
            v.extend_from_slice(transformers);
            v
        }
        None => transformers.to_vec(),
    };
    let new_transformers: &[Transformer<'_>] = &chain;

    match node.kind {
        Kind::Text => {
            // render-node-to-output.ts:140-157: text node rendering.
            // `squash_styled` folds the subtree AND applies each NESTED text
            // child's own transform during the fold (squash-text-nodes.ts:34-39);
            // this node's OWN transform is applied below via `write_styled`
            // (`new_transformers` carries it), never here — see `squash_styled`'s
            // no-double-application note. The plain path's `&|_| None` accessor
            // makes this fold pure concatenation, identical to `squash_text`.
            let text = squash_styled(arena, id, transform_of);
            if text.is_empty() {
                return;
            }

            // render-node-to-output.ts:143-144: widestLine vs maxWidth.
            // maxWidth = computed width of the text node (already constrained
            // by layout). wrap only if text is wider than the layout width.
            //
            // Divergence: ink's condition (rnt:147) is the bare
            // `currentWidth > maxWidth`; the extra `max_width > 0` guard means
            // a zero-computed-width text node is written unwrapped where ink
            // would wrap to width 0 (NaN-adjacent JS output). Reachable only
            // when layout assigns a text node zero width; kept as a deliberate
            // panic-guard for wrap_text_with_mode(_, 0, _).
            let max_width = rect.width as usize;
            let current_width = text.split('\n').map(string_width).max().unwrap_or(0);

            let final_text = if current_width > max_width && max_width > 0 {
                // render-node-to-output.ts:147-149: wrap at render time.
                let wrap_mode = node.style.text_wrap.unwrap_or_default();
                wrap_text_with_mode(&text, max_width, wrap_mode)
            } else {
                text
            };

            // render-node-to-output.ts:154: output.write(x, y, text,
            // {transformers: newTransformers}). `new_transformers` is
            // `[own, ...inherited]` — the node's own transform (`colorize` for a
            // core `<Text color>` caller, or a JS `internal_transform` dispatch
            // for napi) prepended innermost-first onto the inherited chain.
            grid.write_styled(x, y, &final_text, new_transformers);
        }

        Kind::Box | Kind::Root => {
            // render-node-to-output.ts:163-164: paint background fill THEN draw
            // border (Box only — NOT Root). ink calls renderBackground before
            // renderBorder; the fill covers the content area inside borders and
            // the border draws the edges. Background-before-border is the
            // defensive order under last-writer-wins (border corrects any inset).
            if node.kind == Kind::Box {
                render_background(x, y, rect.width, rect.height, &node.style, grid, level);
                render_border(x, y, rect.width, rect.height, &node.style, grid, level);
            }

            // render-node-to-output.ts:166-195: overflow:hidden clip.
            // Per-axis independently (overflowX / overflowY).
            let clip_h = node.style.overflow_x == Some(Overflow::Hidden);
            let clip_v = node.style.overflow_y == Some(Overflow::Hidden);
            let clipped = clip_h || clip_v;

            if clipped {
                // render-node-to-output.ts:173-192: clip rect accounts for border.
                // Border width per edge from the shared helper (Style::border_edges),
                // which is also used by taffy_engine.rs — single source of truth.
                let [bord_top, bord_right, bord_bottom, bord_left] =
                    node.style.border_edges().map(|v| v as i32);

                let clip = Clip {
                    x1: if clip_h { Some(x + bord_left) } else { None },
                    x2: if clip_h {
                        Some(x + rect.width as i32 - bord_right)
                    } else {
                        None
                    },
                    y1: if clip_v { Some(y + bord_top) } else { None },
                    y2: if clip_v {
                        Some(y + rect.height as i32 - bord_bottom)
                    } else {
                        None
                    },
                };
                grid.push_clip(clip);
            }

            // render-node-to-output.ts:197-210: recurse into children, passing
            // THIS node's chain down (render-node-to-output.ts:202
            // `transformers: newTransformers`) — so a Box/Root `internal_transform`
            // (e.g. a `<Transform>` wrapper) is inherited by every descendant.
            for &child_id in &node.children.clone() {
                walk_node(
                    arena,
                    child_id,
                    x,
                    y,
                    new_transformers,
                    skip_static,
                    rects,
                    transform_of,
                    grid,
                    level,
                );
            }

            if clipped {
                grid.pop_clip();
            }
        }

        // VirtualText nodes: folded into their Text parent via squash_text.
        // They never appear as standalone children of Root/Box in practice.
        Kind::VirtualText => {}
    }
}