smelt-term 0.1.0

Terminal rendering library: Grid, Compositor, LayoutTree, diff-flush renderer.
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
//! Frame snapshot: a faithful, round-trippable capture of a rendered
//! terminal frame.
//!
//! Lifecycle:
//! - [`SnapshotFrame::from_grid`] captures a `Grid` snapshot.
//! - [`SnapshotFrame::text`] / [`SnapshotFrame::styles_text`] produce
//!   the diff-friendly text views consumed by `insta` (and humans).
//! - [`SnapshotFrame::parse`] is the lossless inverse of the two views.
//! - [`SnapshotFrame::blit_into`] replays the captured cells into a
//!   live `Grid` (e.g. the storybook viewer).
//!
//! The text views collapse wide-char continuation cells (`\0`) to
//! `' '` and `text()` `trim_end`s for diff cleanliness. The styles
//! sidecar carries a `dim: W H` header so `parse` recovers cell
//! dimensions losslessly — without it, a trailing wide-char
//! continuation that `trim_end` ate would be unrecoverable.

use super::grid::{Cell, Grid, Style};
use smelt_style::style::Color;
use unicode_width::UnicodeWidthChar;

/// Structured copy of one rendered frame. Wide-char continuation cells
/// (`\0`) collapse to a space in `rows`.
#[derive(Clone, Debug)]
pub struct SnapshotFrame {
    pub width: u16,
    pub height: u16,
    pub rows: Vec<String>,
    pub styles: Vec<Vec<Style>>,
}

impl SnapshotFrame {
    pub fn from_grid(grid: &Grid) -> Self {
        let w = grid.width();
        let h = grid.height();
        let mut rows = Vec::with_capacity(h as usize);
        let mut styles = Vec::with_capacity(h as usize);
        for y in 0..h {
            let mut row = String::with_capacity(w as usize);
            let mut row_styles = Vec::with_capacity(w as usize);
            for x in 0..w {
                let cell: &Cell = grid.cell(x, y);
                let ch = if cell.symbol == '\0' {
                    ' '
                } else {
                    cell.symbol
                };
                row.push(ch);
                row_styles.push(cell.style);
            }
            rows.push(row);
            styles.push(row_styles);
        }
        Self {
            width: w,
            height: h,
            rows,
            styles,
        }
    }

    /// Rows joined by `\n` with trailing whitespace stripped per row.
    pub fn text(&self) -> String {
        let mut out = String::with_capacity(self.rows.iter().map(|r| r.len() + 1).sum());
        for (i, row) in self.rows.iter().enumerate() {
            if i > 0 {
                out.push('\n');
            }
            out.push_str(row.trim_end());
        }
        out
    }

    /// Style sidecar. First line is `dim: W H`; remaining lines are
    /// one styled run each as `row col len fg=… bg=… attrs=…`. The
    /// dim header makes [`parse`] losslessly recover cell dimensions
    /// even when [`text`] has trimmed trailing wide-char continuations.
    pub fn styles_text(&self) -> String {
        let mut out = format!("dim: {} {}\n", self.width, self.height);
        for (y, row) in self.styles.iter().enumerate() {
            let mut x = 0usize;
            while x < row.len() {
                let s = row[x];
                if s == Style::default() {
                    x += 1;
                    continue;
                }
                let mut end = x + 1;
                while end < row.len() && row[end] == s {
                    end += 1;
                }
                let len = end - x;
                out.push_str(&format!("{y:>3} {x:>3} {len:>3} {}\n", fmt_style(&s)));
                x = end;
            }
        }
        out
    }

    /// Reconstruct a frame from its text + styles views. Lossless
    /// when `styles_text` carries the `dim:` header. Without the
    /// header, dimensions are inferred from `text` (wide-char aware),
    /// which is correct unless a row ended on a wide glyph whose
    /// continuation slot was trimmed.
    pub fn parse(text: &str, styles_text: &str) -> Self {
        let header = parse_dim_header(styles_text);
        let text_lines: Vec<&str> = text.split('\n').collect();
        let inferred_width = text_lines
            .iter()
            .map(|l| row_visual_width(l))
            .max()
            .unwrap_or(0);
        let inferred_height = text_lines.len() as u16;
        let span_extent = parse_spans(styles_text)
            .iter()
            .map(|(y, c, len, _)| (*y + 1, *c + *len))
            .fold((0u16, 0u16), |(h, w), (rh, rw)| (h.max(rh), w.max(rw)));
        let width = header
            .map(|(w, _)| w)
            .unwrap_or(0)
            .max(inferred_width)
            .max(span_extent.1);
        let height = header
            .map(|(_, h)| h)
            .unwrap_or(0)
            .max(inferred_height)
            .max(span_extent.0);

        let mut rows = Vec::with_capacity(height as usize);
        for y in 0..height as usize {
            let line = text_lines.get(y).copied().unwrap_or("");
            rows.push(parse_row(line, width));
        }

        let mut styles = vec![vec![Style::default(); width as usize]; height as usize];
        for (y, c, len, style) in parse_spans(styles_text) {
            if y >= height {
                continue;
            }
            let start = c as usize;
            let end = ((c + len) as usize).min(width as usize);
            if start >= end {
                continue;
            }
            for cell in &mut styles[y as usize][start..end] {
                *cell = style;
            }
        }

        Self {
            width,
            height,
            rows,
            styles,
        }
    }

