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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Instant;

use boa_engine::{Context, JsResult, JsValue, Source, js_string};

use crate::source::SharedSourceText;

use crate::{
    events::{EventBindings, EventType, HitMap, HitRegion, HtmlEvent, KeyEventInfo},
    html::html_parse::{ParsedDocument, Parser},
    tdom::node::{Node, NodeArena, NodeId, NodeType},
    tui::graph_api::{DirtyInfo, RenderCmd},
};

use super::bindings::{compile_attribute_listeners, register_host_global};
use super::dom::{
    get_attr_handler, get_listeners, install_builtins, make_event_object, node_wrapper,
};
use super::host::HostFn;
use super::msg::{ScriptDirty, ScriptEvent};
use super::state::{ENGINE_STATE, ScriptState};
use super::{EngineBuildError, EngineParts};

/// Browser-aligned JS engine attached to a live DOM.
pub struct ScriptEngine {
    pub(super) context: Context,
    pub(super) state: Rc<RefCell<ScriptState>>,
}

/// Bootstrap script: the GC-rooted listener / element / timer registries.
const BOOTSTRAP: &str = include_str!("bootstrap.js");

impl ScriptEngine {
    /// Create an engine from an HTML document and the application bindings.
    ///
    /// Parses the document, installs the DOM globals and host functions,
    /// compiles `on*` attribute bodies into listeners, then runs every
    /// `<script>` block. Errors are returned as Boa errors; individual script
    /// failures log a warning and continue.
    pub fn new(html: &str, session_js: &str, bindings: EventBindings) -> JsResult<Self> {
        let document = {
            let mut parser = Parser::new(html);
            parser.parse_with_scripts()
        };
        Self::new_from_document(document, session_js, bindings)
    }

    /// Create an engine from an already-parsed document plus session-level JS.
    ///
    /// This startup path parses the HTML once and distributes independent
    /// snapshots to the script and render threads.
    pub fn new_from_document(
        document: ParsedDocument,
        session_js: &str,
        bindings: EventBindings,
    ) -> JsResult<Self> {
        let (context, state) =
            match Self::build_engine(document, bindings.host, Arc::from(session_js)) {
                Ok(v) => v,
                Err((e, _)) => return Err(e),
            };
        Ok(ScriptEngine { context, state })
    }

    /// Replace the live document with a freshly parsed one and re-run its
    /// scripts, keeping the session's host functions.
    ///
    /// The engine is the single source of truth for the document: a
    /// whole-document replacement re-parses here and marks the root dirty, so
    /// the change reaches the render thread as a `RenderArena` — never as an
    /// independent re-parse on the render side. On failure the previous
    /// document is left intact and the error is returned.
    pub fn reload(&mut self, html: &str) -> JsResult<()> {
        let (host_fns, session_js) = {
            let mut st = self.state.borrow_mut();
            (std::mem::take(&mut st.host_fns), Arc::clone(&st.session_js))
        };
        let document = {
            let mut parser = Parser::new(html);
            parser.parse_with_scripts()
        };
        let (context, state) = match Self::build_engine(document, host_fns, session_js) {
            Ok(v) => v,
            Err((e, host_fns)) => {
                // Restore the previous session so a failed reload leaves it
                // usable: put the host map back and re-point the thread-local
                // state the DOM natives read through.
                self.state.borrow_mut().host_fns = host_fns;
                ENGINE_STATE.with(|s| *s.borrow_mut() = Some(Rc::clone(&self.state)));
                return Err(e);
            }
        };
        // The whole document changed: mark the root dirty so the next
        // response carries the fresh arena to the render thread.
        {
            let mut st = state.borrow_mut();
            let root_id = st.root_id;
            st.dirty.nodes.push(root_id);
            st.document_reload = true;
        }
        self.context = context;
        self.state = state;
        // Browser refresh semantics: a whole-document reload replays the load
        // sequence. Handler writes land in the fresh state's dirty set and
        // the dispatched commands re-enter its pending queue — the caller's
        // normal `take_dirty` / `take_pending_cmds` drains pick both up.
        let boot = self.fire_document_loaded();
        {
            let mut st = self.state.borrow_mut();
            st.render_cmds.extend(boot.cmds);
            if let Some(d) = boot.dirty {
                st.dirty.nodes.extend(d.dirty.nodes);
                // `fire_document_loaded` drained the reload flag the reload
                // seeded; restore it so the caller's response still carries
                // the new document CSS.
                if d.document_css.is_some() {
                    st.document_reload = true;
                }
            }
        }
        Ok(())
    }

