htui 0.2.0

A terminal HTML/CSS renderer with an embedded JavaScript engine — build interactive TUIs from HTML, CSS and JS
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
use crossterm::style::Color;
use htui::html::{css_parse, html_parse};
use htui::layout::layout::TermMap;
use htui::tdom::node::{NodeArena, NodeId};
use htui::tui::graph_api::TermLayout;

fn init() {
    let _ = env_logger::builder().is_test(true).try_init();
}

fn setup(html: &str, css: &str) -> (NodeId, NodeArena) {
    let mut html_parser = html_parse::Parser::new(html);
    let (root_id, mut arena, embedded) = html_parser.parse();
    let combined = if css.is_empty() {
        embedded
    } else if embedded.is_empty() {
        css.to_string()
    } else {
        format!("{embedded}\n{css}")
    };
    if !combined.trim().is_empty() {
        let mut css_parser = css_parse::Parser::new(&combined);
        let rules = css_parser.parse();
        css_parse::css_into_node(&mut arena, root_id, &rules);
    }
    (root_id, arena)
}

const COLS: u16 = 80;
const ROWS: u16 = 24;

fn mock_term_map() -> TermMap {
    TermMap {
        columns: COLS,
        rows: ROWS,
    }
}

#[test]
fn test_div_basic() {
    init();
    let (root_id, arena) = setup("<div>hello</div>", "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("hello"), "div should render text");
}

#[test]
fn test_div_with_color() {
    init();
    let html = "<div>colored</div>";
    let css = "div { color: blue; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let has_fg = tl
        .layout
        .iter()
        .any(|b| b.fcolor == Some(Color::Rgb { r: 0, g: 0, b: 255 }));
    assert!(has_fg, "div color should be applied to text cells");
}

#[test]
fn test_div_background_color() {
    init();
    let html = "<div>bg</div>";
    let css = "div { background-color: yellow; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let has_bg = tl.layout.iter().any(|b| {
        b.bcolor
            == Some(Color::Rgb {
                r: 255,
                g: 255,
                b: 0,
            })
    });
    assert!(has_bg, "div background-color should be applied");
}

#[test]
fn test_div_text_and_block_child_stack_on_separate_rows() {
    init();
    // A block's own inline text and its block-level children stack: the text
    // line comes first and children begin below it.
    let html = "<div>parent text<p>child block</p></div>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let cols = term_map.columns as usize;
    let rows: Vec<String> = tl
        .layout
        .chunks(cols)
        .map(|chunk| chunk.iter().map(|b| b.word.as_str()).collect())
        .collect();
    let parent_row = rows
        .iter()
        .position(|r| r.contains("parent text"))
        .expect("parent text should render");
    let child_row = rows
        .iter()
        .position(|r| r.contains("child block"))
        .expect("child block should render");
    assert!(
        parent_row < child_row,
        "parent text must sit above the block child, got {parent_row}/{child_row}"
    );
}

#[test]
fn test_div_bg_fills_full_row_default() {
    init();
    let html = "<div>short</div>";
    let css = "div { background-color: red; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let content_idx = tl
        .layout
        .iter()
        .position(|b| b.word != " " && b.bcolor == Some(Color::Rgb { r: 255, g: 0, b: 0 }))
        .expect("should find colored content");
    let row = content_idx / cols;
    let rstart = row * cols;
    let rend = rstart + cols;
    let bg_count = tl.layout[rstart..rend]
        .iter()
        .filter(|b| b.bcolor == Some(Color::Rgb { r: 255, g: 0, b: 0 }))
        .count();
    assert_eq!(bg_count, cols, "default width should fill entire row");
}

