ratzilla 0.3.1

Build terminal-themed web applications with Ratatui and WebAssembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use std::{
    cell::RefCell,
    io::{Error as IoError, Result as IoResult},
    rc::Rc,
};

use ratatui::{
    backend::WindowSize,
    buffer::Cell,
    layout::{Position, Size},
    prelude::{backend::ClearType, Backend},
};
use web_sys::{window, Document, Element};

use unicode_width::UnicodeWidthStr;

use crate::{
    backend::{
        cell_sized::CellSized,
        event_callback::{
            create_mouse_event, EventCallback, MouseConfig, KEY_EVENT_TYPES, MOUSE_EVENT_TYPES,
        },
        utils::*,
    },
    error::Error,
    event::{KeyEvent, MouseEvent},
    render::WebEventHandler,
    CursorShape,
};

/// Default cell size used as a fallback when measurement fails.
const DEFAULT_CELL_SIZE: (f64, f64) = (10.0, 20.0);

/// Options for the [`DomBackend`].
#[derive(Debug, Default)]
pub struct DomBackendOptions {
    /// The element ID.
    grid_id: Option<String>,
    /// The cursor shape.
    cursor_shape: CursorShape,
}

impl DomBackendOptions {
    /// Constructs a new [`DomBackendOptions`].
    pub fn new(grid_id: Option<String>, cursor_shape: CursorShape) -> Self {
        Self {
            grid_id,
            cursor_shape,
        }
    }

    /// Returns the grid ID.
    ///
    /// - If the grid ID is not set, it returns `"grid"`.
    /// - If the grid ID is set, it returns the grid ID suffixed with
    ///     `"_ratzilla_grid"`.
    pub fn grid_id(&self) -> String {
        match &self.grid_id {
            Some(id) => format!("{id}_ratzilla_grid"),
            None => "grid".to_string(),
        }
    }

    /// Returns the [`CursorShape`].
    pub fn cursor_shape(&self) -> &CursorShape {
        &self.cursor_shape
    }
}

/// DOM backend.
///
/// This backend uses the DOM to render the content to the screen.
///
/// In other words, it transforms the [`Cell`]s into `<span>`s which are then
/// appended to a `<pre>` element.
pub struct DomBackend {
    /// Whether the backend has been initialized.
    initialized: Rc<RefCell<bool>>,
    /// Cells.
    cells: Vec<Element>,
    /// Grid element.
    grid: Element,
    /// The parent of the grid element.
    grid_parent: Element,
    /// Document.
    document: Document,
    /// Options.
    options: DomBackendOptions,
    /// Cursor position.
    cursor_position: Option<Position>,
    /// Last Cursor position.
    last_cursor_position: Option<Position>,
    /// Buffer size to pass to [`ratatui::Terminal`]
    size: Size,
    /// Measured cell dimensions in pixels (width, height).
    cell_size: (f64, f64),
    /// Resize event callback handler.
    _resize_callback: EventCallback<web_sys::Event>,
    /// Mouse event callback handler.
    mouse_callback: Option<DomMouseCallbackState>,
    /// Key event callback handler.
    key_callback: Option<EventCallback<web_sys::KeyboardEvent>>,
}

/// Type alias for mouse event callback state.
type DomMouseCallbackState = EventCallback<web_sys::MouseEvent>;

impl std::fmt::Debug for DomBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DomBackend")
            .field("initialized", &self.initialized)
            .field("cells", &format!("[{} cells]", self.cells.len()))
            .field("size", &self.size)
            .field("cell_size", &self.cell_size)
            .field("cursor_position", &self.cursor_position)
            .field("resize_callback", &"...")
            .field("mouse_callback", &self.mouse_callback.is_some())
            .field("key_callback", &self.key_callback.is_some())
            .finish()
    }
}

impl DomBackend {
    /// Constructs a new [`DomBackend`].
    pub fn new() -> Result<Self, Error> {
        Self::new_with_options(DomBackendOptions::default())
    }