    /// Build a fresh Boa context + DOM state for `html`, consuming `host_fns`.
    ///
    /// On failure the host map is returned inside the `Err` so a caller that
    /// borrowed it (like [`reload`](Self::reload)) can restore the previous
    /// session.
    fn build_engine(
        document: ParsedDocument,
        host_fns: HashMap<String, HostFn>,
        session_js: SharedSourceText,
    ) -> Result<EngineParts, EngineBuildError> {
        let doc = document;
        let run_session_js = Arc::clone(&session_js);
        let (fetch_tx, fetch_rx) = ScriptState::fetch_channel();
        let state = Rc::new(RefCell::new(ScriptState {
            arena: (*doc.arena).clone(),
            root_id: doc.root_id,
            document_css: Arc::clone(&doc.css),
            document_reload: false,
            session_js,
            render_cmds: Vec::new(),
            dirty: DirtyInfo::default(),
            current_event: None,
            host_fns,
            timers: Vec::new(),
            next_timer_id: 0,
            active_fetches: std::collections::HashSet::new(),
            next_fetch_id: 0,
            fetch_rx,
            fetch_tx,
            frame_epoch: Instant::now(),
        }));
        ENGINE_STATE.with(|s| *s.borrow_mut() = Some(Rc::clone(&state)));

        // run boa,add limits
        let mut context = Context::default();
        let limits = context.runtime_limits_mut();
        limits.set_recursion_limit(512);
        limits.set_loop_iteration_limit(1_000_000);

        // GC-rooted registries used by the DOM natives.
        if let Err(e) = context.eval(Source::from_bytes(BOOTSTRAP.as_bytes())) {
            return Err((e, std::mem::take(&mut state.borrow_mut().host_fns)));
        }
        if let Err(e) = install_builtins(&mut context) {
            return Err((e, std::mem::take(&mut state.borrow_mut().host_fns)));
        }

        // Expose host functions as JS globals.
        let host_names: Vec<String> = state.borrow().host_fns.keys().cloned().collect();
        for name in host_names {
            if let Err(e) = register_host_global(&mut context, &name) {
                return Err((e, std::mem::take(&mut state.borrow_mut().host_fns)));
            }
        }

        // Compile `on*` attribute bodies into listeners.
        if let Err(e) = compile_attribute_listeners(&mut context, &state) {
            return Err((e, std::mem::take(&mut state.borrow_mut().host_fns)));
        }

        // Run the document's `<script>` blocks, then session-level JS from
        // `include_js!` / `Session::render`. Session JS intentionally executes
        // after inline scripts, just like a script injected at the end of body.
        let mut scripts: Vec<&str> = doc.scripts.iter().map(String::as_str).collect();
        scripts.push(run_session_js.as_ref());
        for script in scripts {
            if script.is_empty() {
                continue;
            }
            if let Err(e) = context.eval(Source::from_bytes(script.as_bytes())) {
                log::warn!("Script execution failed: {e}");
            }
        }

        // Browser `autofocus`: the first focusable element carrying the
        // `autofocus` attribute (document order) requests focus once the
        // input loop processes the command — the same `FocusRequest` path a
        // JS `el.focus()` uses.
        let autofocus = state.borrow().arena.iter().find_map(|(id, n)| {
            (matches!(n.node_type, NodeType::Input | NodeType::Textarea)
                && n.attributes.contains_key("autofocus"))
            .then_some(id)
        });
        if let Some(id) = autofocus {
            state
                .borrow_mut()
                .render_cmds
                .push(RenderCmd::FocusRequest { node_id: id });
        }
        Ok((context, state))
    }

    /// Clone of the live DOM arena.
    pub fn arena(&self) -> NodeArena {
        self.state.borrow().arena.clone()
    }

    /// Root node id of the live DOM.
    pub fn root_id(&self) -> NodeId {
        self.state.borrow().root_id
    }

    /// Replace session-level JS and evaluate it against the current DOM.
    ///
    /// Unlike [`reload`](Self::reload), this keeps the live arena and node ids.
    /// DOM writes made by the new source are reported through the normal dirty
    /// set. If evaluation fails, the previous source is restored for a future
    /// whole-document reload; runtime side effects already performed by the
    /// failed script cannot be rolled back (matching JS semantics).
    pub fn reload_js(&mut self, js: &str) -> JsResult<()> {
        let source: SharedSourceText = Arc::from(js);
        let previous = {
            let mut st = self.state.borrow_mut();
            std::mem::replace(&mut st.session_js, Arc::clone(&source))
        };
        match self.context.eval(Source::from_bytes(source.as_bytes())) {
            Ok(_) => Ok(()),
            Err(e) => {
                self.state.borrow_mut().session_js = previous;
                Err(e)
            }
        }
    }