#[test]
fn test_div_width_50pct_left() {
    // Browser-like geometry: a block with explicit `width` sits flush left
    // inside its containing block (CSS `margin-left: 0` default). The
    // 50%-wide div occupies cols 0..cols/2; the right half is bg-free.
    init();
    let html = "<div>half</div>";
    let css = "div { width: 50%; background-color: blue; color: white; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let content_idx = tl
        .layout
        .iter()
        .position(|b| b.bcolor.is_some() && b.word != " ")
        .expect("should find colored content");
    let content_row = content_idx / cols;
    let row = &tl.layout[content_row * cols..(content_row + 1) * cols];

    let block_start = 0;
    let block_end = cols / 2;
    let mut has_text = false;
    for (i, cell) in row.iter().enumerate().take(block_end).skip(block_start) {
        assert!(
            cell.bcolor.is_some(),
            "block should have bg col={i} (flush left)"
        );
        if cell.word != " " {
            assert_eq!(
                cell.fcolor,
                Some(Color::Rgb {
                    r: 255,
                    g: 255,
                    b: 255
                }),
                "text should be white"
            );
            has_text = true;
        }
    }
    assert!(has_text, "block should contain text");
    for cell in row.iter().take(cols).skip(block_end) {
        assert!(
            cell.bcolor.is_none(),
            "cols cols/2..cols should be bg-free (outside the block)"
        );
    }
}

#[test]
fn test_div_width_fixed() {
    // Browser-like geometry: a fixed-width block sits flush left. The 20-col
    // block occupies cols 0..20.
    init();
    let html = "<div>Fix</div>";
    let css = "div { width: 20ch; background-color: red; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let content_idx = tl
        .layout
        .iter()
        .position(|b| b.bcolor.is_some() && b.word != " ")
        .expect("should find content");
    let row = content_idx / cols;
    let rstart = row * cols;
    let rend = rstart + cols;
    let bg_count = (rstart..rend)
        .filter(|&i| tl.layout[i].bcolor.is_some())
        .count();
    assert_eq!(
        bg_count, 20,
        "background should be exactly 20 columns (cols 0..20, flush left)"
    );
    // Block bg starts at col 0 (flush left), not centered.
    let first_bg_col = (rstart..rend)
        .find(|&i| tl.layout[i].bcolor.is_some())
        .map(|i| i - rstart)
        .expect("block should have at least one bg cell");
    assert_eq!(
        first_bg_col, 0,
        "fixed-width block must sit flush left at col 0"
    );
}

#[test]
fn test_div_text_align_center() {
    // Browser-like geometry: the BLOCK is flush left (cols 0..40); the TEXT
    // inside is centered within the block.
    init();
    let html = "<div>Centered</div>";
    let css = "div { text-align: center; width: 40ch; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // Find the first text cell; text "Centered" (8 chars) sits at col
    // (40 - 8) / 2 = 16 within the flush-left block.
    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word == *"C")
        .expect("should find text");
    let col = text_idx % cols;
    let expected_padding = (40 - "Centered".len()) / 2;
    assert_eq!(
        col, expected_padding,
        "text should be centered within the (flush-left) 40-col block"
    );
}

#[test]
fn test_div_text_align_right() {
    // Browser-like geometry: the BLOCK is flush left (cols 0..40); the TEXT
    // inside is right-aligned within the block.
    init();
    let html = "<div>Right</div>";
    let css = "div { text-align: right; width: 40ch; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // Find the first text cell; text "Right" (5 chars) sits at col
    // 40 - 5 = 35 within the flush-left block.
    let text_idx = tl
        .layout
        .iter()
        .position(|b| b.word == *"R")
        .expect("should find text");
    let col = text_idx % cols;
    let expected_padding = 40 - "Right".len();
    assert_eq!(
        col, expected_padding,
        "text should be right-aligned within the (flush-left) 40-col block"
    );
}

#[test]
fn test_div_nested_preserves_text() {
    init();
    let html = "<div><p>A</p><div><p>B</p></div></div>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let canvas: String = tl.layout.iter().map(|b| b.word.as_str()).collect();
    assert!(canvas.contains("A"), "outer div should contain A");
    assert!(canvas.contains("B"), "inner div should contain B");
}