    /// Constructs a new [`DomBackend`] and uses the given element ID for the grid.
    pub fn new_by_id(id: &str) -> Result<Self, Error> {
        Self::new_with_options(DomBackendOptions::new(
            Some(id.to_string()),
            CursorShape::default(),
        ))
    }

    /// Set the [`CursorShape`].
    pub fn set_cursor_shape(mut self, shape: CursorShape) -> Self {
        self.options.cursor_shape = shape;
        self
    }

    /// Constructs a new [`DomBackend`] with the given options.
    pub fn new_with_options(options: DomBackendOptions) -> Result<Self, Error> {
        let window = window().ok_or(Error::UnableToRetrieveWindow)?;
        let document = window.document().ok_or(Error::UnableToRetrieveDocument)?;
        let grid_parent = get_element_by_id_or_body(options.grid_id.as_ref())?;
        let cell_size =
            Self::measure_cell_size(&document, &grid_parent).unwrap_or(DEFAULT_CELL_SIZE);
        let size = Self::calculate_size(&grid_parent, cell_size);

        let initialized = Rc::new(RefCell::new(false));
        let initialized_cb = initialized.clone();
        let resize_callback = EventCallback::new(
            window.clone(),
            Self::RESIZE_EVENT_TYPES,
            move |_: web_sys::Event| {
                initialized_cb.replace(false);
            },
        )?;

        let mut backend = Self {
            initialized,
            cells: vec![],
            grid: document.create_element("div")?,
            grid_parent,
            options,
            document,
            cursor_position: None,
            last_cursor_position: None,
            size,
            cell_size,
            _resize_callback: resize_callback,
            mouse_callback: None,
            key_callback: None,
        };
        backend.reset_grid()?;
        Ok(backend)
    }

    /// Measures the pixel dimensions of a single terminal cell.
    ///
    /// Creates a temporary `<pre><span>` probe element that inherits the
    /// page's CSS (font-family, font-size, etc.), measures it with
    /// `getBoundingClientRect()`, then removes the probe.
    fn measure_cell_size(document: &Document, parent: &Element) -> Result<(f64, f64), Error> {
        let pre = document.create_element("pre")?;
        pre.set_attribute(
            "style",
            "margin: 0; padding: 0; border: 0; line-height: normal;",
        )?;
        let span = document.create_element("span")?;
        span.set_inner_html("\u{2588}");
        span.set_attribute("style", "display: inline-block; width: 1ch;")?;
        pre.append_child(&span)?;
        parent.append_child(&pre)?;

        let rect = span.get_bounding_client_rect();
        let width = rect.width();
        let height = rect.height();

        parent.remove_child(&pre)?;

        if width > 0.0 && height > 0.0 {
            Ok((width, height))
        } else {
            Ok(DEFAULT_CELL_SIZE)
        }
    }

    /// Calculates the grid size in cells based on the parent element's dimensions and cell size.
    fn calculate_size(parent: &Element, cell_size: (f64, f64)) -> Size {
        let rect = parent.get_bounding_client_rect();
        let (parent_w, parent_h) = (rect.width(), rect.height());

        // Fall back to window dimensions if the parent has no size
        // (e.g. empty <body> with no explicit height)
        let (w, h) = if parent_w > 0.0 && parent_h > 0.0 {
            (parent_w, parent_h)
        } else {
            let (ww, wh) = get_raw_window_size();
            (ww as f64, wh as f64)
        };

        Size::new((w / cell_size.0) as u16, (h / cell_size.1) as u16)
    }

    /// Resize event types.
    const RESIZE_EVENT_TYPES: &[&str] = &["resize"];

    /// Reset the grid and clear the cells.
    fn reset_grid(&mut self) -> Result<(), Error> {
        self.grid = self.document.create_element("div")?;
        self.grid.set_attribute("id", &self.options.grid_id())?;
        self.cells.clear();
        Ok(())
    }