    /// CSS extracted from the engine's current document.
    pub fn document_css(&self) -> SharedSourceText {
        Arc::clone(&self.state.borrow().document_css)
    }

    /// Whether the engine reloaded its whole document since the last reply.
    pub fn take_document_reload(&mut self) -> bool {
        std::mem::take(&mut self.state.borrow_mut().document_reload)
    }

    /// Whether a JS call mutated the DOM since the last take, and which nodes
    /// were touched. Consumes the accumulated set so each mutation batch is
    /// reported exactly once.
    pub fn take_dirty(&mut self) -> DirtyInfo {
        std::mem::take(&mut self.state.borrow_mut().dirty)
    }

    /// Drain render commands queued *outside* a dispatch — e.g. `el.focus()`
    /// from a top-level `<script>` or a host call inside a settled `fetch`
    /// `.then`. [`dispatch`](Self::fire) only takes the queue for its own
    /// calls, so without an explicit drain a load-time command would sit until
    /// the first event.
    pub fn take_pending_cmds(&mut self) -> Vec<RenderCmd> {
        std::mem::take(&mut self.state.borrow_mut().render_cmds)
    }

    /// Commit an `<input>` field's edited value into the DOM `value`
    /// attribute and mark the node dirty.
    ///
    /// The DOM is the single source of truth for a field's content: editing
    /// while focused repaints through the lightweight `input_states` path, and
    /// this writes the result back on blur / Enter / focus-switch so the next
    /// focus (or any later re-render) sees the edited value. Marking the node
    /// dirty guarantees the commit reaches the render thread as a
    /// `RenderArena`, so a JS blur handler that rewrites the value (e.g.
    /// clearing a submitted box) is what ends up on screen. Committing an
    /// unchanged value is a no-op (no dirty marker), mirroring the `el.value`
    /// JS setter's fast path.
    pub fn set_value(&mut self, node_id: NodeId, value: &str) {
        let mut st = self.state.borrow_mut();
        let existing = st
            .arena
            .get(node_id)
            .and_then(|n| n.attributes.get("value"))
            .cloned()
            .unwrap_or_default();
        if existing == value {
            return;
        }
        if let Some(node) = st.arena.get_mut(node_id) {
            node.attributes
                .insert("value".to_string(), value.to_string());
        }
        st.dirty.nodes.push(node_id);
    }

    /// Commit a new `value` attribute and mark the node dirty.
    ///
    /// A convenience alias of [`set_value`](Self::set_value) for callers that
    /// always change the value (e.g. a `<select>` selection swapping the shown
    /// label), so the next frame re-cascades and re-renders.
    pub fn set_value_dirty(&mut self, node_id: NodeId, value: &str) {
        self.set_value(node_id, value);
    }

    /// Set the `checked` state of a checkbox / radio and mark changed nodes
    /// dirty. Returns `true` when any `checked` attribute actually changed
    /// (the control itself or a cleared radio sibling).
    ///
    /// Radio buttons: checking one clears the `checked` attribute of every
    /// other input with the same `name` (document-scoped group, matching the
    /// engine's single-form model). Unchecking a radio is a no-op in
    /// browsers, but the engine allows it for checkbox parity — callers never
    /// send it for a click (clicking a selected radio keeps it selected).
    pub fn set_checked(&mut self, node_id: NodeId, checked: bool) -> bool {
        let mut st = self.state.borrow_mut();
        let mut changed = false;
        let is_radio = st.arena.get(node_id).is_some_and(|n| {
            n.get_type()
                .is_some_and(|t| t.eq_ignore_ascii_case("radio"))
        });
        let name = st
            .arena
            .get(node_id)
            .and_then(|n| n.attributes.get("name").cloned());
        if checked
            && is_radio
            && let Some(name) = name
        {
            // Clear every same-`name` radio sibling (the clicked member
            // is excluded here and set below).
            let siblings: Vec<NodeId> = st
                .arena
                .iter()
                .filter(|(id, n)| {
                    *id != node_id
                        && n.node_type == NodeType::Input
                        && n.get_type()
                            .is_some_and(|t| t.eq_ignore_ascii_case("radio"))
                        && n.attributes.get("name").is_some_and(|nm| *nm == name)
                })
                .map(|(id, _)| id)
                .collect();
            for id in siblings {
                if let Some(n) = st.arena.get_mut(id)
                    && n.attributes.shift_remove("checked").is_some()
                {
                    changed = true;
                    st.dirty.nodes.push(id);
                }
            }
        }
        let was = st
            .arena
            .get(node_id)
            .is_some_and(|n| n.attributes.contains_key("checked"));
        if was == checked {
            return changed;
        }
        if let Some(n) = st.arena.get_mut(node_id) {
            if checked {
                n.attributes.insert("checked".to_string(), String::new());
            } else {
                n.attributes.shift_remove("checked");
            }
        }
        st.dirty.nodes.push(node_id);
        true
    }