    /// Paint this frame's cells into `grid` starting at `(x_off, y_off)`,
    /// clipped to the grid bounds. Wide-char continuation slots in
    /// `rows` (stored as `' '` after a wide glyph) are reconstructed
    /// as `\0` so the destination grid's flush logic advances by the
    /// glyph's visual width and renders the same way the source did.
    pub fn blit_into(&self, grid: &mut Grid, x_off: u16, y_off: u16) {
        for (r, row) in self.rows.iter().enumerate() {
            let y = y_off.saturating_add(r as u16);
            if y >= grid.height() {
                break;
            }
            let chars: Vec<char> = row.chars().collect();
            let mut c: usize = 0;
            while c < chars.len() {
                let x = x_off.saturating_add(c as u16);
                if x >= grid.width() {
                    break;
                }
                let ch = chars[c];
                let cw = UnicodeWidthChar::width(ch).unwrap_or(0).max(1);
                let style = self
                    .styles
                    .get(r)
                    .and_then(|row| row.get(c).copied())
                    .unwrap_or_default();
                if let Some(cell) = grid.cell_mut(x, y) {
                    cell.symbol = ch;
                    cell.style = style;
                }
                if cw == 2 {
                    // The slot at `c + 1` was the wide char's `\0`
                    // continuation in the source grid (stored as `' '`
                    // after `from_grid` collapses). Stamp `\0` into the
                    // dest so `flush_full` advances by the wide width
                    // instead of treating it as a literal space.
                    let cont_x = x_off.saturating_add(c as u16 + 1);
                    if cont_x < grid.width() {
                        let cont_style = self
                            .styles
                            .get(r)
                            .and_then(|row| row.get(c + 1).copied())
                            .unwrap_or(style);
                        if let Some(cell) = grid.cell_mut(cont_x, y) {
                            cell.symbol = '\0';
                            cell.style = cont_style;
                        }
                    }
                    c += 2;
                } else {
                    c += 1;
                }
            }
        }
    }
}

fn fmt_style(s: &Style) -> String {
    let mut parts = Vec::new();
    if let Some(fg) = s.fg {
        parts.push(format!("fg={fg:?}"));
    }
    if let Some(bg) = s.bg {
        parts.push(format!("bg={bg:?}"));
    }
    let mut attrs = Vec::new();
    if s.bold {
        attrs.push("bold");
    }
    if s.dim {
        attrs.push("dim");
    }
    if s.italic {
        attrs.push("italic");
    }
    if s.underline {
        attrs.push("underline");
    }
    if s.crossedout {
        attrs.push("crossedout");
    }
    if !attrs.is_empty() {
        parts.push(format!("attrs={}", attrs.join("|")));
    }
    parts.join(" ")
}

// ── Parsing ───────────────────────────────────────────────────────

fn parse_dim_header(styles_text: &str) -> Option<(u16, u16)> {
    let first = styles_text.lines().next()?;
    let rest = first.strip_prefix("dim:")?.trim();
    let mut parts = rest.split_whitespace();
    let w: u16 = parts.next()?.parse().ok()?;
    let h: u16 = parts.next()?.parse().ok()?;
    Some((w, h))
}

/// Visual width of a serialized row, treating each char as one cell.
/// `from_grid` stores one char per cell (collapsing `\0` to space), so
/// `chars().count()` is the correct cell width — *except* when the
/// last cell was a wide char's continuation (trimmed by `text()`).
/// In that case the last char is a wide glyph with no trailing slot;
/// we add one cell to compensate.
fn row_visual_width(row: &str) -> u16 {
    let chars: Vec<char> = row.chars().collect();
    let mut cells = chars.len() as u16;
    if let Some(&last) = chars.last() {
        if UnicodeWidthChar::width(last).unwrap_or(0) == 2 {
            // The continuation slot is missing — `trim_end` ate the
            // collapsed `\0`-as-space. Add it back.
            cells = cells.saturating_add(1);
        }
    }
    cells
}