#[test]
fn test_div_no_bg_does_not_fill_row() {
    // Without background-color, div must not paint trailing spaces into the row,
    // otherwise nested scenarios lose outer block's bg.
    init();
    let html = "<div>hi</div>";
    let (root_id, arena) = setup(html, "");
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    let text_idx = tl.layout.iter().position(|b| b.word != " ").unwrap();
    let row = text_idx / cols;
    let rstart = row * cols;
    let rend = rstart + cols;
    let has_bg = tl.layout[rstart..rend].iter().any(|b| b.bcolor.is_some());
    assert!(
        !has_bg,
        "row should not have any bg cells when div has no background-color"
    );
}

#[test]
fn test_div_color_inherited_by_p() {
    // CSS `color` cascades from div to `<p>` descendants. `<p>` reads its own
    // css_attr (populated by `inherit_css`) when rendering, so a div-level
    // color should reach the paragraph without an explicit rule on `<p>`.
    init();
    let html = "<div><p>colored</p></div>";
    let css = "div { color: magenta; }";
    let (root_id, arena) = setup(html, css);
    let term_map = mock_term_map();
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);
    let has_color = tl.layout.iter().any(|b| {
        b.fcolor
            == Some(Color::Rgb {
                r: 255,
                g: 0,
                b: 255,
            })
    });
    assert!(has_color, "div color should inherit to <p> descendant");
}

#[test]
fn test_long_p_text_does_not_overflow_into_next_row() {
    // Each text row clips at its content-box right edge, so a one-row `<p>`
    // must not write past column 79 or overwrite following boxes.
    init();
    let long_text = "A longer paragraph that contains multiple sentences. This demonstrates how text wrapping and layout work in the terminal renderer. The text should flow naturally within the available terminal width.";
    let html = format!("<p>{}</p><h2>Next</h2>", long_text);
    let (root_id, arena) = setup(&html, "");
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // The <p> occupies row 0 (1 row tall). Cells row 1+ belong to the <h2>.
    let p_row = 0;
    let p_row_end = (p_row + 1) * cols;
    for cell in &tl.layout[p_row_end..] {
        // None of the <p>'s colour or characters should appear past row 0.
        // Paint stops at column 79; later cells remain empty unless the next
        // paint pass overwrites them with the <h2>.
        let has_p_text = !cell.word.is_empty()
            && cell.word != " "
            && cell.fcolor
                == Some(Color::Rgb {
                    r: 128,
                    g: 128,
                    b: 128,
                });
        assert!(
            !has_p_text,
            "p text should not bleed past row 0 — found {:?} at cell index {}",
            cell.word, p_row_end
        );
    }
}

#[test]
fn test_long_p_text_stops_at_content_box_right_edge() {
    // Companion to the overflow guard above: the last char of a long
    // single-row <p> sits at col `cols - 1`, not at col `cols` (which would
    // be on the next row).
    init();
    let long_text = "x".repeat(200);
    let html = format!("<p>{}</p>", long_text);
    let (root_id, arena) = setup(&html, "");
    let term_map = mock_term_map();
    let cols = term_map.columns as usize;
    let mut tl = TermLayout::new(&term_map, 1.0);
    tl.draw(&arena, root_id, &term_map);

    // The <p> is 1 row tall. Row 1 should be untouched by the p (no 'x'
    // cells in grey).
    let row1_start = cols;
    let row1_end = 2 * cols;
    let p_chars_on_row1 = tl.layout[row1_start..row1_end]
        .iter()
        .filter(|c| {
            c.fcolor
                == Some(Color::Rgb {
                    r: 128,
                    g: 128,
                    b: 128,
                })
                && c.word == "x"
        })
        .count();
    assert_eq!(
        p_chars_on_row1, 0,
        "no 'x' characters should spill from the p onto row 1"
    );
}