    /// Replace a `<textarea>`'s text content with `value` and mark the node
    /// dirty. The textarea's DOM value lives in its child text nodes (unlike
    /// `<input>`'s `value` attribute); committing an unchanged value is a
    /// no-op.
    pub fn set_textarea_value(&mut self, node_id: NodeId, value: &str) {
        let mut st = self.state.borrow_mut();
        let existing = st
            .arena
            .get(node_id)
            .map(|n| n.text_content(&st.arena))
            .unwrap_or_default();
        if existing == value {
            return;
        }
        let old_children: Vec<NodeId> = st
            .arena
            .get_mut(node_id)
            .map(|n| std::mem::take(&mut n.children))
            .unwrap_or_default();
        for child in old_children {
            if let Some(c) = st.arena.get_mut(child) {
                c.parent = None;
            }
        }
        let text_id = st.arena.insert(Node::text(value));
        Node::append_child(&mut st.arena, node_id, text_id);
        st.dirty.nodes.push(node_id);
    }

    /// Toggle the `open` attribute of a `<details>` element and mark it dirty.
    ///
    /// The native disclosure-widget default action (clicking the `<summary>`)
    /// calls this: the presence of `open` decides whether the element renders
    /// its content, so the dirty marker routes a re-render through the usual
    /// `RenderArena` path.
    pub fn toggle_details(&mut self, node_id: NodeId) {
        let mut st = self.state.borrow_mut();
        let Some(node) = st.arena.get_mut(node_id) else {
            return;
        };
        if node.attributes.contains_key("open") {
            node.attributes.shift_remove("open");
        } else {
            node.attributes.insert("open".to_string(), String::new());
        }
        st.dirty.nodes.push(node_id);
    }

    /// Close a `<dialog>` by removing its `open` attribute and marking it
    /// dirty. Returns whether the dialog was actually open (so callers can
    /// skip the `close` event for already-closed dialogs).
    pub fn close_dialog(&mut self, node_id: NodeId) -> bool {
        let mut st = self.state.borrow_mut();
        let Some(node) = st.arena.get_mut(node_id) else {
            return false;
        };
        if node.attributes.shift_remove("open").is_none() {
            return false;
        }
        st.dirty.nodes.push(node_id);
        true
    }

    /// Dispatch a DOM event along the hit region's ancestor path.
    ///
    /// Builds a JS `Event` object, walks `region.path` target-first and fires
    /// every listener registered (via `addEventListener` or `on*`) for each
    /// element, honouring `stopPropagation()`. Returns any render commands
    /// pushed by host functions during the dispatch.
    pub fn fire(
        &mut self,
        region: &HitRegion,
        event_type: EventType,
        x: u32,
        y: u32,
    ) -> Vec<RenderCmd> {
        self.dispatch(region, event_type, x, y, None).0
    }

    /// Dispatch a non-bubbling event to the region's target element only
    /// (`mouseenter` / `mouseleave` semantics — ancestors never hear it).
    pub fn fire_target(
        &mut self,
        region: &HitRegion,
        event_type: EventType,
        x: u32,
        y: u32,
    ) -> Vec<RenderCmd> {
        let target_only = HitRegion {
            node_id: region.node_id,
            rect: region.rect,
            client: region.client,
            path: region.path[..1].into(),
        };
        self.dispatch(&target_only, event_type, x, y, None).0
    }

    /// Dispatch a `wheel` tick, reporting whether a listener called
    /// `preventDefault()` (the input loop cancels the built-in scroll then).
    /// A missing target still reports "not prevented" so the built-in runs.
    pub fn fire_wheel_gate(
        &mut self,
        hit_map: &HitMap,
        x: u32,
        y: u32,
        up: bool,
    ) -> (Vec<RenderCmd>, bool) {
        match hit_map.hit_test(x, y) {
            Some(region) => {
                let payload = if up {
                    EventPayload::WheelUp
                } else {
                    EventPayload::WheelDown
                };
                self.dispatch(region, EventType::Wheel, x, y, Some(payload))
            }
            None => (Vec::new(), false),
        }
    }

