ntui 0.3.1

An Ink-style TUI library for Rust: components, hooks, flexbox layout, and fullscreen rendering.
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
use std::collections::HashSet;
use std::time::{Duration, Instant};

use crossterm::event::{Event, EventStream};
use futures::{FutureExt, StreamExt};
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};

use crate::backend::inline::{InlineSink, buffer_rows};
use crate::backend::{Backend, FullscreenBackend, InlineBackend};
use crate::buffer::{Buffer, Cell};
use crate::element::Element;
use crate::error::Error;
use crate::fiber::{FiberId, FiberTree};
use crate::hooks::{RuntimeHandle, Wake};
use crate::layout::compute_layout;
use crate::paint::paint;

const FRAME: Duration = Duration::from_millis(16); // ~60fps cap

/// Per-frame bound on burst draining: caps how many immediately-ready input
/// events (paste, key repeat) are drained in a single iteration so wakes
/// can't be starved by a large burst.
const MAX_EVENT_BURST: usize = 128;

/// Cap on outer `process_wakes` fixpoint passes. Mirrors React's
/// "maximum update depth exceeded" guard: a component whose effect
/// re-dirties state on every pass would otherwise spin the loop forever.
const MAX_UPDATE_PASSES: usize = 64;

/// The engine loop's shared core. `render()` drives it with a select loop;
/// `testing::TestTerminal` drives it by hand for deterministic tests.
pub(crate) struct AppCore {
    pub tree: FiberTree,
    pub rt: RuntimeHandle,
    wake_rx: UnboundedReceiver<Wake>,
    pending: Vec<FiberId>,
    prev: Option<Buffer>,
    /// Spare buffer for `draw`'s double-buffering (see `draw`'s doc comment).
    scratch: Option<Buffer>,
    /// Set by `resize`; makes the next `draw` rewrite every cell (blanks
    /// included) instead of diffing, since the terminal's contents after a
    /// resize no longer match `prev`.
    force_full: bool,
    pub size: (u16, u16),
    pub exited: bool,
    /// Clipboard payloads queued via `Wake::CopyToClipboard`, drained by the
    /// backend-driving layer (run loops, `TestTerminal`) through
    /// [`Self::take_pending_clipboard`] — `AppCore` itself never touches a
    /// terminal handle.
    pending_clipboard: Vec<String>,
    /// Last `(width, max_height)` passed to `live_rows`, used to gate its
    /// `compute_layout` call the same way `draw` gates on `layout_dirty` /
    /// `prev.is_none()`. `None` until the first `live_rows` call.
    live_size: Option<(u16, u16)>,
    /// Spare buffer for `live_rows`'s double-buffering, mirroring `scratch`
    /// (see `draw`'s doc comment) so inline mode doesn't allocate a fresh
    /// `Buffer` every frame either.
    live_scratch: Option<Buffer>,
}

impl AppCore {
    pub fn new(el: Element, size: (u16, u16)) -> Self {
        let (wake, wake_rx) = unbounded_channel();
        let rt = RuntimeHandle {
            wake,
            size: std::sync::Arc::new(std::sync::Mutex::new(size)),
            scrollback: std::rc::Rc::new(std::cell::RefCell::new(Vec::new())),
        };
        let mut tree = FiberTree::new();
        tree.mount_root(el, &rt);
        tree.flush_effects();
        AppCore {
            tree,
            rt,
            wake_rx,
            pending: Vec::new(),
            prev: None,
            scratch: None,
            force_full: false,
            size,
            exited: false,
            pending_clipboard: Vec::new(),
            live_size: None,
            live_scratch: None,
        }
    }

    pub fn apply_wake(&mut self, w: Wake) {
        match w {
            Wake::Dirty(id) => self.pending.push(id),
            Wake::Redraw => {
                if let Some(root) = self.tree.root {
                    self.pending.push(root);
                }
                self.prev = None; // full repaint
            }
            Wake::Exit => self.exited = true,
            Wake::CopyToClipboard(text) => self.pending_clipboard.push(text),
        }
    }

