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
//! Node data structures mirroring ink's DOM types (dom.ts:8-93).

/// The four element kinds from ink's `ElementNames` (dom.ts:18-23).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// `ink-root`
    Root,
    /// `ink-box`
    Box,
    /// `ink-text`
    Text,
    /// `ink-virtual-text`
    VirtualText,
}

// ─── Style types ─────────────────────────────────────────────────────────────

/// A length/percentage/auto dimension (mirrors Yoga's percent vs. point APIs).
///
/// Used for width, height, min/max, flex-basis, and inset properties.
/// Percentage is stored as 0–100 (ink JS convention); the taffy mapping
/// divides by 100 to obtain 0.0–1.0.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum Dim {
    /// A fixed size in terminal cells.
    Points(f32),
    /// A percentage (0–100) of the parent's corresponding dimension.
    Percent(f32),
    /// Automatic sizing (yoga/taffy default).
    #[default]
    Auto,
}

/// A length or percentage (no auto) used for margin/padding/border/gap.
///
/// Mirrors yoga's numeric-only API for these properties.
#[derive(Debug, Clone, PartialEq)]
pub enum Lp {
    /// A fixed size in terminal cells.
    Points(f32),
    /// A percentage (0–100) of the relevant parent dimension.
    Percent(f32),
}

/// `flexDirection` (styles.ts:504–525).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexDir {
    #[default]
    Row,
    Column,
    RowReverse,
    ColumnReverse,
}

/// `flexWrap` (styles.ts:527–540).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexWrap {
    #[default]
    NoWrap,
    Wrap,
    WrapReverse,
}

/// `alignItems` / `alignSelf` (styles.ts:552–593).
///
/// Used for both `align_items` (`Option<AlignItems>` in taffy) and
/// `align_self` (`Option<AlignSelf>` in taffy).  Taffy has no explicit
/// `Auto` variant for `AlignSelf`; `None` in the `Option` encodes auto.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Align {
    Stretch,
    FlexStart,
    Center,
    FlexEnd,
    Baseline,
}

/// `alignContent` / `justifyContent` (styles.ts:595–661).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentAlign {
    FlexStart,
    Center,
    FlexEnd,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
    Stretch,
}

/// `display` (styles.ts:721–727).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Display {
    #[default]
    Flex,
    None,
}

/// `borderStyle` — mirrors `keyof Boxes | BoxStyle` from cli-boxes (styles.ts:255 —
/// type declaration; the `typeof borderStyle === 'string' ? cliBoxes[...] : borderStyle`
/// ternary lives in render-border.ts:32-34).
///
/// Presence (`Some`) means border is active (layout width = 1 per edge); `None`
/// means no border (width = 0).  The renderer uses the variant to select the
/// correct box-drawing characters.
///
/// * `Named` — one of cli-boxes's named styles ("single", "double", "round", …).
/// * `Custom` — caller-supplied box-drawing characters matching `BoxStyle` from
///   cli-boxes.  Eight fields: four corners + four edges.
#[derive(Debug, Clone, PartialEq)]
pub enum BorderStyle {
    /// A named style from cli-boxes (e.g. `"single"`, `"double"`, `"round"`).
    Named(String),
    /// A fully custom `BoxStyle` object supplied directly by the caller
    /// (styles.ts:255 — type declaration; ternary in render-border.ts:32-34).
    Custom {
        top_left: String,
        top: String,
        top_right: String,
        right: String,
        bottom_right: String,
        bottom: String,
        bottom_left: String,
        left: String,
    },
}

/// `position` (styles.ts:415–442).
///
/// Yoga has three values: `absolute`, `relative`, and `static`.
/// Taffy only has `Relative` and `Absolute` — `static` maps to `Relative`
/// (divergence documented in `style_to_taffy`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Position {
    #[default]
    Relative,
    Absolute,
    /// Yoga-only; taffy backend maps to `Relative`. The difference is visible
    /// only when inset (top/right/bottom/left) is set on a static node: yoga
    /// ignores inset for static (styles.ts:21), but this mapping honors it.
    /// Accepted: ink's API documents static as ignoring offsets (styles.ts:21)
    /// and Box never defaults to static.
    Static,
}