    /// Fire the browser load sequence: `DOMContentLoaded` then `load` on the
    /// window listeners and the document body. Called once after the engine
    /// built (scripts ran) and again after every whole-document reload —
    /// browser refresh semantics.
    pub fn fire_document_loaded(&mut self) -> ScriptEvent {
        let mut cmds = self.fire_window_and_body("DOMContentLoaded", EventType::DomContentLoaded);
        cmds.extend(self.fire_window_and_body("load", EventType::Load));
        let dirty = self.take_dirty();
        let snapshot = if dirty.is_empty() {
            None
        } else {
            let document_css = self.take_document_reload().then(|| self.document_css());
            Some(ScriptDirty {
                arena: Arc::new(self.arena()),
                root_id: self.root_id(),
                dirty,
                document_css,
            })
        };
        ScriptEvent {
            cmds,
            dirty: snapshot,
            hovered: None,
            key_gate: None,
            wheel_gate: None,
        }
    }

    /// Fire `event.resize` on the window listeners and the document body.
    pub fn fire_resize(&mut self) -> Vec<RenderCmd> {
        self.fire_window_and_body("resize", EventType::Resize)
    }

    /// Fire `event.scroll` on the window listeners and the document body
    /// (after the page scroll offset changed; handlers read `window.scrollY`).
    pub fn fire_scroll(&mut self) -> Vec<RenderCmd> {
        self.fire_window_and_body("scroll", EventType::Scroll)
    }

    /// Fire `selectionchange` after a page or field selection changed.
    pub fn fire_selection_change(&mut self) -> Vec<RenderCmd> {
        self.fire_window_and_body("selectionchange", EventType::SelectionChange)
    }

    /// Shared dispatch of the document-level events (`resize` / `scroll`)
    /// that have no node target: `window.addEventListener(type, fn)` handlers
    /// run first (no node target), then the `<body>` → root ancestor chain —
    /// the dispatch shape key events use for their no-focused-field fallback.
    /// Returns the render commands pushed by host functions during the
    /// dispatch.
    fn fire_window_and_body(&mut self, type_name: &str, event_type: EventType) -> Vec<RenderCmd> {
        // Window-level listeners: same event object, no node target.
        let window_cmd = {
            let window_listeners =
                super::dom::get_window_listeners(&mut self.context, type_name).unwrap_or_default();
            let target = JsValue::undefined();
            let Ok(event) = make_event_object(&mut self.context, event_type, &target, 0, 0) else {
                return Vec::new();
            };
            let mut cmds = Vec::new();
            for listener in window_listeners {
                let Ok(f) = listener.to_object(&mut self.context) else {
                    continue;
                };
                if let Err(e) = f.call(&target, std::slice::from_ref(&event), &mut self.context) {
                    log::warn!("window {type_name} listener threw: {e}");
                }
            }
            let mut st = self.state.borrow_mut();
            cmds.extend(std::mem::take(&mut st.render_cmds));
            cmds
        };
        // Document-level chain (target = `<body>`, like the keydown fallback).
        let region = {
            let arena = self.arena();
            let body_id = arena
                .iter()
                .find(|(_, n)| n.node_type == NodeType::Body)
                .map(|(id, _)| id)
                .unwrap_or_else(|| self.root_id());
            super::msg::region_for(&arena, body_id)
        };
        let mut cmds = self.fire(&region, event_type, 0, 0);
        cmds.extend(window_cmd);
        cmds
    }

