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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Node-tree traversal natives: parent / sibling / child accessors, live
//! NodeList, containment / equality checks and `querySelector` search.

use boa_engine::{Context, JsNativeError, JsResult, JsValue, NativeFunction, js_string};

use crate::{
    html::css_parse::{CssSelector, selector_chain_matches},
    tdom::node::{NodeArena, NodeId, document_base_href},
};

use super::{f64_to_node_id, js_fn, node_id_to_f64, node_wrapper, this_node_id, with_state};

pub(super) fn native_get_parent(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let parent = st.arena.get(node_id).and_then(|n| n.parent);
    match parent {
        Some(pid) => node_wrapper(context, pid),
        None => Ok(JsValue::null()),
    }
}

// ============================================================
// Node interface natives (shared by every node kind)
// ============================================================

pub(super) fn native_get_node_type(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let Some(node) = st.arena.get(node_id) else {
        return Ok(JsValue::null());
    };
    Ok(JsValue::from(node.node_type_constant() as u32))
}

pub(super) fn native_get_node_name(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(js_string!().into());
    };
    let st = rc.borrow();
    let Some(node) = st.arena.get(node_id) else {
        return Ok(js_string!().into());
    };
    Ok(js_string!(node.node_name()).into())
}

pub(super) fn native_get_tag_name(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(js_string!().into());
    };
    let st = rc.borrow();
    let name = st
        .arena
        .get(node_id)
        .and_then(|n| n.node_type.tag_name())
        .map(str::to_uppercase)
        .unwrap_or_default();
    Ok(js_string!(name).into())
}

pub(super) fn native_get_parent_element(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let parent = st.arena.get(node_id).and_then(|n| n.parent).filter(|&pid| {
        st.arena
            .get(pid)
            .map(|p| p.node_type_constant() == 1)
            .unwrap_or(false)
    });
    match parent {
        Some(pid) => node_wrapper(context, pid),
        None => Ok(JsValue::null()),
    }
}

pub(super) fn native_get_child_nodes(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    call_live_list(context, node_id)
}

/// Build a live NodeList proxy over `node_id`'s children. True liveness:
/// the returned object's `length` / indexed access / enumeration read the
/// arena on every access, so a held reference reflects later DOM mutations.
fn call_live_list(context: &mut Context, node_id: NodeId) -> JsResult<JsValue> {
    let node_key = node_id_to_f64(node_id);
    let get_len = js_fn(
        context,
        NativeFunction::from_copy_closure_with_captures(nodelist_len, node_key),
    );
    let get_item = js_fn(
        context,
        NativeFunction::from_copy_closure_with_captures(nodelist_item, node_key),
    );
    let global = context.global_object();
    let helper = global
        .get(js_string!("__htuiLiveList"), context)?
        .to_object(context)?;
    helper.call(
        &JsValue::undefined(),
        &[get_len.into(), get_item.into()],
        context,
    )
}

/// Live `NodeList.length` (reads the arena on every call).
fn nodelist_len(
    _this: &JsValue,
    _args: &[JsValue],
    node_key: &f64,
    _context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = f64_to_node_id(*node_key);
    let len = with_state()
        .map(|rc| {
            rc.borrow()
                .arena
                .get(node_id)
                .map(|n| n.children.len())
                .unwrap_or(0)
        })
        .unwrap_or(0);
    Ok(JsValue::from(len as u32))
}

/// Live `NodeList[i]` (reads the arena on every call).
fn nodelist_item(
    _this: &JsValue,
    args: &[JsValue],
    node_key: &f64,
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = f64_to_node_id(*node_key);
    let idx = args
        .first()
        .and_then(|v| v.to_number(context).ok())
        .unwrap_or(-1.0);
    if idx < 0.0 {
        return Ok(JsValue::null());
    }
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let child = st
        .arena
        .get(node_id)
        .and_then(|n| n.children.get(idx as usize))
        .copied();
    match child {
        Some(cid) => node_wrapper(context, cid),
        None => Ok(JsValue::null()),
    }
}

pub(super) fn native_get_first_child(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let child = st
        .arena
        .get(node_id)
        .and_then(|n| n.children.first())
        .copied();
    match child {
        Some(cid) => node_wrapper(context, cid),
        None => Ok(JsValue::null()),
    }
}

pub(super) fn native_get_last_child(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let child = st
        .arena
        .get(node_id)
        .and_then(|n| n.children.last())
        .copied();
    match child {
        Some(cid) => node_wrapper(context, cid),
        None => Ok(JsValue::null()),
    }
}

pub(super) fn native_get_prev_sibling(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let prev = st
        .arena
        .get(node_id)
        .and_then(|n| n.parent)
        .and_then(|pid| {
            let parent = &st.arena[pid];
            let mut prev = None;
            for &cid in &parent.children {
                if cid == node_id {
                    break;
                }
                prev = Some(cid);
            }
            prev
        });
    match prev {
        Some(cid) => node_wrapper(context, cid),
        None => Ok(JsValue::null()),
    }
}

pub(super) fn native_get_next_sibling(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let next = st
        .arena
        .get(node_id)
        .and_then(|n| n.parent)
        .and_then(|pid| {
            let parent = &st.arena[pid];
            let mut found = false;
            let mut next = None;
            for &cid in &parent.children {
                if found {
                    next = Some(cid);
                    break;
                }
                if cid == node_id {
                    found = true;
                }
            }
            next
        });
    match next {
        Some(cid) => node_wrapper(context, cid),
        None => Ok(JsValue::null()),
    }
}

pub(super) fn native_get_owner_document(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    if node_id == st.root_id {
        return Ok(JsValue::null());
    }
    node_wrapper(context, st.root_id)
}