/// `textWrap` (styles.ts:10-16) — controls text wrapping within an ink-text
/// node.  Lives on `Style` (not a node attribute) because `dom.ts:242` reads
/// it as `node.style?.textWrap`; `wrap-text.ts:3` types it `Styles['textWrap']`.
///
/// Default (when `None`) is `Wrap`, matching ink's `node.style?.textWrap ?? 'wrap'`
/// (dom.ts:242).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextWrap {
    /// `'wrap'` — soft word-wrap with hard=true, trim=false (wrap-text.ts:21-25).
    #[default]
    Wrap,
    /// `'hard'` — character-level hard wrap, word_wrap=false (wrap-text.ts:27-32).
    Hard,
    /// `'truncate'` or `'truncate-end'` — truncate at end (wrap-text.ts:33-47).
    TruncateEnd,
    /// `'truncate-middle'` — truncate in the middle.
    TruncateMiddle,
    /// `'truncate-start'` — truncate at the start.
    TruncateStart,
}

/// `overflow` per-axis (styles.ts; Box.tsx resolves the `overflow` shorthand
/// to `overflowX`/`overflowY` before reaching the DOM — styles.ts:731–734).
///
/// Only `overflowX` and `overflowY` are stored here; the `overflow` shorthand
/// is resolved JS-side in Box.tsx (Box.tsx:90-92) and never reaches Rust.
///
/// styles.ts defines overflow as `'visible' | 'hidden'` only (styles.ts:384/391/398).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Overflow {
    #[default]
    Visible,
    Hidden,
}