    /// Re-evaluate every registered `matchMedia` list against the current
    /// viewport and fire `change` on the ones that flipped. Backed by the
    /// `__htuiMQLs` GC-rooted array; the current viewport comes from the
    /// shared UI state (zeros match nothing, so a missing input loop never
    /// spurious-fires).
    pub fn evaluate_media_changes(&mut self) {
        // `mql_matches_now` reads the shared UI state itself; the presence
        // check only avoids spurious change events with no input loop attached.
        if super::with_ui().is_none() {
            return;
        }
        let Ok(mqls) = self
            .context
            .global_object()
            .get(js_string!("__htuiMQLs"), &mut self.context)
            .and_then(|v| v.to_object(&mut self.context))
        else {
            return;
        };
        let Ok(len) = mqls
            .get(js_string!("length"), &mut self.context)
            .and_then(|v| v.to_u32(&mut self.context))
        else {
            return;
        };
        for i in 0..len {
            let Ok(obj) = mqls
                .get(i, &mut self.context)
                .and_then(|v| v.to_object(&mut self.context))
            else {
                continue;
            };
            let Some(query) = super::dom::mql_query(&obj, &mut self.context) else {
                continue;
            };
            let matches = super::dom::mql_matches_now(&query);
            let last = super::dom::mql_last_matches(&obj, &mut self.context);
            if matches == last {
                continue;
            }
            if let Err(e) = obj.set(
                js_string!("_lastMatches"),
                matches,
                false,
                &mut self.context,
            ) {
                log::warn!("Failed to store matchMedia state: {e}");
                continue;
            }
            let event = {
                let mut init = boa_engine::object::ObjectInitializer::new(&mut self.context);
                init.property(
                    js_string!("type"),
                    js_string!("change"),
                    boa_engine::property::Attribute::all(),
                )
                .property(
                    js_string!("matches"),
                    matches,
                    boa_engine::property::Attribute::all(),
                )
                .build()
            };
            let listeners = obj
                .get(js_string!("_listeners"), &mut self.context)
                .and_then(|v| v.to_object(&mut self.context));
            if let Ok(list) = listeners {
                let len = list
                    .get(js_string!("length"), &mut self.context)
                    .and_then(|v| v.to_u32(&mut self.context))
                    .unwrap_or(0);
                for li in 0..len {
                    let Ok(listener) = list.get(li, &mut self.context) else {
                        continue;
                    };
                    let Ok(f) = listener.to_object(&mut self.context) else {
                        continue;
                    };
                    if let Err(e) = f.call(
                        &obj.clone().into(),
                        &[event.clone().into()],
                        &mut self.context,
                    ) {
                        log::warn!("matchMedia change listener threw: {e}");
                    }
                }
            }
            if let Ok(onchange) = obj.get(js_string!("onchange"), &mut self.context)
                && onchange.is_callable()
                && let Ok(f) = onchange.to_object(&mut self.context)
                && let Err(e) = f.call(&obj.clone().into(), &[event.into()], &mut self.context)
            {
                log::warn!("matchMedia onchange handler threw: {e}");
            }
        }
    }

    /// Dispatch a keyboard event ([`EventType::KeyDown`] / [`EventType::KeyUp`])
    /// along the hit region's ancestor path.
    ///
    /// Like [`fire`](Self::fire) but attaches the [`KeyEventInfo`] payload so
    /// JS listeners read `event.key` / `event.code` / `event.ctrlKey` / …;
    /// coordinates are meaningless for keys and report `0, 0`.
    pub fn fire_key(
        &mut self,
        region: &HitRegion,
        event_type: EventType,
        key: &KeyEventInfo,
    ) -> Vec<RenderCmd> {
        self.fire_key_gated(region, event_type, key).0
    }

    /// Gated variant of [`fire_key`](Self::fire_key): additionally reports
    /// whether any listener on the bubbling path called `event.preventDefault()`,
    /// so the input loop can skip the built-in shortcut for that key.
    pub(crate) fn fire_key_gated(
        &mut self,
        region: &HitRegion,
        event_type: EventType,
        key: &KeyEventInfo,
    ) -> (Vec<RenderCmd>, bool) {
        self.dispatch(region, event_type, 0, 0, Some(EventPayload::Key(key)))
    }