    /// Drains queued clipboard payloads (see the `pending_clipboard` field).
    /// The caller writes each to the backend; call before drawing so a copy
    /// lands on the same frame that requested it.
    pub fn take_pending_clipboard(&mut self) -> Vec<String> {
        std::mem::take(&mut self.pending_clipboard)
    }

    /// Drain the wake channel, re-render dirty fibers shallowest-first,
    /// then run effects (which may queue more wakes for the next pass).
    pub fn process_wakes(&mut self) {
        while let Ok(w) = self.wake_rx.try_recv() {
            self.apply_wake(w);
        }
        // Loop: effects may set state synchronously.
        let mut passes = 0;
        while !self.pending.is_empty() {
            passes += 1;
            if passes > MAX_UPDATE_PASSES {
                panic!(
                    "ntui: maximum update depth exceeded ({MAX_UPDATE_PASSES} passes) — a use_effect that sets state unconditionally, or a state update during every render, is preventing the UI from reaching a stable state"
                );
            }
            let mut dirty = std::mem::take(&mut self.pending);
            let mut seen = HashSet::new();
            dirty.retain(|id| seen.insert(*id));
            dirty.sort_by_key(|id| self.depth(*id));
            let rt = self.rt.clone();
            for id in dirty {
                self.tree.render_fiber(id, &rt); // no-ops if already unmounted
            }
            self.tree.flush_effects();
            while let Ok(w) = self.wake_rx.try_recv() {
                self.apply_wake(w);
            }
        }
    }

    /// Route a key event deepest-first through mounted `use_input` handlers,
    /// stopping early if a handler calls `stop_propagation`. Release events
    /// (Windows/kitty protocol) are dropped — only Press/Repeat are dispatched.
    pub fn dispatch_key(&mut self, ev: crossterm::event::KeyEvent) {
        if ev.kind == crossterm::event::KeyEventKind::Release {
            return;
        }
        let handlers = self.tree.collect_input_handlers();
        let mut ctx = crate::hooks::input::InputCtx { stopped: false };
        for h in handlers {
            h.borrow_mut()(ev, &mut ctx);
            if ctx.stopped {
                break;
            }
        }
    }

    /// Route a bracketed-paste event deepest-first through mounted `use_paste`
    /// handlers, with the same bubbling semantics as [`Self::dispatch_key`].
    pub fn dispatch_paste(&mut self, text: &str) {
        let handlers = self.tree.collect_paste_handlers();
        let mut ctx = crate::hooks::input::InputCtx { stopped: false };
        for h in handlers {
            h.borrow_mut()(text, &mut ctx);
            if ctx.stopped {
                break;
            }
        }
    }

    fn depth(&self, mut id: FiberId) -> usize {
        let mut d = 0;
        while self.tree.contains(id) {
            match self.tree.get(id).parent {
                Some(p) => {
                    d += 1;
                    id = p;
                }
                None => break,
            }
        }
        d
    }

    /// Layout (if dirty), paint, diff against previous frame, flush.
    pub fn draw(&mut self, backend: &mut dyn Backend) -> Result<(), Error> {
        if self.tree.layout_dirty || self.prev.is_none() {
            compute_layout(&mut self.tree, self.size.0, self.size.1);
        }
        // Double-buffer: paint into `self.scratch` (the buffer from two
        // frames ago, if any) instead of allocating fresh every frame, diff
        // against `self.prev` (last frame's buffer), then swap the two
        // roles for next time. This avoids a Vec alloc+zero-fill per frame
        // in the common case where the terminal size hasn't changed.
        let mut buf = self
            .scratch
            .take()
            .unwrap_or_else(|| Buffer::new(self.size.0, self.size.1));
        buf.resize_and_clear(self.size.0, self.size.1);
        paint(&self.tree, &mut buf);
        let baseline;
        let prev: &Buffer = if self.force_full {
            // After a resize the terminal still shows the old frame in
            // whatever cells the new frame doesn't overwrite — so diff
            // against a size-mismatched baseline, which makes `Buffer::diff`
            // emit every cell (blanks included), not just the non-blank ones
            // a blank baseline would produce.
            baseline = Buffer::new(0, 0);
            &baseline
        } else if let Some(p) = &self.prev {
            p
        } else {
            // First frame: enter() left the screen cleared, so a blank
            // baseline at the current size skips writing the blank cells.
            baseline = Buffer::new(self.size.0, self.size.1);
            &baseline
        };
        backend.flush(&buf.diff(prev))?;
        self.force_full = false;
        self.scratch = self.prev.take();
        self.prev = Some(buf);
        Ok(())
    }