/// The layout style for a DOM node.
///
/// Mirrors ink's `Styles` type (styles.ts) with every prop that ink's
/// `apply*` functions write to yoga (styles.ts:415–777).  Layout-inert
/// props (text color, background, border colors) are carried as raw strings
/// for the renderer (M1-5) without influencing the taffy layout pass.
///
/// ### Shorthand resolution
/// * `overflow` shorthand: resolved JS-side in Box.tsx before `setStyle` —
///   only `overflow_x`/`overflow_y` per-axis values reach Rust.
/// * `margin`/`marginX`/`marginY`, `padding`/`paddingX`/`paddingY`, `gap`
///   shorthands: NOT resolved JS-side (yoga handles via `EDGE_ALL` /
///   `GUTTER_ALL`).  Rust carries these shorthands; the taffy mapping
///   collapses them with an `Option::or` cascade.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Style {
    // ── Position (styles.ts:415–442) ──────────────────────────────────────
    pub position: Option<Position>,
    pub top: Option<Dim>,
    pub right: Option<Dim>,
    pub bottom: Option<Dim>,
    pub left: Option<Dim>,

    // ── Margin (styles.ts:444–472) ────────────────────────────────────────
    /// Shorthand — applies to all four edges (yoga `EDGE_ALL`).
    pub margin: Option<Lp>,
    /// Horizontal shorthand — left + right (yoga `EDGE_HORIZONTAL`).
    pub margin_x: Option<Lp>,
    /// Vertical shorthand — top + bottom (yoga `EDGE_VERTICAL`).
    pub margin_y: Option<Lp>,
    pub margin_top: Option<Lp>,
    pub margin_right: Option<Lp>,
    pub margin_bottom: Option<Lp>,
    pub margin_left: Option<Lp>,

    // ── Padding (styles.ts:474–502) ───────────────────────────────────────
    /// Shorthand — applies to all four edges.
    pub padding: Option<Lp>,
    /// Horizontal shorthand — left + right.
    pub padding_x: Option<Lp>,
    /// Vertical shorthand — top + bottom.
    pub padding_y: Option<Lp>,
    pub padding_top: Option<Lp>,
    pub padding_right: Option<Lp>,
    pub padding_bottom: Option<Lp>,
    pub padding_left: Option<Lp>,

    // ── Flex (styles.ts:504–661) ──────────────────────────────────────────
    pub flex_direction: Option<FlexDir>,
    pub flex_wrap: Option<FlexWrap>,
    pub flex_grow: Option<f32>,
    pub flex_shrink: Option<f32>,
    /// `flexBasis` — yoga accepts number (points), percent string, or auto.
    pub flex_basis: Option<Dim>,
    pub align_items: Option<Align>,
    /// `None` encodes `auto` (taffy has no explicit `AlignSelf::Auto` variant).
    pub align_self: Option<Align>,
    pub align_content: Option<ContentAlign>,
    pub justify_content: Option<ContentAlign>,

    // ── Dimensions (styles.ts:663–719) ────────────────────────────────────
    pub width: Option<Dim>,
    pub height: Option<Dim>,
    pub min_width: Option<Dim>,
    pub min_height: Option<Dim>,
    pub max_width: Option<Dim>,
    pub max_height: Option<Dim>,
    pub aspect_ratio: Option<f32>,

    // ── Display (styles.ts:721–727) ───────────────────────────────────────
    pub display: Option<Display>,

    // ── Border (styles.ts:729–763) ────────────────────────────────────────
    /// `borderStyle` value (styles.ts:255, 745).  `Some(_)` → border active,
    /// layout width = 1 per enabled edge.  `None` → no border (width = 0).
    /// Renderer uses the variant to select box-drawing characters (M1-5).
    pub border_style: Option<BorderStyle>,
    /// `borderTop === false` disables the top border edge (styles.ts:748-749).
    pub border_top: Option<bool>,
    pub border_right: Option<bool>,
    pub border_bottom: Option<bool>,
    pub border_left: Option<bool>,

    // ── Gap (styles.ts:765–777) ───────────────────────────────────────────
    /// All-axes shorthand (yoga `GUTTER_ALL`).
    pub gap: Option<f32>,
    pub column_gap: Option<f32>,
    pub row_gap: Option<f32>,

    // ── Text wrap (styles.ts:10-16; dom.ts:242 reads `node.style?.textWrap`) ──
    /// `textWrap` mode for `ink-text` nodes.  `None` → default `Wrap`
    /// (matches ink's `?? 'wrap'` fallback at dom.ts:242).
    pub text_wrap: Option<TextWrap>,

    // ── Overflow per-axis (Box.tsx:90-92 resolves the shorthand JS-side) ──
    pub overflow_x: Option<Overflow>,
    pub overflow_y: Option<Overflow>,

    // ── Layout-inert visual props (carried for M1-5 renderer) ─────────────
    pub background_color: Option<String>,
    pub border_color: Option<String>,
    pub border_top_color: Option<String>,
    pub border_right_color: Option<String>,
    pub border_bottom_color: Option<String>,
    pub border_left_color: Option<String>,
    pub border_background_color: Option<String>,
    pub border_top_background_color: Option<String>,
    pub border_right_background_color: Option<String>,
    pub border_bottom_background_color: Option<String>,
    pub border_left_background_color: Option<String>,

    // ── Per-edge border dim flags (BOOLEAN) — ink reads these from
    // `node.style.border{Edge}DimColor`; render-border.ts:54-64 resolves
    // border{Edge}DimColor ?? borderDimColor and threads `dim` through stylePiece.
    pub border_dim_color: Option<bool>,
    pub border_top_dim_color: Option<bool>,
    pub border_right_dim_color: Option<bool>,
    pub border_bottom_dim_color: Option<bool>,
    pub border_left_dim_color: Option<bool>,
}

