htui 0.1.0

A terminal HTML/CSS renderer with an embedded JavaScript engine — build interactive TUIs from HTML, CSS and JS
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
//! Inline-text collection shared by the block flow and the flex algorithm.
//!
//! [`collect_runs`] walks a node's direct children and produces a flat list of
//! [`InlineRun`]s — the painted representation of inline text within a block.
//! Both the block layout ([`super::inner_formatting_context::flow`]) and the
//! flex layout ([`super::inner_formatting_context::flex`]) call into this
//! routine, so it lives in `layoutbox` rather than inside either formatting
//! context's implementation.

use crossterm::style::Color;

use super::InlineRun;
use super::generation::visible_children;
use crate::{
    graphics::{FontStyle, block_style},
    html::css_parse::{TextTransform, WhiteSpace},
    tdom::node::{Node, NodeArena, NodeId, NodeType},
};

/// Collect inline runs from a block's inline tree, preserving `<span>` style
/// boundaries.
///
/// Walks `node`'s direct children in document order. Each `Text` leaf becomes
/// one run that inherits the currently-active style. `<span>`, `<a>` and
/// `<em>` boundaries push a new style onto the stack: the element's own
/// `font-weight` / `font-style` / `text-decoration` flags are OR-ed into the
/// inherited `FontStyle`, and its own `color` / `background-color` override
/// the inherited `fg` / `bg` when present. `<a>` additionally applies
/// browser-style user-agent defaults (blue foreground, underline) whenever
/// the matching property has not been declared on the link itself or on any
/// ancestor; `<em>` applies an italic default for the same reason — both
/// match CSS cascade precedence for UA defaults. Block-level children are
/// skipped — they are dispatched as their own `LayoutBox` by the layout
/// registry, so folding them into the parent's runs would either
/// double-render them or wrap them in an unintended inline context.
pub fn collect_runs(
    arena: &NodeArena,
    node_id: NodeId,
    node: &Node,
    fg: Option<Color>,
    bg: Option<Color>,
    style: FontStyle,
) -> Vec<InlineRun> {
    let transform = node.css_attr.get_text_transform();
    let white_space = node.css_attr.get_white_space(&node.node_type);
    let mut runs = Vec::new();
    walk_runs(
        arena,
        node_id,
        node,
        fg,
        bg,
        style,
        transform,
        white_space,
        None,
        &mut runs,
    );
    runs
}

/// Collect a single raw text node's inline run (whitespace-collapsed and
/// text-transformed), or `None` for empty / whitespace-only text.
///
/// Used by the flex container to promote its direct text children into
/// anonymous flex items, mirroring the `NodeType::Text` branch of
/// [`walk_runs`] without walking an element's children.
pub(crate) fn text_node_run(
    arena: &NodeArena,
    text_node_id: NodeId,
    fg: Option<Color>,
    bg: Option<Color>,
    style: FontStyle,
    transform: TextTransform,
    white_space: WhiteSpace,
) -> Option<InlineRun> {
    let child = &arena[text_node_id];
    if child.node_type != NodeType::Text {
        return None;
    }
    if child.text_is_painted(white_space)
        && let Some(s) = child.data.as_deref()
        && !s.is_empty()
    {
        let text = apply_text_transform(s, transform);
        return Some(InlineRun::owned(text, style, fg, bg, None));
    }
    None
}