    /// Shared dispatch core of [`fire`](Self::fire) and
    /// [`fire_key`](Self::fire_key): build the JS event object (with the
    /// payload fields the event kind carries), walk `region.path` target-first
    /// firing every registered listener, honouring `stopPropagation()`.
    /// Returns any render commands pushed by host functions during the
    /// dispatch, plus whether a listener called `event.preventDefault()`.
    fn dispatch(
        &mut self,
        region: &HitRegion,
        event_type: EventType,
        x: u32,
        y: u32,
        payload: Option<EventPayload<'_>>,
    ) -> (Vec<RenderCmd>, bool) {
        let target_id = region.path.first().and_then(|e| e.id.clone());
        let key_info = match payload {
            Some(EventPayload::Key(k)) => Some(k.clone()),
            _ => None,
        };

        let event = match self.build_event_object(event_type, &region.path, x, y, payload) {
            Ok(e) => e,
            Err(e) => {
                log::warn!("Failed to build JS event object: {e}");
                return (Vec::new(), false);
            }
        };

        {
            let mut st = self.state.borrow_mut();
            st.current_event = Some(HtmlEvent {
                event_type,
                target: target_id,
                current_target: None,
                x,
                y,
                bubbles: true,
                key: key_info,
            });
        }

        for element in region.path.iter() {
            // The element wrapper doubles as the listener's `this`: browsers
            // bind `this` inside a listener to the element it is attached to
            // (the current target of the dispatch).
            let Ok(wrapper) = node_wrapper(&mut self.context, element.node_id) else {
                log::warn!("Failed to wrap node {:?} during dispatch", element.node_id);
                continue;
            };
            // `currentTarget` must track the element being dispatched.
            if let Some(obj) = event.as_object()
                && let Err(e) = obj.set(
                    js_string!("currentTarget"),
                    wrapper.clone(),
                    false,
                    &mut self.context,
                )
            {
                log::warn!("Failed to set event.currentTarget: {e}");
            }

            if let Some(ev) = &mut self.state.borrow_mut().current_event {
                ev.current_target = element.id.clone();
            }

            let listeners = match get_listeners(&mut self.context, element.node_id, event_type) {
                Ok(l) => l,
                Err(e) => {
                    log::warn!("Failed to read listeners for {:?}: {e}", element.node_id);
                    Vec::new()
                }
            };
            // `stopImmediatePropagation` only — `stopPropagation` lets the
            // remaining listeners of the *current* element run and just ends
            // the bubbling afterwards (browser semantics).
            let mut immediate = false;
            for listener in listeners {
                let call = listener.to_object(&mut self.context).and_then(|f| {
                    f.call(&wrapper, std::slice::from_ref(&event), &mut self.context)
                });
                if let Err(e) = call {
                    log::warn!("Listener threw: {e}");
                }
                if self.event_flag(&event, "_stoppedImmediate") {
                    immediate = true;
                    break;
                }
            }

            // The `on*` attribute handler is a single slot per (element,
            // event type); per the DOM spec it runs after that element's
            // `addEventListener` listeners, still inside this element's leg
            // of the bubbling path — suppressed only by an immediate stop.
            if !immediate {
                let handler = match get_attr_handler(&mut self.context, element.node_id, event_type)
                {
                    Ok(h) => h,
                    Err(e) => {
                        log::warn!(
                            "Failed to read attribute handler for {:?}: {e}",
                            element.node_id
                        );
                        None
                    }
                };
                if let Some(handler) = handler {
                    let call = handler.to_object(&mut self.context).and_then(|f| {
                        f.call(&wrapper, std::slice::from_ref(&event), &mut self.context)
                    });
                    if let Err(e) = call {
                        log::warn!("Attribute handler threw: {e}");
                    }
                    if self.event_flag(&event, "_stoppedImmediate") {
                        immediate = true;
                    }
                }
            }

            if immediate || self.event_flag(&event, "_stopped") {
                break;
            }
        }

        // Any listener may have called `preventDefault()` — the input loop
        // reads this verdict to decide whether the built-in shortcut runs.
        let prevented = event
            .as_object()
            .and_then(|obj| obj.get(js_string!("_prevented"), &mut self.context).ok())
            .is_some_and(|v| v.is_boolean() && v.to_boolean());

        let mut st = self.state.borrow_mut();
        st.current_event = None;
        let cmds = std::mem::take(&mut st.render_cmds);
        drop(st);
        (cmds, prevented)
    }

    /// Read a boolean control flag (`_stopped` / `_stoppedImmediate` /
    /// `_prevented`) off the in-flight event object.
    fn event_flag(&mut self, event: &JsValue, name: &str) -> bool {
        event
            .as_object()
            .and_then(|obj| obj.get(js_string!(name), &mut self.context).ok())
            .is_some_and(|v| v.is_boolean() && v.to_boolean())
    }

    /// Evaluate a JS snippet in the engine's global scope.
    ///
    /// Used by tests and diagnostic tooling to probe or seed engine state
    /// (reading globals back, running setup snippets). Returns the completion
    /// value of the snippet.
    pub fn eval_source(&mut self, src: &str) -> JsResult<JsValue> {
        self.context.eval(Source::from_bytes(src.as_bytes()))
    }

    /// Invoke a JS global function by name.
    ///
    /// The name may be a `<script>`-defined function or a registered host
    /// function. Returns any render commands pushed during the call.
    pub fn invoke_action(&mut self, name: &str) -> Vec<RenderCmd> {
        let global = self.context.global_object();
        let f = match global.get(js_string!(name), &mut self.context) {
            Ok(f) => f,
            Err(e) => {
                log::warn!("Failed to resolve action `{name}`: {e}");
                return Vec::new();
            }
        };
        if !f.is_callable() {
            log::warn!("Action `{name}` is not a function");
            return Vec::new();
        }
        if let Some(f) = f.to_object(&mut self.context).ok()
            && let Err(e) = f.call(&JsValue::undefined(), &[], &mut self.context)
        {
            log::warn!("Action `{name}` threw: {e}");
        }
        let mut st = self.state.borrow_mut();
        let cmds = std::mem::take(&mut st.render_cmds);
        drop(st);
        cmds
    }

