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::{Backend, BackendClock, BackendEventSource, BackendFeatures, BackendPresenter};
59use ftui_core::event::Event;
60use ftui_core::terminal_capabilities::TerminalCapabilities;
61use ftui_render::buffer::Buffer;
62use ftui_render::cell::{Cell, CellAttrs, CellContent};
63use ftui_render::diff::BufferDiff;
64
65const GRAPHEME_FALLBACK_CODEPOINT: u32 = '□' as u32;
66const ATTR_STYLE_MASK: u32 = 0xFF;
67const ATTR_LINK_ID_MAX: u32 = CellAttrs::LINK_ID_MAX;
68const WEB_PATCH_CELL_BYTES: u64 = 16;
69const PATCH_HASH_ALGO: &str = "fnv1a64";
70const FNV64_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
71const FNV64_PRIME: u64 = 0x100000001b3;
72
73/// Web backend error type.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum WebBackendError {
76    /// Generic unsupported operation.
77    Unsupported(&'static str),
78}
79
80impl core::fmt::Display for WebBackendError {
81    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
82        match self {
83            Self::Unsupported(msg) => write!(f, "unsupported: {msg}"),
84        }
85    }
86}
87
88impl std::error::Error for WebBackendError {}
89
90/// Deterministic monotonic clock controlled by the host.
91#[derive(Debug, Default, Clone)]
92pub struct DeterministicClock {
93    now: Duration,
94}
95
96impl DeterministicClock {
97    /// Create a clock starting at `0`.
98    #[must_use]
99    pub const fn new() -> Self {
100        Self {
101            now: Duration::ZERO,
102        }
103    }
104
105    /// Set current monotonic time.
106    pub fn set(&mut self, now: Duration) {
107        self.now = now;
108    }
109
110    /// Advance monotonic time by `dt`.
111    pub fn advance(&mut self, dt: Duration) {
112        self.now = self.now.saturating_add(dt);
113    }
114}
115
116impl BackendClock for DeterministicClock {
117    fn now_mono(&self) -> Duration {
118        self.now
119    }
120}
121
122/// Host-driven event source for WASM.
123///
124/// The host is responsible for pushing [`Event`] values and updating size.
125#[derive(Debug, Clone)]
126pub struct WebEventSource {
127    size: (u16, u16),
128    features: BackendFeatures,
129    queue: VecDeque<Event>,
130}
131
132impl WebEventSource {
133    /// Create a new event source with an initial size.
134    #[must_use]
135    pub fn new(width: u16, height: u16) -> Self {
136        Self {
137            size: (width, height),
138            features: BackendFeatures::default(),
139            queue: VecDeque::new(),
140        }
141    }
142
143    /// Update the current size.
144    pub fn set_size(&mut self, width: u16, height: u16) {
145        self.size = (width, height);
146    }
147
148    /// Read back the currently requested backend features.
149    #[must_use]
150    pub const fn features(&self) -> BackendFeatures {
151        self.features
152    }
153
154    /// Push a canonical event into the queue.
155    pub fn push_event(&mut self, event: Event) {
156        self.queue.push_back(event);
157    }
158
159    /// Drain all pending events.
160    pub fn drain_events(&mut self) -> impl Iterator<Item = Event> + '_ {
161        self.queue.drain(..)
162    }
163}
164
165impl BackendEventSource for WebEventSource {
166    type Error = WebBackendError;
167
168    fn size(&self) -> Result<(u16, u16), Self::Error> {
169        Ok(self.size)
170    }
171
172    fn set_features(&mut self, features: BackendFeatures) -> Result<(), Self::Error> {
173        self.features = features;
174        Ok(())
175    }
176
177    fn poll_event(&mut self, timeout: Duration) -> Result<bool, Self::Error> {
178        // WASM backend is host-driven; we never block.
179        let _ = timeout;
180        Ok(!self.queue.is_empty())
181    }
182
183    fn read_event(&mut self) -> Result<Option<Event>, Self::Error> {
184        Ok(self.queue.pop_front())
185    }
186}
187
188/// Captured presentation outputs for host consumption.
189#[derive(Debug, Default, Clone)]
190pub struct WebOutputs {
191    /// Log lines written by the runtime.
192    pub logs: Vec<String>,
193    /// Last fully-rendered buffer presented.
194    pub last_buffer: Option<Buffer>,
195    /// Last emitted incremental/full patch runs in row-major order.
196    pub last_patches: Vec<WebPatchRun>,
197    /// Aggregate patch upload accounting for the last present.
198    pub last_patch_stats: Option<WebPatchStats>,
199    /// Deterministic hash of the last patch batch (lazy — computed on first read).
200    pub last_patch_hash: Option<String>,
201    /// Whether the last present requested a full repaint.
202    pub last_full_repaint_hint: bool,
203    /// Whether the hash has been computed for the current patches.
204    hash_computed: bool,
205}
206
207impl WebOutputs {
208    /// Compute and return the patch hash, caching the result.
209    ///
210    /// The hash is computed lazily on first call and cached for subsequent reads.
211    pub fn compute_patch_hash(&mut self) -> Option<&str> {
212        if !self.hash_computed && !self.last_patches.is_empty() {
213            self.last_patch_hash = Some(patch_batch_hash(&self.last_patches));
214            self.hash_computed = true;
215        }
216        self.last_patch_hash.as_deref()
217    }
218}
219
220impl WebOutputs {
221    /// Flatten patch runs for low-overhead JS/WASM bridge transport.
222    ///
223    /// Cells are emitted as a contiguous `u32` payload in:
224    /// `[bg, fg, glyph, attrs]` order. Spans are emitted as `u32` pairs:
225    /// `[offset, len, offset, len, ...]`.
226    #[must_use]
227    pub fn flatten_patches_u32(&self) -> WebFlatPatchBatch {
228        let total_cells = self
229            .last_patches
230            .iter()
231            .map(|patch| patch.cells.len())
232            .sum::<usize>();
233        let mut cells = Vec::with_capacity(total_cells.saturating_mul(4));
234        let mut spans = Vec::with_capacity(self.last_patches.len().saturating_mul(2));
235
236        for patch in &self.last_patches {
237            spans.push(patch.offset);
238            let len = patch.cells.len().min(u32::MAX as usize) as u32;
239            spans.push(len);
240
241            for cell in &patch.cells {
242                cells.push(cell.bg);
243                cells.push(cell.fg);
244                cells.push(cell.glyph);
245                cells.push(cell.attrs);
246            }
247        }
248
249        WebFlatPatchBatch { cells, spans }
250    }
251}
252
253/// One GPU patch cell payload (`bg`, `fg`, `glyph`, `attrs`) matching the
254/// `frankenterm-web` `applyPatch` schema.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub struct WebPatchCell {
257    pub bg: u32,
258    pub fg: u32,
259    pub glyph: u32,
260    pub attrs: u32,
261}
262
263/// One contiguous run of changed cells starting at linear `offset`.
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct WebPatchRun {
266    pub offset: u32,
267    pub cells: Vec<WebPatchCell>,
268}
269
270/// Compact, flat patch payload for JS/WASM transport.
271#[derive(Debug, Default, Clone, PartialEq, Eq)]
272pub struct WebFlatPatchBatch {
273    /// Cell payload in `[bg, fg, glyph, attrs]` order.
274    pub cells: Vec<u32>,
275    /// Span payload in `[offset, len, offset, len, ...]` order.
276    pub spans: Vec<u32>,
277}
278
279/// Aggregate patch-upload stats for host instrumentation and JSONL reporting.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub struct WebPatchStats {
282    pub dirty_cells: u32,
283    pub patch_count: u32,
284    pub bytes_uploaded: u64,
285}
286
287/// WASM presenter that captures buffers and logs for the host.
288#[derive(Debug, Clone)]
289pub struct WebPresenter {
290    caps: TerminalCapabilities,
291    outputs: WebOutputs,
292}
293
294impl WebPresenter {
295    /// Create a new presenter with modern capabilities.
296    #[must_use]
297    pub fn new() -> Self {
298        Self {
299            caps: TerminalCapabilities::modern(),
300            outputs: WebOutputs::default(),
301        }
302    }
303
304    /// Get captured outputs.
305    #[must_use]
306    pub const fn outputs(&self) -> &WebOutputs {
307        &self.outputs
308    }
309
310    /// Mutably access captured outputs.
311    pub fn outputs_mut(&mut self) -> &mut WebOutputs {
312        &mut self.outputs
313    }
314
315    /// Take captured outputs, leaving empty defaults.
316    pub fn take_outputs(&mut self) -> WebOutputs {
317        std::mem::take(&mut self.outputs)
318    }
319
320    /// Flatten patch runs into caller-provided reusable buffers.
321    ///
322    /// Clears and refills the provided `cells` and `spans` Vecs, reusing
323    /// their heap capacity across frames to avoid per-frame allocation.
324    pub fn flatten_patches_into(&self, cells: &mut Vec<u32>, spans: &mut Vec<u32>) {
325        cells.clear();
326        spans.clear();
327
328        let total_cells = self
329            .outputs
330            .last_patches
331            .iter()
332            .map(|p| p.cells.len())
333            .sum::<usize>();
334        cells.reserve(total_cells.saturating_mul(4));
335        spans.reserve(self.outputs.last_patches.len().saturating_mul(2));
336
337        for patch in &self.outputs.last_patches {
338            spans.push(patch.offset);
339            let len = patch.cells.len().min(u32::MAX as usize) as u32;
340            spans.push(len);
341
342            for cell in &patch.cells {
343                cells.push(cell.bg);
344                cells.push(cell.fg);
345                cells.push(cell.glyph);
346                cells.push(cell.attrs);
347            }
348        }
349    }
350
351    /// Present a frame, taking ownership of the buffer to avoid cloning.
352    ///
353    /// This is the zero-copy fast path for callers that can give up ownership
354    /// (e.g. `StepProgram::render_frame`). The buffer is moved directly into
355    /// `last_buffer` instead of being cloned.
356    pub fn present_ui_owned(
357        &mut self,
358        buf: Buffer,
359        diff: Option<&BufferDiff>,
360        full_repaint_hint: bool,
361    ) {
362        let patches = build_patch_runs(&buf, diff, full_repaint_hint);
363        let stats = patch_batch_stats(&patches);
364        self.outputs.last_buffer = Some(buf);
365        self.outputs.last_patches = patches;
366        self.outputs.last_patch_stats = Some(stats);
367        self.outputs.last_patch_hash = None;
368        self.outputs.hash_computed = false;
369        self.outputs.last_full_repaint_hint = full_repaint_hint;
370    }
371}
372
373impl Default for WebPresenter {
374    fn default() -> Self {
375        Self::new()
376    }
377}
378
379impl BackendPresenter for WebPresenter {
380    type Error = WebBackendError;
381
382    fn capabilities(&self) -> &TerminalCapabilities {
383        &self.caps
384    }
385
386    fn write_log(&mut self, text: &str) -> Result<(), Self::Error> {
387        self.outputs.logs.push(text.to_owned());
388        Ok(())
389    }
390
391    fn present_ui(
392        &mut self,
393        buf: &Buffer,
394        diff: Option<&BufferDiff>,
395        full_repaint_hint: bool,
396    ) -> Result<(), Self::Error> {
397        let patches = build_patch_runs(buf, diff, full_repaint_hint);
398        let stats = patch_batch_stats(&patches);
399        self.outputs.last_buffer = Some(buf.clone());
400        self.outputs.last_patches = patches;
401        self.outputs.last_patch_stats = Some(stats);
402        self.outputs.last_patch_hash = None;
403        self.outputs.hash_computed = false;
404        self.outputs.last_full_repaint_hint = full_repaint_hint;
405        Ok(())
406    }
407}
408
409#[must_use]
410fn fnv1a64_extend(mut hash: u64, bytes: &[u8]) -> u64 {
411    for &byte in bytes {
412        hash ^= u64::from(byte);
413        hash = hash.wrapping_mul(FNV64_PRIME);
414    }
415    hash
416}
417
418#[must_use]
419fn cell_to_patch(cell: &Cell) -> WebPatchCell {
420    let glyph = match cell.content {
421        CellContent::EMPTY | CellContent::CONTINUATION => 0,
422        other if other.is_grapheme() => GRAPHEME_FALLBACK_CODEPOINT,
423        other => other.as_char().map_or(0, |c| c as u32),
424    };
425    let style_bits = u32::from(cell.attrs.flags().bits()) & ATTR_STYLE_MASK;
426    let link_id = cell.attrs.link_id().min(ATTR_LINK_ID_MAX);
427    WebPatchCell {
428        bg: cell.bg.0,
429        fg: cell.fg.0,
430        glyph,
431        attrs: style_bits | (link_id << 8),
432    }
433}
434
435#[must_use]
436fn full_buffer_patch(buffer: &Buffer) -> WebPatchRun {
437    let cols = buffer.width();
438    let rows = buffer.height();
439    let total = usize::from(cols) * usize::from(rows);
440    let mut cells = Vec::with_capacity(total);
441    for y in 0..rows {
442        for x in 0..cols {
443            cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
444        }
445    }
446    WebPatchRun { offset: 0, cells }
447}
448
449#[must_use]
450fn diff_to_patches(buffer: &Buffer, diff: &BufferDiff) -> Vec<WebPatchRun> {
451    if diff.is_empty() {
452        return Vec::new();
453    }
454    let width = buffer.width();
455    let height = buffer.height();
456    let cols = u32::from(width);
457    // Heuristic: most sparse diffs produce one patch per ~8 dirty cells.
458    let est_patches = diff.len().div_ceil(8).max(1);
459    let mut patches = Vec::with_capacity(est_patches);
460    let mut span_start: u32 = 0;
461    let mut span_cells: Vec<WebPatchCell> = Vec::with_capacity(diff.len());
462    let mut prev_offset: u32 = 0;
463    let mut has_span = false;
464
465    for &(x, y) in diff.changes() {
466        // Safety: diffs can become stale across resize; fall back to a full patch.
467        if x >= width || y >= height {
468            return vec![full_buffer_patch(buffer)];
469        }
470        let offset = u32::from(y) * cols + u32::from(x);
471        if !has_span {
472            span_start = offset;
473            prev_offset = offset;
474            has_span = true;
475            span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
476            continue;
477        }
478        if offset == prev_offset {
479            continue;
480        }
481        if offset == prev_offset + 1 {
482            span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
483        } else {
484            patches.push(WebPatchRun {
485                offset: span_start,
486                cells: std::mem::take(&mut span_cells),
487            });
488            span_start = offset;
489            span_cells.push(cell_to_patch(buffer.get_unchecked(x, y)));
490        }
491        prev_offset = offset;
492    }
493    if !span_cells.is_empty() {
494        patches.push(WebPatchRun {
495            offset: span_start,
496            cells: span_cells,
497        });
498    }
499    patches
500}
501
502#[must_use]
503fn build_patch_runs(
504    buffer: &Buffer,
505    diff: Option<&BufferDiff>,
506    full_repaint_hint: bool,
507) -> Vec<WebPatchRun> {
508    if full_repaint_hint {
509        return vec![full_buffer_patch(buffer)];
510    }
511    match diff {
512        Some(dirty) => diff_to_patches(buffer, dirty),
513        None => vec![full_buffer_patch(buffer)],
514    }
515}
516
517#[must_use]
518fn patch_batch_stats(patches: &[WebPatchRun]) -> WebPatchStats {
519    let dirty_cells_u64 = patches
520        .iter()
521        .map(|patch| patch.cells.len() as u64)
522        .sum::<u64>();
523    let dirty_cells = dirty_cells_u64.min(u64::from(u32::MAX)) as u32;
524    let patch_count = patches.len().min(u32::MAX as usize) as u32;
525    let bytes_uploaded = dirty_cells_u64.saturating_mul(WEB_PATCH_CELL_BYTES);
526    WebPatchStats {
527        dirty_cells,
528        patch_count,
529        bytes_uploaded,
530    }
531}
532
533#[must_use]
534fn patch_batch_hash(patches: &[WebPatchRun]) -> String {
535    let mut hash = FNV64_OFFSET_BASIS;
536    let patch_count = u64::try_from(patches.len()).unwrap_or(u64::MAX);
537    hash = fnv1a64_extend(hash, &patch_count.to_le_bytes());
538
539    // Pre-allocate a 16-byte buffer for batching cell fields into a single
540    // fnv1a64_extend call (4× fewer function calls per cell).
541    let mut cell_bytes = [0u8; 16];
542    for patch in patches {
543        let cell_count = u64::try_from(patch.cells.len()).unwrap_or(u64::MAX);
544        hash = fnv1a64_extend(hash, &patch.offset.to_le_bytes());
545        hash = fnv1a64_extend(hash, &cell_count.to_le_bytes());
546        for cell in &patch.cells {
547            cell_bytes[0..4].copy_from_slice(&cell.bg.to_le_bytes());
548            cell_bytes[4..8].copy_from_slice(&cell.fg.to_le_bytes());
549            cell_bytes[8..12].copy_from_slice(&cell.glyph.to_le_bytes());
550            cell_bytes[12..16].copy_from_slice(&cell.attrs.to_le_bytes());
551            hash = fnv1a64_extend(hash, &cell_bytes);
552        }
553    }
554
555    format!("{PATCH_HASH_ALGO}:{hash:016x}")
556}
557
558/// A minimal, host-driven WASM backend.
559///
560/// This backend is intended to be driven by a JS host:
561/// - push events via [`Self::events_mut`]
562/// - advance time via [`Self::clock_mut`]
563/// - read rendered buffers via [`Self::presenter_mut`]
564#[derive(Debug, Clone)]
565pub struct WebBackend {
566    clock: DeterministicClock,
567    events: WebEventSource,
568    presenter: WebPresenter,
569}
570
571impl WebBackend {
572    /// Create a backend with an initial size.
573    #[must_use]
574    pub fn new(width: u16, height: u16) -> Self {
575        Self {
576            clock: DeterministicClock::new(),
577            events: WebEventSource::new(width, height),
578            presenter: WebPresenter::new(),
579        }
580    }
581
582    /// Mutably access the clock.
583    pub fn clock_mut(&mut self) -> &mut DeterministicClock {
584        &mut self.clock
585    }
586
587    /// Mutably access the event source.
588    pub fn events_mut(&mut self) -> &mut WebEventSource {
589        &mut self.events
590    }
591
592    /// Mutably access the presenter.
593    pub fn presenter_mut(&mut self) -> &mut WebPresenter {
594        &mut self.presenter
595    }
596}
597
598impl Backend for WebBackend {
599    type Error = WebBackendError;
600
601    type Clock = DeterministicClock;
602    type Events = WebEventSource;
603    type Presenter = WebPresenter;
604
605    fn clock(&self) -> &Self::Clock {
606        &self.clock
607    }
608
609    fn events(&mut self) -> &mut Self::Events {
610        &mut self.events
611    }
612
613    fn presenter(&mut self) -> &mut Self::Presenter {
614        &mut self.presenter
615    }
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621    use ftui_render::cell::Cell;
622
623    use pretty_assertions::assert_eq;
624
625    #[test]
626    fn deterministic_clock_advances_monotonically() {
627        let mut c = DeterministicClock::new();
628        assert_eq!(c.now_mono(), Duration::ZERO);
629
630        c.advance(Duration::from_millis(10));
631        assert_eq!(c.now_mono(), Duration::from_millis(10));
632
633        c.advance(Duration::from_millis(5));
634        assert_eq!(c.now_mono(), Duration::from_millis(15));
635
636        // Saturation: don't panic or wrap.
637        c.set(Duration::MAX);
638        c.advance(Duration::from_secs(1));
639        assert_eq!(c.now_mono(), Duration::MAX);
640    }
641
642    #[test]
643    fn web_event_source_fifo_queue() {
644        let mut ev = WebEventSource::new(80, 24);
645        assert_eq!(ev.size().unwrap(), (80, 24));
646        assert_eq!(ev.poll_event(Duration::from_millis(0)).unwrap(), false);
647
648        ev.push_event(Event::Tick);
649        ev.push_event(Event::Resize {
650            width: 100,
651            height: 40,
652        });
653
654        assert_eq!(ev.poll_event(Duration::from_millis(0)).unwrap(), true);
655        assert_eq!(ev.read_event().unwrap(), Some(Event::Tick));
656        assert_eq!(
657            ev.read_event().unwrap(),
658            Some(Event::Resize {
659                width: 100,
660                height: 40,
661            })
662        );
663        assert_eq!(ev.read_event().unwrap(), None);
664    }
665
666    #[test]
667    fn presenter_captures_logs_and_last_buffer() {
668        let mut p = WebPresenter::new();
669        p.write_log("hello").unwrap();
670        p.write_log("world").unwrap();
671
672        let buf = Buffer::new(2, 2);
673        p.present_ui(&buf, None, true).unwrap();
674
675        let mut outputs = p.take_outputs();
676        assert_eq!(outputs.logs, vec!["hello", "world"]);
677        assert_eq!(outputs.last_full_repaint_hint, true);
678        assert_eq!(outputs.last_buffer.as_ref().unwrap().width(), 2);
679        assert_eq!(outputs.last_patches.len(), 1);
680        let stats = outputs.last_patch_stats.expect("stats should be present");
681        assert_eq!(stats.patch_count, 1);
682        assert_eq!(stats.dirty_cells, 4);
683        assert_eq!(stats.bytes_uploaded, 64);
684        let hash = outputs
685            .compute_patch_hash()
686            .expect("hash should be present");
687        assert!(hash.starts_with("fnv1a64:"));
688    }
689
690    #[test]
691    fn presenter_emits_incremental_patch_runs_from_diff() {
692        let mut presenter = WebPresenter::new();
693        let old = Buffer::new(6, 2);
694        presenter.present_ui(&old, None, true).unwrap();
695
696        let mut next = Buffer::new(6, 2);
697        next.set_raw(2, 0, Cell::from_char('A'));
698        next.set_raw(3, 0, Cell::from_char('B'));
699        next.set_raw(0, 1, Cell::from_char('C'));
700        let diff = BufferDiff::compute(&old, &next);
701        presenter.present_ui(&next, Some(&diff), false).unwrap();
702
703        let mut outputs = presenter.take_outputs();
704        assert_eq!(outputs.last_full_repaint_hint, false);
705        assert_eq!(outputs.last_patches.len(), 2);
706        assert_eq!(outputs.last_patches[0].offset, 2);
707        assert_eq!(outputs.last_patches[0].cells.len(), 2);
708        assert_eq!(outputs.last_patches[1].offset, 6);
709        assert_eq!(outputs.last_patches[1].cells.len(), 1);
710        let stats = outputs.last_patch_stats.expect("stats should be present");
711        assert_eq!(stats.patch_count, 2);
712        assert_eq!(stats.dirty_cells, 3);
713        assert_eq!(stats.bytes_uploaded, 48);
714        let hash = outputs
715            .compute_patch_hash()
716            .expect("hash should be present");
717        assert!(hash.starts_with("fnv1a64:"));
718    }
719
720    #[test]
721    fn stale_diff_falls_back_to_full_patch() {
722        let old = Buffer::new(4, 2);
723        let mut next = Buffer::new(4, 2);
724        next.set_raw(3, 1, Cell::from_char('X'));
725        let stale_diff = BufferDiff::compute(&old, &next);
726
727        let resized = Buffer::new(2, 1);
728        let patches = build_patch_runs(&resized, Some(&stale_diff), false);
729
730        assert_eq!(patches.len(), 1);
731        assert_eq!(patches[0].offset, 0);
732        assert_eq!(patches[0].cells.len(), 2);
733    }
734
735    #[test]
736    fn patch_batch_hash_is_deterministic() {
737        let patches = vec![
738            WebPatchRun {
739                offset: 2,
740                cells: vec![
741                    WebPatchCell {
742                        bg: 0x1122_3344,
743                        fg: 0x5566_7788,
744                        glyph: 'A' as u32,
745                        attrs: 0x0000_0001,
746                    },
747                    WebPatchCell {
748                        bg: 0x1122_3344,
749                        fg: 0x5566_7788,
750                        glyph: 'B' as u32,
751                        attrs: 0x0000_0002,
752                    },
753                ],
754            },
755            WebPatchRun {
756                offset: 10,
757                cells: vec![WebPatchCell {
758                    bg: 0xAABB_CCDD,
759                    fg: 0xDDEE_FF00,
760                    glyph: '中' as u32,
761                    attrs: 0x0000_0010,
762                }],
763            },
764        ];
765
766        let hash_a = patch_batch_hash(&patches);
767        let hash_b = patch_batch_hash(&patches);
768        assert_eq!(hash_a, hash_b);
769        assert!(hash_a.starts_with("fnv1a64:"));
770    }
771
772    #[test]
773    fn patch_batch_hash_changes_with_patch_payload() {
774        let baseline = vec![WebPatchRun {
775            offset: 4,
776            cells: vec![WebPatchCell {
777                bg: 0x0000_00FF,
778                fg: 0xFFFF_FFFF,
779                glyph: 'x' as u32,
780                attrs: 0x0000_0001,
781            }],
782        }];
783        let mut changed = baseline.clone();
784        changed[0].offset = 5;
785
786        let base_hash = patch_batch_hash(&baseline);
787        let changed_hash = patch_batch_hash(&changed);
788        assert_ne!(base_hash, changed_hash);
789
790        changed[0].offset = 4;
791        changed[0].cells[0].glyph = 'y' as u32;
792        let changed_glyph_hash = patch_batch_hash(&changed);
793        assert_ne!(base_hash, changed_glyph_hash);
794    }
795
796    #[test]
797    fn flatten_patches_u32_emits_row_major_cells_and_spans() {
798        let outputs = WebOutputs {
799            last_patches: vec![
800                WebPatchRun {
801                    offset: 2,
802                    cells: vec![
803                        WebPatchCell {
804                            bg: 10,
805                            fg: 11,
806                            glyph: 12,
807                            attrs: 13,
808                        },
809                        WebPatchCell {
810                            bg: 20,
811                            fg: 21,
812                            glyph: 22,
813                            attrs: 23,
814                        },
815                    ],
816                },
817                WebPatchRun {
818                    offset: 9,
819                    cells: vec![WebPatchCell {
820                        bg: 30,
821                        fg: 31,
822                        glyph: 32,
823                        attrs: 33,
824                    }],
825                },
826            ],
827            ..WebOutputs::default()
828        };
829
830        let flat = outputs.flatten_patches_u32();
831        assert_eq!(flat.spans, vec![2, 2, 9, 1]);
832        assert_eq!(
833            flat.cells,
834            vec![
835                10, 11, 12, 13, //
836                20, 21, 22, 23, //
837                30, 31, 32, 33
838            ]
839        );
840    }
841
842    #[test]
843    fn flatten_patches_u32_handles_empty_payload() {
844        let outputs = WebOutputs::default();
845        let flat = outputs.flatten_patches_u32();
846        assert!(flat.cells.is_empty());
847        assert!(flat.spans.is_empty());
848    }
849
850    // --- WebBackendError ---
851
852    #[test]
853    fn web_backend_error_display() {
854        let err = WebBackendError::Unsupported("test op");
855        assert_eq!(format!("{err}"), "unsupported: test op");
856    }
857
858    #[test]
859    fn web_backend_error_is_std_error() {
860        let err = WebBackendError::Unsupported("foo");
861        let _: &dyn std::error::Error = &err;
862    }
863
864    #[test]
865    fn web_backend_error_eq() {
866        assert_eq!(
867            WebBackendError::Unsupported("a"),
868            WebBackendError::Unsupported("a")
869        );
870        assert_ne!(
871            WebBackendError::Unsupported("a"),
872            WebBackendError::Unsupported("b")
873        );
874    }
875
876    // --- DeterministicClock ---
877
878    #[test]
879    fn clock_set_overrides_current() {
880        let mut c = DeterministicClock::new();
881        c.set(Duration::from_secs(42));
882        assert_eq!(c.now_mono(), Duration::from_secs(42));
883    }
884
885    #[test]
886    fn clock_default_is_zero() {
887        let c = DeterministicClock::default();
888        assert_eq!(c.now_mono(), Duration::ZERO);
889    }
890
891    #[test]
892    fn clock_clone() {
893        let mut c = DeterministicClock::new();
894        c.advance(Duration::from_millis(100));
895        let c2 = c.clone();
896        assert_eq!(c2.now_mono(), Duration::from_millis(100));
897    }
898
899    // --- WebEventSource ---
900
901    #[test]
902    fn event_source_set_size() {
903        let mut ev = WebEventSource::new(80, 24);
904        ev.set_size(120, 50);
905        assert_eq!(ev.size().unwrap(), (120, 50));
906    }
907
908    #[test]
909    fn event_source_drain_events() {
910        let mut ev = WebEventSource::new(80, 24);
911        ev.push_event(Event::Tick);
912        ev.push_event(Event::Tick);
913
914        let drained: Vec<_> = ev.drain_events().collect();
915        assert_eq!(drained.len(), 2);
916        assert_eq!(ev.poll_event(Duration::ZERO).unwrap(), false);
917    }
918
919    #[test]
920    fn event_source_features() {
921        let mut ev = WebEventSource::new(80, 24);
922        let f = BackendFeatures::default();
923        ev.set_features(f).unwrap();
924        let _ = ev.features(); // should not panic
925    }
926
927    #[test]
928    fn event_source_empty_read_returns_none() {
929        let mut ev = WebEventSource::new(80, 24);
930        assert_eq!(ev.read_event().unwrap(), None);
931    }
932
933    // --- WebPresenter ---
934
935    #[test]
936    fn presenter_default_is_new() {
937        let a = WebPresenter::new();
938        let b = WebPresenter::default();
939        assert!(a.outputs().logs.is_empty());
940        assert!(b.outputs().logs.is_empty());
941    }
942
943    #[test]
944    fn presenter_outputs_accessor() {
945        let mut p = WebPresenter::new();
946        p.write_log("test").unwrap();
947        assert_eq!(p.outputs().logs.len(), 1);
948    }
949
950    #[test]
951    fn presenter_outputs_mut() {
952        let mut p = WebPresenter::new();
953        p.outputs_mut().logs.push("manual".to_string());
954        assert_eq!(p.outputs().logs, vec!["manual"]);
955    }
956
957    #[test]
958    fn presenter_take_outputs_clears() {
959        let mut p = WebPresenter::new();
960        p.write_log("a").unwrap();
961        let taken = p.take_outputs();
962        assert_eq!(taken.logs, vec!["a"]);
963        assert!(p.outputs().logs.is_empty());
964    }
965
966    #[test]
967    fn presenter_capabilities_are_modern() {
968        let p = WebPresenter::new();
969        let caps = p.capabilities();
970        assert!(caps.supports_true_color());
971    }
972
973    #[test]
974    fn presenter_present_ui_owned() {
975        let mut p = WebPresenter::new();
976        let buf = Buffer::new(3, 2);
977        p.present_ui_owned(buf, None, true);
978
979        let mut out = p.take_outputs();
980        assert!(out.last_full_repaint_hint);
981        assert_eq!(out.last_buffer.as_ref().unwrap().width(), 3);
982        assert_eq!(out.last_patches.len(), 1);
983        assert!(out.last_patch_stats.is_some());
984        assert!(out.compute_patch_hash().is_some());
985    }
986
987    // --- WebBackend ---
988
989    #[test]
990    fn web_backend_construction() {
991        let mut wb = WebBackend::new(80, 24);
992        assert_eq!(wb.events_mut().size().unwrap(), (80, 24));
993        assert_eq!(wb.clock_mut().now_mono(), Duration::ZERO);
994    }
995
996    #[test]
997    fn web_backend_implements_backend_trait() {
998        let mut wb = WebBackend::new(80, 24);
999        // Verify Backend trait methods
1000        let _ = wb.clock();
1001        let _ = wb.events();
1002        let _ = wb.presenter();
1003    }
1004
1005    // --- patch_batch_stats ---
1006
1007    #[test]
1008    fn patch_batch_stats_empty() {
1009        let stats = patch_batch_stats(&[]);
1010        assert_eq!(stats.dirty_cells, 0);
1011        assert_eq!(stats.patch_count, 0);
1012        assert_eq!(stats.bytes_uploaded, 0);
1013    }
1014
1015    #[test]
1016    fn patch_batch_stats_counts_cells() {
1017        let patches = vec![
1018            WebPatchRun {
1019                offset: 0,
1020                cells: vec![
1021                    WebPatchCell {
1022                        bg: 0,
1023                        fg: 0,
1024                        glyph: 0,
1025                        attrs: 0,
1026                    };
1027                    3
1028                ],
1029            },
1030            WebPatchRun {
1031                offset: 10,
1032                cells: vec![WebPatchCell {
1033                    bg: 0,
1034                    fg: 0,
1035                    glyph: 0,
1036                    attrs: 0,
1037                }],
1038            },
1039        ];
1040        let stats = patch_batch_stats(&patches);
1041        assert_eq!(stats.dirty_cells, 4);
1042        assert_eq!(stats.patch_count, 2);
1043        assert_eq!(stats.bytes_uploaded, 64); // 4 cells * 16 bytes
1044    }
1045
1046    // --- patch_batch_hash ---
1047
1048    #[test]
1049    fn patch_hash_empty_is_deterministic() {
1050        let a = patch_batch_hash(&[]);
1051        let b = patch_batch_hash(&[]);
1052        assert_eq!(a, b);
1053        assert!(a.starts_with("fnv1a64:"));
1054    }
1055
1056    // --- build_patch_runs ---
1057
1058    #[test]
1059    fn build_patch_runs_full_repaint_hint() {
1060        let buf = Buffer::new(2, 2);
1061        let patches = build_patch_runs(&buf, None, true);
1062        assert_eq!(patches.len(), 1);
1063        assert_eq!(patches[0].offset, 0);
1064        assert_eq!(patches[0].cells.len(), 4);
1065    }
1066
1067    #[test]
1068    fn build_patch_runs_no_diff_triggers_full() {
1069        let buf = Buffer::new(3, 1);
1070        let patches = build_patch_runs(&buf, None, false);
1071        // None diff → full buffer patch
1072        assert_eq!(patches.len(), 1);
1073        assert_eq!(patches[0].cells.len(), 3);
1074    }
1075
1076    // --- WebOutputs default ---
1077
1078    #[test]
1079    fn web_outputs_default_is_empty() {
1080        let out = WebOutputs::default();
1081        assert!(out.logs.is_empty());
1082        assert!(out.last_buffer.is_none());
1083        assert!(out.last_patches.is_empty());
1084        assert!(out.last_patch_stats.is_none());
1085        assert!(out.last_patch_hash.is_none());
1086        assert!(!out.last_full_repaint_hint);
1087    }
1088
1089    // --- cell_to_patch ---
1090
1091    #[test]
1092    fn cell_to_patch_empty_cell() {
1093        let cell = Cell::default();
1094        let patch = cell_to_patch(&cell);
1095        // Empty cell should have glyph=0
1096        assert_eq!(patch.glyph, 0);
1097    }
1098
1099    #[test]
1100    fn cell_to_patch_ascii_char() {
1101        let cell = Cell::from_char('A');
1102        let patch = cell_to_patch(&cell);
1103        assert_eq!(patch.glyph, 'A' as u32);
1104    }
1105
1106    #[test]
1107    fn cell_to_patch_preserves_max_link_id() {
1108        use ftui_render::cell::{CellAttrs, StyleFlags};
1109
1110        let cell = Cell::from_char('L').with_attrs(CellAttrs::new(
1111            StyleFlags::UNDERLINE,
1112            CellAttrs::LINK_ID_MAX,
1113        ));
1114        let patch = cell_to_patch(&cell);
1115
1116        assert_eq!(patch.attrs >> 8, CellAttrs::LINK_ID_MAX);
1117    }
1118}