impl Style {
    /// Per-edge border widths `[top, right, bottom, left]` in cells.
    ///
    /// Single source for BOTH the taffy layout reservation and the
    /// render clip inset — these two must never disagree.
    ///
    /// Returns 1 for each edge that is active (border_style is `Some` and
    /// the edge flag is not explicitly `false`), 0 otherwise.
    pub(crate) fn border_edges(&self) -> [u16; 4] {
        let on = self.border_style.is_some();
        let edge = |f: Option<bool>| if on && f != Some(false) { 1u16 } else { 0u16 };
        [
            edge(self.border_top),
            edge(self.border_right),
            edge(self.border_bottom),
            edge(self.border_left),
        ]
    }
}

/// Inline text styling for an `ink-text` subtree (P5.1 SET_TEXT_STYLE).  Mirrors
/// ink's `<Text>` styling props (color, backgroundColor, bold, italic, underline,
/// strikethrough, inverse, dimColor).
///
/// The render walk reads this via `resolve_transform` (render/walk.rs) to compose
/// SGR natively instead of dispatching a per-line JS transform.  Stored alongside
/// `has_transform`; a node carries exactly one of the two.  A styled→plain
/// rerender clears it via `ClearTextStyle` (P6.2 CLEAR_TEXT_STYLE).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct TextStyle {
    pub color: Option<String>,
    pub background_color: Option<String>,
    pub bold: bool,
    pub italic: bool,
    pub underline: bool,
    pub strikethrough: bool,
    pub inverse: bool,
    pub dim_color: bool,
}

// ─── Node ────────────────────────────────────────────────────────────────────

/// Attribute value enum mirroring `DOMNodeAttribute` (dom.ts:93).
///
/// JS `DOMNodeAttribute = boolean | string | number`; the number variant
/// uses `f64` to match JS numeric semantics.
#[derive(Debug, Clone, PartialEq)]
pub enum AttrValue {
    Bool(bool),
    Str(String),
    Number(f64),
}

/// A single node in the arena.
///
/// Mirrors the union of `DOMElement` + `TextNode` from dom.ts (dom.ts:27-81).
/// Fields common to both are always present; `text` is meaningful only on
/// `Text` and `VirtualText` kinds (where ink stores it in a child `#text`
/// node — folded here per task spec).
#[derive(Debug, Clone)]
pub struct Node {
    pub kind: Kind,
    pub parent: Option<u32>,
    pub children: Vec<u32>,
    /// Text content.  Mirrors `TextNode.nodeValue` (dom.ts:79-81).
    /// For `Text`/`VirtualText` nodes.  No-op field on `Root`/`Box`.
    pub text: Option<String>,
    /// Layout and visual style for this node.
    pub style: Style,
    /// String/bool/number attributes — mirrors `DOMElement.attributes`
    /// (dom.ts:29).  Does NOT include `internal_transform` or
    /// `internal_static`; those are separate flags per the reconciler
    /// (reconciler.ts:231-245).
    pub attributes: Vec<(String, AttrValue)>,
    /// `internal_static` flag (reconciler.ts:237-244).
    pub is_static: bool,
    /// Set by `Hide`/`Unhide` ops.  The actual yoga display effect is JS-side.
    pub is_hidden: bool,
    /// `internal_transform` presence flag (reconciler.ts:231-235).
    /// The transform function itself stays JS-side per the FFI design.
    pub has_transform: bool,
    /// Inline text styling (P5.1 SET_TEXT_STYLE).  Read by the render walk via
    /// `resolve_transform` to compose SGR natively.  `None` until a `SetTextStyle`
    /// op writes it; reset to `None` by `ClearTextStyle` on a styled→plain
    /// rerender (P6.2).
    pub text_styling: Option<TextStyle>,
}

impl Node {
    pub fn new(kind: Kind) -> Self {
        Self {
            kind,
            parent: None,
            children: Vec::new(),
            text: None,
            style: Style::default(),
            attributes: Vec::new(),
            is_static: false,
            is_hidden: false,
            has_transform: false,
            text_styling: None,
        }
    }
}