/// Reconstruct one cell-aligned row string of length exactly `width`.
/// Walks chars from the (possibly trim-ended) line, inserts a space
/// for the wide char's continuation slot if it was trimmed, and pads
/// with spaces if the line is shorter than `width`.
fn parse_row(line: &str, width: u16) -> String {
    let chars: Vec<char> = line.chars().collect();
    let mut out = String::with_capacity(width as usize);
    let mut cells: u16 = 0;
    let mut i = 0;
    while i < chars.len() && cells < width {
        let ch = chars[i];
        let cw = UnicodeWidthChar::width(ch).unwrap_or(0).max(1) as u16;
        out.push(ch);
        cells += 1;
        if cw == 2 && cells < width {
            if i + 1 < chars.len() && chars[i + 1] == ' ' {
                out.push(' ');
                i += 2;
                cells += 1;
                continue;
            }
            out.push(' ');
            cells += 1;
        }
        i += 1;
    }
    while cells < width {
        out.push(' ');
        cells += 1;
    }
    out
}

fn parse_spans(styles_text: &str) -> Vec<(u16, u16, u16, Style)> {
    let mut out = Vec::new();
    for line in styles_text.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with("dim:") {
            continue;
        }
        // Numeric fields are right-aligned with padding, so use
        // `split_whitespace` (collapses runs) for the three numbers,
        // then recover the tail from the original string by scanning
        // past the third token.
        let mut nums = trimmed.split_whitespace();
        let Some(row) = nums.next().and_then(|s| s.parse::<u16>().ok()) else {
            continue;
        };
        let Some(col) = nums.next().and_then(|s| s.parse::<u16>().ok()) else {
            continue;
        };
        let Some(len_tok) = nums.next() else { continue };
        let Ok(len) = len_tok.parse::<u16>() else {
            continue;
        };
        // `len_tok` is a slice of `trimmed` — derive the tail offset
        // from pointer arithmetic via `str::find` on the same source.
        let tail_start = nums
            .next()
            .map(|first| first.as_ptr() as usize - trimmed.as_ptr() as usize)
            .unwrap_or(trimmed.len());
        let tail = trimmed.get(tail_start..).unwrap_or("").trim();
        let mut style = Style::default();
        apply_kv_string(&mut style, tail);
        out.push((row, col, len, style));
    }
    out
}

fn apply_kv_string(style: &mut Style, s: &str) {
    // Format from `fmt_style`: `fg=… bg=… attrs=…`, each optional.
    // Values are `Debug`-formatted, so `Rgb { r: 60, g: 20, b: 20 }`
    // contains spaces — split on known key prefixes, not whitespace.
    const KEYS: &[&str] = &["fg=", "bg=", "attrs="];
    let mut cursor = 0;
    while cursor < s.len() {
        let rest = &s[cursor..];
        let Some(off) = KEYS.iter().filter_map(|k| rest.find(k)).min() else {
            break;
        };
        let key_start = cursor + off;
        let Some(eq_rel) = s[key_start..].find('=') else {
            break;
        };
        let eq = key_start + eq_rel;
        let key = &s[key_start..eq];
        let value_start = eq + 1;
        let value_end = KEYS
            .iter()
            .filter_map(|k| {
                s[value_start..]
                    .find(&format!(" {k}"))
                    .map(|p| value_start + p)
            })
            .min()
            .unwrap_or(s.len());
        let value = s[value_start..value_end].trim();
        match key {
            "fg" => style.fg = parse_color(value),
            "bg" => style.bg = parse_color(value),
            "attrs" => apply_attrs(style, value),
            _ => {}
        }
        cursor = value_end;
    }
}

fn apply_attrs(style: &mut Style, value: &str) {
    for attr in value.split('|') {
        match attr.trim() {
            "bold" => style.bold = true,
            "dim" => style.dim = true,
            "italic" => style.italic = true,
            "underline" => style.underline = true,
            "crossedout" => style.crossedout = true,
            _ => {}
        }
    }
}