/// `baseURI` — the document base URL established by the first `<base href>`,
/// or an empty string when the document declares no `<base>`. Mirrors the DOM
/// property that reports the base URL relative references (`<img src>`,
/// `<script src>`, `fetch`, …) resolve against.
pub(super) fn native_get_base_uri(
    _this: &JsValue,
    _args: &[JsValue],
    _context: &mut Context,
) -> JsResult<JsValue> {
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let uri = document_base_href(&st.arena, st.root_id).unwrap_or_default();
    Ok(js_string!(uri).into())
}

pub(super) fn native_has_child_nodes(
    this: &JsValue,
    _args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let has = with_state()
        .map(|rc| {
            rc.borrow()
                .arena
                .get(node_id)
                .map(|n| !n.children.is_empty())
                .unwrap_or(false)
        })
        .unwrap_or(false);
    Ok(JsValue::from(has))
}

pub(super) fn native_contains(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(other_id) = this_node_id(args.first().unwrap_or(&JsValue::undefined()), context).ok()
    else {
        return Ok(JsValue::from(false));
    };
    let Some(rc) = with_state() else {
        return Ok(JsValue::from(false));
    };
    let st = rc.borrow();
    // A node contains itself and all of its descendants.
    let mut cur = Some(other_id);
    while let Some(id) = cur {
        if id == node_id {
            return Ok(JsValue::from(true));
        }
        cur = st.arena.get(id).and_then(|n| n.parent);
    }
    Ok(JsValue::from(false))
}

pub(super) fn native_is_same_node(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let other = this_node_id(args.first().unwrap_or(&JsValue::undefined()), context).ok();
    Ok(JsValue::from(other == Some(node_id)))
}

pub(super) fn native_is_equal_node(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let node_id = this_node_id(this, context)?;
    let Some(other_id) = this_node_id(args.first().unwrap_or(&JsValue::undefined()), context).ok()
    else {
        return Ok(JsValue::from(false));
    };
    let Some(rc) = with_state() else {
        return Ok(JsValue::from(false));
    };
    let st = rc.borrow();
    Ok(JsValue::from(nodes_equal(&st.arena, node_id, other_id)))
}

/// Structural equality: same node kind / data / attributes (order-insensitive,
/// matching the DOM's set semantics) and equal children recursively.
fn nodes_equal(arena: &NodeArena, a: NodeId, b: NodeId) -> bool {
    let (na, nb) = match (arena.get(a), arena.get(b)) {
        (Some(x), Some(y)) => (x, y),
        _ => return false,
    };
    if na.node_type != nb.node_type || na.data != nb.data {
        return false;
    }
    if na.attributes.len() != nb.attributes.len() {
        return false;
    }
    for (k, v) in &na.attributes {
        if nb.attributes.get(k) != Some(v) {
            return false;
        }
    }
    na.children.len() == nb.children.len()
        && na
            .children
            .iter()
            .zip(&nb.children)
            .all(|(&ca, &cb)| nodes_equal(arena, ca, cb))
}

// ============================================================
// Element natives
// ============================================================

/// Parse a CSS selector string for `querySelector` / `querySelectorAll`,
/// throwing a JS `SyntaxError` on invalid input (browser behavior).
fn parse_query_selector(args: &[JsValue], context: &mut Context) -> JsResult<CssSelector> {
    let raw = args
        .first()
        .map(|v| v.to_string(context).map(|s| s.to_std_string_lossy()))
        .transpose()?
        .unwrap_or_default();
    raw.parse::<CssSelector>().map_err(|e| {
        JsNativeError::syntax()
            .with_message(format!("invalid selector `{raw}`: {e}"))
            .into()
    })
}

/// Document-order (pre-order DFS) list of every node under `scope` matching
/// `selector`. The scope element itself is never considered — matching
/// `document.querySelector` (the root's children) and `element.querySelector`
/// (the element's subtree) semantics.
fn query_selector_nodes(arena: &NodeArena, scope: NodeId, selector: &CssSelector) -> Vec<NodeId> {
    let mut out = Vec::new();
    let mut stack: Vec<NodeId> = arena[scope].children.iter().rev().copied().collect();
    while let Some(id) = stack.pop() {
        if selector_chain_matches(arena, id, selector) {
            out.push(id);
        }
        stack.extend(arena[id].children.iter().rev().copied());
    }
    out
}

/// `document.querySelector(sel)` / `element.querySelector(sel)` — the first
/// matching element in document order, or `null`. On an element the search is
/// scoped to its subtree; `:hover` never matches (no pointer context).
pub(super) fn native_query_selector(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let selector = parse_query_selector(args, context)?;
    let scope = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::null());
    };
    let st = rc.borrow();
    let first = query_selector_nodes(&st.arena, scope, &selector)
        .into_iter()
        .next();
    drop(st);
    match first {
        Some(node_id) => node_wrapper(context, node_id),
        None => Ok(JsValue::null()),
    }
}

/// `document.querySelectorAll(sel)` / `element.querySelectorAll(sel)` — every
/// matching element in document order, returned as a static array of element
/// wrappers (indexable / `.length` / `.forEach`, like a browser NodeList).
pub(super) fn native_query_selector_all(
    this: &JsValue,
    args: &[JsValue],
    context: &mut Context,
) -> JsResult<JsValue> {
    let selector = parse_query_selector(args, context)?;
    let scope = this_node_id(this, context)?;
    let Some(rc) = with_state() else {
        return Ok(JsValue::undefined());
    };
    let st = rc.borrow();
    let ids = query_selector_nodes(&st.arena, scope, &selector);
    drop(st);
    let arr = boa_engine::object::builtins::JsArray::new(context);
    for id in ids {
        arr.push(node_wrapper(context, id)?, context)?;
    }
    Ok(arr.into())
}