    /// Pre-render a blank content to the screen.
    ///
    /// This function is called from [`draw`] once (or after a resize)
    /// to render the right number of cells to the screen.
    fn populate(&mut self) -> Result<(), Error> {
        for _y in 0..self.size.height {
            let mut line_cells: Vec<Element> = Vec::new();
            for _x in 0..self.size.width {
                let span = create_span(&self.document, &Cell::default())?;
                self.cells.push(span.clone());
                line_cells.push(span);
            }

            // Create a <pre> element for the line
            let pre = self.document.create_element("pre")?;
            let line_height = format!("height: {}px;", self.cell_size.1);
            pre.set_attribute("style", &line_height)?;

            // Append all elements (spans and anchors) to the <pre>
            for elem in line_cells {
                pre.append_child(&elem)?;
            }

            // Append the <pre> to the grid
            self.grid.append_child(&pre)?;
        }
        Ok(())
    }
}

impl CellSized for DomBackend {
    fn cell_size_px(&self) -> (f32, f32) {
        let dpr = get_device_pixel_ratio();
        (self.cell_size.0 as f32 * dpr, self.cell_size.1 as f32 * dpr)
    }

    fn cell_size_css_px(&self) -> (f32, f32) {
        (self.cell_size.0 as f32, self.cell_size.1 as f32)
    }
}

impl Backend for DomBackend {
    type Error = IoError;

