Skip to main content

ftui_web/
lib.rs

1#![forbid(unsafe_code)]
2
3//! `ftui-web` provides a WASM-friendly backend implementation for FrankenTUI.
4//!
5//! Design goals:
6//! - **Host-driven I/O**: the embedding environment (JS) pushes input events and size changes.
7//! - **Deterministic time**: the host advances a monotonic clock explicitly.
8//! - **No blocking / no threads**: suitable for `wasm32-unknown-unknown`.
9//!
10//! This crate intentionally does not bind to `wasm-bindgen` yet. The primary
11//! purpose is to provide backend building blocks that `frankenterm-web` can
12//! wrap with a stable JS API.
13
14#[cfg(feature = "input-parser")]
15pub mod input_parser;
16pub mod pane_keyboard;
17pub mod pane_pointer_capture;
18pub mod release_readiness;
19pub mod runtime_options;
20pub mod sdk_adapter;
21pub mod sdk_event_model;
22pub mod session_record;
23pub mod step_program;
24
25/// Curated web-host pane surface (bd-zpnp5).
26///
27/// **Decision:** `ftui-web` is the canonical import path for the pane web
28/// adapters; the terminal-oriented `ftui::pane` facade deliberately does NOT
29/// re-export them. Each host crate curates its own pane surface — this module
30/// mirrors the shape of `ftui::pane::keyboard` for the web host — and
31/// cross-host behavioral alignment is guaranteed by the parity contract
32/// (`docs/spec/pane-parity-contract-and-program.md`) plus the
33/// `pane_cross_host_parity` suite, not by a unified import path. Rationale
34/// and the supported-surface listing live in
35/// `docs/api/pane-stability-contract.md` (§ Web host surface).
36pub mod pane {
37    /// Pointer capture: browser pointer events → pane drag/resize semantics.
38    pub mod pointer {
39        pub use crate::pane_pointer_capture::{
40            PanePointerCaptureAdapter, PanePointerCaptureCommand, PanePointerCaptureConfig,
41            PanePointerDispatch, PanePointerIgnoredReason, PanePointerLifecyclePhase,
42            PanePointerLogEntry, PanePointerLogOutcome,
43        };
44    }
45
46    /// Browser-safe keyboard bindings + accessibility tree projection.
47    pub mod keyboard {
48        pub use crate::pane_keyboard::{
49            PaneAriaNode, PaneAriaOrientation, PaneAriaRole, PaneWebKeyOutcome,
50            PaneWebKeyboardController, key_to_pane_command, pane_accessibility_tree,
51        };
52    }
53}
54
55use core::time::Duration;
56use std::collections::VecDeque;
57
58use ftui_backend::{
59    Backend, BackendClock, BackendEventSource, BackendFeatures, BackendPresenter, ScreenMode,
60};
61use ftui_core::event::Event;
62use ftui_core::terminal_capabilities::TerminalCapabilities;
63use ftui_render::buffer::Buffer;
64use ftui_render::cell::{Cell, CellAttrs, CellContent};
65use ftui_render::diff::BufferDiff;
66use ftui_render::grapheme_pool::GraphemePool;
67use ftui_render::link_registry::LinkRegistry;
68
69const GRAPHEME_FALLBACK_CODEPOINT: u32 = '□' as u32;
70const ATTR_STYLE_MASK: u32 = 0xFF;
71const ATTR_LINK_ID_MAX: u32 = CellAttrs::LINK_ID_MAX;
72const WEB_PATCH_CELL_BYTES: u64 = 16;
73const PATCH_HASH_ALGO: &str = "fnv1a64";
74const FNV64_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
75const FNV64_PRIME: u64 = 0x100000001b3;
76
77/// Web backend error type.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum WebBackendError {
80    /// Generic unsupported operation.
81    Unsupported(&'static str),
82    /// Input was rejected before admission. The caller retains ownership of
83    /// the event and can retry after draining the queue.
84    InputQueueFull {
85        /// Which bound prevented admission.
86        limit: WebInputLimit,
87        /// The event that was not accepted.
88        event: Event,
89    },
90}
91
92/// Resource bound enforced by the host-driven input queue.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum WebInputLimit {
95    /// The pending event count reached its bound.
96    Events,
97    /// Retained paste, IME and clipboard allocations would exceed the byte bound.
98    PayloadBytes,
99}
100
101impl core::fmt::Display for WebBackendError {
102    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
103        match self {
104            Self::Unsupported(msg) => write!(f, "unsupported: {msg}"),
105            Self::InputQueueFull { limit, .. } => {
106                write!(f, "input queue full ({limit:?}); drain before retrying")
107            }
108        }
109    }
110}
111
112impl std::error::Error for WebBackendError {}
113
114/// Deterministic monotonic clock controlled by the host.
115#[derive(Debug, Default, Clone)]
116pub struct DeterministicClock {
117    now: Duration,
118}
119
120impl DeterministicClock {
121    /// Create a clock starting at `0`.
122    #[must_use]
123    pub const fn new() -> Self {
124        Self {
125            now: Duration::ZERO,
126        }
127    }
128
129    /// Set current monotonic time.
130    pub fn set(&mut self, now: Duration) {
131        self.now = now;
132    }
133
134    /// Advance monotonic time by `dt`.
135    pub fn advance(&mut self, dt: Duration) {
136        self.now = self.now.saturating_add(dt);
137    }
138}
139
140impl BackendClock for DeterministicClock {
141    fn now_mono(&self) -> Duration {
142        self.now
143    }
144}
145
146/// Host-driven event source for WASM.
147///
148/// The host is responsible for pushing [`Event`] values and updating size.
149#[derive(Debug)]
150pub struct WebEventSource {
151    size: (u16, u16),
152    features: BackendFeatures,
153    queue: VecDeque<Event>,
154    queued_payload_bytes: usize,
155}
156
157impl Clone for WebEventSource {
158    fn clone(&self) -> Self {
159        let queue = self.queue.clone();
160        // String::clone may reduce spare capacity; account for the allocations
161        // actually retained by the clone rather than copying the original sum.
162        let queued_payload_bytes = queue.iter().map(event_payload_bytes).sum();
163        Self {
164            size: self.size,
165            features: self.features,
166            queue,
167            queued_payload_bytes,
168        }
169    }
170}
171
172fn event_payload_bytes(event: &Event) -> usize {
173    match event {
174        Event::Paste(paste) => paste.text.capacity(),
175        Event::Ime(ime) => ime.text.capacity(),
176        Event::Clipboard(clipboard) => clipboard.content.capacity(),
177        Event::Key(_) | Event::Mouse(_) | Event::Resize { .. } | Event::Focus(_) | Event::Tick => 0,
178    }
179}
180
181impl WebEventSource {
182    /// Maximum pending events. Accepted input is never evicted to admit new input.
183    pub const MAX_EVENTS: usize = 4096;
184    /// Maximum retained payload allocation bytes (including String spare capacity).
185    pub const MAX_PAYLOAD_BYTES: usize = 1024 * 1024;
186
187    /// Create a new event source with an initial size.
188    #[must_use]
189    pub fn new(width: u16, height: u16) -> Self {
190        Self {
191            size: (width, height),
192            features: BackendFeatures::default(),
193            queue: VecDeque::new(),
194            queued_payload_bytes: 0,
195        }
196    }
197
198    /// Update the current size.
199    pub fn set_size(&mut self, width: u16, height: u16) {
200        self.size = (width, height);
201    }
202
203    /// Read back the currently requested backend features.
204    #[must_use]
205    pub const fn features(&self) -> BackendFeatures {
206        self.features
207    }
208
209    /// Admit a canonical event without evicting previously accepted input.
210    ///
211    /// On overflow, returns the rejected event. Drain pending events before
212    /// retrying; an oversized individual payload must be rejected by the host.
213    pub fn push_event(&mut self, event: Event) -> Result<(), WebBackendError> {
214        if self.queue.len() >= Self::MAX_EVENTS {
215            return Err(WebBackendError::InputQueueFull {
216                limit: WebInputLimit::Events,
217                event,
218            });
219        }
220        let payload_bytes = event_payload_bytes(&event);
221        if payload_bytes > Self::MAX_PAYLOAD_BYTES - self.queued_payload_bytes {
222            return Err(WebBackendError::InputQueueFull {
223                limit: WebInputLimit::PayloadBytes,
224                event,
225            });
226        }
227        self.queued_payload_bytes += payload_bytes;
228        self.queue.push_back(event);
229        Ok(())
230    }
231
232    /// Number of pending accepted events.
233    #[must_use]
234    pub fn queued_events(&self) -> usize {
235        self.queue.len()
236    }
237
238    /// Total allocation bytes retained by pending text payloads.
239    #[must_use]
240    pub const fn queued_payload_bytes(&self) -> usize {
241        self.queued_payload_bytes
242    }
243
244    fn pop_event(&mut self) -> Option<Event> {
245        let event = self.queue.pop_front()?;
246        self.queued_payload_bytes -= event_payload_bytes(&event);
247        Some(event)
248    }
249
250    /// Drain pending events in FIFO order. Dropping the iterator early leaves
251    /// unconsumed input queued for the next drain or read.
252    pub fn drain_events(&mut self) -> impl Iterator<Item = Event> + '_ {
253        std::iter::from_fn(|| self.pop_event())
254    }
255}
256
257impl BackendEventSource for WebEventSource {
258    type Error = WebBackendError;
259
260    fn size(&self) -> Result<(u16, u16), Self::Error> {
261        Ok(self.size)
262    }
263
264    fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
265        self.features = features;
266        Ok(())
267    }
268
269    fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
270        // WASM backend is host-driven; we never block.
271        let _ = timeout;
272        Ok(!self.queue.is_empty())
273    }
274
275    fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
276        Ok(self.pop_event())
277    }
278}
279
280/// Captured presentation outputs for host consumption.
281#[derive(Debug, Default, Clone)]
282pub struct WebOutputs {
283    /// Log lines written by the runtime.
284    pub logs: Vec<String>,
285    /// Last fully-rendered buffer presented.
286    pub last_buffer: Option<Buffer>,
287    /// Last emitted incremental/full patch runs in row-major order.
288    pub last_patches: Vec<WebPatchRun>,
289    /// Aggregate patch upload accounting for the last present.
290    pub last_patch_stats: Option<WebPatchStats>,
291    /// Deterministic hash of the last patch batch (lazy — computed on first read).
292    pub last_patch_hash: Option<String>,
293    /// Whether the last present requested a full repaint.
294    pub last_full_repaint_hint: bool,
295    /// Whether the hash has been computed for the current patches.
296    hash_computed: bool,
297}
298
299impl WebOutputs {
300    /// Compute and return the patch hash, caching the result.
301    ///
302    /// The hash is computed lazily on first call and cached for subsequent reads.
303    pub fn compute_patch_hash(&mut self) -> Option<&str> {
304        if !self.hash_computed && !self.last_patches.is_empty() {
305            self.last_patch_hash = Some(patch_batch_hash(&self.last_patches));
306            self.hash_computed = true;
307        }
308        self.last_patch_hash.as_deref()
309    }
310}
311
312impl WebOutputs {
313    /// Flatten patch runs for low-overhead JS/WASM bridge transport.
314    ///
315    /// Cells are emitted as a contiguous `u32` payload in:
316    /// `[bg, fg, glyph, attrs]` order. Spans are emitted as `u32` pairs:
317    /// `[offset, len, offset, len, ...]`.
318    #[must_use]
319    pub fn flatten_patches_u32(&self) -> WebFlatPatchBatch {
320        let total_cells = self
321            .last_patches
322            .iter()
323            .map(|patch| patch.cells.len())
324            .sum::<usize>();
325        let mut cells = Vec::with_capacity(total_cells.saturating_mul(4));
326        let mut spans = Vec::with_capacity(self.last_patches.len().saturating_mul(2));
327
328        for patch in &self.last_patches {
329            spans.push(patch.offset);
330            let len = patch.cells.len().min(u32::MAX as usize) as u32;
331            spans.push(len);
332
333            for cell in &patch.cells {
334                cells.push(cell.bg);
335                cells.push(cell.fg);
336                cells.push(cell.glyph);
337                cells.push(cell.attrs);
338            }
339        }
340
341        WebFlatPatchBatch { cells, spans }
342    }
343}
344
345/// One GPU patch cell payload (`bg`, `fg`, `glyph`, `attrs`) matching the
346/// `frankenterm-web` `applyPatch` schema.
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348pub struct WebPatchCell {
349    pub bg: u32,
350    pub fg: u32,
351    pub glyph: u32,
352    pub attrs: u32,
353}
354
355/// One contiguous run of changed cells starting at linear `offset`.
356#[derive(Debug, Clone, PartialEq, Eq)]
357pub struct WebPatchRun {
358    pub offset: u32,
359    pub cells: Vec<WebPatchCell>,
360}
361
362/// Compact, flat patch payload for JS/WASM transport.
363#[derive(Debug, Default, Clone, PartialEq, Eq)]
364pub struct WebFlatPatchBatch {
365    /// Cell payload in `[bg, fg, glyph, attrs]` order.
366    pub cells: Vec<u32>,
367    /// Span payload in `[offset, len, offset, len, ...]` order.
368    pub spans: Vec<u32>,
369}
370
371/// Aggregate patch-upload stats for host instrumentation and JSONL reporting.
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373pub struct WebPatchStats {
374    pub dirty_cells: u32,
375    pub patch_count: u32,
376    pub bytes_uploaded: u64,
377}
378
379/// WASM presenter that captures buffers and logs for the host.
380#[derive(Debug, Clone)]
381pub struct WebPresenter {
382    caps: TerminalCapabilities,
383    outputs: WebOutputs,
384    pool: GraphemePool,
385    links: LinkRegistry,
386    screen_mode: ScreenMode,
387    width: u16,
388    height: u16,
389}
390
391impl WebPresenter {
392    /// Create a new presenter with modern capabilities.
393    #[must_use]
394    pub fn new() -> Self {
395        Self {
396            caps: TerminalCapabilities::modern(),
397            outputs: WebOutputs::default(),
398            pool: GraphemePool::new(),
399            links: LinkRegistry::new(),
400            screen_mode: ScreenMode::default(),
401            width: 80,
402            height: 24,
403        }
404    }
405
406    /// Create a new presenter with explicit initial dimensions.
407    #[must_use]
408    pub fn with_size(width: u16, height: u16) -> Self {
409        Self {
410            caps: TerminalCapabilities::modern(),
411            outputs: WebOutputs::default(),
412            pool: GraphemePool::new(),
413            links: LinkRegistry::new(),
414            screen_mode: ScreenMode::default(),
415            width,
416            height,
417        }
418    }
419
420    /// Get captured outputs.
421    #[must_use]
422    pub const fn outputs(&self) -> &WebOutputs {
423        &self.outputs
424    }
425
426    /// Mutably access captured outputs.
427    pub fn outputs_mut(&mut self) -> &mut WebOutputs {
428        &mut self.outputs
429    }
430
431    /// Take captured outputs, leaving empty defaults.
432    pub fn take_outputs(&mut self) -> WebOutputs {
433        std::mem::take(&mut self.outputs)
434    }
435
436    /// Reference to the grapheme pool.
437    #[must_use]
438    pub const fn pool(&self) -> &GraphemePool {
439        &self.pool
440    }
441
442    /// Mutably access the grapheme pool.
443    pub fn pool_mut(&mut self) -> &mut GraphemePool {
444        &mut self.pool
445    }
446
447    /// Reference to the link registry.
448    #[must_use]
449    pub const fn links(&self) -> &LinkRegistry {
450        &self.links
451    }
452
453    /// Mutably access the link registry.
454    pub fn links_mut(&mut self) -> &mut LinkRegistry {
455        &mut self.links
456    }
457
458    /// Current width of the presenter.
459    #[must_use]
460    pub const fn width(&self) -> u16 {
461        self.width
462    }
463
464    /// Current height of the presenter.
465    #[must_use]
466    pub const fn height(&self) -> u16 {
467        self.height
468    }
469
470    /// Flatten patch runs into caller-provided reusable buffers.
471    ///
472    /// Clears and refills the provided `cells` and `spans` Vecs, reusing
473    /// their heap capacity across frames to avoid per-frame allocation.
474    pub fn flatten_patches_into(&self, cells: &mut Vec<u32>, spans: &mut Vec<u32>) {
475        cells.clear();
476        spans.clear();
477
478        let total_cells = self
479            .outputs
480            .last_patches
481            .iter()
482            .map(|p| p.cells.len())
483            .sum::<usize>();
484        cells.reserve(total_cells.saturating_mul(4));
485        spans.reserve(self.outputs.last_patches.len().saturating_mul(2));
486
487        for patch in &self.outputs.last_patches {
488            spans.push(patch.offset);
489            let len = patch.cells.len().min(u32::MAX as usize) as u32;
490            spans.push(len);
491
492            for cell in &patch.cells {
493                cells.push(cell.bg);
494                cells.push(cell.fg);
495                cells.push(cell.glyph);
496                cells.push(cell.attrs);
497            }
498        }
499    }
500
501    /// Present a frame, taking ownership of the buffer to avoid cloning.
502    ///
503    /// This is the zero-copy fast path for callers that can give up ownership
504    /// (e.g. `StepProgram::render_frame`). The buffer is moved directly into
505    /// `last_buffer` instead of being cloned.
506    pub fn present_ui_owned(
507        &mut self,
508        buf: Buffer,
509        diff: Option<&BufferDiff>,
510        full_repaint_hint: bool,
511    ) {
512        let patches = build_patch_runs(&buf, diff, full_repaint_hint);
513        let stats = patch_batch_stats(&patches);
514        self.outputs.last_buffer = Some(buf);
515        self.outputs.last_patches = patches;
516        self.outputs.last_patch_stats = Some(stats);
517        self.outputs.last_patch_hash = None;
518        self.outputs.hash_computed = false;
519        self.outputs.last_full_repaint_hint = full_repaint_hint;
520    }
521}
522
523impl Default for WebPresenter {
524    fn default() -> Self {
525        Self::new()
526    }
527}
528
529impl BackendPresenter for WebPresenter {
530    type Error = WebBackendError;
531
532    fn capabilities(&self) -> &TerminalCapabilities {
533        &self.caps
534    }
535
536    fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
537        self.outputs.logs.push(text.to_owned());
538        Ok(())
539    }
540
541    fn resize(&mut self, cols: u16, rows: u16) {
542        self.width = cols;
543        self.height = rows;
544    }
545
546    fn screen_mode(&self) -> ScreenMode {
547        self.screen_mode
548    }
549
550    fn set_screen_mode(&mut self, mode: ScreenMode) {
551        self.screen_mode = mode;
552    }
553
554    fn pool_and_links_mut(&mut self) -> (&mut GraphemePool, &mut LinkRegistry) {
555        (&mut self.pool, &mut self.links)
556    }
557
558    fn pool_mut(&mut self) -> &mut GraphemePool {
559        &mut self.pool
560    }
561
562    fn present_ui(
563        &mut self,
564        buf: &Buffer,
565        diff: Option<&BufferDiff>,
566        full_repaint_hint: bool,
567    ) -> Result<(), Self::Error> {
568        let patches = build_patch_runs(buf, diff, full_repaint_hint);
569        let stats = patch_batch_stats(&patches);
570        self.outputs.last_buffer = Some(buf.clone());
571        self.outputs.last_patches = patches;
572        self.outputs.last_patch_stats = Some(stats);
573        self.outputs.last_patch_hash = None;
574        self.outputs.hash_computed = false;
575        self.outputs.last_full_repaint_hint = full_repaint_hint;
576        Ok(())
577    }
578
579    fn present_ui_owned(
580        &mut self,
581        buf: Buffer,
582        cursor: Option<(u16, u16)>,
583        cursor_visible: bool,
584    ) -> Result<(), Self::Error> {
585        let _ = (cursor, cursor_visible);
586        self.present_ui_owned(buf, None, false);
587        Ok(())
588    }
589}
590
591#[must_use]
592fn fnv1a64_extend(mut hash: u64, bytes: &[u8]) -> u64 {
593    for &byte in bytes {
594        hash ^= u64::from(byte);
595        hash = hash.wrapping_mul(FNV64_PRIME);
596    }
597    hash
598}
599
600#[must_use]
601fn cell_to_patch(cell: &Cell) -> WebPatchCell {
602    let glyph = match cell.content {
603        CellContent::EMPTY | CellContent::CONTINUATION => 0,
604        other if other.is_grapheme() => GRAPHEME_FALLBACK_CODEPOINT,
605        other => other.as_char().map_or(0, |c| c as u32),
606    };
607    let style_bits = u32::from(cell.attrs.flags().bits()) & ATTR_STYLE_MASK;
608    let link_id = cell.attrs.link_id().min(ATTR_LINK_ID_MAX);
609    WebPatchCell {
610        bg: cell.bg.0,
611        fg: cell.fg.0,
612        glyph,
613        attrs: style_bits | (link_id << 8),
614    }
615}
616
617#[must_use]
618fn full_buffer_patch(buffer: &Buffer) -> WebPatchRun {
619    let cols = buffer.width();
620    let rows = buffer.height();
621    let total = usize::from(cols) * usize::from(rows);
622    let mut cells = Vec::with_capacity(total);
623    for y in 0..rows {
624        for x in 0..cols {
625            cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
626        }
627    }
628    WebPatchRun { offset: 0, cells }
629}
630
631#[must_use]
632fn diff_to_patches(buffer: &Buffer, diff: &BufferDiff) -> Vec<WebPatchRun> {
633    if diff.is_empty() {
634        return Vec::new();
635    }
636    let width = buffer.width();
637    let height = buffer.height();
638    let cols = u32::from(width);
639    // Heuristic: most sparse diffs produce one patch per ~8 dirty cells.
640    let est_patches = diff.len().div_ceil(8).max(1);
641    let mut patches = Vec::with_capacity(est_patches);
642    let mut span_start: u32 = 0;
643    let mut span_cells: Vec<WebPatchCell> = Vec::with_capacity(diff.len());
644    let mut prev_offset: u32 = 0;
645    let mut has_span = false;
646
647    for &(x, y) in diff.changes() {
648        // Safety: diffs can become stale across resize; fall back to a full patch.
649        if x >= width || y >= height {
650            return vec![full_buffer_patch(buffer)];
651        }
652        let offset = u32::from(y) * cols + u32::from(x);
653        if !has_span {
654            span_start = offset;
655            prev_offset = offset;
656            has_span = true;
657            span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
658            continue;
659        }
660        if offset == prev_offset {
661            continue;
662        }
663        if offset == prev_offset + 1 {
664            span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
665        } else {
666            patches.push(WebPatchRun {
667                offset: span_start,
668                cells: std::mem::take(&mut span_cells),
669            });
670            span_start = offset;
671            span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
672        }
673        prev_offset = offset;
674    }
675    if !span_cells.is_empty() {
676        patches.push(WebPatchRun {
677            offset: span_start,
678            cells: span_cells,
679        });
680    }
681    patches
682}
683
684#[must_use]
685fn build_patch_runs(
686    buffer: &Buffer,
687    diff: Option<&BufferDiff>,
688    full_repaint_hint: bool,
689) -> Vec<WebPatchRun> {
690    if full_repaint_hint {
691        return vec![full_buffer_patch(buffer)];
692    }
693    match diff {
694        Some(dirty) => diff_to_patches(buffer, dirty),
695        None => vec![full_buffer_patch(buffer)],
696    }
697}
698
699#[must_use]
700fn patch_batch_stats(patches: &[WebPatchRun]) -> WebPatchStats {
701    let dirty_cells_u64 = patches
702        .iter()
703        .map(|patch| patch.cells.len() as u64)
704        .sum::<u64>();
705    let dirty_cells = dirty_cells_u64.min(u64::from(u32::MAX)) as u32;
706    let patch_count = patches.len().min(u32::MAX as usize) as u32;
707    let bytes_uploaded = dirty_cells_u64.saturating_mul(WEB_PATCH_CELL_BYTES);
708    WebPatchStats {
709        dirty_cells,
710        patch_count,
711        bytes_uploaded,
712    }
713}
714
715#[must_use]
716fn patch_batch_hash(patches: &[WebPatchRun]) -> String {
717    let mut hash = FNV64_OFFSET_BASIS;
718    let patch_count = u64::try_from(patches.len()).unwrap_or(u64::MAX);
719    hash = fnv1a64_extend(hash, &patch_count.to_le_bytes());
720
721    // Pre-allocate a 16-byte buffer for batching cell fields into a single
722    // fnv1a64_extend call (4× fewer function calls per cell).
723    let mut cell_bytes = [0u8; 16];
724    for patch in patches {
725        let cell_count = u64::try_from(patch.cells.len()).unwrap_or(u64::MAX);
726        hash = fnv1a64_extend(hash, &patch.offset.to_le_bytes());
727        hash = fnv1a64_extend(hash, &cell_count.to_le_bytes());
728        for cell in &patch.cells {
729            cell_bytes[0..4].copy_from_slice(&cell.bg.to_le_bytes());
730            cell_bytes[4..8].copy_from_slice(&cell.fg.to_le_bytes());
731            cell_bytes[8..12].copy_from_slice(&cell.glyph.to_le_bytes());
732            cell_bytes[12..16].copy_from_slice(&cell.attrs.to_le_bytes());
733            hash = fnv1a64_extend(hash, &cell_bytes);
734        }
735    }
736
737    format!("{PATCH_HASH_ALGO}:{hash:016x}")
738}
739
740/// A minimal, host-driven WASM backend.
741///
742/// This backend is intended to be driven by a JS host:
743/// - push events via [`Self::events_mut`]
744/// - advance time via [`Self::clock_mut`]
745/// - read rendered buffers via [`Self::presenter_mut`]
746#[derive(Debug, Clone)]
747pub struct WebBackend {
748    clock: DeterministicClock,
749    events: WebEventSource,
750    presenter: WebPresenter,
751}
752
753impl WebBackend {
754    /// Create a backend with an initial size.
755    #[must_use]
756    pub fn new(width: u16, height: u16) -> Self {
757        Self {
758            clock: DeterministicClock::new(),
759            events: WebEventSource::new(width, height),
760            presenter: WebPresenter::with_size(width, height),
761        }
762    }
763
764    /// Mutably access the clock.
765    pub fn clock_mut(&mut self) -> &mut DeterministicClock {
766        &mut self.clock
767    }
768
769    /// Mutably access the event source.
770    pub fn events_mut(&mut self) -> &mut WebEventSource {
771        &mut self.events
772    }
773
774    /// Access the presenter.
775    #[must_use]
776    pub const fn presenter(&self) -> &WebPresenter {
777        &self.presenter
778    }
779
780    /// Mutably access the presenter.
781    pub fn presenter_mut(&mut self) -> &mut WebPresenter {
782        &mut self.presenter
783    }
784}
785
786impl Backend for WebBackend {
787    type Error = WebBackendError;
788
789    type Clock = DeterministicClock;
790    type Events = WebEventSource;
791
792    fn clock(&self) -> &Self::Clock {
793        &self.clock
794    }
795
796    fn events(&mut self) -> &mut Self::Events {
797        &mut self.events
798    }
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804    use ftui_core::event::{
805        ClipboardEvent, ClipboardSource, ImeEvent, KeyCode, KeyEvent, PasteEvent,
806    };
807    use ftui_render::cell::Cell;
808
809    use pretty_assertions::assert_eq;
810
811    #[test]
812    fn deterministic_clock_advances_monotonically() {
813        let mut c = DeterministicClock::new();
814        assert_eq!(c.now_mono(), Duration::ZERO);
815
816        c.advance(Duration::from_millis(10));
817        assert_eq!(c.now_mono(), Duration::from_millis(10));
818
819        c.advance(Duration::from_millis(5));
820        assert_eq!(c.now_mono(), Duration::from_millis(15));
821
822        // Saturation: don't panic or wrap.
823        c.set(Duration::MAX);
824        c.advance(Duration::from_secs(1));
825        assert_eq!(c.now_mono(), Duration::MAX);
826    }
827
828    #[test]
829    fn web_event_source_fifo_queue() {
830        let mut ev = WebEventSource::new(80, 24);
831        assert_eq!(ev.size().unwrap(), (80, 24));
832        assert_eq!(ev.poll_event(Duration::from_millis(0)).unwrap(), false);
833
834        ev.push_event(Event::Tick).unwrap();
835        ev.push_event(Event::Resize {
836            width: 100,
837            height: 40,
838        })
839        .unwrap();
840
841        assert_eq!(ev.poll_event(Duration::from_millis(0)).unwrap(), true);
842        assert_eq!(ev.read_event().unwrap(), Some(Event::Tick));
843        assert_eq!(
844            ev.read_event().unwrap(),
845            Some(Event::Resize {
846                width: 100,
847                height: 40,
848            })
849        );
850        assert_eq!(ev.read_event().unwrap(), None);
851    }
852
853    #[test]
854    fn presenter_captures_logs_and_last_buffer() {
855        let mut p = WebPresenter::new();
856        p.write_log("hello").unwrap();
857        p.write_log("world").unwrap();
858
859        let buf = Buffer::new(2, 2);
860        p.present_ui(&buf, None, true).unwrap();
861
862        let mut outputs = p.take_outputs();
863        assert_eq!(outputs.logs, vec!["hello", "world"]);
864        assert_eq!(outputs.last_full_repaint_hint, true);
865        assert_eq!(outputs.last_buffer.as_ref().unwrap().width(), 2);
866        assert_eq!(outputs.last_patches.len(), 1);
867        let stats = outputs.last_patch_stats.expect("stats should be present");
868        assert_eq!(stats.patch_count, 1);
869        assert_eq!(stats.dirty_cells, 4);
870        assert_eq!(stats.bytes_uploaded, 64);
871        let hash = outputs
872            .compute_patch_hash()
873            .expect("hash should be present");
874        assert!(hash.starts_with("fnv1a64:"));
875    }
876
877    #[test]
878    fn presenter_emits_incremental_patch_runs_from_diff() {
879        let mut presenter = WebPresenter::new();
880        let old = Buffer::new(6, 2);
881        presenter.present_ui(&old, None, true).unwrap();
882
883        let mut next = Buffer::new(6, 2);
884        next.set_raw(2, 0, Cell::from_char('A'));
885        next.set_raw(3, 0, Cell::from_char('B'));
886        next.set_raw(0, 1, Cell::from_char('C'));
887        let diff = BufferDiff::compute(&old, &next);
888        presenter.present_ui(&next, Some(&diff), false).unwrap();
889
890        let mut outputs = presenter.take_outputs();
891        assert_eq!(outputs.last_full_repaint_hint, false);
892        assert_eq!(outputs.last_patches.len(), 2);
893        assert_eq!(outputs.last_patches[0].offset, 2);
894        assert_eq!(outputs.last_patches[0].cells.len(), 2);
895        assert_eq!(outputs.last_patches[1].offset, 6);
896        assert_eq!(outputs.last_patches[1].cells.len(), 1);
897        let stats = outputs.last_patch_stats.expect("stats should be present");
898        assert_eq!(stats.patch_count, 2);
899        assert_eq!(stats.dirty_cells, 3);
900        assert_eq!(stats.bytes_uploaded, 48);
901        let hash = outputs
902            .compute_patch_hash()
903            .expect("hash should be present");
904        assert!(hash.starts_with("fnv1a64:"));
905    }
906
907    #[test]
908    fn stale_diff_falls_back_to_full_patch() {
909        let old = Buffer::new(4, 2);
910        let mut next = Buffer::new(4, 2);
911        next.set_raw(3, 1, Cell::from_char('X'));
912        let stale_diff = BufferDiff::compute(&old, &next);
913
914        let resized = Buffer::new(2, 1);
915        let patches = build_patch_runs(&resized, Some(&stale_diff), false);
916
917        assert_eq!(patches.len(), 1);
918        assert_eq!(patches[0].offset, 0);
919        assert_eq!(patches[0].cells.len(), 2);
920    }
921
922    #[test]
923    fn patch_batch_hash_is_deterministic() {
924        let patches = vec![
925            WebPatchRun {
926                offset: 2,
927                cells: vec![
928                    WebPatchCell {
929                        bg: 0x1122_3344,
930                        fg: 0x5566_7788,
931                        glyph: 'A' as u32,
932                        attrs: 0x0000_0001,
933                    },
934                    WebPatchCell {
935                        bg: 0x1122_3344,
936                        fg: 0x5566_7788,
937                        glyph: 'B' as u32,
938                        attrs: 0x0000_0002,
939                    },
940                ],
941            },
942            WebPatchRun {
943                offset: 10,
944                cells: vec![WebPatchCell {
945                    bg: 0xAABB_CCDD,
946                    fg: 0xDDEE_FF00,
947                    glyph: '中' as u32,
948                    attrs: 0x0000_0010,
949                }],
950            },
951        ];
952
953        let hash_a = patch_batch_hash(&patches);
954        let hash_b = patch_batch_hash(&patches);
955        assert_eq!(hash_a, hash_b);
956        assert!(hash_a.starts_with("fnv1a64:"));
957    }
958
959    #[test]
960    fn patch_batch_hash_changes_with_patch_payload() {
961        let baseline = vec![WebPatchRun {
962            offset: 4,
963            cells: vec![WebPatchCell {
964                bg: 0x0000_00FF,
965                fg: 0xFFFF_FFFF,
966                glyph: 'x' as u32,
967                attrs: 0x0000_0001,
968            }],
969        }];
970        let mut changed = baseline.clone();
971        changed[0].offset = 5;
972
973        let base_hash = patch_batch_hash(&baseline);
974        let changed_hash = patch_batch_hash(&changed);
975        assert_ne!(base_hash, changed_hash);
976
977        changed[0].offset = 4;
978        changed[0].cells[0].glyph = 'y' as u32;
979        let changed_glyph_hash = patch_batch_hash(&changed);
980        assert_ne!(base_hash, changed_glyph_hash);
981    }
982
983    #[test]
984    fn flatten_patches_u32_emits_row_major_cells_and_spans() {
985        let outputs = WebOutputs {
986            last_patches: vec![
987                WebPatchRun {
988                    offset: 2,
989                    cells: vec![
990                        WebPatchCell {
991                            bg: 10,
992                            fg: 11,
993                            glyph: 12,
994                            attrs: 13,
995                        },
996                        WebPatchCell {
997                            bg: 20,
998                            fg: 21,
999                            glyph: 22,
1000                            attrs: 23,
1001                        },
1002                    ],
1003                },
1004                WebPatchRun {
1005                    offset: 9,
1006                    cells: vec![WebPatchCell {
1007                        bg: 30,
1008                        fg: 31,
1009                        glyph: 32,
1010                        attrs: 33,
1011                    }],
1012                },
1013            ],
1014            ..WebOutputs::default()
1015        };
1016
1017        let flat = outputs.flatten_patches_u32();
1018        assert_eq!(flat.spans, vec![2, 2, 9, 1]);
1019        assert_eq!(
1020            flat.cells,
1021            vec![
1022                10, 11, 12, 13, //
1023                20, 21, 22, 23, //
1024                30, 31, 32, 33
1025            ]
1026        );
1027    }
1028
1029    #[test]
1030    fn flatten_patches_u32_handles_empty_payload() {
1031        let outputs = WebOutputs::default();
1032        let flat = outputs.flatten_patches_u32();
1033        assert!(flat.cells.is_empty());
1034        assert!(flat.spans.is_empty());
1035    }
1036
1037    // --- WebBackendError ---
1038
1039    #[test]
1040    fn web_backend_error_display() {
1041        let err = WebBackendError::Unsupported("test op");
1042        assert_eq!(format!("{err}"), "unsupported: test op");
1043    }
1044
1045    #[test]
1046    fn web_backend_error_is_std_error() {
1047        let err = WebBackendError::Unsupported("foo");
1048        let _: &dyn std::error::Error = &err;
1049    }
1050
1051    #[test]
1052    fn web_backend_error_eq() {
1053        assert_eq!(
1054            WebBackendError::Unsupported("a"),
1055            WebBackendError::Unsupported("a")
1056        );
1057        assert_ne!(
1058            WebBackendError::Unsupported("a"),
1059            WebBackendError::Unsupported("b")
1060        );
1061    }
1062
1063    // --- DeterministicClock ---
1064
1065    #[test]
1066    fn clock_set_overrides_current() {
1067        let mut c = DeterministicClock::new();
1068        c.set(Duration::from_secs(42));
1069        assert_eq!(c.now_mono(), Duration::from_secs(42));
1070    }
1071
1072    #[test]
1073    fn clock_default_is_zero() {
1074        let c = DeterministicClock::default();
1075        assert_eq!(c.now_mono(), Duration::ZERO);
1076    }
1077
1078    #[test]
1079    fn clock_clone() {
1080        let mut c = DeterministicClock::new();
1081        c.advance(Duration::from_millis(100));
1082        let c2 = c.clone();
1083        assert_eq!(c2.now_mono(), Duration::from_millis(100));
1084    }
1085
1086    // --- WebEventSource ---
1087
1088    #[test]
1089    fn event_source_set_size() {
1090        let mut ev = WebEventSource::new(80, 24);
1091        ev.set_size(120, 50);
1092        assert_eq!(ev.size().unwrap(), (120, 50));
1093    }
1094
1095    #[test]
1096    fn event_source_drain_events() {
1097        let mut ev = WebEventSource::new(80, 24);
1098        ev.push_event(Event::Tick).unwrap();
1099        ev.push_event(Event::Tick).unwrap();
1100
1101        let drained: Vec<_> = ev.drain_events().collect();
1102        assert_eq!(drained.len(), 2);
1103        assert_eq!(ev.poll_event(Duration::ZERO).unwrap(), false);
1104    }
1105
1106    #[test]
1107    fn event_source_count_limit_preserves_every_accepted_event_and_retry_order() {
1108        let mut source = WebEventSource::new(80, 24);
1109        let accepted: Vec<_> = (0..WebEventSource::MAX_EVENTS)
1110            .map(|index| {
1111                Event::Key(KeyEvent::new(KeyCode::Char(
1112                    char::from_u32(0x1000 + index as u32).unwrap(),
1113                )))
1114            })
1115            .collect();
1116        for event in &accepted {
1117            source.push_event(event.clone()).unwrap();
1118        }
1119        let tail = Event::Paste(PasteEvent::bracketed("rejected tail: 日本語 👩‍💻"));
1120        let error = source.push_event(tail.clone()).unwrap_err();
1121        assert_eq!(
1122            error,
1123            WebBackendError::InputQueueFull {
1124                limit: WebInputLimit::Events,
1125                event: tail.clone(),
1126            }
1127        );
1128        assert_eq!(source.queued_events(), WebEventSource::MAX_EVENTS);
1129        assert_eq!(source.queued_payload_bytes(), 0);
1130        assert_eq!(source.read_event().unwrap(), Some(accepted[0].clone()));
1131        let WebBackendError::InputQueueFull { event, .. } = error else {
1132            unreachable!();
1133        };
1134        source.push_event(event).unwrap();
1135        let delivered: Vec<_> = source.drain_events().collect();
1136        assert_eq!(&delivered[..delivered.len() - 1], &accepted[1..]);
1137        assert_eq!(delivered.last(), Some(&tail));
1138        assert_eq!(source.queued_events(), 0);
1139        assert_eq!(source.queued_payload_bytes(), 0);
1140    }
1141
1142    #[test]
1143    fn event_source_bounds_cumulative_paste_ime_and_clipboard_allocations() {
1144        let half = "x".repeat(WebEventSource::MAX_PAYLOAD_BYTES / 2);
1145        let events = [
1146            Event::Paste(PasteEvent::bracketed(half.clone())),
1147            Event::Ime(ImeEvent::commit(half.clone())),
1148            Event::Clipboard(ClipboardEvent::new(half, ClipboardSource::Osc52)),
1149        ];
1150        for event in events {
1151            let mut source = WebEventSource::new(80, 24);
1152            source.push_event(event.clone()).unwrap();
1153            source.push_event(event.clone()).unwrap();
1154            assert_eq!(
1155                source.queued_payload_bytes(),
1156                WebEventSource::MAX_PAYLOAD_BYTES
1157            );
1158            let error = source.push_event(event.clone()).unwrap_err();
1159            assert_eq!(
1160                error,
1161                WebBackendError::InputQueueFull {
1162                    limit: WebInputLimit::PayloadBytes,
1163                    event: event.clone(),
1164                }
1165            );
1166            // A byte-full queue can still admit non-text control input.
1167            source.push_event(Event::Focus(false)).unwrap();
1168            assert_eq!(source.read_event().unwrap(), Some(event.clone()));
1169            let WebBackendError::InputQueueFull { event: retry, .. } = error else {
1170                unreachable!();
1171            };
1172            source.push_event(retry).unwrap();
1173            assert_eq!(
1174                source.drain_events().collect::<Vec<_>>(),
1175                vec![event.clone(), Event::Focus(false), event]
1176            );
1177            assert_eq!(source.queued_payload_bytes(), 0);
1178        }
1179    }
1180
1181    #[test]
1182    fn event_source_rejects_oversized_allocation_without_retaining_or_logging_text() {
1183        let mut text = String::with_capacity(WebEventSource::MAX_PAYLOAD_BYTES + 1);
1184        text.push_str("private clipboard text");
1185        let event = Event::Clipboard(ClipboardEvent::new(text, ClipboardSource::Unknown));
1186        let allocation = event_payload_bytes(&event);
1187        let mut source = WebEventSource::new(80, 24);
1188        let error = source.push_event(event).unwrap_err();
1189        assert_eq!(
1190            error.to_string(),
1191            "input queue full (PayloadBytes); drain before retrying"
1192        );
1193        let WebBackendError::InputQueueFull { limit, event } = error else {
1194            unreachable!();
1195        };
1196        assert_eq!(limit, WebInputLimit::PayloadBytes);
1197        assert_eq!(event_payload_bytes(&event), allocation);
1198        assert_eq!(source.queued_events(), 0);
1199        assert_eq!(source.queued_payload_bytes(), 0);
1200        source.push_event(Event::Ime(ImeEvent::cancel())).unwrap();
1201        assert_eq!(
1202            source.read_event().unwrap(),
1203            Some(Event::Ime(ImeEvent::cancel()))
1204        );
1205    }
1206
1207    #[test]
1208    fn event_source_partial_drain_and_clone_account_for_actual_allocations() {
1209        let mut text = String::with_capacity(4096);
1210        text.push('中');
1211        let allocation = text.capacity();
1212        let mut source = WebEventSource::new(80, 24);
1213        source.push_event(Event::Tick).unwrap();
1214        source
1215            .push_event(Event::Paste(PasteEvent::bracketed(text)))
1216            .unwrap();
1217        {
1218            let mut drain = source.drain_events();
1219            assert_eq!(drain.next(), Some(Event::Tick));
1220        }
1221        assert_eq!(source.queued_events(), 1);
1222        assert_eq!(source.queued_payload_bytes(), allocation);
1223        let mut cloned = source.clone();
1224        let clone_bytes = cloned.queued_payload_bytes();
1225        let delivered = cloned.read_event().unwrap().unwrap();
1226        assert_eq!(clone_bytes, event_payload_bytes(&delivered));
1227        assert_eq!(delivered, Event::Paste(PasteEvent::bracketed("中")));
1228        assert_eq!(cloned.queued_payload_bytes(), 0);
1229        assert_eq!(source.queued_payload_bytes(), allocation);
1230        assert_eq!(source.read_event().unwrap(), Some(delivered));
1231        assert_eq!(source.queued_payload_bytes(), 0);
1232    }
1233
1234    #[test]
1235    fn event_source_features() {
1236        let mut ev = WebEventSource::new(80, 24);
1237        let f = BackendFeatures::default();
1238        ev.set_features(f).unwrap();
1239        let _ = ev.features(); // should not panic
1240    }
1241
1242    #[test]
1243    fn event_source_empty_read_returns_none() {
1244        let mut ev = WebEventSource::new(80, 24);
1245        assert_eq!(ev.read_event().unwrap(), None);
1246    }
1247
1248    // --- WebPresenter ---
1249
1250    #[test]
1251    fn presenter_default_is_new() {
1252        let a = WebPresenter::new();
1253        let b = WebPresenter::default();
1254        assert!(a.outputs().logs.is_empty());
1255        assert!(b.outputs().logs.is_empty());
1256    }
1257
1258    #[test]
1259    fn presenter_outputs_accessor() {
1260        let mut p = WebPresenter::new();
1261        p.write_log("test").unwrap();
1262        assert_eq!(p.outputs().logs.len(), 1);
1263    }
1264
1265    #[test]
1266    fn presenter_outputs_mut() {
1267        let mut p = WebPresenter::new();
1268        p.outputs_mut().logs.push("manual".to_string());
1269        assert_eq!(p.outputs().logs, vec!["manual"]);
1270    }
1271
1272    #[test]
1273    fn presenter_take_outputs_clears() {
1274        let mut p = WebPresenter::new();
1275        p.write_log("a").unwrap();
1276        let taken = p.take_outputs();
1277        assert_eq!(taken.logs, vec!["a"]);
1278        assert!(p.outputs().logs.is_empty());
1279    }
1280
1281    #[test]
1282    fn presenter_capabilities_are_modern() {
1283        let p = WebPresenter::new();
1284        let caps = p.capabilities();
1285        assert!(caps.supports_true_color());
1286    }
1287
1288    #[test]
1289    fn presenter_present_ui_owned() {
1290        let mut p = WebPresenter::new();
1291        let buf = Buffer::new(3, 2);
1292        p.present_ui_owned(buf, None, true);
1293
1294        let mut out = p.take_outputs();
1295        assert!(out.last_full_repaint_hint);
1296        assert_eq!(out.last_buffer.as_ref().unwrap().width(), 3);
1297        assert_eq!(out.last_patches.len(), 1);
1298        assert!(out.last_patch_stats.is_some());
1299        assert!(out.compute_patch_hash().is_some());
1300    }
1301
1302    #[test]
1303    fn presenter_resize_and_screen_mode() {
1304        let mut p = WebPresenter::new();
1305        assert_eq!(p.screen_mode(), ScreenMode::default());
1306        p.set_screen_mode(ScreenMode::AltScreen);
1307        assert_eq!(p.screen_mode(), ScreenMode::AltScreen);
1308
1309        p.resize(100, 50);
1310        assert_eq!(p.width(), 100);
1311        assert_eq!(p.height(), 50);
1312    }
1313
1314    #[test]
1315    fn presenter_pool_and_links() {
1316        let mut p = WebPresenter::new();
1317        let (pool, links) = p.pool_and_links_mut();
1318        let id = pool.intern("hello", 1);
1319        let _link = links.register("https://example.com");
1320        assert_eq!(p.pool_mut().get(id), Some("hello"));
1321    }
1322
1323    // --- WebBackend ---
1324
1325    #[test]
1326    fn web_backend_construction() {
1327        let mut wb = WebBackend::new(80, 24);
1328        assert_eq!(wb.events_mut().size().unwrap(), (80, 24));
1329        assert_eq!(wb.clock_mut().now_mono(), Duration::ZERO);
1330    }
1331
1332    #[test]
1333    fn web_backend_implements_backend_trait() {
1334        let mut wb = WebBackend::new(80, 24);
1335        // Verify Backend trait methods
1336        let _ = wb.clock();
1337        let _ = wb.events();
1338        let _ = wb.presenter();
1339    }
1340
1341    // --- patch_batch_stats ---
1342
1343    #[test]
1344    fn patch_batch_stats_empty() {
1345        let stats = patch_batch_stats(&[]);
1346        assert_eq!(stats.dirty_cells, 0);
1347        assert_eq!(stats.patch_count, 0);
1348        assert_eq!(stats.bytes_uploaded, 0);
1349    }
1350
1351    #[test]
1352    fn patch_batch_stats_counts_cells() {
1353        let patches = vec![
1354            WebPatchRun {
1355                offset: 0,
1356                cells: vec![
1357                    WebPatchCell {
1358                        bg: 0,
1359                        fg: 0,
1360                        glyph: 0,
1361                        attrs: 0,
1362                    };
1363                    3
1364                ],
1365            },
1366            WebPatchRun {
1367                offset: 10,
1368                cells: vec![WebPatchCell {
1369                    bg: 0,
1370                    fg: 0,
1371                    glyph: 0,
1372                    attrs: 0,
1373                }],
1374            },
1375        ];
1376        let stats = patch_batch_stats(&patches);
1377        assert_eq!(stats.dirty_cells, 4);
1378        assert_eq!(stats.patch_count, 2);
1379        assert_eq!(stats.bytes_uploaded, 64); // 4 cells * 16 bytes
1380    }
1381
1382    // --- patch_batch_hash ---
1383
1384    #[test]
1385    fn patch_hash_empty_is_deterministic() {
1386        let a = patch_batch_hash(&[]);
1387        let b = patch_batch_hash(&[]);
1388        assert_eq!(a, b);
1389        assert!(a.starts_with("fnv1a64:"));
1390    }
1391
1392    // --- build_patch_runs ---
1393
1394    #[test]
1395    fn build_patch_runs_full_repaint_hint() {
1396        let buf = Buffer::new(2, 2);
1397        let patches = build_patch_runs(&buf, None, true);
1398        assert_eq!(patches.len(), 1);
1399        assert_eq!(patches[0].offset, 0);
1400        assert_eq!(patches[0].cells.len(), 4);
1401    }
1402
1403    #[test]
1404    fn build_patch_runs_no_diff_triggers_full() {
1405        let buf = Buffer::new(3, 1);
1406        let patches = build_patch_runs(&buf, None, false);
1407        // None diff → full buffer patch
1408        assert_eq!(patches.len(), 1);
1409        assert_eq!(patches[0].cells.len(), 3);
1410    }
1411
1412    // --- WebOutputs default ---
1413
1414    #[test]
1415    fn web_outputs_default_is_empty() {
1416        let out = WebOutputs::default();
1417        assert!(out.logs.is_empty());
1418        assert!(out.last_buffer.is_none());
1419        assert!(out.last_patches.is_empty());
1420        assert!(out.last_patch_stats.is_none());
1421        assert!(out.last_patch_hash.is_none());
1422        assert!(!out.last_full_repaint_hint);
1423    }
1424
1425    // --- cell_to_patch ---
1426
1427    #[test]
1428    fn cell_to_patch_empty_cell() {
1429        let cell = Cell::default();
1430        let patch = cell_to_patch(&cell);
1431        // Empty cell should have glyph=0
1432        assert_eq!(patch.glyph, 0);
1433    }
1434
1435    #[test]
1436    fn cell_to_patch_ascii_char() {
1437        let cell = Cell::from_char('A');
1438        let patch = cell_to_patch(&cell);
1439        assert_eq!(patch.glyph, 'A' as u32);
1440    }
1441
1442    #[test]
1443    fn cell_to_patch_preserves_max_link_id() {
1444        use ftui_render::cell::{CellAttrs, StyleFlags};
1445
1446        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(
1447            StyleFlags::UNDERLINE,
1448            CellAttrs::LINK_ID_MAX,
1449        ));
1450        let patch = cell_to_patch(&cell);
1451
1452        assert_eq!(patch.attrs >> 8, CellAttrs::LINK_ID_MAX);
1453    }
1454}