    /// Inline mode: content-sized rows of the live region. Lays out at `width`
    /// (bounded to `max_height`), paints, and drops trailing blank rows.
    pub fn live_rows(&mut self, width: u16, max_height: u16) -> Vec<Vec<Cell>> {
        let size_changed = self.live_size != Some((width, max_height));
        if self.tree.layout_dirty || size_changed {
            compute_layout(&mut self.tree, width, max_height);
            self.live_size = Some((width, max_height));
        }
        let mut buf = self
            .live_scratch
            .take()
            .unwrap_or_else(|| Buffer::new(width, max_height));
        buf.resize_and_clear(width, max_height);
        paint(&self.tree, &mut buf);
        let rows = trim_rows(buffer_rows(&buf));
        self.live_scratch = Some(buf);
        rows
    }

    /// Inline mode: drain queued scrollback elements, rendering each to rows to
    /// be committed permanently. Each element is laid out and painted on its own.
    pub fn take_committed(&mut self, width: u16, max_height: u16) -> Vec<Vec<Cell>> {
        let queued: Vec<Element> = std::mem::take(&mut *self.rt.scrollback.borrow_mut());
        let mut rows = Vec::new();
        for el in queued {
            let mut tree = FiberTree::new();
            tree.mount_root(el, &self.rt);
            compute_layout(&mut tree, width, max_height);
            let mut buf = Buffer::new(width, max_height);
            paint(&tree, &mut buf);
            rows.extend(trim_rows(buffer_rows(&buf)));
        }
        rows
    }

    // Used by the render() event-loop task to await the next wake.
    #[cfg_attr(coverage_nightly, coverage(off))]
    pub async fn wait_wake(&mut self) -> Option<Wake> {
        self.wake_rx.recv().await
    }

    pub fn resize(&mut self, w: u16, h: u16) {
        self.size = (w, h);
        *self
            .rt
            .size
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = (w, h);
        self.tree.layout_dirty = true;
        // Force a true full repaint on the next draw: the terminal still
        // shows the old frame, so every cell — including ones blank in the
        // new frame — must be rewritten. (Setting `prev = None` instead
        // would diff against an assumed-blank screen and skip blank cells,
        // leaving stale content wherever the new frame has none.)
        self.force_full = true;
        // Push the root as dirty so components reading use_terminal_size()
        // re-render with the new size. The caller must invoke
        // process_wakes() after resize() to actually apply this;
        // TestTerminal::resize does, and so does the render() loop, which
        // calls process_wakes() on its next iteration after Event::Resize.
        if let Some(root) = self.tree.root {
            self.pending.push(root);
        }
    }
}

/// Restores the terminal even when a panic unwinds through the render future.
pub(crate) struct RestoreGuard<'a, B: Backend + ?Sized> {
    pub backend: &'a mut B,
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl<'a, B: Backend + ?Sized> Drop for RestoreGuard<'a, B> {
    fn drop(&mut self) {
        let _ = self.backend.leave();
    }
}