    /// Draw the new content to the screen.
    ///
    /// This function is called in the [`ratatui::Terminal::flush`] function.
    /// This function recreate the DOM structure when it gets a resize event.
    fn draw<'a, I>(&mut self, content: I) -> IoResult<()>
    where
        I: Iterator<Item = (u16, u16, &'a Cell)>,
    {
        if !*self.initialized.borrow() {
            self.initialized.replace(true);

            // Clear cursor position to avoid modifying css style of a non-existent cell
            self.cursor_position = None;
            self.last_cursor_position = None;

            // Only runs on resize event.
            if self
                .document
                .get_element_by_id(&self.options.grid_id())
                .is_some()
            {
                self.grid_parent.set_inner_html("");
                self.reset_grid()?;

                // re-measure cell size and update grid dimensions
                self.cell_size = Self::measure_cell_size(&self.document, &self.grid_parent)
                    .unwrap_or(DEFAULT_CELL_SIZE);
                self.size = Self::calculate_size(&self.grid_parent, self.cell_size);
            }

            self.grid_parent
                .append_child(&self.grid)
                .map_err(Error::from)?;
            self.populate()?;
        }

        for (x, y, cell) in content {
            let cell_position = (y * self.size.width + x) as usize;
            let elem = &self.cells[cell_position];

            elem.set_inner_html(cell.symbol());
            elem.set_attribute("style", &get_cell_style_as_css(cell))
                .map_err(Error::from)?;

            // don't display the next cell if a fullwidth glyph preceeds it
            if cell.symbol().len() > 1 && cell.symbol().width() == 2 {
                if (cell_position + 1) < self.cells.len() {
                    let next_elem = &self.cells[cell_position + 1];
                    next_elem.set_inner_html("");
                    next_elem
                        .set_attribute("style", &get_cell_style_as_css(&Cell::new("")))
                        .map_err(Error::from)?;
                }
            }
        }

        Ok(())
    }

    /// This function is called after the [`DomBackend::draw`] function.
    ///
    /// This function does nothing because the content is directly
    /// displayed by the draw function.
    fn flush(&mut self) -> IoResult<()> {
        Ok(())
    }

    fn hide_cursor(&mut self) -> IoResult<()> {
        if let Some(pos) = self.cursor_position {
            let cell_position = (pos.y * self.size.width + pos.x) as usize;

            // Use CursorShape::None to clear cursor CSS
            update_css_field(
                CursorShape::None.get_css_attribute(),
                &self.cells[cell_position],
            )
            .map_err(Error::from)?;
        }

        Ok(())
    }

    fn show_cursor(&mut self) -> IoResult<()> {
        // Remove cursor at last position
        if let Some(pos) = self.last_cursor_position {
            let cell_position = (pos.y * self.size.width + pos.x) as usize;
            update_css_field(
                CursorShape::None.get_css_attribute(),
                &self.cells[cell_position],
            )
            .map_err(Error::from)?;
        }

        // Show cursor at current position
        if let Some(pos) = self.cursor_position {
            let cell_position = (pos.y * self.size.width + pos.x) as usize;

            update_css_field(
                self.options.cursor_shape.get_css_attribute(),
                &self.cells[cell_position],
            )
            .map_err(Error::from)?;
        }

        Ok(())
    }

    fn get_cursor(&mut self) -> IoResult<(u16, u16)> {
        Ok((0, 0))
    }

    fn set_cursor(&mut self, _x: u16, _y: u16) -> IoResult<()> {
        Ok(())
    }

    fn clear(&mut self) -> IoResult<()> {
        Ok(())
    }

    fn size(&self) -> IoResult<Size> {
        let size = get_size();
        Ok(Size::new(
            size.width.saturating_sub(1),
            size.height.saturating_sub(1),
        ))
    }

    fn window_size(&mut self) -> IoResult<WindowSize> {
        Ok(WindowSize {
            columns_rows: self.size,
            pixels: Size::new(
                (self.size.width as f64 * self.cell_size.0) as u16,
                (self.size.height as f64 * self.cell_size.1) as u16,
            ),
        })
    }

    fn get_cursor_position(&mut self) -> IoResult<Position> {
        match self.cursor_position {
            None => Ok((0, 0).into()),
            Some(position) => Ok(position),
        }
    }

    /// Update cursor_position and last_cursor_position
    fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> IoResult<()> {
        self.last_cursor_position = self.cursor_position;
        self.cursor_position = Some(position.into());

        Ok(())
    }

    fn clear_region(&mut self, clear_type: ClearType) -> Result<(), Self::Error> {
        match clear_type {
            ClearType::All => self.clear(),
            _ => Err(IoError::other("unimplemented")),
        }
    }
}

impl WebEventHandler for DomBackend {
    fn on_mouse_event<F>(&mut self, mut callback: F) -> Result<(), Error>
    where
        F: FnMut(MouseEvent) + 'static,
    {
        // Clear any existing handlers first
        self.clear_mouse_events();

        // Configure coordinate translation for DOM backend
        // Cell dimensions are derived from element dimensions / grid size
        let config = MouseConfig::new(self.size.width, self.size.height);

        // Use the grid element for coordinate calculation
        let element = self.grid.clone();

        // Create mouse event callback
        let mouse_callback = EventCallback::new(
            self.grid.clone(),
            MOUSE_EVENT_TYPES,
            move |event: web_sys::MouseEvent| {
                let mouse_event = create_mouse_event(&event, &element, &config);
                callback(mouse_event);
            },
        )?;

        self.mouse_callback = Some(mouse_callback);

        Ok(())
    }

    fn clear_mouse_events(&mut self) {
        self.mouse_callback = None;
    }

    fn on_key_event<F>(&mut self, mut callback: F) -> Result<(), Error>
    where
        F: FnMut(KeyEvent) + 'static,
    {
        // Clear any existing handlers first
        self.clear_key_events();

        // Make the grid element focusable so it can receive key events
        self.grid.set_attribute("tabindex", "0")?;

        self.key_callback = Some(EventCallback::new(
            self.grid.clone(),
            KEY_EVENT_TYPES,
            move |event: web_sys::KeyboardEvent| {
                callback(event.into());
            },
        )?);

        Ok(())
    }

    fn clear_key_events(&mut self) {
        self.key_callback = None;
    }
}