fn walk_runs(
    arena: &NodeArena,
    node_id: NodeId,
    node: &Node,
    fg: Option<Color>,
    bg: Option<Color>,
    style: FontStyle,
    transform: TextTransform,
    white_space: WhiteSpace,
    owner: Option<NodeId>,
    runs: &mut Vec<InlineRun>,
) {
    // A closed `<details>` shows only its first `<summary>` child, so its own
    // inline content (text / spans directly inside the element) stays hidden
    // too — the same filter the box generation and block layout apply.
    for child_id in visible_children(arena, node_id) {
        let child = &arena[child_id];
        // In a flex container every element child is a flex item (inline
        // elements are blockified), so only raw text folds into the
        // container's own inline runs. Block children are already skipped by
        // the `match` fallthrough below; this additionally keeps inline
        // children (`<span>` / `<em>` / …) out of the container's text so
        // they are not rendered twice (once above the flex items and again
        // as items).
        if node.css_attr.display().is_some_and(|d| d.is_flex())
            && !matches!(child.node_type, NodeType::Text)
        {
            continue;
        }
        match &child.node_type {
            NodeType::Text => {
                // Keep every non-empty text node (including whitespace-only
                // runs): the wrap phase collapses / preserves whitespace
                // according to `white-space`, so a whitespace-only node between
                // two words correctly collapses to a single space instead of
                // vanishing.
                if let Some(s) = child.data.as_deref()
                    && !s.is_empty()
                {
                    let text = apply_text_transform(s, transform);
                    runs.push(InlineRun::owned(text, style, fg, bg, owner));
                }
            }
            NodeType::Span => {
                // Span inherits parent's fg/bg unless explicit overrides exist.
                let span_fg = child.css_attr.get_color().or(fg);
                let span_bg = child.css_attr.get_bg_color().or(bg);
                let span_style = style | block_style(&child.css_attr);
                let span_transform = child.css_attr.get_text_transform();
                let span_ws = child.white_space_or(white_space);
                walk_runs(
                    arena,
                    child_id,
                    child,
                    span_fg,
                    span_bg,
                    span_style,
                    span_transform,
                    span_ws,
                    owner,
                    runs,
                );
            }
            NodeType::A => {
                // A block-level anchor is painted by its own `LayoutBox`
                // and must not have its text folded into the parent's
                // inline runs. A direct anchor child of a flex
                // container is likewise a flex item. Either way, the
                // anchor does not belong here.
                if child.css_attr.display().is_some_and(|d| d.is_block_level())
                    || node.css_attr.display().is_some_and(|d| d.is_flex())
                {
                    continue;
                }

                // User-agent defaults: unstyled links are blue and
                // underlined, matching browser behaviour. Both defaults
                // yield to anything the author (or an ancestor CSS rule)
                // has already declared for the matching property, so
                // `a { text-decoration: none }` or `a { color: green }`
                // take effect normally.
                let a_fg = if child.css_attr.is_set("color") {
                    child.css_attr.get_color().or(fg)
                } else {
                    // Standard blue (#0000FF) — must match the block-<a>
                    // UA default, which inserts the CSS name `blue` into
                    // `css_attr` and resolves it through `parse_color_str`.
                    Some(Color::Rgb {
                        r: 0x00,
                        g: 0x00,
                        b: 0xFF,
                    })
                };
                let a_bg = child.css_attr.get_bg_color().or(bg);
                let mut a_style = style | block_style(&child.css_attr);
                if !child.css_attr.is_set("text-decoration") {
                    a_style |= FontStyle::UNDERLINED;
                }
                let a_transform = child.css_attr.get_text_transform();
                let a_ws = child.white_space_or(white_space);
                walk_runs(
                    arena,
                    child_id,
                    child,
                    a_fg,
                    a_bg,
                    a_style,
                    a_transform,
                    a_ws,
                    Some(child_id),
                    runs,
                );
            }
            NodeType::Em => {
                // User-agent default: `<em>` renders italic. Anything the
                // author (or an ancestor rule) declared for `font-style`
                // takes precedence — `em { font-style: normal }` or
                // `em { font-style: oblique }` are honoured.
                let em_fg = child.css_attr.get_color().or(fg);
                let em_bg = child.css_attr.get_bg_color().or(bg);
                let mut em_style = style | block_style(&child.css_attr);
                if !child.css_attr.is_set("font-style") {
                    em_style |= FontStyle::ITALIC;
                }
                let em_transform = child.css_attr.get_text_transform();
                let em_ws = child.white_space_or(white_space);
                walk_runs(
                    arena,
                    child_id,
                    child,
                    em_fg,
                    em_bg,
                    em_style,
                    em_transform,
                    em_ws,
                    owner,
                    runs,
                );
            }
            NodeType::Strong | NodeType::B => {
                // User-agent default: bold. Anything the author (or an
                // ancestor rule) declared for `font-weight` takes precedence.
                let mut st = style | block_style(&child.css_attr);
                if !child.css_attr.is_set("font-weight") {
                    st |= FontStyle::BOLD;
                }
                walk_inline_children(arena, child_id, child, fg, bg, st, white_space, owner, runs);
            }
            NodeType::I | NodeType::Cite | NodeType::Dfn | NodeType::Var => {
                // User-agent default: italic (same precedence rule as `<em>`).
                let mut st = style | block_style(&child.css_attr);
                if !child.css_attr.is_set("font-style") {
                    st |= FontStyle::ITALIC;
                }
                walk_inline_children(arena, child_id, child, fg, bg, st, white_space, owner, runs);
            }
            NodeType::Label => {
                // `<label>` is a plain inline container (like `<span>`), but
                // its runs carry the label's node id so the hit map can give
                // the label text its own region — the click-delegation target
                // for `<label for>` / wrapped controls.
                let label_fg = child.css_attr.get_color().or(fg);
                let label_bg = child.css_attr.get_bg_color().or(bg);
                walk_inline_children(
                    arena,
                    child_id,
                    child,
                    label_fg,
                    label_bg,
                    style | block_style(&child.css_attr),
                    white_space,
                    Some(child_id),
                    runs,
                );
            }
            NodeType::U | NodeType::Ins => {
                // User-agent default: underline. An explicit
                // `text-decoration` (author or inherited) wins.
                let mut st = style | block_style(&child.css_attr);
                if !child.css_attr.is_set("text-decoration") {
                    st |= FontStyle::UNDERLINED;
                }
                walk_inline_children(arena, child_id, child, fg, bg, st, white_space, owner, runs);
            }
            NodeType::S | NodeType::Del => {
                // User-agent default: line-through. An explicit
                // `text-decoration` (author or inherited) wins.
                let mut st = style | block_style(&child.css_attr);
                if !child.css_attr.is_set("text-decoration") {
                    st |= FontStyle::CROSSED_OUT;
                }
                walk_inline_children(arena, child_id, child, fg, bg, st, white_space, owner, runs);
            }
            NodeType::Mark => {
                // User-agent default: yellow background + black foreground
                // (the highlight). Explicit declarations win.
                let child_fg = child.css_attr.get_color().or(fg);
                let child_bg = child.css_attr.get_bg_color().or(bg);
                let mark_fg = if child.css_attr.is_set("color") {
                    child_fg
                } else {
                    Some(Color::Black)
                };
                let mark_bg = if child.css_attr.is_set("background-color") {
                    child_bg
                } else {
                    Some(Color::Yellow)
                };
                let st = style | block_style(&child.css_attr);
                walk_inline_children(
                    arena,
                    child_id,
                    child,
                    mark_fg,
                    mark_bg,
                    st,
                    white_space,
                    owner,
                    runs,
                );
            }
            NodeType::Q => {
                // User-agent default: `<q>` wraps its content in generated
                // quote marks (`q::before { content: open-quote }` /
                // `::after { content: close-quote }`). The pair alternates
                // with nesting depth like the CSS `quotes` property: even
                // depth uses double quotes, odd depth single quotes.
                let q_fg = child.css_attr.get_color().or(fg);
                let q_bg = child.css_attr.get_bg_color().or(bg);
                let q_style = style | block_style(&child.css_attr);
                let (open, close) = q_quote_pair(arena, child_id);
                runs.push(InlineRun::owned(
                    open.to_string(),
                    q_style,
                    q_fg,
                    q_bg,
                    owner,
                ));
                let q_transform = child.css_attr.get_text_transform();
                let q_ws = child.white_space_or(white_space);
                walk_runs(
                    arena,
                    child_id,
                    child,
                    q_fg,
                    q_bg,
                    q_style,
                    q_transform,
                    q_ws,
                    owner,
                    runs,
                );
                runs.push(InlineRun::owned(
                    close.to_string(),
                    q_style,
                    q_fg,
                    q_bg,
                    owner,
                ));
            }
            NodeType::Abbr => {
                // User-agent default: `abbr[title]` carries a dotted underline
                // as a tooltip affordance. The terminal has no dotted
                // underline primitive, so the approximation is a solid
                // underline; an explicit `text-decoration` (author or
                // inherited) wins.
                let fg = child.css_attr.get_color().or(fg);
                let bg = child.css_attr.get_bg_color().or(bg);
                let mut st = style | block_style(&child.css_attr);
                if child.attributes.get("title").is_some()
                    && !child.css_attr.is_set("text-decoration")
                {
                    st |= FontStyle::UNDERLINED;
                }
                walk_inline_children(arena, child_id, child, fg, bg, st, white_space, owner, runs);
            }
            NodeType::Code | NodeType::Kbd | NodeType::Samp => {
                // User-agent default `font-family: monospace` is already the
                // terminal's native font, so no style bit applies — the
                // element is kept for CSS / DOM addressing.
                let fg = child.css_attr.get_color().or(fg);
                let bg = child.css_attr.get_bg_color().or(bg);
                walk_inline_children(
                    arena,
                    child_id,
                    child,
                    fg,
                    bg,
                    style | block_style(&child.css_attr),
                    white_space,
                    owner,
                    runs,
                );
            }
            NodeType::Data | NodeType::Time | NodeType::Output => {
                // No UA visual default: plain inline containers like `<span>`.
                // The `value` / `datetime` attributes are machine-readable
                // only and carry no visual effect, matching browsers.
                let fg = child.css_attr.get_color().or(fg);
                let bg = child.css_attr.get_bg_color().or(bg);
                walk_inline_children(
                    arena,
                    child_id,
                    child,
                    fg,
                    bg,
                    style | block_style(&child.css_attr),
                    white_space,
                    owner,
                    runs,
                );
            }
            NodeType::Br => {
                // `<br>` forces a line break in every `white-space` mode.
                runs.push(InlineRun::forced_break(style, fg, bg));
            }
            // Block-level nested elements live in their own LayoutBox;
            // unknown inline tags are flattened by the HTML parser so they
            // never reach here as an unknown NodeType.
            _ => {}
        }
    }
}