/// Belt-and-braces: if a panic is printed while the alternate screen is
/// active, the message would be invisible and raw mode would linger. Restore
/// first, then run the default hook.
///
/// Note: a panic inside a use_future/use_stream task fires this hook
/// (restoring the terminal) but does NOT stop the main loop — the app keeps
/// running against a restored screen. v1 accepts this seam; joining/
/// propagating task panics is future work.
#[cfg_attr(coverage_nightly, coverage(off))]
fn install_panic_hook() {
    use std::sync::Once;
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        let prev = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            let _ = crossterm::terminal::disable_raw_mode();
            let _ = crossterm::execute!(
                std::io::stdout(),
                crossterm::cursor::Show,
                crossterm::terminal::LeaveAlternateScreen,
                crossterm::event::DisableBracketedPaste
            );
            prev(info);
        }));
    });
}

/// Run the app fullscreen until a component calls `use_app().exit()`.
/// Note: the returned future is !Send — use `#[tokio::main(flavor = "current_thread")]`.
#[cfg_attr(coverage_nightly, coverage(off))]
pub async fn render(el: Element) -> Result<(), Error> {
    install_panic_hook();
    let mut backend = FullscreenBackend::new();
    backend.enter()?;
    let guard = RestoreGuard {
        backend: &mut backend,
    };
    run_loop(el, guard).await
}

#[cfg_attr(coverage_nightly, coverage(off))]
async fn run_loop<B: Backend>(el: Element, guard: RestoreGuard<'_, B>) -> Result<(), Error> {
    let size = guard.backend.size()?;
    let mut core = AppCore::new(el, size);
    core.process_wakes();
    flush_clipboard(&mut core, guard.backend);
    core.draw(guard.backend)?;

    let mut events = EventStream::new();
    let mut last_frame = Instant::now();

    while !core.exited {
        tokio::select! {
            ev = events.next() => match ev {
                Some(Ok(Event::Key(k))) => core.dispatch_key(k),
                Some(Ok(Event::Paste(s))) => core.dispatch_paste(&s),
                Some(Ok(Event::Resize(w, h))) => core.resize(w, h),
                Some(Err(e)) => return Err(e.into()),
                None => break, // stdin closed
                _ => {}
            },
            w = core.wait_wake() => match w {
                Some(w) => core.apply_wake(w),
                None => break,
            },
        }
        // Drain any input burst (paste, key repeat) before the frame; bounded so wakes can't starve.
        for _ in 0..MAX_EVENT_BURST {
            match events.next().now_or_never() {
                Some(Some(Ok(Event::Key(k)))) => core.dispatch_key(k),
                Some(Some(Ok(Event::Paste(s)))) => core.dispatch_paste(&s),
                Some(Some(Ok(Event::Resize(w, h)))) => core.resize(w, h),
                Some(Some(Ok(_))) => {}
                Some(Some(Err(e))) => return Err(e.into()),
                Some(None) | None => break,
            }
        }
        core.process_wakes();
        // Flushed before the exited check so a copy queued in the same pass
        // as `app.exit()` (yank-and-quit) still reaches the terminal.
        flush_clipboard(&mut core, guard.backend);
        if core.exited {
            break;
        }
        // Coalesce: hold the frame if we're ahead of the cap, absorbing more wakes.
        let elapsed = last_frame.elapsed();
        if elapsed < FRAME {
            tokio::time::sleep(FRAME - elapsed).await;
            core.process_wakes();
            flush_clipboard(&mut core, guard.backend);
            if core.exited {
                break;
            }
        }
        // Fullscreen never draws committed scrollback (only render_inline does),
        // so discard anything use_scrollback queued to keep it from growing without
        // bound. Committing under render() is a documented no-op.
        core.rt.scrollback.borrow_mut().clear();
        flush_clipboard(&mut core, guard.backend);
        core.draw(guard.backend)?;
        last_frame = Instant::now();
    }
    Ok(()) // guard drops here -> leave()
}

/// Writes any clipboard payloads queued since the last frame to the backend.
/// Best-effort: a failed OSC 52 write (or a terminal that ignores it) must
/// not take down the render loop.
fn flush_clipboard<B: Backend + ?Sized>(core: &mut AppCore, backend: &mut B) {
    for text in core.take_pending_clipboard() {
        let _ = backend.copy_to_clipboard(&text);
    }
}