    /// Build a JS `Event` object for a dispatch: the shared object from
    /// [`super::dom::make_event_object`] plus the keyboard payload fields
    /// when a [`KeyEventInfo`] rides along, or the mouse payload fields
    /// (`clientX` / `clientY` / `pageX` / `pageY`, `deltaY` for wheel) for
    /// the pointer-driven event types.
    fn build_event_object(
        &mut self,
        event_type: EventType,
        path: &[crate::events::ElementRef],
        x: u32,
        y: u32,
        payload: Option<EventPayload<'_>>,
    ) -> JsResult<JsValue> {
        let target = match path.first() {
            Some(el) => node_wrapper(&mut self.context, el.node_id)?,
            None => JsValue::null(),
        };
        let event = make_event_object(&mut self.context, event_type, &target, x, y)?;
        let Some(obj) = event.as_object() else {
            return Ok(event);
        };
        match payload {
            Some(EventPayload::Key(k)) => {
                let fields: [(&str, JsValue); 8] = [
                    ("key", js_string!(k.key.as_str()).into()),
                    ("code", js_string!(k.code.as_str()).into()),
                    ("keyCode", JsValue::from(k.key_code as f64)),
                    ("shiftKey", JsValue::from(k.shift)),
                    ("ctrlKey", JsValue::from(k.ctrl)),
                    ("altKey", JsValue::from(k.alt)),
                    ("metaKey", JsValue::from(k.meta)),
                    ("repeat", JsValue::from(k.repeat)),
                ];
                for (name, value) in fields {
                    obj.set(js_string!(name), value, false, &mut self.context)?;
                }
            }
            Some(up @ (EventPayload::WheelUp | EventPayload::WheelDown)) => {
                // Line-mode wheel delta (browser `deltaMode: 1`); negative
                // scrolls up. Mirrors the input layer's per-tick line count.
                const WHEEL_DELTA_LINES: f64 = 3.0;
                let delta = if matches!(up, EventPayload::WheelUp) {
                    -WHEEL_DELTA_LINES
                } else {
                    WHEEL_DELTA_LINES
                };
                obj.set(js_string!("deltaY"), delta, false, &mut self.context)?;
            }
            None => {}
        }
        if is_mouse_event_type(event_type) {
            // `pageX/pageY` are the canvas (document) coordinates; `clientX`
            // / `clientY` subtract the page scroll offset (viewport space).
            let (_, _, scroll_y) = super::with_ui().unwrap_or((0, 0, 0));
            let client_y = y.saturating_sub(scroll_y);
            let fields: [(&str, JsValue); 4] = [
                ("clientX", JsValue::from(f64::from(x))),
                ("clientY", JsValue::from(f64::from(client_y))),
                ("pageX", JsValue::from(f64::from(x))),
                ("pageY", JsValue::from(f64::from(y))),
            ];
            for (name, value) in fields {
                obj.set(js_string!(name), value, false, &mut self.context)?;
            }
        }
        Ok(event)
    }
}

/// Extra payload a dispatch can attach to the JS event object beyond the
/// shared surface.
enum EventPayload<'a> {
    /// Keyboard fields (`event.key` / `event.code` / …).
    Key(&'a KeyEventInfo),
    /// Wheel tick scrolling up (`deltaY` negative).
    WheelUp,
    /// Wheel tick scrolling down (`deltaY` positive).
    WheelDown,
}

/// Event types whose JS objects carry the mouse coordinate fields
/// (`clientX` / `clientY` / `pageX` / `pageY`).
fn is_mouse_event_type(event_type: EventType) -> bool {
    matches!(
        event_type,
        EventType::Click
            | EventType::DblClick
            | EventType::MouseDown
            | EventType::MouseUp
            | EventType::MouseMove
            | EventType::MouseOver
            | EventType::MouseOut
            | EventType::MouseEnter
            | EventType::MouseLeave
            | EventType::ContextMenu
            | EventType::Wheel
    )
}

impl Drop for ScriptEngine {
    fn drop(&mut self) {
        ENGINE_STATE.with(|s| *s.borrow_mut() = None);
    }
}