/// Recurse into an inline element's children, carrying the resolved `fg` /
/// `bg` / `style` (already merged with the element's own CSS), the element's
/// own `text-transform` / `white-space` overrides, and the owning inline
/// element (`owner`) for hit-map attribution.
fn walk_inline_children(
    arena: &NodeArena,
    child_id: NodeId,
    child: &Node,
    fg: Option<Color>,
    bg: Option<Color>,
    style: FontStyle,
    parent_ws: WhiteSpace,
    owner: Option<NodeId>,
    runs: &mut Vec<InlineRun>,
) {
    let transform = child.css_attr.get_text_transform();
    let ws = child.white_space_or(parent_ws);
    walk_runs(
        arena, child_id, child, fg, bg, style, transform, ws, owner, runs,
    );
}

/// Quote pair for a `<q>` element based on its nesting depth, mirroring the
/// CSS `quotes` alternation: even depth uses double quotes (`“`/`”`), odd
/// depth single quotes (`‘`/`’`).
pub(crate) fn q_quote_pair(arena: &NodeArena, node_id: NodeId) -> (&'static str, &'static str) {
    let mut depth = 0usize;
    let mut current = arena[node_id].parent;
    while let Some(pid) = current {
        if arena[pid].node_type == NodeType::Q {
            depth = depth.saturating_add(1);
        }
        current = arena[pid].parent;
    }
    if depth.is_multiple_of(2) {
        ("\u{201C}", "\u{201D}")
    } else {
        ("\u{2018}", "\u{2019}")
    }
}

/// Apply a [`TextTransform`] to a text node's content.
///
/// `capitalize` uppercases the first character of each whitespace / punct
/// delimited word; `to_uppercase` / `to_lowercase` delegate to the Unicode
/// case mappings (a single char may expand, e.g. `ß` → `SS`).
fn apply_text_transform(text: &str, transform: TextTransform) -> String {
    match transform {
        TextTransform::None => text.to_string(),
        TextTransform::Uppercase => text.to_uppercase(),
        TextTransform::Lowercase => text.to_lowercase(),
        TextTransform::Capitalize => {
            let mut out = String::with_capacity(text.len());
            let mut new_word = true;
            for ch in text.chars() {
                if ch.is_alphanumeric() {
                    if new_word {
                        out.extend(ch.to_uppercase());
                    } else {
                        out.push(ch);
                    }
                    new_word = false;
                } else {
                    out.push(ch);
                    new_word = true;
                }
            }
            out
        }
    }
}