fn parse_color(s: &str) -> Option<Color> {
    if let Some(rest) = s.strip_prefix("Rgb { ") {
        let inner = rest.trim_end_matches(" }");
        let mut r = None;
        let mut g = None;
        let mut b = None;
        for kv in inner.split(',') {
            let kv = kv.trim();
            if let Some(v) = kv.strip_prefix("r:") {
                r = v.trim().parse().ok();
            } else if let Some(v) = kv.strip_prefix("g:") {
                g = v.trim().parse().ok();
            } else if let Some(v) = kv.strip_prefix("b:") {
                b = v.trim().parse().ok();
            }
        }
        return match (r, g, b) {
            (Some(r), Some(g), Some(b)) => Some(Color::Rgb { r, g, b }),
            _ => None,
        };
    }
    if let Some(rest) = s.strip_prefix("AnsiValue(") {
        let n: u8 = rest.trim_end_matches(')').parse().ok()?;
        return Some(Color::AnsiValue(n));
    }
    Some(match s {
        "Reset" => Color::Reset,
        "Black" => Color::Black,
        "DarkGrey" | "DarkGray" => Color::DarkGrey,
        "Red" => Color::Red,
        "DarkRed" => Color::DarkRed,
        "Green" => Color::Green,
        "DarkGreen" => Color::DarkGreen,
        "Yellow" => Color::Yellow,
        "DarkYellow" => Color::DarkYellow,
        "Blue" => Color::Blue,
        "DarkBlue" => Color::DarkBlue,
        "Magenta" => Color::Magenta,
        "DarkMagenta" => Color::DarkMagenta,
        "Cyan" => Color::Cyan,
        "DarkCyan" => Color::DarkCyan,
        "White" => Color::White,
        "Grey" | "Gray" => Color::Grey,
        _ => return None,
    })
}

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

    fn snap_grid(setup: impl FnOnce(&mut Grid)) -> SnapshotFrame {
        let mut g = Grid::new(16, 3);
        setup(&mut g);
        SnapshotFrame::from_grid(&g)
    }

    #[test]
    fn roundtrip_ascii_preserves_text_and_styles() {
        let frame = snap_grid(|g| {
            g.put_str(
                0,
                0,
                "hello",
                Style {
                    bold: true,
                    ..Style::default()
                },
            );
        });
        let parsed = SnapshotFrame::parse(&frame.text(), &frame.styles_text());
        assert_eq!(parsed.width, frame.width);
        assert_eq!(parsed.height, frame.height);
        assert_eq!(parsed.rows, frame.rows);
        assert_eq!(parsed.styles, frame.styles);
    }

    #[test]
    fn roundtrip_with_trailing_wide_char() {
        // Row ends on a wide glyph — `trim_end` ate the continuation
        // slot in `text()`; `dim:` header recovers width.
        let frame = snap_grid(|g| {
            g.put_str(0, 0, "你好", Style::default());
        });
        let parsed = SnapshotFrame::parse(&frame.text(), &frame.styles_text());
        assert_eq!(parsed.width, 16);
        assert_eq!(parsed.rows[0].chars().count(), 16);
        assert_eq!(parsed.rows[0].chars().next(), Some(''));
    }

    #[test]
    fn blit_into_replays_wide_chars_correctly() {
        // Snapshot a wide-char source, parse it back, blit into a
        // larger grid, and confirm the destination cells match: the
        // wide chars at the right offset, with `\0` continuation
        // slots so flush will advance by the visual width.
        let frame = snap_grid(|g| {
            g.put_str(0, 0, "你好", Style::default());
        });
        let parsed = SnapshotFrame::parse(&frame.text(), &frame.styles_text());
        let mut dest = Grid::new(20, 3);
        parsed.blit_into(&mut dest, 2, 1);
        assert_eq!(dest.cell(2, 1).symbol, '');
        assert_eq!(dest.cell(3, 1).symbol, '\0');
        assert_eq!(dest.cell(4, 1).symbol, '');
        assert_eq!(dest.cell(5, 1).symbol, '\0');
    }

    #[test]
    fn styles_text_includes_dim_header_for_empty_styles() {
        let frame = snap_grid(|_| {});
        let styles = frame.styles_text();
        assert_eq!(styles.lines().next(), Some("dim: 16 3"));
    }

    #[test]
    fn parse_recovers_rgb_and_attrs() {
        let frame = snap_grid(|g| {
            g.put_str(
                0,
                0,
                "x",
                Style {
                    fg: Some(Color::Rgb {
                        r: 60,
                        g: 20,
                        b: 20,
                    }),
                    bg: Some(Color::AnsiValue(208)),
                    bold: true,
                    dim: true,
                    ..Style::default()
                },
            );
        });
        let parsed = SnapshotFrame::parse(&frame.text(), &frame.styles_text());
        let s = parsed.styles[0][0];
        assert_eq!(
            s.fg,
            Some(Color::Rgb {
                r: 60,
                g: 20,
                b: 20
            })
        );
        assert_eq!(s.bg, Some(Color::AnsiValue(208)));
        assert!(s.bold);
        assert!(s.dim);
    }
}