/// Drop trailing all-blank rows so the live/committed region is content-sized.
fn trim_rows(mut rows: Vec<Vec<Cell>>) -> Vec<Vec<Cell>> {
    while rows
        .last()
        .is_some_and(|r| r.iter().all(|c| *c == Cell::default()))
    {
        rows.pop();
    }
    rows
}

/// Restores the terminal for inline mode even if a panic unwinds through it.
pub(crate) struct InlineRestoreGuard<'a, S: InlineSink + ?Sized> {
    pub backend: &'a mut S,
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl<'a, S: InlineSink + ?Sized> Drop for InlineRestoreGuard<'a, S> {
    fn drop(&mut self) {
        let _ = self.backend.leave();
    }
}

/// Run an app **inline**: finished output committed via
/// [`use_scrollback`](crate::Hooks::use_scrollback) is printed permanently into
/// the terminal's real scrollback, while a live region at the bottom is redrawn
/// in place. Unlike [`render`], this does not use the alternate screen.
///
/// [`use_scrollback`] only draws under this entry point: committing under the
/// fullscreen [`render`] is a no-op (the queued content is discarded each frame).
///
/// The returned future is `!Send` — use `#[tokio::main(flavor = "current_thread")]`.
#[cfg_attr(coverage_nightly, coverage(off))]
pub async fn render_inline(el: Element) -> Result<(), Error> {
    install_panic_hook();
    let mut backend = InlineBackend::new();
    backend.enter()?;
    let guard = InlineRestoreGuard {
        backend: &mut backend,
    };
    run_inline_loop(el, guard).await
}

#[cfg_attr(coverage_nightly, coverage(off))]
async fn run_inline_loop<S: InlineSink>(
    el: Element,
    guard: InlineRestoreGuard<'_, S>,
) -> Result<(), Error> {
    let (w, h) = guard.backend.size()?;
    let mut core = AppCore::new(el, (w, h));
    core.process_wakes();
    commit_and_present(&mut core, guard.backend)?;

    let mut events = EventStream::new();
    let mut last_frame = Instant::now();
    while !core.exited {
        tokio::select! {
            ev = events.next() => match ev {
                Some(Ok(Event::Key(k))) => core.dispatch_key(k),
                Some(Ok(Event::Paste(s))) => core.dispatch_paste(&s),
                Some(Ok(Event::Resize(nw, nh))) => core.resize(nw, nh),
                Some(Err(e)) => return Err(e.into()),
                None => break,
                _ => {}
            },
            wk = core.wait_wake() => match wk {
                Some(wk) => core.apply_wake(wk),
                None => break,
            },
        }
        for _ in 0..MAX_EVENT_BURST {
            match events.next().now_or_never() {
                Some(Some(Ok(Event::Key(k)))) => core.dispatch_key(k),
                Some(Some(Ok(Event::Paste(s)))) => core.dispatch_paste(&s),
                Some(Some(Ok(Event::Resize(nw, nh)))) => core.resize(nw, nh),
                Some(Some(Ok(_))) => {}
                Some(Some(Err(e))) => return Err(e.into()),
                Some(None) | None => break,
            }
        }
        core.process_wakes();
        // Same yank-and-quit rule as run_loop: a copy queued in the exiting
        // pass must still be written before the loop breaks.
        flush_clipboard_inline(&mut core, guard.backend);
        if core.exited {
            break;
        }
        let elapsed = last_frame.elapsed();
        if elapsed < FRAME {
            tokio::time::sleep(FRAME - elapsed).await;
            core.process_wakes();
            flush_clipboard_inline(&mut core, guard.backend);
            if core.exited {
                break;
            }
        }
        commit_and_present(&mut core, guard.backend)?;
        last_frame = Instant::now();
    }
    Ok(())
}

