Skip to main content

slt_wasm/
lib.rs

1//! WASM/browser backend for SuperLightTUI.
2//!
3//! Renders an SLT [`Context`] into a grid of `<span>` elements inside a host
4//! container and drives it from `requestAnimationFrame`, translating DOM
5//! keyboard/mouse/wheel/resize/paste events into SLT [`Event`]s.
6
7// Mirror the library-only hygiene lints kept out of [workspace.lints]; this
8// crate has no example targets so they apply cleanly to its single lib.
9#![warn(missing_docs)]
10#![warn(unreachable_pub)]
11#![deny(clippy::unwrap_in_result)]
12#![warn(clippy::unwrap_used)]
13#![warn(clippy::dbg_macro)]
14#![warn(clippy::print_stdout)]
15#![warn(clippy::print_stderr)]
16#![forbid(unsafe_code)]
17
18use std::cell::{Cell, RefCell};
19use std::io;
20use std::rc::{Rc, Weak};
21
22use slt::{
23    AppState, Backend, Buffer, Color, Context, Event, KeyCode, KeyModifiers, Modifiers,
24    MouseButton, MouseEvent as SltMouseEvent, MouseKind, Rect, RunConfig,
25};
26use wasm_bindgen::JsCast;
27use wasm_bindgen::prelude::*;
28use web_sys::{
29    Document, EventTarget, HtmlElement, HtmlPreElement, HtmlTextAreaElement, KeyboardEvent, Window,
30};
31
32type RafCallback = Closure<dyn FnMut(f64)>;
33
34#[wasm_bindgen(
35    inline_js = "export function guardedFrame(frame, failed) { return ts => { try { frame(ts); } catch (error) { failed(String(error)); } }; } export function deferCleanup(callback) { queueMicrotask(callback); }"
36)]
37extern "C" {
38    #[wasm_bindgen(js_name = guardedFrame)]
39    fn guarded_frame(frame: &js_sys::Function, failed: &js_sys::Function) -> js_sys::Function;
40    #[wasm_bindgen(js_name = deferCleanup)]
41    fn defer_cleanup(callback: &js_sys::Function);
42}
43
44/// Mount-time options specific to the browser runtime, not the terminal.
45#[derive(Clone)]
46pub struct WasmOptions {
47    /// Initial grid width in cells. Default: 80. Must be positive.
48    pub width: u32,
49    /// Initial grid height in cells. Default: 24. Must be positive.
50    pub height: u32,
51    /// Initial colors. Can be overridden by `Context::set_theme`.
52    pub theme: slt::Theme,
53    /// Initial widget color overrides.
54    pub widget_theme: slt::WidgetTheme,
55    /// Lines scrolled for each browser wheel event.
56    pub scroll_speed: u32,
57    /// Maximum rendered frames per second; `None` renders every RAF.
58    /// `Some(0)` is rejected. Input remains queued while throttled.
59    pub max_fps: Option<u32>,
60    /// Fit the host content box on mount and element resize. The host must
61    /// have an independently sized width and height. Default: fixed grid.
62    pub auto_fit: bool,
63    /// Install focused keyboard, editable text, pointer and wheel listeners.
64    /// Disable for a display-only mount. Never captures global keyboard input.
65    pub input: bool,
66}
67
68impl Default for WasmOptions {
69    fn default() -> Self {
70        let config = RunConfig::default();
71        Self {
72            width: 80,
73            height: 24,
74            theme: config.theme,
75            widget_theme: config.widget_theme,
76            scroll_speed: config.scroll_speed,
77            max_fps: Some(60),
78            auto_fit: false,
79            input: true,
80        }
81    }
82}
83
84thread_local! {
85    static ACTIVE_APPS: RefCell<Vec<WasmAppHandle>> = const { RefCell::new(Vec::new()) };
86}
87
88struct EventListener {
89    target: EventTarget,
90    event_type: &'static str,
91    callback: Closure<dyn Fn(web_sys::Event)>,
92}
93
94impl EventListener {
95    fn install(
96        target: EventTarget,
97        event_type: &'static str,
98        callback: Closure<dyn Fn(web_sys::Event)>,
99    ) -> Result<Self, JsValue> {
100        target.add_event_listener_with_callback(event_type, callback.as_ref().unchecked_ref())?;
101        Ok(Self {
102            target,
103            event_type,
104            callback,
105        })
106    }
107}
108
109impl Drop for EventListener {
110    fn drop(&mut self) {
111        let _ = self.target.remove_event_listener_with_callback(
112            self.event_type,
113            self.callback.as_ref().unchecked_ref(),
114        );
115    }
116}
117
118struct WasmAppInner {
119    window: Window,
120    listeners: Vec<EventListener>,
121    events: Rc<RefCell<Vec<Event>>>,
122    raf: Option<RafCallback>,
123    guarded_raf: Option<js_sys::Function>,
124    failure_callback: Option<Closure<dyn FnMut(String)>>,
125    raf_id: Option<i32>,
126    running: bool,
127    input_active: Rc<Cell<bool>>,
128    error: Option<String>,
129    input: Option<InputSurface>,
130    observer: Option<web_sys::ResizeObserver>,
131    observer_callback: Option<Closure<dyn FnMut()>>,
132    pointer: Rc<Cell<Option<(i32, MouseButton)>>>,
133    container: HtmlElement,
134    added_tab_stop: bool,
135}
136
137impl WasmAppInner {
138    fn new(window: Window, container: HtmlElement, events: Rc<RefCell<Vec<Event>>>) -> Self {
139        Self {
140            window,
141            listeners: Vec::new(),
142            events,
143            raf: None,
144            guarded_raf: None,
145            failure_callback: None,
146            raf_id: None,
147            running: true,
148            input_active: Rc::new(Cell::new(true)),
149            error: None,
150            input: None,
151            observer: None,
152            observer_callback: None,
153            pointer: Rc::new(Cell::new(None)),
154            container,
155            added_tab_stop: false,
156        }
157    }
158}
159
160/// Owned browser runtime handle returned by [`run_wasm_with_handle`].
161///
162/// Dropping or explicitly disposing the handle removes DOM event listeners,
163/// cancels any pending `requestAnimationFrame`, and releases the app closure.
164/// The compatibility [`run_wasm`] API stores this handle internally until the
165/// app exits so existing fire-and-forget callers continue to work.
166#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
167pub struct WasmAppHandle {
168    inner: Rc<RefCell<WasmAppInner>>,
169}
170
171#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
172impl WasmAppHandle {
173    /// Stop the app and release all browser resources owned by this handle.
174    pub fn dispose(&self) {
175        dispose_inner_now(&self.inner);
176    }
177
178    /// Return whether the app is still scheduled to render future frames.
179    #[must_use]
180    pub fn is_running(&self) -> bool {
181        self.inner.borrow().running
182    }
183
184    /// The last fatal frame/scheduling error, or `None` after a normal stop.
185    /// A trapped WASM instance must be discarded, not restarted.
186    #[must_use]
187    pub fn error(&self) -> Option<String> {
188        self.inner.borrow().error.clone()
189    }
190}
191
192impl WasmAppHandle {
193    fn new(inner: Rc<RefCell<WasmAppInner>>) -> Self {
194        Self { inner }
195    }
196}
197
198impl Drop for WasmAppHandle {
199    fn drop(&mut self) {
200        dispose_inner_now(&self.inner);
201    }
202}
203
204/// SLT [`Backend`] that paints into a DOM `<pre>`/`<span>` grid and diffs
205/// against the previously flushed frame so only changed cells are rewritten.
206pub struct DomBackend {
207    buffer: Buffer,
208    /// Snapshot of the buffer as it was last flushed to the DOM. Used to diff
209    /// against the live `buffer` so `flush` only mutates spans whose cell
210    /// actually changed — mirroring the native ANSI diff in `src/buffer.rs`.
211    prev: Buffer,
212    container: HtmlElement,
213    grid: Option<HtmlPreElement>,
214    cells: Vec<HtmlElement>,
215    initialized: bool,
216    width: u32,
217    height: u32,
218}
219
220impl DomBackend {
221    /// Create a backend that renders a `width`×`height` cell grid into
222    /// `container`. The DOM grid is built lazily on the first flush.
223    pub fn new(container: HtmlElement, width: u32, height: u32) -> Self {
224        Self {
225            buffer: Buffer::empty(Rect::new(0, 0, width, height)),
226            prev: Buffer::empty(Rect::new(0, 0, width, height)),
227            container,
228            grid: None,
229            cells: Vec::new(),
230            initialized: false,
231            width,
232            height,
233        }
234    }
235
236    /// Resize the backend to a new cell grid, rebuilding its painted cells.
237    ///
238    /// The next [`flush`](DomBackend::flush) rebuilds the `<span>` grid and
239    /// repaints every cell. Both the live and previous buffers are resized so
240    /// the diff baseline stays consistent with the new dimensions. A no-op when
241    /// the dimensions are unchanged or either axis is zero.
242    pub fn resize(&mut self, width: u32, height: u32) {
243        if width == 0 || height == 0 || (width == self.width && height == self.height) {
244            return;
245        }
246        self.width = width;
247        self.height = height;
248        let area = Rect::new(0, 0, width, height);
249        self.buffer.resize(area);
250        self.prev.resize(area);
251        // Keep the grid and editable sink mounted while rebuilding cells.
252        self.initialized = false;
253    }
254
255    fn document(&self) -> Result<Document, io::Error> {
256        self.container
257            .owner_document()
258            .ok_or_else(|| io::Error::other("owner document unavailable"))
259    }
260
261    fn initialize_grid(&mut self) -> io::Result<()> {
262        let document = self.document()?;
263        let pre = if let Some(grid) = &self.grid {
264            grid.clone()
265        } else {
266            document
267                .create_element("pre")
268                .map_err(|e| io::Error::other(format!("create pre failed: {e:?}")))?
269                .dyn_into::<HtmlPreElement>()
270                .map_err(|_| io::Error::other("failed to cast pre element"))?
271        };
272
273        for cell in self.cells.drain(..) {
274            cell.remove();
275        }
276        let mut child = pre.first_child();
277        while let Some(node) = child {
278            child = node.next_sibling();
279            if node.node_type() == web_sys::Node::TEXT_NODE {
280                pre.remove_child(&node)
281                    .map_err(|e| io::Error::other(format!("remove row break failed: {e:?}")))?;
282            }
283        }
284
285        pre.set_attribute(
286            "style",
287            &format!("position:relative;margin:0;padding:0;border:0;line-height:16px;font-family:monospace;font-size:14px;white-space:pre;direction:ltr;box-sizing:content-box;width:{}ch;height:{}px;", self.width, self.height * 16),
288        )
289        .map_err(|e| io::Error::other(format!("set pre style failed: {e:?}")))?;
290        pre.set_attribute("data-slt-grid", "")
291            .map_err(|e| io::Error::other(format!("mark grid failed: {e:?}")))?;
292
293        for y in 0..self.height {
294            for _x in 0..self.width {
295                let span = document
296                    .create_element("span")
297                    .map_err(|e| io::Error::other(format!("create span failed: {e:?}")))?
298                    .dyn_into::<HtmlElement>()
299                    .map_err(|_| io::Error::other("failed to cast span element"))?;
300                span.set_text_content(Some(" "));
301                pre.append_child(&span)
302                    .map_err(|e| io::Error::other(format!("append span failed: {e:?}")))?;
303                self.cells.push(span);
304            }
305
306            if y + 1 < self.height {
307                let newline = document.create_text_node("\n");
308                pre.append_child(&newline)
309                    .map_err(|e| io::Error::other(format!("append newline failed: {e:?}")))?;
310            }
311        }
312
313        if self.grid.is_none() {
314            self.container
315                .append_child(&pre)
316                .map_err(|e| io::Error::other(format!("append pre failed: {e:?}")))?;
317        }
318        self.initialized = true;
319        self.grid = Some(pre);
320        Ok(())
321    }
322
323    /// Compute the cell grid `(cols, rows)` that fits the container's current
324    /// pixel size, given a measured per-cell pixel size.
325    ///
326    /// Returns `None` when either the container or a cell reports a zero size so
327    /// the caller can keep the existing dimensions instead of collapsing to a
328    /// degenerate grid.
329    fn fit_grid_to_container(&self) -> Option<(u32, u32)> {
330        let grid = self.grid.as_ref()?;
331        let style = web_sys::window()?
332            .get_computed_style(&self.container)
333            .ok()??;
334        let padding = |name| {
335            style
336                .get_property_value(name)
337                .ok()
338                .and_then(|v| v.trim_end_matches("px").parse::<f64>().ok())
339                .unwrap_or(0.0)
340        };
341        let cont_w = self.container.client_width() as f64
342            - padding("padding-left")
343            - padding("padding-right");
344        let cont_h = self.container.client_height() as f64
345            - padding("padding-top")
346            - padding("padding-bottom");
347        let cell_w = grid.get_bounding_client_rect().width() / self.width.max(1) as f64;
348        let host_scale = self.container.get_bounding_client_rect().width()
349            / self.container.offset_width().max(1) as f64;
350        let cell_w = cell_w / host_scale;
351        let cell_h = 16.0;
352        if cont_w <= 0.0 || cont_h <= 0.0 {
353            return None;
354        }
355        let cols = (cont_w / cell_w).floor().max(1.0) as u32;
356        let rows = (cont_h / cell_h).floor().max(1.0) as u32;
357        Some((cols, rows))
358    }
359}
360
361impl Backend for DomBackend {
362    fn size(&self) -> (u32, u32) {
363        (self.width, self.height)
364    }
365
366    fn buffer_mut(&mut self) -> &mut Buffer {
367        &mut self.buffer
368    }
369
370    fn flush(&mut self) -> io::Result<()> {
371        // When the grid is (re)built every span starts blank, so the previous
372        // snapshot must be treated as empty to force a full repaint. Otherwise
373        // we diff against the cells we actually painted last frame and skip the
374        // unchanged ones — the common steady-state case writes almost nothing.
375        let full_repaint = !self.initialized;
376        if full_repaint {
377            self.initialize_grid()?;
378        }
379
380        let ox = self.buffer.area.x;
381        let oy = self.buffer.area.y;
382        let pox = self.prev.area.x;
383        let poy = self.prev.area.y;
384        for y in 0..self.height {
385            for x in 0..self.width {
386                let idx = (y * self.width + x) as usize;
387                let cell = self.buffer.get(ox + x, oy + y);
388
389                // `Cell` derives `PartialEq` over (symbol, style, hyperlink), so
390                // an equality check captures every visible difference. After a
391                // grid rebuild `full_repaint` is set and we always write.
392                if !full_repaint && cell == self.prev.get(pox + x, poy + y) {
393                    continue;
394                }
395
396                let span = self
397                    .cells
398                    .get(idx)
399                    .ok_or_else(|| io::Error::other("dom cell index out of bounds"))?;
400
401                let continuation = cell.is_continuation();
402                let occupied = if x + 1 < self.width
403                    && self.buffer.get(ox + x + 1, oy + y).is_continuation()
404                {
405                    2
406                } else {
407                    1
408                };
409                span.set_attribute("style", &format!("position:absolute;display:{};left:{}%;top:{}px;width:{}%;height:16px;line-height:16px;overflow:hidden;unicode-bidi:isolate;{}", if continuation { "none" } else { "block" }, x as f64 * 100.0 / self.width.max(1) as f64, y * 16, occupied as f64 * 100.0 / self.width.max(1) as f64, style_to_css(cell.style)))
410                    .map_err(|e| io::Error::other(format!("set span style failed: {e:?}")))?;
411                let symbol = cell.symbol.as_str();
412                span.set_text_content(Some(symbol));
413            }
414        }
415
416        // Record what is now on screen so the next frame can diff against it.
417        self.prev.resize(self.buffer.area);
418        self.prev.content.clone_from(&self.buffer.content);
419
420        Ok(())
421    }
422}
423
424fn style_to_css(style: slt::Style) -> String {
425    let mut css = String::new();
426
427    if let Some(fg) = color_to_css(style.fg) {
428        css.push_str("color:");
429        css.push_str(&fg);
430        css.push(';');
431    }
432    if let Some(bg) = color_to_css(style.bg) {
433        css.push_str("background-color:");
434        css.push_str(&bg);
435        css.push(';');
436    }
437
438    if style.modifiers.contains(Modifiers::BOLD) {
439        css.push_str("font-weight:bold;");
440    }
441    if style.modifiers.contains(Modifiers::DIM) {
442        css.push_str("opacity:0.7;");
443    }
444    if style.modifiers.contains(Modifiers::ITALIC) {
445        css.push_str("font-style:italic;");
446    }
447    let mut text_decorations = Vec::new();
448    if style.modifiers.contains(Modifiers::UNDERLINE) {
449        text_decorations.push("underline");
450    }
451    if style.modifiers.contains(Modifiers::STRIKETHROUGH) {
452        text_decorations.push("line-through");
453    }
454    if !text_decorations.is_empty() {
455        css.push_str("text-decoration-line:");
456        css.push_str(&text_decorations.join(" "));
457        css.push(';');
458    }
459    if style.modifiers.contains(Modifiers::REVERSED) {
460        css.push_str("filter:invert(100%);");
461    }
462
463    css
464}
465
466fn color_to_css(color: Option<Color>) -> Option<String> {
467    match color? {
468        Color::Reset => None,
469        Color::Black => Some("#000000".to_string()),
470        Color::Red => Some("#cd3131".to_string()),
471        Color::Green => Some("#0dbc79".to_string()),
472        Color::Yellow => Some("#e5e510".to_string()),
473        Color::Blue => Some("#2472c8".to_string()),
474        Color::Magenta => Some("#bc3fbc".to_string()),
475        Color::Cyan => Some("#11a8cd".to_string()),
476        Color::White => Some("#e5e5e5".to_string()),
477        Color::DarkGray => Some("#808080".to_string()),
478        Color::LightRed => Some("#ff0000".to_string()),
479        Color::LightGreen => Some("#00ff00".to_string()),
480        Color::LightYellow => Some("#ffff00".to_string()),
481        Color::LightBlue => Some("#0000ff".to_string()),
482        Color::LightMagenta => Some("#ff00ff".to_string()),
483        Color::LightCyan => Some("#00ffff".to_string()),
484        Color::LightWhite => Some("#ffffff".to_string()),
485        Color::Rgb(r, g, b) => Some(format!("#{r:02x}{g:02x}{b:02x}")),
486        Color::Indexed(i) => {
487            let (r, g, b) = indexed_to_rgb(i);
488            Some(format!("#{r:02x}{g:02x}{b:02x}"))
489        }
490        _ => None,
491    }
492}
493
494fn indexed_to_rgb(i: u8) -> (u8, u8, u8) {
495    if i < 16 {
496        return match i {
497            0 => (0, 0, 0),
498            1 => (128, 0, 0),
499            2 => (0, 128, 0),
500            3 => (128, 128, 0),
501            4 => (0, 0, 128),
502            5 => (128, 0, 128),
503            6 => (0, 128, 128),
504            7 => (192, 192, 192),
505            8 => (128, 128, 128),
506            9 => (255, 0, 0),
507            10 => (0, 255, 0),
508            11 => (255, 255, 0),
509            12 => (0, 0, 255),
510            13 => (255, 0, 255),
511            14 => (0, 255, 255),
512            _ => (255, 255, 255),
513        };
514    }
515
516    if (16..=231).contains(&i) {
517        let idx = i - 16;
518        let r = idx / 36;
519        let g = (idx % 36) / 6;
520        let b = idx % 6;
521        let comp = |v: u8| if v == 0 { 0 } else { 55 + v * 40 };
522        return (comp(r), comp(g), comp(b));
523    }
524
525    let gray = 8 + (i - 232) * 10;
526    (gray, gray, gray)
527}
528
529fn modifiers_from_bools(shift: bool, control: bool, alt: bool, super_key: bool) -> KeyModifiers {
530    let mut modifiers = KeyModifiers::NONE;
531    if shift {
532        modifiers.0 |= KeyModifiers::SHIFT.0;
533    }
534    if control {
535        modifiers.0 |= KeyModifiers::CONTROL.0;
536    }
537    if alt {
538        modifiers.0 |= KeyModifiers::ALT.0;
539    }
540    if super_key {
541        modifiers.0 |= KeyModifiers::SUPER.0;
542    }
543    modifiers
544}
545
546fn keyboard_event_modifiers(event: &KeyboardEvent) -> KeyModifiers {
547    modifiers_from_bools(
548        event.shift_key(),
549        event.ctrl_key(),
550        event.alt_key(),
551        event.meta_key(),
552    )
553}
554
555fn reflect_bool(target: &JsValue, key: &str) -> bool {
556    js_sys::Reflect::get(target, &JsValue::from_str(key))
557        .ok()
558        .and_then(|v| v.as_bool())
559        .unwrap_or(false)
560}
561
562fn reflect_event_modifiers(target: &JsValue) -> KeyModifiers {
563    modifiers_from_bools(
564        reflect_bool(target, "shiftKey"),
565        reflect_bool(target, "ctrlKey"),
566        reflect_bool(target, "altKey"),
567        reflect_bool(target, "metaKey"),
568    )
569}
570
571fn keyboard_event_to_slt(event: &KeyboardEvent) -> Option<Event> {
572    let key = event.key();
573    let code = match key.as_str() {
574        "Enter" => KeyCode::Enter,
575        "Escape" => KeyCode::Esc,
576        "Tab" => {
577            if event.shift_key() {
578                KeyCode::BackTab
579            } else {
580                KeyCode::Tab
581            }
582        }
583        "Backspace" => KeyCode::Backspace,
584        "Delete" => KeyCode::Delete,
585        "ArrowUp" => KeyCode::Up,
586        "ArrowDown" => KeyCode::Down,
587        "ArrowLeft" => KeyCode::Left,
588        "ArrowRight" => KeyCode::Right,
589        "Home" => KeyCode::Home,
590        "End" => KeyCode::End,
591        "PageUp" => KeyCode::PageUp,
592        "PageDown" => KeyCode::PageDown,
593        s => {
594            if s.chars().count() == 1 {
595                KeyCode::Char(s.chars().next()?)
596            } else {
597                return None;
598            }
599        }
600    };
601
602    Some(Event::key_mod(code, keyboard_event_modifiers(event)))
603}
604
605fn mouse_button(button: i16) -> MouseButton {
606    match button {
607        1 => MouseButton::Middle,
608        2 => MouseButton::Right,
609        _ => MouseButton::Left,
610    }
611}
612
613#[derive(Clone)]
614struct GridGeometry {
615    grid: HtmlPreElement,
616    width: u32,
617    height: u32,
618}
619
620impl GridGeometry {
621    fn position(&self, event: &JsValue, outside: bool) -> Option<(u32, u32)> {
622        let rect = self.grid.get_bounding_client_rect();
623        let x = reflect_f64(event, "clientX")? - rect.left();
624        let y = reflect_f64(event, "clientY")? - rect.top();
625        if rect.width() <= 0.0 || rect.height() <= 0.0 {
626            return None;
627        }
628        if x < 0.0 || y < 0.0 || x >= rect.width() || y >= rect.height() {
629            // An outside release must never become a click on an edge widget.
630            return outside.then_some((u32::MAX, u32::MAX));
631        }
632        Some((
633            (x * self.width as f64 / rect.width()).floor() as u32,
634            (y * self.height as f64 / rect.height()).floor() as u32,
635        ))
636    }
637}
638
639/// Read a numeric property off a JS value via reflection.
640///
641/// `web-sys` typed wrappers for `WheelEvent` / `ClipboardEvent` are not enabled
642/// in this crate's feature set, so the wheel and paste listeners receive the
643/// generic [`web_sys::Event`] and pull the fields they need by name. Returns
644/// `None` when the property is missing or not a number.
645fn reflect_f64(target: &JsValue, key: &str) -> Option<f64> {
646    js_sys::Reflect::get(target, &JsValue::from_str(key))
647        .ok()
648        .and_then(|v| v.as_f64())
649}
650
651/// Translate a `wheel` event's scroll deltas into an SLT [`MouseKind`].
652///
653/// The dominant axis wins so a mostly-vertical gesture maps to
654/// `ScrollUp`/`ScrollDown` and a mostly-horizontal one to
655/// `ScrollLeft`/`ScrollRight`, mirroring how crossterm reports terminal wheel
656/// events. Returns `None` for a zero-delta event so we never enqueue a no-op.
657fn wheel_delta_to_kind(delta_x: f64, delta_y: f64) -> Option<MouseKind> {
658    if delta_y.abs() >= delta_x.abs() {
659        if delta_y < 0.0 {
660            Some(MouseKind::ScrollUp)
661        } else if delta_y > 0.0 {
662            Some(MouseKind::ScrollDown)
663        } else {
664            None
665        }
666    } else if delta_x < 0.0 {
667        Some(MouseKind::ScrollLeft)
668    } else {
669        Some(MouseKind::ScrollRight)
670    }
671}
672
673/// Extract pasted text from a `paste` event's `clipboardData`.
674///
675/// `clipboardData.getData("text")` returns the plain-text flavor of the
676/// clipboard. Read reflectively because the `ClipboardEvent` / `DataTransfer`
677/// web-sys wrappers are not enabled. Returns `None` when there is no text
678/// payload so we never enqueue an empty paste.
679fn paste_event_text(target: &JsValue) -> Option<String> {
680    let clipboard_data = js_sys::Reflect::get(target, &JsValue::from_str("clipboardData")).ok()?;
681    if clipboard_data.is_null() || clipboard_data.is_undefined() {
682        return None;
683    }
684    let get_data = js_sys::Reflect::get(&clipboard_data, &JsValue::from_str("getData")).ok()?;
685    let get_data: js_sys::Function = get_data.dyn_into().ok()?;
686    let text = get_data
687        .call1(&clipboard_data, &JsValue::from_str("text"))
688        .ok()?
689        .as_string()?;
690    if text.is_empty() { None } else { Some(text) }
691}
692
693fn event_target<T: JsCast>(target: &T) -> EventTarget {
694    target.unchecked_ref::<EventTarget>().clone()
695}
696
697fn dispose_inner_now(inner: &Rc<RefCell<WasmAppInner>>) {
698    let (container, added_tab_stop, pointer, input) = {
699        let mut app = inner.borrow_mut();
700        app.running = false;
701        app.input_active.set(false);
702        if let Some(raf_id) = app.raf_id.take() {
703            let _ = app.window.cancel_animation_frame(raf_id);
704        }
705        (
706            app.container.clone(),
707            std::mem::take(&mut app.added_tab_stop),
708            app.pointer.take(),
709            app.input.clone(),
710        )
711    };
712    // Release shared host ownership before a synchronous remount can claim it.
713    // Deferred cleanup below only destroys this runtime's private resources.
714    if added_tab_stop && container.get_attribute("tabindex").as_deref() == Some("0") {
715        let _ = container.remove_attribute("tabindex");
716    }
717    if let Some((id, _)) = pointer {
718        let _ = container.release_pointer_capture(id);
719    }
720    if let Some(input) = input {
721        input.preedit.clear();
722    }
723    // Also safe when called synchronously from a user frame or DOM callback:
724    // the currently executing wasm-bindgen closure is not destroyed on its stack.
725    let inner = Rc::clone(inner);
726    let cleanup = Closure::once_into_js(move || {
727        let mut app = inner.borrow_mut();
728        let listeners = std::mem::take(&mut app.listeners);
729        let observer = app.observer.take();
730        let observer_callback = app.observer_callback.take();
731        let input = app.input.take();
732        app.events.borrow_mut().clear();
733        let raf = app.raf.take();
734        let guarded = app.guarded_raf.take();
735        let failure_callback = app.failure_callback.take();
736        drop(app);
737        drop(listeners);
738        if let Some(observer) = observer {
739            observer.disconnect();
740        }
741        if let Some(input) = input {
742            input.sink.remove();
743            input.preedit.element.remove();
744        }
745        drop((observer_callback, raf, guarded, failure_callback));
746        ACTIVE_APPS.with(|apps| apps.borrow_mut().retain(WasmAppHandle::is_running));
747    });
748    defer_cleanup(cleanup.unchecked_ref());
749}
750
751fn fail_runtime(inner: &Rc<RefCell<WasmAppInner>>, error: String) {
752    web_sys::console::error_1(&JsValue::from_str(&error));
753    inner.borrow_mut().error = Some(error);
754    dispose_inner_now(inner);
755}
756
757fn schedule_raf(inner: &Rc<RefCell<WasmAppInner>>) -> Result<(), JsValue> {
758    let raf_id = {
759        let app = inner.borrow();
760        if !app.running {
761            return Ok(());
762        }
763        let callback = app
764            .guarded_raf
765            .as_ref()
766            .ok_or_else(|| JsValue::from_str("RAF callback unavailable"))?;
767        app.window.request_animation_frame(callback)?
768    };
769    inner.borrow_mut().raf_id = Some(raf_id);
770    Ok(())
771}
772
773#[derive(Default)]
774struct TextBridge {
775    composing: bool,
776    committed: Option<String>,
777    printable_modifiers: Option<KeyModifiers>,
778    focused: bool,
779}
780
781#[derive(Clone)]
782struct InputSurface {
783    sink: HtmlTextAreaElement,
784    preedit: Rc<Preedit>,
785}
786
787#[derive(Clone, Copy, PartialEq, Eq)]
788struct PreeditAnchor {
789    x: u32,
790    y: u32,
791    width: u32,
792    style: slt::Style,
793}
794
795struct Preedit {
796    element: HtmlElement,
797    grid: HtmlPreElement,
798    anchor: Cell<Option<PreeditAnchor>>,
799    suppressed: Cell<bool>,
800    dirty: Cell<bool>,
801    text: RefCell<String>,
802    foreground: Color,
803    background: Color,
804    runtime: Weak<RefCell<WasmAppInner>>,
805}
806
807impl Preedit {
808    fn new(
809        grid: HtmlPreElement,
810        foreground: Color,
811        background: Color,
812        runtime: Weak<RefCell<WasmAppInner>>,
813    ) -> Result<Self, JsValue> {
814        let document = grid
815            .owner_document()
816            .ok_or_else(|| JsValue::from_str("preedit document unavailable"))?;
817        let element = document.create_element("div")?.dyn_into::<HtmlElement>()?;
818        element.set_attribute("data-slt-preedit", "")?;
819        element.set_attribute("aria-hidden", "true")?;
820        element.set_attribute("style", "display:none;pointer-events:none;")?;
821        Ok(Self {
822            element,
823            grid,
824            anchor: Cell::new(None),
825            suppressed: Cell::new(true),
826            dirty: Cell::new(false),
827            text: RefCell::new(String::new()),
828            foreground,
829            background,
830            runtime,
831        })
832    }
833
834    fn clear(&self) {
835        self.dirty.set(false);
836        let had_text = !self.text.borrow().is_empty();
837        self.text.borrow_mut().clear();
838        if had_text {
839            self.element.set_text_content(None);
840            let _ = self.element.style().set_property("display", "none");
841        }
842    }
843
844    fn begin(&self) {
845        self.clear();
846        self.suppressed.set(self.anchor.get().is_none());
847    }
848
849    fn update(&self, text: &str) {
850        if self.suppressed.get() || self.anchor.get().is_none() {
851            return;
852        }
853        if text.is_empty() {
854            self.clear();
855            return;
856        }
857        if *self.text.borrow() == text {
858            return;
859        }
860        {
861            let mut current = self.text.borrow_mut();
862            current.clear();
863            current.push_str(text);
864        }
865        // The next runtime frame checks the current caret privacy before
866        // painting; queued focus/masking changes must not use a stale policy.
867        self.dirty.set(true);
868    }
869
870    fn sync(&self, buffer: &Buffer) {
871        let anchor = buffer
872            .cursor_position()
873            .filter(|&(x, y)| !buffer.cursor_is_masked() && buffer.area.contains(x, y))
874            .map(|(x, y)| PreeditAnchor {
875                x,
876                y,
877                width: buffer.area.width,
878                style: buffer.get(x, y).style,
879            });
880        if anchor.is_none() {
881            self.anchor.set(None);
882            // Once a composition touches a private/unknown caret, do not
883            // reveal its text even if focus or masking changes before it ends.
884            self.suppressed.set(true);
885            self.clear();
886            return;
887        }
888        let moved = self.anchor.replace(anchor) != anchor;
889        let changed = self.dirty.replace(false);
890        if !self.suppressed.get() && (moved || changed) && !self.text.borrow().is_empty() {
891            self.redraw();
892        }
893    }
894
895    fn redraw(&self) {
896        if let Err(error) = self.paint()
897            && let Some(runtime) = self.runtime.upgrade()
898        {
899            fail_runtime(&runtime, format!("slt preedit error: {error:?}"));
900        }
901    }
902
903    fn paint(&self) -> Result<(), JsValue> {
904        let text = self.text.borrow().clone();
905        let Some(anchor) = self.anchor.get() else {
906            self.element.style().set_property("display", "none")?;
907            return Ok(());
908        };
909        let available = anchor.width - anchor.x;
910        // Reuse the core's grapheme, width, bidi and clipping rules without
911        // writing any preedit text into the application's presented buffer.
912        let mut buffer = Buffer::empty(Rect::new(0, 0, available, 1));
913        buffer.set_string(0, 0, &text, slt::Style::new().underline());
914        let end = buffer
915            .content
916            .iter()
917            .rposition(|cell| cell.style.modifiers.contains(Modifiers::UNDERLINE))
918            .map_or(0, |i| i + 1);
919        let document = self
920            .grid
921            .owner_document()
922            .ok_or_else(|| JsValue::from_str("preedit document unavailable"))?;
923        let mut style = anchor.style.underline();
924        if color_to_css(style.fg).is_none() {
925            style.fg = Some(self.foreground);
926        }
927        let mut css = style_to_css(style);
928        if color_to_css(style.bg).is_none() {
929            css.push_str(&format!("background-color:{};", self.background_css()));
930        }
931        self.element.set_text_content(None);
932        self.element.set_attribute("style", &format!("position:absolute;display:block;left:{}%;top:{}px;width:{}%;height:16px;line-height:16px;z-index:2;overflow:hidden;pointer-events:none;", anchor.x as f64 * 100.0 / anchor.width as f64, anchor.y * 16, available as f64 * 100.0 / anchor.width as f64))?;
933        for x in 0..end {
934            let cell = &buffer.content[x];
935            if cell.is_continuation() {
936                continue;
937            }
938            let occupied = if buffer
939                .content
940                .get(x + 1)
941                .is_some_and(slt::Cell::is_continuation)
942            {
943                2
944            } else {
945                1
946            };
947            let glyph = document.create_element("span")?;
948            glyph.set_attribute("style", &format!("position:absolute;left:{}%;top:0;width:{}%;height:16px;line-height:16px;white-space:pre;overflow:hidden;text-underline-offset:2px;{}", x as f64 * 100.0 / available as f64, occupied as f64 * 100.0 / available as f64, css))?;
949            glyph.set_text_content(Some(cell.symbol.as_str()));
950            self.element.append_child(&glyph)?;
951        }
952        Ok(())
953    }
954
955    fn background_css(&self) -> String {
956        let mut element = Some(web_sys::Element::from(self.grid.clone()));
957        if let Some(window) = web_sys::window() {
958            while let Some(current) = element {
959                if let Ok(Some(style)) = window.get_computed_style(&current)
960                    && let Ok(color) = style.get_property_value("background-color")
961                    && !color.is_empty()
962                    && color != "transparent"
963                    && color != "rgba(0, 0, 0, 0)"
964                {
965                    return color;
966                }
967                element = current.parent_element();
968            }
969        }
970        color_to_css(Some(self.background)).unwrap_or_else(|| "#000000".into())
971    }
972}
973
974fn owns_focus(container: &HtmlElement, input: &HtmlTextAreaElement) -> bool {
975    container
976        .owner_document()
977        .and_then(|document| document.active_element())
978        .is_some_and(|active| {
979            &active == container.unchecked_ref::<web_sys::Element>()
980                || &active == input.unchecked_ref::<web_sys::Element>()
981        })
982}
983
984fn enqueue_mouse(
985    events: &RefCell<Vec<Event>>,
986    geometry: &RefCell<GridGeometry>,
987    event: &web_sys::Event,
988    kind: MouseKind,
989    outside: bool,
990) {
991    if let Some((x, y)) = geometry.borrow().position(event.as_ref(), outside) {
992        events.borrow_mut().push(Event::Mouse(SltMouseEvent::new(
993            kind,
994            x,
995            y,
996            reflect_event_modifiers(event.as_ref()),
997            None,
998            None,
999        )));
1000    }
1001}
1002
1003fn cancel_pointer(
1004    pointer: &Cell<Option<(i32, MouseButton)>>,
1005    events: &RefCell<Vec<Event>>,
1006    host: &HtmlElement,
1007) {
1008    if let Some((id, button)) = pointer.take() {
1009        events.borrow_mut().push(Event::Mouse(SltMouseEvent::new(
1010            MouseKind::Up(button),
1011            u32::MAX,
1012            u32::MAX,
1013            KeyModifiers::NONE,
1014            None,
1015            None,
1016        )));
1017        let _ = host.release_pointer_capture(id);
1018    }
1019}
1020
1021fn install_event_listeners(
1022    container: &HtmlElement,
1023    surface: &InputSurface,
1024    window: &Window,
1025    geometry: Rc<RefCell<GridGeometry>>,
1026    events: Rc<RefCell<Vec<Event>>>,
1027    pointer: Rc<Cell<Option<(i32, MouseButton)>>>,
1028    running: Rc<Cell<bool>>,
1029) -> Result<Vec<EventListener>, JsValue> {
1030    let input = &surface.sink;
1031    let mut listeners = Vec::new();
1032    let bridge = Rc::new(RefCell::new(TextBridge::default()));
1033
1034    for event_type in [
1035        "keydown",
1036        "beforeinput",
1037        "input",
1038        "compositionstart",
1039        "compositionupdate",
1040        "compositionend",
1041        "paste",
1042        "focusin",
1043        "focusout",
1044    ] {
1045        let host = container.clone();
1046        let sink = input.clone();
1047        let events = Rc::clone(&events);
1048        let bridge = Rc::clone(&bridge);
1049        let pointer = Rc::clone(&pointer);
1050        let running = Rc::clone(&running);
1051        let preedit = Rc::clone(&surface.preedit);
1052        let callback = Closure::wrap(Box::new(move |event: web_sys::Event| {
1053            if !running.get() {
1054                return;
1055            }
1056            if event_type == "focusin" {
1057                if !owns_focus(&host, &sink) {
1058                    return;
1059                }
1060                let was_focused = bridge.borrow().focused;
1061                bridge.borrow_mut().focused = true;
1062                if !was_focused {
1063                    events.borrow_mut().push(Event::FocusGained);
1064                }
1065                if event
1066                    .target()
1067                    .is_some_and(|target| target == event_target(&host))
1068                {
1069                    let _ = sink.focus();
1070                }
1071                return;
1072            }
1073            if event_type == "focusout" {
1074                if !bridge.borrow().focused {
1075                    return;
1076                }
1077                let related = event
1078                    .dyn_ref::<web_sys::FocusEvent>()
1079                    .and_then(|e| e.related_target());
1080                if related.is_some_and(|target| {
1081                    target == event_target(&sink) || target == event_target(&host)
1082                }) {
1083                    return;
1084                }
1085                *bridge.borrow_mut() = TextBridge::default();
1086                sink.set_value("");
1087                preedit.clear();
1088                cancel_pointer(&pointer, &events, &host);
1089                events.borrow_mut().push(Event::FocusLost);
1090                return;
1091            }
1092            if !owns_focus(&host, &sink) {
1093                return;
1094            }
1095            match event_type {
1096                "keydown" => {
1097                    let Some(key) = event.dyn_ref::<KeyboardEvent>() else {
1098                        return;
1099                    };
1100                    if key.is_composing() || key.key_code() == 229 || bridge.borrow().composing {
1101                        return;
1102                    }
1103                    bridge.borrow_mut().committed = None;
1104                    bridge.borrow_mut().printable_modifiers = None;
1105                    let name = key.key();
1106                    if (key.ctrl_key() || key.meta_key())
1107                        && matches!(name.to_ascii_lowercase().as_str(), "v" | "c" | "x")
1108                    {
1109                        return;
1110                    }
1111                    // Printable/dead-key/AltGraph text is committed by the editable sink.
1112                    if ((!key.ctrl_key() && !key.meta_key()) || key.get_modifier_state("AltGraph"))
1113                        && (name.chars().count() == 1 || name == "Dead")
1114                    {
1115                        if !key.alt_key() && name.chars().count() == 1 {
1116                            bridge.borrow_mut().printable_modifiers =
1117                                Some(keyboard_event_modifiers(key));
1118                        }
1119                        return;
1120                    }
1121                    if let Some(mapped) = keyboard_event_to_slt(key) {
1122                        events.borrow_mut().push(mapped);
1123                        key.prevent_default();
1124                    }
1125                }
1126                "compositionstart" => {
1127                    let mut state = bridge.borrow_mut();
1128                    state.composing = true;
1129                    state.committed = None;
1130                    state.printable_modifiers = None;
1131                    drop(state);
1132                    preedit.begin();
1133                }
1134                "compositionupdate" => {
1135                    if bridge.borrow().composing {
1136                        let text = event
1137                            .dyn_ref::<web_sys::CompositionEvent>()
1138                            .and_then(|e| e.data())
1139                            .unwrap_or_default();
1140                        preedit.update(&text);
1141                    }
1142                }
1143                "compositionend" => {
1144                    if !bridge.borrow().composing {
1145                        return;
1146                    }
1147                    let text = event
1148                        .dyn_ref::<web_sys::CompositionEvent>()
1149                        .and_then(|e| e.data())
1150                        .unwrap_or_default();
1151                    let mut state = bridge.borrow_mut();
1152                    state.composing = false;
1153                    state.committed = (!text.is_empty()).then(|| text.clone());
1154                    if !text.is_empty() {
1155                        events.borrow_mut().push(Event::Paste(text));
1156                    }
1157                    drop(state);
1158                    preedit.clear();
1159                    sink.set_value("");
1160                }
1161                "beforeinput" => {
1162                    let Some(input_event) = event.dyn_ref::<web_sys::InputEvent>() else {
1163                        return;
1164                    };
1165                    if input_event.is_composing() || bridge.borrow().composing {
1166                        return;
1167                    }
1168                    let code = match input_event.input_type().as_str() {
1169                        "deleteContentBackward" => Some(KeyCode::Backspace),
1170                        "deleteContentForward" => Some(KeyCode::Delete),
1171                        "insertLineBreak" | "insertParagraph" => Some(KeyCode::Enter),
1172                        _ => None,
1173                    };
1174                    if let Some(code) = code {
1175                        events.borrow_mut().push(Event::key(code));
1176                        if event.cancelable() {
1177                            event.prevent_default();
1178                        }
1179                        sink.set_value("");
1180                    }
1181                }
1182                "input" => {
1183                    let Some(input_event) = event.dyn_ref::<web_sys::InputEvent>() else {
1184                        return;
1185                    };
1186                    if input_event.is_composing() || bridge.borrow().composing {
1187                        if !bridge.borrow().composing {
1188                            preedit.begin();
1189                        }
1190                        bridge.borrow_mut().composing = true;
1191                        preedit.update(&input_event.data().unwrap_or_else(|| sink.value()));
1192                        return;
1193                    }
1194                    let kind = input_event.input_type();
1195                    let text = input_event
1196                        .data()
1197                        .filter(|text| !text.is_empty())
1198                        .unwrap_or_else(|| sink.value());
1199                    let duplicate = bridge.borrow_mut().committed.take().as_ref() == Some(&text);
1200                    let modifiers = bridge.borrow_mut().printable_modifiers.take();
1201                    if !duplicate
1202                        && kind.starts_with("insert")
1203                        && !text.is_empty()
1204                        && kind != "insertLineBreak"
1205                        && kind != "insertParagraph"
1206                    {
1207                        let mapped = if text.chars().count() == 1 {
1208                            modifiers.and_then(|modifiers| {
1209                                text.chars()
1210                                    .next()
1211                                    .map(|ch| Event::key_mod(KeyCode::Char(ch), modifiers))
1212                            })
1213                        } else {
1214                            None
1215                        };
1216                        events
1217                            .borrow_mut()
1218                            .push(mapped.unwrap_or(Event::Paste(text)));
1219                    }
1220                    sink.set_value("");
1221                }
1222                "paste" => {
1223                    if let Some(text) = paste_event_text(event.as_ref()) {
1224                        events.borrow_mut().push(Event::Paste(text));
1225                        event.prevent_default();
1226                        sink.set_value("");
1227                    }
1228                }
1229                _ => {}
1230            }
1231        }) as Box<dyn Fn(_)>);
1232        listeners.push(EventListener::install(
1233            event_target(container),
1234            event_type,
1235            callback,
1236        )?);
1237    }
1238
1239    for event_type in [
1240        "pointerdown",
1241        "pointermove",
1242        "pointerup",
1243        "pointercancel",
1244        "lostpointercapture",
1245        "wheel",
1246    ] {
1247        let host = container.clone();
1248        let sink = input.clone();
1249        let events = Rc::clone(&events);
1250        let geometry = Rc::clone(&geometry);
1251        let pointer = Rc::clone(&pointer);
1252        let running = Rc::clone(&running);
1253        let callback = Closure::wrap(Box::new(move |event: web_sys::Event| {
1254            if !running.get() {
1255                return;
1256            }
1257            if event_type == "wheel" {
1258                let value = event.as_ref();
1259                if let Some(kind) = wheel_delta_to_kind(
1260                    reflect_f64(value, "deltaX").unwrap_or(0.0),
1261                    reflect_f64(value, "deltaY").unwrap_or(0.0),
1262                ) && geometry.borrow().position(value, false).is_some()
1263                {
1264                    enqueue_mouse(&events, &geometry, &event, kind, false);
1265                    event.prevent_default();
1266                }
1267                return;
1268            }
1269            let Some(pe) = event.dyn_ref::<web_sys::PointerEvent>() else {
1270                return;
1271            };
1272            match event_type {
1273                "pointerdown" => {
1274                    if pointer.get().is_some()
1275                        || geometry.borrow().position(event.as_ref(), false).is_none()
1276                    {
1277                        return;
1278                    }
1279                    let _ = sink.focus();
1280                    let button = mouse_button(pe.button());
1281                    pointer.set(Some((pe.pointer_id(), button)));
1282                    let _ = host.set_pointer_capture(pe.pointer_id());
1283                    enqueue_mouse(&events, &geometry, &event, MouseKind::Down(button), false);
1284                    // Keep right-button defaults so browser context-menu paste remains available.
1285                    if button == MouseButton::Left {
1286                        event.prevent_default();
1287                    }
1288                }
1289                "pointermove" => {
1290                    let kind = match pointer.get() {
1291                        Some((id, button)) if id == pe.pointer_id() => MouseKind::Drag(button),
1292                        Some(_) => return,
1293                        None => {
1294                            if !event
1295                                .target()
1296                                .and_then(|t| t.dyn_into::<web_sys::Node>().ok())
1297                                .is_some_and(|target| host.contains(Some(&target)))
1298                            {
1299                                return;
1300                            }
1301                            MouseKind::Moved
1302                        }
1303                    };
1304                    enqueue_mouse(&events, &geometry, &event, kind, false);
1305                }
1306                "pointerup" => {
1307                    if let Some((id, button)) = pointer.get() {
1308                        if id != pe.pointer_id() || mouse_button(pe.button()) != button {
1309                            return;
1310                        }
1311                        pointer.set(None);
1312                        enqueue_mouse(&events, &geometry, &event, MouseKind::Up(button), true);
1313                        let _ = host.release_pointer_capture(id);
1314                    }
1315                }
1316                _ => {
1317                    if pointer.get().is_some_and(|(id, _)| id == pe.pointer_id()) {
1318                        cancel_pointer(&pointer, &events, &host);
1319                    }
1320                }
1321            }
1322        }) as Box<dyn Fn(_)>);
1323        let target = if matches!(event_type, "pointermove" | "pointerup") {
1324            event_target(window)
1325        } else {
1326            event_target(container)
1327        };
1328        listeners.push(EventListener::install(target, event_type, callback)?);
1329    }
1330    for event_type in ["blur", "focus"] {
1331        let events = Rc::clone(&events);
1332        let bridge = Rc::clone(&bridge);
1333        let pointer = Rc::clone(&pointer);
1334        let running = Rc::clone(&running);
1335        let host = container.clone();
1336        let sink = input.clone();
1337        let preedit = Rc::clone(&surface.preedit);
1338        let callback = Closure::wrap(Box::new(move |_: web_sys::Event| {
1339            if !running.get() {
1340                return;
1341            }
1342            if event_type == "blur" && bridge.borrow().focused {
1343                *bridge.borrow_mut() = TextBridge::default();
1344                sink.set_value("");
1345                preedit.clear();
1346                cancel_pointer(&pointer, &events, &host);
1347                events.borrow_mut().push(Event::FocusLost);
1348            } else if event_type == "focus" && owns_focus(&host, &sink) && !bridge.borrow().focused
1349            {
1350                bridge.borrow_mut().focused = true;
1351                events.borrow_mut().push(Event::FocusGained);
1352            }
1353        }) as Box<dyn Fn(_)>);
1354        listeners.push(EventListener::install(
1355            event_target(window),
1356            event_type,
1357            callback,
1358        )?);
1359    }
1360    Ok(listeners)
1361}
1362
1363/// Mount a fixed grid with default browser options and retain its runtime owner.
1364///
1365/// # Errors
1366/// Returns an error for invalid dimensions or unavailable browser resources.
1367pub fn run_wasm_with_handle<F>(
1368    container: HtmlElement,
1369    width: u32,
1370    height: u32,
1371    app: F,
1372) -> Result<WasmAppHandle, JsValue>
1373where
1374    F: FnMut(&mut Context) + 'static,
1375{
1376    run_wasm_with_options(
1377        container,
1378        WasmOptions {
1379            width,
1380            height,
1381            ..WasmOptions::default()
1382        },
1383        app,
1384    )
1385}
1386
1387/// Mount a browser application with explicit mount-time configuration.
1388///
1389/// Every rendered frame starts with a fresh live buffer. Direct
1390/// `DomBackend::buffer_mut`/`flush` users keep incremental drawing semantics.
1391/// The host is not owned: disposal retains its content and last rendered grid.
1392/// A detached host keeps running until disposal, drop, quit, or failure.
1393///
1394/// # Errors
1395/// Returns an error for zero dimensions/FPS or unavailable browser resources.
1396pub fn run_wasm_with_options<F>(
1397    container: HtmlElement,
1398    options: WasmOptions,
1399    mut app: F,
1400) -> Result<WasmAppHandle, JsValue>
1401where
1402    F: FnMut(&mut Context) + 'static,
1403{
1404    let (width, height) = (options.width, options.height);
1405    if width == 0 || height == 0 || options.max_fps == Some(0) {
1406        return Err(JsValue::from_str(
1407            "grid dimensions and max_fps must be positive",
1408        ));
1409    }
1410    let window = web_sys::window().ok_or_else(|| JsValue::from_str("window unavailable"))?;
1411    // A disposed runtime deliberately leaves its last frame in place. A new
1412    // mount replaces that grid only, without deleting caller-owned children.
1413    if let Some(previous_grid) = container.query_selector("pre[data-slt-grid]")? {
1414        previous_grid.remove();
1415    }
1416    let mut backend = DomBackend::new(container.clone(), width, height);
1417    backend
1418        .initialize_grid()
1419        .map_err(|e| JsValue::from_str(&e.to_string()))?;
1420    if options.auto_fit
1421        && let Some((cols, rows)) = backend.fit_grid_to_container()
1422    {
1423        backend.resize(cols, rows);
1424        if !backend.initialized {
1425            backend
1426                .initialize_grid()
1427                .map_err(|e| JsValue::from_str(&e.to_string()))?;
1428        }
1429    }
1430    let geometry = Rc::new(RefCell::new(GridGeometry {
1431        grid: backend
1432            .grid
1433            .clone()
1434            .ok_or_else(|| JsValue::from_str("grid unavailable"))?,
1435        width: backend.width,
1436        height: backend.height,
1437    }));
1438    let events = Rc::new(RefCell::new(Vec::new()));
1439    let inner = Rc::new(RefCell::new(WasmAppInner::new(
1440        window.clone(),
1441        container.clone(),
1442        Rc::clone(&events),
1443    )));
1444    let handle = WasmAppHandle::new(Rc::clone(&inner));
1445    let running = Rc::clone(&inner.borrow().input_active);
1446    if options.input {
1447        if !container.has_attribute("tabindex") {
1448            container.set_tab_index(0);
1449            inner.borrow_mut().added_tab_stop = true;
1450        }
1451        let document = container
1452            .owner_document()
1453            .ok_or_else(|| JsValue::from_str("document unavailable"))?;
1454        let input = document
1455            .create_element("textarea")?
1456            .dyn_into::<HtmlTextAreaElement>()?;
1457        input.set_attribute("data-slt-input", "")?;
1458        input.set_attribute("aria-label", "Terminal input")?;
1459        input.set_attribute("autocapitalize", "off")?;
1460        input.set_attribute("autocomplete", "off")?;
1461        input.set_attribute("spellcheck", "false")?;
1462        input.set_attribute("style", "position:absolute;left:0;top:0;width:100%;height:100%;z-index:1;opacity:0.01;background:transparent;color:transparent;caret-color:transparent;outline:none;padding:0;margin:0;border:0;box-sizing:border-box;resize:none;overflow:hidden;pointer-events:auto;font:14px/16px monospace;white-space:pre;")?;
1463        input.set_tab_index(-1);
1464        let grid = geometry.borrow().grid.clone();
1465        let preedit = Rc::new(Preedit::new(
1466            grid.clone(),
1467            options.theme.text,
1468            options.theme.bg,
1469            Rc::downgrade(&inner),
1470        )?);
1471        let surface = InputSurface {
1472            sink: input.clone(),
1473            preedit,
1474        };
1475        inner.borrow_mut().input = Some(surface.clone());
1476        grid.append_child(&input)?;
1477        grid.append_child(&surface.preedit.element)?;
1478        let listeners = install_event_listeners(
1479            &container,
1480            &surface,
1481            &window,
1482            Rc::clone(&geometry),
1483            Rc::clone(&events),
1484            Rc::clone(&inner.borrow().pointer),
1485            Rc::clone(&running),
1486        )?;
1487        inner.borrow_mut().listeners = listeners;
1488    }
1489    let resize_pending = Rc::new(Cell::new(false));
1490    if options.auto_fit {
1491        let pending = Rc::clone(&resize_pending);
1492        let callback = Closure::wrap(Box::new(move || pending.set(true)) as Box<dyn FnMut()>);
1493        let observer = web_sys::ResizeObserver::new(callback.as_ref().unchecked_ref())?;
1494        observer.observe(&container);
1495        inner.borrow_mut().observer = Some(observer);
1496        inner.borrow_mut().observer_callback = Some(callback);
1497    }
1498    let mut config = RunConfig::default();
1499    config.theme = options.theme;
1500    config.widget_theme = options.widget_theme;
1501    config.scroll_speed = options.scroll_speed;
1502    config.handle_ctrl_c = false;
1503    let mut state = AppState::new();
1504    let mut last_frame = None;
1505    let mut last_input_cursor = None;
1506    let interval = options.max_fps.map(|fps| 1000.0 / fps as f64);
1507    let weak: Weak<RefCell<WasmAppInner>> = Rc::downgrade(&inner);
1508    let raf = Closure::wrap(Box::new(move |timestamp: f64| {
1509        let Some(inner) = weak.upgrade() else {
1510            return;
1511        };
1512        {
1513            let mut runtime = inner.borrow_mut();
1514            runtime.raf_id = None;
1515            if !runtime.running {
1516                running.set(false);
1517                return;
1518            }
1519        }
1520        if !frame_due(&mut last_frame, timestamp, interval) {
1521            if let Err(error) = schedule_raf(&inner) {
1522                fail_runtime(&inner, format!("{error:?}"));
1523            }
1524            return;
1525        }
1526        if resize_pending.replace(false)
1527            && let Some((cols, rows)) = backend.fit_grid_to_container()
1528            && backend.size() != (cols, rows)
1529        {
1530            backend.resize(cols, rows);
1531            events.borrow_mut().push(Event::Resize(cols, rows));
1532        }
1533        let frame_events = std::mem::take(&mut *events.borrow_mut());
1534        backend.buffer_mut().reset();
1535        let result = slt::frame_owned(&mut backend, &mut state, &config, frame_events, &mut app);
1536        if let Some(grid) = backend.grid.clone() {
1537            *geometry.borrow_mut() = GridGeometry {
1538                grid,
1539                width: backend.width,
1540                height: backend.height,
1541            };
1542        }
1543        let input = inner.borrow().input.clone();
1544        if let Some(surface) = input {
1545            surface.preedit.sync(&backend.buffer);
1546            let input = &surface.sink;
1547            let (x, y) = backend.buffer.cursor_position().unwrap_or((0, 0));
1548            // Paint and editing share local grid coordinates, so ancestor
1549            // transforms apply exactly once to both the overlay and IME caret.
1550            let cursor = (x, y, backend.width);
1551            if last_input_cursor != Some(cursor) {
1552                let _ = input.style().set_property(
1553                    "padding-left",
1554                    &format!("{}%", x as f64 * 100.0 / backend.width as f64),
1555                );
1556                let _ = input
1557                    .style()
1558                    .set_property("padding-top", &format!("{}px", y * 16));
1559                last_input_cursor = Some(cursor);
1560            }
1561        }
1562        match result {
1563            Ok(true) if inner.borrow().running => {
1564                if let Err(error) = schedule_raf(&inner) {
1565                    fail_runtime(&inner, format!("{error:?}"));
1566                }
1567            }
1568            Ok(_) => {
1569                running.set(false);
1570                dispose_inner_now(&inner);
1571            }
1572            Err(error) => {
1573                running.set(false);
1574                fail_runtime(&inner, error.to_string());
1575            }
1576        }
1577    }) as Box<dyn FnMut(f64)>);
1578    let weak = Rc::downgrade(&inner);
1579    let failed = Closure::wrap(Box::new(move |message: String| {
1580        if let Some(inner) = weak.upgrade() {
1581            fail_runtime(
1582                &inner,
1583                format!("fatal browser frame: {message}; discard this WASM instance"),
1584            );
1585        }
1586    }) as Box<dyn FnMut(String)>);
1587    let guarded = guarded_frame(
1588        raf.as_ref().unchecked_ref(),
1589        failed.as_ref().unchecked_ref(),
1590    );
1591    {
1592        let mut runtime = inner.borrow_mut();
1593        runtime.raf = Some(raf);
1594        runtime.guarded_raf = Some(guarded);
1595        runtime.failure_callback = Some(failed);
1596    }
1597    schedule_raf(&inner)?;
1598    Ok(handle)
1599}
1600
1601fn frame_due(last: &mut Option<f64>, timestamp: f64, interval: Option<f64>) -> bool {
1602    if let (Some(previous), Some(interval)) = (*last, interval) {
1603        if timestamp >= previous && timestamp - previous + 0.01 < interval {
1604            return false;
1605        }
1606        // Retain fractional RAF remainder; do not catch up a suspended tab.
1607        *last = Some(if timestamp - previous < interval * 2.0 {
1608            previous + interval
1609        } else {
1610            timestamp
1611        });
1612    } else {
1613        *last = Some(timestamp);
1614    }
1615    true
1616}
1617
1618/// Mount `app` into `container` and run it until it requests exit.
1619///
1620/// This compatibility API preserves the original fire-and-forget behavior by
1621/// storing the owned [`WasmAppHandle`] internally. New integrations that need
1622/// explicit unmount/dispose control should prefer [`run_wasm_with_handle`].
1623///
1624/// # Errors
1625///
1626/// Returns a [`JsValue`] error when the `window` is unavailable, a listener
1627/// fails to install, or the initial frame cannot be scheduled.
1628pub fn run_wasm<F>(container: HtmlElement, width: u32, height: u32, app: F) -> Result<(), JsValue>
1629where
1630    F: FnMut(&mut Context) + 'static,
1631{
1632    let handle = run_wasm_with_handle(container, width, height, app)?;
1633    ACTIVE_APPS.with(|apps| {
1634        let mut apps = apps.borrow_mut();
1635        apps.retain(WasmAppHandle::is_running);
1636        apps.push(handle);
1637    });
1638    Ok(())
1639}
1640
1641/// `wasm-bindgen` entry point that mounts an empty SLT app into `container`.
1642///
1643/// Thin wrapper over [`run_wasm`] with a no-op closure, exported to JS so the
1644/// browser harness can smoke-test the backend wiring. Errors are dropped.
1645#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
1646pub fn run_wasm_raw(container: HtmlElement, width: u32, height: u32) {
1647    let _ = run_wasm(container, width, height, |_ui| {});
1648}
1649
1650/// `wasm-bindgen` entry point that mounts an empty SLT app and returns a
1651/// disposable handle.
1652///
1653/// This is the JS-friendly counterpart to [`run_wasm_with_handle`] for browser
1654/// harnesses that want to unmount the backend explicitly.
1655///
1656/// # Errors
1657///
1658/// Returns a [`JsValue`] error when mounting the empty app fails.
1659#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
1660pub fn run_wasm_raw_handle(
1661    container: HtmlElement,
1662    width: u32,
1663    height: u32,
1664) -> Result<WasmAppHandle, JsValue> {
1665    run_wasm_with_handle(container, width, height, |_ui| {})
1666}
1667
1668#[cfg(test)]
1669mod tests {
1670    //! Logic-level tests for the DOM backend's pure helpers. The DOM-touching
1671    //! paths (`DomBackend`, the event listeners) require a browser and are
1672    //! exercised via the example harness; these cover the platform-independent
1673    //! translation logic that runs on the host.
1674    use super::*;
1675
1676    #[test]
1677    fn wheel_vertical_maps_to_scroll_up_down() {
1678        // Negative deltaY scrolls up, positive scrolls down (crossterm parity).
1679        assert_eq!(wheel_delta_to_kind(0.0, -1.0), Some(MouseKind::ScrollUp));
1680        assert_eq!(wheel_delta_to_kind(0.0, 1.0), Some(MouseKind::ScrollDown));
1681    }
1682
1683    #[test]
1684    fn wheel_horizontal_maps_to_scroll_left_right() {
1685        assert_eq!(wheel_delta_to_kind(-3.0, 0.0), Some(MouseKind::ScrollLeft));
1686        assert_eq!(wheel_delta_to_kind(3.0, 0.0), Some(MouseKind::ScrollRight));
1687    }
1688
1689    #[test]
1690    fn wheel_dominant_axis_wins() {
1691        // A mostly-vertical diagonal gesture resolves to vertical scroll.
1692        assert_eq!(wheel_delta_to_kind(2.0, 10.0), Some(MouseKind::ScrollDown));
1693        // A mostly-horizontal diagonal gesture resolves to horizontal scroll.
1694        assert_eq!(wheel_delta_to_kind(-10.0, 2.0), Some(MouseKind::ScrollLeft));
1695    }
1696
1697    #[test]
1698    fn wheel_zero_delta_is_ignored() {
1699        // Edge case: a wheel event with no movement must not enqueue a scroll.
1700        assert_eq!(wheel_delta_to_kind(0.0, 0.0), None);
1701    }
1702
1703    #[test]
1704    fn wheel_ties_prefer_vertical() {
1705        // Equal magnitudes (|dy| >= |dx|) resolve to the vertical axis.
1706        assert_eq!(wheel_delta_to_kind(5.0, 5.0), Some(MouseKind::ScrollDown));
1707        assert_eq!(wheel_delta_to_kind(5.0, -5.0), Some(MouseKind::ScrollUp));
1708    }
1709
1710    #[test]
1711    fn rgb_color_renders_as_hex() {
1712        assert_eq!(
1713            color_to_css(Some(Color::Rgb(0x12, 0x34, 0x56))),
1714            Some("#123456".to_string())
1715        );
1716    }
1717
1718    #[test]
1719    fn reset_color_is_transparent() {
1720        assert_eq!(color_to_css(Some(Color::Reset)), None);
1721        assert_eq!(color_to_css(None), None);
1722    }
1723
1724    #[test]
1725    fn indexed_color_cube_and_grayscale() {
1726        // 16-color base, the 6x6x6 cube, and the grayscale ramp must all map.
1727        assert_eq!(indexed_to_rgb(0), (0, 0, 0));
1728        assert_eq!(indexed_to_rgb(15), (255, 255, 255));
1729        assert_eq!(indexed_to_rgb(16), (0, 0, 0)); // cube origin
1730        assert_eq!(indexed_to_rgb(231), (255, 255, 255)); // cube far corner
1731        assert_eq!(indexed_to_rgb(232), (8, 8, 8)); // grayscale start
1732        assert_eq!(indexed_to_rgb(255), (238, 238, 238)); // grayscale end
1733    }
1734
1735    #[test]
1736    fn style_css_includes_modifiers() {
1737        let style = slt::Style::new()
1738            .fg(Color::Red)
1739            .bg(Color::Black)
1740            .bold()
1741            .underline();
1742        let css = style_to_css(style);
1743        assert!(css.contains("color:#cd3131;"));
1744        assert!(css.contains("background-color:#000000;"));
1745        assert!(css.contains("font-weight:bold;"));
1746        assert!(css.contains("text-decoration-line:underline;"));
1747    }
1748
1749    #[test]
1750    fn style_css_combines_text_decorations() {
1751        let style = slt::Style::new().underline().strikethrough();
1752        let css = style_to_css(style);
1753        assert!(css.contains("text-decoration-line:underline line-through;"));
1754        assert!(!css.contains("text-decoration:underline;"));
1755        assert!(!css.contains("text-decoration:line-through;"));
1756    }
1757
1758    #[test]
1759    fn dom_modifier_bits_match_slt_modifiers() {
1760        let modifiers = modifiers_from_bools(true, true, true, true);
1761        assert!(modifiers.contains(KeyModifiers::SHIFT));
1762        assert!(modifiers.contains(KeyModifiers::CONTROL));
1763        assert!(modifiers.contains(KeyModifiers::ALT));
1764        assert!(modifiers.contains(KeyModifiers::SUPER));
1765
1766        assert_eq!(
1767            modifiers_from_bools(false, false, false, false),
1768            KeyModifiers::NONE
1769        );
1770    }
1771
1772    #[test]
1773    fn default_style_emits_no_css() {
1774        // Edge case: a plain default style produces no inline CSS at all.
1775        assert_eq!(style_to_css(slt::Style::new()), "");
1776    }
1777
1778    #[test]
1779    fn pacing_caps_high_refresh_without_losing_fractional_remainder() {
1780        for refresh in [60, 120, 144] {
1781            let mut last = None;
1782            let frames = (0..refresh)
1783                .filter(|n| {
1784                    frame_due(
1785                        &mut last,
1786                        *n as f64 * 1000.0 / refresh as f64,
1787                        Some(1000.0 / 60.0),
1788                    )
1789                })
1790                .count();
1791            assert_eq!(frames, 60, "refresh rate {refresh}");
1792        }
1793    }
1794
1795    #[test]
1796    fn pacing_handles_uncapped_suspension_and_timestamp_reset() {
1797        let mut last = None;
1798        assert!(frame_due(&mut last, 0.0, Some(50.0)));
1799        assert!(!frame_due(&mut last, 49.0, Some(50.0)));
1800        assert!(frame_due(&mut last, 50.0, Some(50.0)));
1801        assert!(frame_due(&mut last, 10_000.0, Some(50.0)));
1802        assert!(!frame_due(&mut last, 10_001.0, Some(50.0)));
1803        assert!(frame_due(&mut last, 0.0, Some(50.0)));
1804        assert!(frame_due(&mut last, 1.0, None));
1805        assert!(frame_due(&mut last, 2.0, None));
1806        assert_eq!(WasmOptions::default().max_fps, Some(60));
1807    }
1808}
1809
1810#[cfg(all(test, target_arch = "wasm32"))]
1811mod browser_tests {
1812    use super::*;
1813    use wasm_bindgen_test::wasm_bindgen_test;
1814
1815    wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
1816
1817    fn test_container() -> HtmlElement {
1818        let document = web_sys::window()
1819            .and_then(|window| window.document())
1820            .expect("browser document");
1821        let container = document
1822            .create_element("div")
1823            .expect("create test container")
1824            .dyn_into::<HtmlElement>()
1825            .expect("container is HtmlElement");
1826        document
1827            .body()
1828            .expect("document body")
1829            .append_child(&container)
1830            .expect("append test container");
1831        container
1832    }
1833
1834    #[wasm_bindgen_test]
1835    fn dom_backend_flush_builds_grid_and_updates_text() {
1836        let container = test_container();
1837        let mut backend = DomBackend::new(container.clone(), 4, 1);
1838        backend
1839            .buffer_mut()
1840            .set_string(0, 0, "SLT", slt::Style::new().fg(Color::Red));
1841
1842        backend.flush().expect("flush DOM backend");
1843
1844        assert!(container.inner_html().contains("<pre"));
1845        assert_eq!(container.text_content().as_deref(), Some("SLT "));
1846        container.remove();
1847    }
1848
1849    #[wasm_bindgen_test]
1850    fn run_wasm_handle_mounts_and_disposes_runtime() {
1851        let container = test_container();
1852        let handle = run_wasm_raw_handle(container.clone(), 4, 1).expect("mount wasm runtime");
1853
1854        assert!(handle.is_running());
1855        handle.dispose();
1856        assert!(!handle.is_running());
1857        container.remove();
1858    }
1859}