/// Commit any queued scrollback rows, then redraw the live region.
#[cfg_attr(coverage_nightly, coverage(off))]
fn commit_and_present<S: InlineSink>(core: &mut AppCore, backend: &mut S) -> Result<(), Error> {
    flush_clipboard_inline(core, backend);
    let (w, h) = core.size;
    let committed = core.take_committed(w, h);
    if !committed.is_empty() {
        backend.commit(&committed)?;
    }
    let live = core.live_rows(w, h);
    backend.present(&live)?;
    Ok(())
}

/// `flush_clipboard` for the inline sink — same best-effort rule: a failed
/// OSC 52 write must not take down the loop.
fn flush_clipboard_inline<S: InlineSink>(core: &mut AppCore, backend: &mut S) {
    for text in core.take_pending_clipboard() {
        let _ = backend.copy_to_clipboard(&text);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::TestBackend;
    use crate::backend::inline::{InlineSink, RecordingSink};
    use crate::component::Component;
    use crate::hooks::Hooks;
    use crate::props::{Dimension, FlexDirection, TextProps, ViewProps};

    #[test]
    fn restore_guard_leaves_on_drop() {
        let mut be = TestBackend::new(4, 2);
        be.enter().unwrap();
        {
            let _guard = RestoreGuard { backend: &mut be };
        }
        assert_eq!(be.lifecycle, vec!["enter", "leave"]);
    }

    struct Inline;
    impl Component for Inline {
        type Props = ();
        fn render(_: &(), hooks: &mut Hooks) -> Element {
            let sb = hooks.use_scrollback();
            hooks.use_effect((), move || {
                sb.commit(Element::text(TextProps {
                    content: "committed turn".into(),
                    ..Default::default()
                }));
            });
            Element::view(
                ViewProps::default(),
                vec![Element::text(TextProps {
                    content: "> live prompt".into(),
                    ..Default::default()
                })],
            )
        }
    }

    #[test]
    fn inline_splits_committed_scrollback_from_live_region() {
        let mut core = AppCore::new(Element::component::<Inline>(()), (20, 6));
        core.process_wakes(); // runs the mount effect, which queues a commit

        let mut sink = RecordingSink::new(20, 6);
        commit_and_present_into(&mut core, &mut sink);

        // Finished output went to scrollback; the prompt stayed in the live region.
        assert!(
            sink.committed.iter().any(|l| l.contains("committed turn")),
            "committed: {:?}",
            sink.committed
        );
        assert!(
            sink.live.iter().any(|l| l.contains("> live prompt")),
            "live: {:?}",
            sink.live
        );
        assert!(
            !sink.live.iter().any(|l| l.contains("committed turn")),
            "committed content must not remain in the live region"
        );
    }

    #[test]
    fn appcore_wakes_dispatch_release_and_resize_with_depth() {
        use crate::hooks::input::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
        use crate::hooks::state::State;
        use crate::test_util::Shared;

        #[derive(Clone, PartialEq, Default)]
        struct CP {
            handle: Shared<Option<State<i32>>>,
            seen: Shared<i32>,
        }
        struct Child;
        impl Component for Child {
            type Props = CP;
            fn render(props: &CP, hooks: &mut Hooks) -> Element {
                let n = hooks.use_state(|| 0);
                *props.handle.lock() = Some(n.clone());
                *props.seen.lock() = n.get();
                Element::text(TextProps {
                    content: n.get().to_string(),
                    ..Default::default()
                })
            }
        }
        #[derive(Clone, PartialEq, Default)]
        struct PP {
            child: CP,
        }
        struct Parent;
        impl Component for Parent {
            type Props = PP;
            fn render(props: &PP, _hooks: &mut Hooks) -> Element {
                Element::view(
                    ViewProps::default(),
                    vec![Element::component::<Child>(props.child.clone())],
                )
            }
        }

        let props = PP::default();
        let mut core = AppCore::new(Element::component::<Parent>(props.clone()), (10, 5));
        core.process_wakes();

        // Dirty a non-root (child) fiber so depth() walks up to the root.
        let st = props.child.handle.lock().clone().unwrap();
        st.set(7);
        core.process_wakes();
        assert_eq!(*props.child.seen.lock(), 7);

        core.apply_wake(Wake::Redraw);
        core.resize(20, 8);
        core.process_wakes();
        assert_eq!(core.size, (20, 8));

        // A key Release is dropped (only Press/Repeat dispatch).
        core.dispatch_key(KeyEvent::new_with_kind(
            KeyCode::Char('a'),
            KeyModifiers::NONE,
            KeyEventKind::Release,
        ));

        core.apply_wake(Wake::Exit);
        assert!(core.exited);
    }

    #[test]
    fn recording_sink_lifecycle() {
        let mut s = crate::backend::inline::RecordingSink::new(4, 2);
        assert_eq!(s.size().unwrap(), (4, 2));
        s.enter().unwrap();
        s.leave().unwrap();
        assert_eq!(s.lifecycle, vec!["enter", "leave"]);
    }

    // Test shim mirroring commit_and_present for a concrete sink.
    fn commit_and_present_into<S: InlineSink>(core: &mut AppCore, sink: &mut S) {
        let (w, h) = core.size;
        let committed = core.take_committed(w, h);
        sink.commit(&committed).unwrap();
        let live = core.live_rows(w, h);
        sink.present(&live).unwrap();
    }

    struct SizeLabel;
    impl Component for SizeLabel {
        type Props = ();
        fn render(_: &(), hooks: &mut Hooks) -> Element {
            let (w, h) = hooks.use_terminal_size();
            Element::text(TextProps {
                content: format!("{w}x{h}"),
                ..Default::default()
            })
        }
    }

    #[test]
    fn draw_double_buffer_reflects_new_dimensions_after_resize() {
        // Backend sized to the larger of the two dimensions we'll draw at,
        // so both frames' updates land fully inside its buffer.
        let mut core = AppCore::new(Element::component::<SizeLabel>(()), (6, 2));
        core.process_wakes();
        let mut be = TestBackend::new(10, 3);

        core.draw(&mut be).unwrap();
        let row0 = be.to_text().lines().next().unwrap().to_string();
        assert!(
            row0.starts_with("6x2"),
            "expected first frame to show 6x2, got {row0:?}"
        );
        assert_eq!(
            core.prev.as_ref().map(|b| (b.width(), b.height())),
            Some((6, 2))
        );

        core.resize(10, 3);
        core.process_wakes();
        // resize() sets force_full, so this draw is a true full repaint at
        // the new size — it must overwrite every cell of the backend's
        // buffer, including the leftover content from the (6, 2) frame above.
        core.draw(&mut be).unwrap();
        let row0 = be.to_text().lines().next().unwrap().to_string();
        assert!(
            row0.starts_with("10x3"),
            "expected second frame to show 10x3, got {row0:?}"
        );
        assert_eq!(
            core.prev.as_ref().map(|b| (b.width(), b.height())),
            Some((10, 3))
        );
    }

    struct Label;
    #[derive(Clone, PartialEq, Default)]
    struct LabelProps {
        text: crate::test_util::Shared<Option<crate::hooks::state::State<String>>>,
    }
    impl Component for Label {
        type Props = LabelProps;
        fn render(props: &LabelProps, hooks: &mut Hooks) -> Element {
            let s = hooks.use_state(|| "XXXXXX".to_string());
            *props.text.lock() = Some(s.clone());
            Element::text(TextProps {
                content: s.get(),
                ..Default::default()
            })
        }
    }

    #[test]
    fn resize_repaints_cells_that_became_blank() {
        // After a resize the terminal still shows the old frame — the redraw
        // must overwrite every cell, *including* ones that are blank in the
        // new frame. A diff against an assumed-blank baseline (the pre-fix
        // `prev = None` behavior) skips exactly those cells, leaving stale
        // text wherever content shrank across the resize.
        let props = LabelProps::default();
        let mut core = AppCore::new(Element::component::<Label>(props.clone()), (10, 2));
        core.process_wakes();
        let mut be = TestBackend::new(10, 2);
        core.draw(&mut be).unwrap();
        assert!(be.to_text().contains("XXXXXX"));

        props.text.lock().clone().unwrap().set("Y".into());
        core.resize(10, 2);
        core.process_wakes();
        core.draw(&mut be).unwrap();
        let out = be.to_text();
        assert!(out.contains('Y'), "{out:?}");
        assert!(
            !out.contains('X'),
            "stale cells from before the resize were never cleared: {out:?}"
        );
    }

    struct Wrapping;
    impl Component for Wrapping {
        type Props = ();
        fn render(_: &(), _hooks: &mut Hooks) -> Element {
            // `flex_direction: Column` + `width: Percent(1.0)` stretches the
            // Text child to the View's full (resolved) width via
            // `align_items: Stretch` on the cross axis, so it actually wraps
            // at the available width instead of sizing to its unwrapped
            // content length (see `widgets/divider.rs`'s comment on Text's
            // min-content size).
            Element::view(
                ViewProps {
                    flex_direction: FlexDirection::Column,
                    width: Dimension::Percent(100.0),
                    ..Default::default()
                },
                vec![Element::text(TextProps {
                    content: "hello brave new world foo bar".into(),
                    ..Default::default()
                })],
            )
        }
    }

    #[test]
    fn live_rows_gate_skips_recompute_unless_size_changes() {
        let mut core = AppCore::new(Element::component::<Wrapping>(()), (20, 10));
        core.process_wakes();

        let first = core.live_rows(10, 10);
        let second = core.live_rows(10, 10);
        assert_eq!(
            first, second,
            "calling live_rows twice with the same size must be stable"
        );
        assert_eq!(core.live_size, Some((10, 10)));

        let wider = core.live_rows(20, 10);
        assert_eq!(core.live_size, Some((20, 10)));
        assert_ne!(
            wider.len(),
            first.len(),
            "a genuine width change must change how the text wraps"
        );
    }

    #[test]
    fn depth_orders_dirty_fibers_shallowest_first() {
        use crate::hooks::state::State;
        use crate::test_util::Shared;

        // Root (depth 0) wraps Mid (deeper). Both log their id when they render;
        // dirtying both must re-render Root before Mid (shallowest-first).
        #[derive(Clone, PartialEq, Default)]
        struct Ctx {
            root_state: Shared<Option<State<i32>>>,
            mid_state: Shared<Option<State<i32>>>,
            log: Shared<Vec<char>>,
        }
        struct Mid;
        impl Component for Mid {
            type Props = Ctx;
            fn render(ctx: &Ctx, hooks: &mut Hooks) -> Element {
                let n = hooks.use_state(|| 0);
                *ctx.mid_state.lock() = Some(n.clone());
                ctx.log.lock().push('M');
                Element::text(TextProps {
                    content: n.get().to_string(),
                    ..Default::default()
                })
            }
        }
        struct Root;
        impl Component for Root {
            type Props = Ctx;
            fn render(ctx: &Ctx, hooks: &mut Hooks) -> Element {
                let n = hooks.use_state(|| 0);
                *ctx.root_state.lock() = Some(n.clone());
                ctx.log.lock().push('R');
                let _ = n.get();
                Element::view(
                    ViewProps::default(),
                    vec![Element::component::<Mid>(ctx.clone())],
                )
            }
        }

        let ctx = Ctx::default();
        let mut core = AppCore::new(Element::component::<Root>(ctx.clone()), (10, 5));
        core.process_wakes();
        ctx.log.lock().clear(); // drop the mount-time renders

        // Dirty both fibers in one batch so process_wakes must sort by depth.
        ctx.root_state.lock().clone().unwrap().set(1);
        ctx.mid_state.lock().clone().unwrap().set(1);
        core.process_wakes();

        // Root is shallower, so it re-renders first; Root's reconcile leaves Mid's
        // props unchanged (props_eq), so Mid re-renders exactly once, from its own
        // dirty mark — after Root.
        assert_eq!(*ctx.log.lock(), vec!['R', 'M']);
    }
}