Skip to main content

ftui_widgets/
lib.rs

1// Index walks over parallel slices by a single counter; an iterator rewrite would
2// obscure the arithmetic without changing behaviour.
3#![allow(clippy::needless_range_loop)]
4#![forbid(unsafe_code)]
5
6//! Core widgets for FrankenTUI.
7//!
8//! This crate provides the [`Widget`] and [`StatefulWidget`] traits, along with
9//! a collection of ready-to-use widgets for building terminal UIs.
10//!
11//! # Widget Trait Design
12//!
13//! Widgets render into a [`Frame`] rather than directly into a [`Buffer`]. The Frame
14//! provides access to several subsystems beyond the cell grid:
15//!
16//! - **`frame.buffer`** - The cell grid for drawing characters and styles
17//! - **`frame.hit_grid`** - Optional mouse hit testing (for interactive widgets)
18//! - **`frame.cursor_position`** - Cursor placement (for input widgets)
19//! - **`frame.cursor_visible`** - Cursor visibility control
20//! - **`frame.degradation`** - Performance budget hints (for adaptive rendering)
21//!
22//! # Role in FrankenTUI
23//! `ftui-widgets` is the standard widget library. It provides the reusable
24//! building blocks (tables, lists, inputs, graphs, etc.) that most apps will
25//! render inside their `view()` functions.
26//!
27//! # How it fits in the system
28//! Widgets render into `ftui-render::Frame` using `ftui-style` for appearance
29//! and `ftui-text` for text measurement and wrapping. The runtime drives these
30//! widgets by calling your model's `view()` on each frame.
31//!
32//! # Widget Categories
33//!
34//! Widgets fall into four categories based on which Frame features they use:
35//!
36//! ## Category A: Simple Buffer-Only Widgets
37//!
38//! Most widgets only need buffer access. These are the simplest to implement:
39//!
40//! ```ignore
41//! impl Widget for MyWidget {
42//!     fn render(&self, area: Rect, frame: &mut Frame) {
43//!         // Just write to the buffer
44//!         frame.buffer.set(area.x, area.y, Cell::from_char('X'));
45//!     }
46//! }
47//! ```
48//!
49//! Examples: [`block::Block`], [`paragraph::Paragraph`], [`rule::Rule`], [`StatusLine`]
50//!
51//! ## Category B: Interactive Widgets with Hit Testing
52//!
53//! Widgets that handle mouse clicks register hit regions:
54//!
55//! ```ignore
56//! impl Widget for ClickableList {
57//!     fn render(&self, area: Rect, frame: &mut Frame) {
58//!         // Draw items...
59//!         for (i, item) in self.items.iter().enumerate() {
60//!             let row_area = Rect::new(area.x, area.y + i as u16, area.width, 1);
61//!             // Draw item to buffer...
62//!
63//!             // Register hit region for mouse interaction
64//!             if let Some(id) = self.hit_id {
65//!                 frame.register_hit(row_area, id, HitRegion::Content, i as u64);
66//!             }
67//!         }
68//!     }
69//! }
70//! ```
71//!
72//! Examples: [`list::List`], [`table::Table`], [`scrollbar::Scrollbar`]
73//!
74//! ## Category C: Input Widgets with Cursor Control
75//!
76//! Text input widgets need to position the cursor:
77//!
78//! ```ignore
79//! impl Widget for TextInput {
80//!     fn render(&self, area: Rect, frame: &mut Frame) {
81//!         // Draw the input content...
82//!
83//!         // Position cursor when focused
84//!         if self.focused {
85//!             let cursor_x = area.x + self.cursor_offset as u16;
86//!             frame.cursor_position = Some((cursor_x, area.y));
87//!             frame.cursor_visible = true;
88//!         }
89//!     }
90//! }
91//! ```
92//!
93//! Examples: [`TextInput`](input::TextInput)
94//!
95//! ## Category D: Adaptive Widgets with Degradation Support
96//!
97//! Complex widgets can adapt their rendering based on performance budget:
98//!
99//! ```ignore
100//! impl Widget for FancyProgressBar {
101//!     fn render(&self, area: Rect, frame: &mut Frame) {
102//!         let deg = frame.buffer.degradation;
103//!
104//!         if !deg.render_decorative() {
105//!             // Skip decorative elements at reduced budgets
106//!             return;
107//!         }
108//!
109//!         if deg.apply_styling() {
110//!             // Use full styling and effects
111//!         } else {
112//!             // Use simplified ASCII rendering
113//!         }
114//!     }
115//! }
116//! ```
117//!
118//! Examples: [`ProgressBar`](progress::ProgressBar), [`Spinner`](spinner::Spinner)
119//!
120//! # Essential vs Decorative Widgets
121//!
122//! The [`Widget::is_essential`] method indicates whether a widget should always render,
123//! even at `EssentialOnly` degradation level:
124//!
125//! - **Essential**: Text inputs, primary content, status information
126//! - **Decorative**: Borders, scrollbars, spinners, visual separators
127//!
128//! [`Frame`]: ftui_render::frame::Frame
129//! [`Buffer`]: ftui_render::buffer::Buffer
130
131pub mod adaptive_radix;
132pub mod align;
133/// Badge widget (status/priority pills).
134pub mod badge;
135/// Block widget with borders, titles, and padding.
136pub mod block;
137pub mod borders;
138pub mod cached;
139pub mod choreography;
140pub mod columns;
141pub mod command_palette;
142pub mod constraint_overlay;
143#[cfg(feature = "debug-overlay")]
144pub mod debug_overlay;
145/// Galaxy-brain decision card widget with progressive-disclosure transparency.
146pub mod decision_card;
147/// Reusable diagnostic logging and telemetry substrate for JSONL diagnostics.
148pub mod diagnostics;
149/// Drag-and-drop protocol: [`Draggable`] sources, [`DropTarget`] targets, and [`DragPayload`] payloads.
150pub mod drag;
151/// Drift-triggered fallback visualization with per-domain confidence sparklines.
152pub mod drift_visualization;
153/// Elias-Fano encoding for monotone integer sequences (succinct prefix sums).
154pub mod elias_fano;
155pub mod emoji;
156pub mod error_boundary;
157/// Fenwick tree (Binary Indexed Tree) for O(log n) prefix sum queries.
158pub mod fenwick;
159pub mod file_picker;
160/// Focus management: navigation graph for keyboard-driven focus traversal.
161pub mod focus;
162pub mod group;
163/// Bayesian height prediction with conformal bounds for virtualized lists.
164pub mod height_predictor;
165pub mod help;
166pub mod help_registry;
167/// Utility-based keybinding hint ranking with Bayesian posteriors.
168pub mod hint_ranker;
169/// Undo/redo history panel widget for displaying command history.
170pub mod history_panel;
171pub mod input;
172/// UI Inspector overlay for debugging widget trees and hit-test regions.
173pub mod inspector;
174pub mod json_view;
175pub mod keyboard_drag;
176pub mod layout;
177pub mod layout_debugger;
178pub mod list;
179pub mod log_ring;
180pub mod log_viewer;
181pub mod louds;
182/// Intrinsic sizing support for content-aware layout.
183pub mod measurable;
184/// Measure cache for memoizing widget measure results.
185pub mod measure_cache;
186pub mod modal;
187/// Shared mouse event result type for widget mouse handling.
188pub mod mouse;
189/// Notification queue for managing multiple toast notifications.
190pub mod notification_queue;
191pub mod padding;
192pub mod paginator;
193pub mod panel;
194/// Multi-line styled text paragraph widget.
195pub mod paragraph;
196pub mod popover;
197pub mod pretty;
198pub mod progress;
199/// Receipt verifier panel — renders signed-decision-receipt verifier verdicts.
200pub mod receipt_verifier_panel;
201pub mod rule;
202pub mod scrollbar;
203pub mod sparkline;
204pub mod spinner;
205/// Opt-in persistable state trait for widgets.
206pub mod stateful;
207pub mod status_line;
208pub mod stopwatch;
209/// Table widget with rows, columns, and selection.
210pub mod table;
211pub mod tabs;
212pub mod textarea;
213pub mod timer;
214/// Toast widget for transient notifications.
215pub mod toast;
216pub mod tree;
217/// Undo support for widgets.
218pub mod undo_support;
219/// Inline validation error display widget.
220pub mod validation_error;
221pub mod virtualized;
222pub mod voi_debug_overlay;
223
224/// Standard style names and conventions for [`StyleSheet`] lookups.
225pub mod style_names {
226    /// Suffix appended to a block style name to resolve its border style (e.g. `".border"`).
227    pub const BLOCK_BORDER_SUFFIX: &str = ".border";
228
229    /// Default prefix for table style roles (e.g. `"table"`).
230    pub const TABLE_PREFIX: &str = "table";
231
232    // Standard role names matching TableTheme
233    /// Table border role name (`"border"`).
234    pub const TABLE_BORDER: &str = "border";
235    /// Table header role name (`"header"`).
236    pub const TABLE_HEADER: &str = "header";
237    /// Table row role name (`"row"`).
238    pub const TABLE_ROW: &str = "row";
239    /// Table alternating row role name (`"row_alt"`).
240    pub const TABLE_ROW_ALT: &str = "row_alt";
241    /// Table selected row role name (`"row_selected"`).
242    pub const TABLE_ROW_SELECTED: &str = "row_selected";
243    /// Table hovered row role name (`"row_hover"`).
244    pub const TABLE_ROW_HOVER: &str = "row_hover";
245    /// Table divider role name (`"divider"`).
246    pub const TABLE_DIVIDER: &str = "divider";
247}
248
249#[cfg(all(test, feature = "tracing"))]
250pub(crate) mod tracing_test_support {
251    use std::sync::{Mutex, MutexGuard, OnceLock};
252
253    /// Serialize tests that install tracing subscribers and rebuild the
254    /// callsite interest cache.
255    pub(crate) struct TraceTestGuard {
256        _lock: MutexGuard<'static, ()>,
257    }
258
259    impl Drop for TraceTestGuard {
260        fn drop(&mut self) {
261            tracing::callsite::rebuild_interest_cache();
262        }
263    }
264
265    pub(crate) fn acquire() -> TraceTestGuard {
266        static TRACE_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
267
268        // Preserve serialization even if an earlier tracing assertion panicked.
269        let lock = TRACE_TEST_LOCK
270            .get_or_init(|| Mutex::new(()))
271            .lock()
272            .unwrap_or_else(|e| e.into_inner());
273        tracing::callsite::rebuild_interest_cache();
274        TraceTestGuard { _lock: lock }
275    }
276}
277
278pub use align::{Align, VerticalAlignment};
279pub use badge::Badge;
280pub use cached::{CacheKey, CachedWidget, CachedWidgetState, FnKey, HashKey, NoCacheKey};
281pub use columns::{Column, Columns};
282pub use constraint_overlay::{ConstraintOverlay, ConstraintOverlayStyle};
283#[cfg(feature = "debug-overlay")]
284pub use debug_overlay::{
285    DebugOverlay, DebugOverlayOptions, DebugOverlayState, DebugOverlayStateful,
286    DebugOverlayStatefulState,
287};
288pub use decision_card::DecisionCard;
289pub use ftui_style::StyleSheet;
290pub use group::Group;
291pub use help_registry::{HelpContent, HelpId, HelpRegistry, Keybinding};
292pub use history_panel::{HistoryEntry, HistoryPanel, HistoryPanelMode};
293pub use layout_debugger::{LayoutConstraints, LayoutDebugger, LayoutRecord};
294pub use log_ring::LogRing;
295pub use log_viewer::{LogViewer, LogViewerState, LogWrapMode, SearchConfig, SearchMode};
296pub use paginator::{Paginator, PaginatorMode};
297pub use panel::Panel;
298pub use sparkline::{Sparkline, SparklineMarkers};
299pub use status_line::{StatusItem, StatusLine};
300pub use table::{ColumnSpec, Row, Table, TableState, Truncate};
301pub use tabs::{Tab, Tabs, TabsState};
302pub use virtualized::{
303    HeightCache, ItemHeight, RenderItem, Virtualized, VirtualizedList, VirtualizedListState,
304    VirtualizedStorage,
305};
306pub use voi_debug_overlay::{
307    VoiDebugOverlay, VoiDecisionSummary, VoiLedgerEntry, VoiObservationSummary, VoiOverlayData,
308    VoiOverlayStyle, VoiPosteriorSummary,
309};
310
311// Toast notification widget
312pub use toast::{
313    KeyEvent as ToastKeyEvent, Toast, ToastAction, ToastAnimationConfig, ToastAnimationPhase,
314    ToastAnimationState, ToastConfig, ToastContent, ToastEasing, ToastEntranceAnimation,
315    ToastEvent, ToastExitAnimation, ToastIcon, ToastId, ToastPosition, ToastState, ToastStyle,
316};
317
318// Notification queue manager
319pub use notification_queue::{
320    NotificationPriority, NotificationQueue, QueueAction, QueueConfig, QueueStats,
321};
322
323// Re-export accessibility trait and types for widget implementations.
324pub use ftui_a11y::Accessible;
325
326// Shared mouse result type for widget mouse handling
327pub use mouse::MouseResult;
328
329// Measurable widget support for intrinsic sizing
330pub use measurable::{MeasurableWidget, SizeConstraints};
331
332// Measure cache for memoizing measure() results
333pub use measure_cache::{CacheStats, MeasureCache, WidgetId};
334pub use modal::{
335    BackdropConfig, MODAL_HIT_BACKDROP, MODAL_HIT_CONTENT, Modal, ModalAction, ModalConfig,
336    ModalPosition, ModalSizeConstraints, ModalState,
337};
338
339// UI Inspector for debugging
340pub use inspector::{
341    DiagnosticEntry, DiagnosticEventKind, DiagnosticLog, HitInfo, InspectorMode, InspectorOverlay,
342    InspectorState, InspectorStyle, TelemetryCallback, TelemetryHooks, WidgetInfo,
343    diagnostics_enabled, init_diagnostics, is_deterministic_mode, reset_event_counter,
344    set_diagnostics_enabled,
345};
346
347// Focus management
348pub use focus::{
349    FocusEvent, FocusGraph, FocusGroup, FocusId, FocusIndicator, FocusIndicatorKind, FocusManager,
350    FocusNode, FocusTrap, NavDirection,
351};
352
353// Drag-and-drop protocol (source + target)
354pub use drag::{DragPayload, DragState, Draggable, DropPosition, DropResult, DropTarget};
355
356// Stateful persistence trait
357pub use stateful::{StateKey, Stateful, VersionedState};
358
359// Widget persist state types for state-persistence
360pub use list::ListPersistState;
361pub use table::TablePersistState;
362pub use tree::TreePersistState;
363pub use virtualized::VirtualizedListPersistState;
364
365// Undo support for widgets
366pub use undo_support::{
367    ListOperation, ListUndoExt, SelectionOperation, TableOperation, TableUndoExt,
368    TextEditOperation, TextInputUndoExt, TreeOperation, TreeUndoExt, UndoSupport, UndoWidgetId,
369    WidgetTextEditCmd,
370};
371
372// Inline validation error display
373pub use validation_error::{
374    ANIMATION_DURATION_MS, ERROR_BG_DEFAULT, ERROR_FG_DEFAULT, ERROR_ICON_DEFAULT,
375    ValidationErrorDisplay, ValidationErrorState,
376};
377
378use ftui_core::geometry::Rect;
379use ftui_render::buffer::Buffer;
380use ftui_render::cell::Cell;
381use ftui_render::frame::{Frame, WidgetSignal};
382use ftui_style::Style;
383use ftui_text::grapheme_width;
384
385/// Render a widget's own [`Block`](block::Block) without letting it contribute
386/// an accessibility node.
387///
388/// A widget that owns a block folds the block's title into its *own* node -
389/// `Paragraph`, `Table`, `List` and `Progress` all do - so the block's `Group`
390/// is redundant semantics. It is worse than redundant. `Block`'s node and the
391/// widget's both take their id from [`a11y_node_id`], which is a function of
392/// the rect alone, and the widget renders its block at the very rect it just
393/// pushed its own node for. `A11yTreeBuilder::add_node` replaces on a
394/// duplicate id, and the block renders second - so the `Group` silently
395/// overwrote the widget. A `Paragraph::new("hello").block(..)` reached the
396/// screen reader as an empty group with its text gone.
397///
398/// Lifting the builder out for the duration is how `List` already handled
399/// this; this is that, in one place. `catch_unwind` because a panic mid-render
400/// must not leave the frame without its builder.
401///
402/// This does not make [`a11y_node_id`] collision-proof - two *sibling* widgets
403/// at the same rect would still land on one id. It removes the case that is
404/// structural rather than accidental: a widget and the block it draws around
405/// itself always share a rect.
406pub(crate) fn render_block_without_a11y(block: &block::Block<'_>, area: Rect, frame: &mut Frame) {
407    if !frame.a11y_enabled() {
408        block.render(area, frame);
409        return;
410    }
411    let builder = frame.a11y.take();
412    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
413        block.render(area, frame);
414    }));
415    frame.a11y = builder;
416    if let Err(payload) = result {
417        std::panic::resume_unwind(payload);
418    }
419}
420
421/// Generate a deterministic accessibility node ID from a widget's bounding rect.
422///
423/// Uses FNV-1a to hash the area coordinates. Stable across frames for widgets
424/// rendered at the same position, enabling efficient A11yTree diffing.
425///
426/// The id depends on the rect and nothing else, so two nodes pushed for the
427/// same rect in one frame collide and the later one wins - see
428/// [`render_block_without_a11y`].
429#[must_use]
430pub(crate) fn a11y_node_id(area: Rect) -> u64 {
431    // FNV-1a 64-bit
432    const FNV_OFFSET: u64 = 14_695_981_039_346_656_037;
433    const FNV_PRIME: u64 = 1_099_511_628_211;
434    let mut h = FNV_OFFSET;
435    for byte in area
436        .x
437        .to_le_bytes()
438        .iter()
439        .chain(&area.y.to_le_bytes())
440        .chain(&area.width.to_le_bytes())
441        .chain(&area.height.to_le_bytes())
442    {
443        h ^= u64::from(*byte);
444        h = h.wrapping_mul(FNV_PRIME);
445    }
446    h
447}
448
449/// A widget that can render itself into a [`Frame`].
450///
451/// # Frame vs Buffer
452///
453/// Widgets render into a `Frame` rather than directly into a `Buffer`. This provides:
454///
455/// - **Buffer access**: `frame.buffer` for drawing cells
456/// - **Hit testing**: `frame.register_hit()` for mouse interaction
457/// - **Cursor control**: `frame.cursor_position` for input widgets
458/// - **Performance hints**: `frame.buffer.degradation` for adaptive rendering
459///
460/// # Implementation Guide
461///
462/// Most widgets only need buffer access:
463///
464/// ```ignore
465/// fn render(&self, area: Rect, frame: &mut Frame) {
466///     for y in area.y..area.bottom() {
467///         for x in area.x..area.right() {
468///             frame.buffer.set(x, y, Cell::from_char('.'));
469///         }
470///     }
471/// }
472/// ```
473///
474/// Interactive widgets should register hit regions when a `hit_id` is set.
475/// Input widgets should set `frame.cursor_position` when focused.
476///
477/// # Degradation Levels
478///
479/// Check `frame.buffer.degradation` to adapt rendering:
480///
481/// - `Full`: All features enabled
482/// - `SimpleBorders`: Skip fancy borders, use ASCII
483/// - `NoStyling`: Skip colors and attributes
484/// - `EssentialOnly`: Only render essential widgets
485/// - `Skeleton`: Minimal placeholder rendering
486///
487/// [`Frame`]: ftui_render::frame::Frame
488pub trait Widget {
489    /// Render the widget into the frame at the given area.
490    ///
491    /// The `area` defines the bounding rectangle within which the widget
492    /// should render. Widgets should respect the area bounds and not
493    /// draw outside them (the buffer's scissor stack enforces this).
494    fn render(&self, area: Rect, frame: &mut Frame);
495
496    /// Whether this widget is essential and should always render.
497    ///
498    /// Essential widgets render even at `EssentialOnly` degradation level.
499    /// Override this to return `true` for:
500    ///
501    /// - Text inputs (user needs to see what they're typing)
502    /// - Primary content areas (main information display)
503    /// - Critical status indicators
504    ///
505    /// Returns `false` by default, appropriate for decorative widgets.
506    fn is_essential(&self) -> bool {
507        false
508    }
509}
510
511/// Frame-side rendering helpers so `view()` code reads top-down:
512/// `frame.render_widget(&sidebar, left)` instead of `sidebar.render(left, frame)`.
513///
514/// This is an extension trait because [`Frame`] lives in `ftui-render`, which
515/// does not know the widget traits; import it through `ftui::prelude::*` or
516/// `use ftui_widgets::FrameExt`.
517pub trait FrameExt {
518    /// Render a stateless widget into `area`.
519    fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect);
520
521    /// Render a stateful widget into `area`, giving it mutable access to its
522    /// state for the duration of the render.
523    fn render_stateful_widget<W: StatefulWidget + ?Sized>(
524        &mut self,
525        widget: &W,
526        area: Rect,
527        state: &mut W::State,
528    );
529}
530
531impl FrameExt for Frame<'_> {
532    #[inline]
533    fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect) {
534        widget.render(area, self);
535    }
536
537    #[inline]
538    fn render_stateful_widget<W: StatefulWidget + ?Sized>(
539        &mut self,
540        widget: &W,
541        area: Rect,
542        state: &mut W::State,
543    ) {
544        widget.render(area, self, state);
545    }
546}
547
548/// Budget-aware wrapper that registers widget signals and respects refresh budgets.
549pub struct Budgeted<W> {
550    widget_id: u64,
551    signal: WidgetSignal,
552    inner: W,
553}
554
555impl<W> Budgeted<W> {
556    /// Wrap a widget with a stable identifier and default signal values.
557    #[must_use]
558    pub fn new(widget_id: u64, inner: W) -> Self {
559        Self {
560            widget_id,
561            signal: WidgetSignal::new(widget_id),
562            inner,
563        }
564    }
565
566    /// Override the widget signal template.
567    #[must_use]
568    pub fn with_signal(mut self, mut signal: WidgetSignal) -> Self {
569        signal.widget_id = self.widget_id;
570        self.signal = signal;
571        self
572    }
573
574    /// Access the wrapped widget.
575    #[must_use]
576    pub fn inner(&self) -> &W {
577        &self.inner
578    }
579}
580
581impl<W: Widget> Widget for Budgeted<W> {
582    fn render(&self, area: Rect, frame: &mut Frame) {
583        let mut signal = self.signal.clone();
584        signal.widget_id = self.widget_id;
585        signal.essential = self.inner.is_essential();
586        signal.area_cells = area.width as u32 * area.height as u32;
587        frame.register_widget_signal(signal);
588
589        if frame.should_render_budgeted_widget(self.widget_id, self.inner.is_essential()) {
590            self.inner.render(area, frame);
591        }
592    }
593
594    fn is_essential(&self) -> bool {
595        self.inner.is_essential()
596    }
597}
598
599impl<W: StatefulWidget + Widget> StatefulWidget for Budgeted<W> {
600    type State = W::State;
601
602    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
603        let mut signal = self.signal.clone();
604        signal.widget_id = self.widget_id;
605        signal.essential = self.inner.is_essential();
606        signal.area_cells = area.width as u32 * area.height as u32;
607        frame.register_widget_signal(signal);
608
609        if frame.should_render_budgeted_widget(self.widget_id, self.inner.is_essential()) {
610            StatefulWidget::render(&self.inner, area, frame, state);
611        }
612    }
613}
614
615/// A widget that renders based on mutable state.
616///
617/// Use `StatefulWidget` when the widget needs to:
618///
619/// - Update scroll position during render
620/// - Track selection state
621/// - Cache computed layout information
622/// - Synchronize view with external model
623///
624/// # Example
625///
626/// ```ignore
627/// pub struct ListState {
628///     pub selected: Option<usize>,
629///     pub offset: usize,
630/// }
631///
632/// impl StatefulWidget for List<'_> {
633///     type State = ListState;
634///
635///     fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
636///         // Adjust offset to keep selection visible
637///         if let Some(sel) = state.selected {
638///             if sel < state.offset {
639///                 state.offset = sel;
640///             }
641///         }
642///         // Render items starting from offset...
643///     }
644/// }
645/// ```
646///
647/// # Stateful vs Stateless
648///
649/// Prefer stateless [`Widget`] when possible. Use `StatefulWidget` only when
650/// the render pass genuinely needs to modify state (e.g., scroll adjustment).
651pub trait StatefulWidget {
652    /// The state type associated with this widget.
653    type State;
654
655    /// Render the widget into the frame, potentially modifying state.
656    ///
657    /// State modifications should be limited to:
658    /// - Scroll offset adjustments
659    /// - Selection clamping
660    /// - Layout caching
661    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State);
662}
663
664/// Merge a [`Style`] into a cell, preserving existing properties for unset fields.
665///
666/// - **Foreground / Background:** Only overwritten when the style explicitly sets
667///   the field (`Some`).  Background colours with alpha < 255 are composited via
668///   Porter-Duff SourceOver so semi-transparent overlays blend correctly.
669/// - **Attributes:** New flags are OR-ed on top of existing flags (never cleared).
670pub(crate) fn apply_style(cell: &mut Cell, style: Style) {
671    if let Some(fg) = style.fg {
672        cell.fg = fg;
673    }
674    if let Some(bg) = style.bg {
675        match bg.a() {
676            0 => {}                          // Fully transparent: no-op
677            255 => cell.bg = bg,             // Fully opaque: replace
678            _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
679        }
680    }
681    if let Some(attrs) = style.attrs {
682        let cell_flags: ftui_render::cell::StyleFlags = attrs.into();
683        cell.attrs = cell.attrs.merged_flags(cell_flags);
684    }
685}
686
687/// Apply a style to all cells in a rectangular area using **merge** semantics.
688///
689/// Only fields that are explicitly set in `style` (i.e. `Some`) are applied;
690/// unset fields leave the existing cell values intact.  This is the correct
691/// behaviour for selection / highlight overlays that specify only a background
692/// colour — per-cell foreground colours from earlier text rendering are preserved.
693///
694/// - **Background:** Alpha-aware compositing (Porter-Duff SourceOver).
695/// - **Attributes:** OR-ed on top of existing flags (never cleared).
696pub(crate) fn set_style_area(buf: &mut Buffer, area: Rect, style: Style) {
697    if style.is_empty() {
698        return;
699    }
700    let clipped = area.intersection(&buf.current_scissor());
701    if clipped.is_empty() {
702        return;
703    }
704
705    let opacity = buf.current_opacity();
706    let fg = style.fg.map(|fg| fg.with_opacity(opacity));
707    let bg = style.bg.map(|bg| bg.with_opacity(opacity));
708    let attrs = style.attrs.map(ftui_render::cell::StyleFlags::from);
709    for y in clipped.y..clipped.bottom() {
710        let Some(row) = buf.row_cells_mut_span(y, clipped.x, clipped.right()) else {
711            continue;
712        };
713        for cell in row {
714            if let Some(fg) = fg {
715                cell.fg = fg;
716            }
717            if let Some(bg) = bg {
718                match bg.a() {
719                    0 => {}                          // Fully transparent: no-op
720                    255 => cell.bg = bg,             // Fully opaque: replace
721                    _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
722                }
723            }
724            if let Some(attrs) = attrs {
725                cell.attrs = cell.attrs.merged_flags(attrs);
726            }
727        }
728    }
729}
730
731/// Clear a text area with styled spaces before rendering new content.
732pub(crate) fn clear_text_area(frame: &mut Frame, area: Rect, style: Style) {
733    if area.width == 0 || area.height == 0 {
734        return;
735    }
736
737    let mut cell = Cell::from_char(' ');
738    apply_style(&mut cell, style);
739    frame.buffer.fill(area, cell);
740}
741
742/// Clear a single text row with styled spaces before rendering new content.
743pub(crate) fn clear_text_row(frame: &mut Frame, area: Rect, style: Style) {
744    clear_text_area(frame, Rect::new(area.x, area.y, area.width, 1), style);
745}
746
747/// Build a text cell that inherits existing visual styling from the buffer.
748///
749/// This preserves foreground/background/style flags applied by prior area-wide
750/// overlays (for example selection/highlight passes) while intentionally
751/// dropping any stale hyperlink ID before new text is written.
752fn inherited_text_cell(
753    frame: &Frame,
754    x: u16,
755    y: u16,
756    content: ftui_render::cell::CellContent,
757) -> Cell {
758    let mut cell = frame.buffer.get(x, y).copied().unwrap_or_default();
759    cell.content = content;
760    cell.attrs = ftui_render::cell::CellAttrs::new(cell.attrs.flags(), 0);
761    cell
762}
763
764/// Draw a text span into a frame at the given position.
765///
766/// Returns the x position after the last drawn character.
767/// Stops at `max_x` (exclusive).
768pub(crate) fn draw_text_span(
769    frame: &mut Frame,
770    mut x: u16,
771    y: u16,
772    content: &str,
773    style: Style,
774    max_x: u16,
775) -> u16 {
776    use unicode_segmentation::UnicodeSegmentation;
777
778    for grapheme in content.graphemes(true) {
779        if x >= max_x {
780            break;
781        }
782        let w = grapheme_width(grapheme);
783        if w == 0 {
784            continue;
785        }
786        if x.saturating_add(w as u16) > max_x {
787            break;
788        }
789
790        // Intern grapheme if needed
791        let cell_content = if w > 1 || grapheme.chars().count() > 1 {
792            let id = frame.intern_with_width(grapheme, w as u8);
793            ftui_render::cell::CellContent::from_grapheme(id)
794        } else if let Some(c) = grapheme.chars().next() {
795            ftui_render::cell::CellContent::from_char(c)
796        } else {
797            continue;
798        };
799
800        let mut cell = inherited_text_cell(frame, x, y, cell_content);
801        apply_style(&mut cell, style);
802
803        // set_fast() skips scissor/opacity/compositing checks for common
804        // single-width opaque cells; falls back to set() otherwise.
805        frame.buffer.set_fast(x, y, cell);
806
807        x = x.saturating_add(w as u16);
808    }
809    x
810}
811
812/// Draw a text span, optionally attaching a hyperlink.
813#[allow(dead_code)]
814pub(crate) fn draw_text_span_with_link(
815    frame: &mut Frame,
816    x: u16,
817    y: u16,
818    content: &str,
819    style: Style,
820    max_x: u16,
821    link_url: Option<&str>,
822) -> u16 {
823    draw_text_span_scrolled(frame, x, y, content, style, max_x, 0, link_url)
824}
825
826/// Draw a text span with horizontal scrolling (skip first `scroll_x` visual cells).
827#[allow(dead_code, clippy::too_many_arguments)]
828pub(crate) fn draw_text_span_scrolled(
829    frame: &mut Frame,
830    mut x: u16,
831    y: u16,
832    content: &str,
833    style: Style,
834    max_x: u16,
835    scroll_x: u16,
836    link_url: Option<&str>,
837) -> u16 {
838    use unicode_segmentation::UnicodeSegmentation;
839
840    // Register link if present
841    let link_id = if let Some(url) = link_url {
842        frame.register_link(url)
843    } else {
844        0
845    };
846
847    // The logical span may extend beyond the terminal coordinate range.
848    let scroll_x = usize::from(scroll_x);
849    let mut visual_pos: usize = 0;
850
851    for grapheme in content.graphemes(true) {
852        if x >= max_x {
853            break;
854        }
855        let w = grapheme_width(grapheme);
856        if w == 0 {
857            continue;
858        }
859
860        let next_visual_pos = visual_pos.saturating_add(w);
861
862        // Check if this grapheme is visible
863        if next_visual_pos <= scroll_x {
864            // Fully scrolled out
865            visual_pos = next_visual_pos;
866            continue;
867        }
868
869        if visual_pos < scroll_x {
870            // Partially scrolled out (e.g. wide char starting at scroll_x - 1)
871            // We skip the whole character because we can't render half a cell.
872            visual_pos = next_visual_pos;
873            continue;
874        }
875
876        if x.saturating_add(w as u16) > max_x {
877            break;
878        }
879
880        // Intern grapheme if needed
881        let cell_content = if w > 1 || grapheme.chars().count() > 1 {
882            let id = frame.intern_with_width(grapheme, w as u8);
883            ftui_render::cell::CellContent::from_grapheme(id)
884        } else if let Some(c) = grapheme.chars().next() {
885            ftui_render::cell::CellContent::from_char(c)
886        } else {
887            continue;
888        };
889
890        let mut cell = inherited_text_cell(frame, x, y, cell_content);
891        apply_style(&mut cell, style);
892
893        // Apply link ID if present
894        if link_id != 0 {
895            cell.attrs = cell.attrs.with_link(link_id);
896        }
897
898        frame.buffer.set_fast(x, y, cell);
899
900        x = x.saturating_add(w as u16);
901        visual_pos = next_visual_pos;
902    }
903    x
904}
905
906/// Helper for allocation-free case-insensitive containment check.
907pub(crate) fn contains_ignore_case(haystack: &str, needle_lower: &str) -> bool {
908    if needle_lower.is_empty() {
909        return true;
910    }
911    // Fast path for ASCII
912    if haystack.is_ascii() && needle_lower.is_ascii() {
913        let haystack_bytes = haystack.as_bytes();
914        let needle_bytes = needle_lower.as_bytes();
915        if needle_bytes.len() > haystack_bytes.len() {
916            return false;
917        }
918        // Naive byte-by-byte scan is fast enough for short strings (UI labels)
919        for i in 0..=haystack_bytes.len() - needle_bytes.len() {
920            let mut match_found = true;
921            for (j, &b) in needle_bytes.iter().enumerate() {
922                if haystack_bytes[i + j].to_ascii_lowercase() != b {
923                    match_found = false;
924                    break;
925                }
926            }
927            if match_found {
928                return true;
929            }
930        }
931        return false;
932    }
933    // Fallback for Unicode (allocates, but correct)
934    haystack.to_lowercase().contains(needle_lower)
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940    use ftui_render::cell::PackedRgba;
941    use ftui_render::grapheme_pool::GraphemePool;
942
943    /// `frame.render_widget(&w, area)` must be exactly `w.render(area, frame)`:
944    /// same cells, same clipping, no extra state.
945    #[test]
946    fn frame_ext_render_widget_matches_direct_render() {
947        struct Fill(char);
948        impl Widget for Fill {
949            fn render(&self, area: Rect, frame: &mut Frame) {
950                for y in area.y..area.y + area.height {
951                    for x in area.x..area.x + area.width {
952                        frame.buffer.set_raw(x, y, Cell::from_char(self.0));
953                    }
954                }
955            }
956        }
957
958        let mut pool_a = GraphemePool::new();
959        let mut direct = Frame::new(6, 2, &mut pool_a);
960        Fill('d').render(Rect::new(1, 0, 3, 2), &mut direct);
961
962        let mut pool_b = GraphemePool::new();
963        let mut via_ext = Frame::new(6, 2, &mut pool_b);
964        via_ext.render_widget(&Fill('d'), Rect::new(1, 0, 3, 2));
965        assert_eq!(via_ext.area(), Rect::new(0, 0, 6, 2));
966
967        for y in 0..2 {
968            for x in 0..6 {
969                assert_eq!(
970                    direct.buffer.get(x, y).map(|cell| cell.content),
971                    via_ext.buffer.get(x, y).map(|cell| cell.content),
972                    "cell ({x},{y}) differs between direct render and FrameExt"
973                );
974            }
975        }
976        assert_eq!(
977            via_ext.buffer.get(1, 0).map(|cell| cell.content),
978            Some(Cell::from_char('d').content)
979        );
980        assert_eq!(
981            via_ext.buffer.get(0, 0).map(|cell| cell.content),
982            Some(Cell::default().content)
983        );
984    }
985
986    /// With a tree builder attached to the frame, rendering an `Accessible`
987    /// widget pushes its nodes (a list with items, a titled block, a
988    /// paragraph) so the runtime can build the tree; without one nothing is
989    /// collected and rendering is unchanged.
990    #[test]
991    fn rendering_accessible_widgets_pushes_their_nodes_into_the_frame() {
992        use crate::block::Block;
993        use crate::list::{List, ListState};
994        use crate::paragraph::Paragraph;
995        use ftui_a11y::node::A11yRole;
996        use ftui_a11y::tree::A11yTreeBuilder;
997
998        let mut pool = GraphemePool::new();
999        let mut builder = A11yTreeBuilder::new();
1000        let mut frame = Frame::new(30, 8, &mut pool);
1001        frame.set_a11y(&mut builder);
1002
1003        let mut list_state = ListState::default();
1004        let list = List::new(["alpha", "beta"]);
1005        StatefulWidget::render(&list, Rect::new(0, 0, 30, 3), &mut frame, &mut list_state);
1006        Block::new()
1007            .title("Details")
1008            .render(Rect::new(0, 3, 30, 3), &mut frame);
1009        Paragraph::new("hello").render(Rect::new(0, 6, 30, 1), &mut frame);
1010        frame.finish_a11y();
1011        let order = frame.take_a11y_order();
1012        drop(frame);
1013
1014        let tree = builder.build();
1015        assert_eq!(order.len(), tree.node_count());
1016        assert!(
1017            order.len() >= 5,
1018            "list + 2 items + block + paragraph: {order:?}"
1019        );
1020        let roles: Vec<A11yRole> = order
1021            .iter()
1022            .filter_map(|id| tree.node(*id).map(|n| n.role))
1023            .collect();
1024        assert_eq!(roles[0], A11yRole::List);
1025        assert_eq!(roles[1], A11yRole::ListItem);
1026        assert_eq!(roles[2], A11yRole::ListItem);
1027        assert!(roles.contains(&A11yRole::Group), "{roles:?}");
1028        let list_id = order[0];
1029        assert_eq!(
1030            tree.node(list_id).map(|n| n.children.len()),
1031            Some(2),
1032            "list items are the list's children"
1033        );
1034        assert_eq!(
1035            tree.root_id(),
1036            Some(list_id),
1037            "first parentless node is the root"
1038        );
1039        let text = tree.dump_text(&order);
1040        assert!(text.contains("ListItem \"alpha\""), "{text}");
1041        assert!(text.contains("Group \"Details\""), "{text}");
1042
1043        // No builder: nothing collected, rendering still works.
1044        let mut pool = GraphemePool::new();
1045        let mut frame = Frame::new(30, 8, &mut pool);
1046        Paragraph::new("hello").render(Rect::new(0, 0, 30, 1), &mut frame);
1047        assert!(frame.a11y_order().is_empty());
1048    }
1049
1050    /// The stateful helper hands the widget its state and keeps mutations.
1051    #[test]
1052    fn frame_ext_render_stateful_widget_passes_state() {
1053        struct Counter;
1054        impl StatefulWidget for Counter {
1055            type State = u32;
1056            fn render(&self, _area: Rect, _frame: &mut Frame, state: &mut u32) {
1057                *state += 1;
1058            }
1059        }
1060        let mut pool = GraphemePool::new();
1061        let mut frame = Frame::new(4, 1, &mut pool);
1062        let mut count = 0;
1063        frame.render_stateful_widget(&Counter, frame.area(), &mut count);
1064        frame.render_stateful_widget(&Counter, Rect::new(0, 0, 1, 1), &mut count);
1065        assert_eq!(count, 2);
1066    }
1067
1068    #[test]
1069    fn apply_style_sets_fg() {
1070        let mut cell = Cell::default();
1071        let style = Style::new().fg(PackedRgba::rgb(255, 0, 0));
1072        apply_style(&mut cell, style);
1073        assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
1074    }
1075
1076    #[test]
1077    fn apply_style_sets_bg() {
1078        let mut cell = Cell::default();
1079        let style = Style::new().bg(PackedRgba::rgb(0, 255, 0));
1080        apply_style(&mut cell, style);
1081        assert_eq!(cell.bg, PackedRgba::rgb(0, 255, 0));
1082    }
1083
1084    #[test]
1085    fn apply_style_preserves_content() {
1086        let mut cell = Cell::from_char('Z');
1087        let style = Style::new().fg(PackedRgba::rgb(1, 2, 3));
1088        apply_style(&mut cell, style);
1089        assert_eq!(cell.content.as_char(), Some('Z'));
1090    }
1091
1092    #[test]
1093    fn apply_style_empty_is_noop() {
1094        let original = Cell::default();
1095        let mut cell = Cell::default();
1096        apply_style(&mut cell, Style::default());
1097        assert_eq!(cell.fg, original.fg);
1098        assert_eq!(cell.bg, original.bg);
1099    }
1100
1101    #[test]
1102    fn apply_style_bg_only_preserves_fg() {
1103        // Simulate: cell already has syntax-highlighted fg, selection overlay sets only bg.
1104        let mut cell = Cell::from_char('x').with_fg(PackedRgba::rgb(0, 200, 0));
1105        let selection = Style::new().bg(PackedRgba::rgb(0, 0, 180));
1106        apply_style(&mut cell, selection);
1107        // fg must survive — the selection style didn't set a fg.
1108        assert_eq!(cell.fg, PackedRgba::rgb(0, 200, 0));
1109        assert_eq!(cell.bg, PackedRgba::rgb(0, 0, 180));
1110    }
1111
1112    #[test]
1113    fn apply_style_composites_alpha_bg() {
1114        let base_bg = PackedRgba::rgb(200, 0, 0);
1115        let mut cell = Cell::default().with_bg(base_bg);
1116        let overlay = PackedRgba::rgba(0, 0, 200, 128);
1117        apply_style(&mut cell, Style::new().bg(overlay));
1118        assert_eq!(cell.bg, overlay.over(base_bg));
1119    }
1120
1121    #[test]
1122    fn apply_style_transparent_bg_is_noop() {
1123        let base_bg = PackedRgba::rgb(100, 100, 100);
1124        let mut cell = Cell::default().with_bg(base_bg);
1125        apply_style(&mut cell, Style::new().bg(PackedRgba::rgba(255, 0, 0, 0)));
1126        assert_eq!(cell.bg, base_bg);
1127    }
1128
1129    #[test]
1130    fn apply_style_merges_attrs_not_replaces() {
1131        use ftui_render::cell::StyleFlags as CellFlags;
1132        // Cell starts with BOLD.
1133        let mut cell = Cell::default();
1134        cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1135        // Overlay adds ITALIC — should NOT clear BOLD.
1136        let overlay = Style::new().italic();
1137        apply_style(&mut cell, overlay);
1138        assert!(cell.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1139        assert!(
1140            cell.attrs.has_flag(CellFlags::ITALIC),
1141            "ITALIC must be added"
1142        );
1143    }
1144
1145    #[test]
1146    fn set_style_area_bg_only_preserves_per_cell_fg() {
1147        // A 3-cell buffer where each cell has a distinct fg.
1148        let mut buf = Buffer::new(3, 1);
1149        buf.set(0, 0, Cell::from_char('R').with_fg(PackedRgba::RED));
1150        buf.set(1, 0, Cell::from_char('G').with_fg(PackedRgba::GREEN));
1151        buf.set(2, 0, Cell::from_char('B').with_fg(PackedRgba::BLUE));
1152
1153        // Selection highlight sets only bg.
1154        let highlight = Style::new().bg(PackedRgba::rgb(40, 40, 40));
1155        set_style_area(&mut buf, Rect::new(0, 0, 3, 1), highlight);
1156
1157        // All fg colours must be preserved.
1158        assert_eq!(buf.get(0, 0).unwrap().fg, PackedRgba::RED);
1159        assert_eq!(buf.get(1, 0).unwrap().fg, PackedRgba::GREEN);
1160        assert_eq!(buf.get(2, 0).unwrap().fg, PackedRgba::BLUE);
1161        // bg should be the highlight colour.
1162        assert_eq!(buf.get(0, 0).unwrap().bg, PackedRgba::rgb(40, 40, 40));
1163    }
1164
1165    #[test]
1166    fn set_style_area_merges_attrs_not_replaces() {
1167        use ftui_render::cell::StyleFlags as CellFlags;
1168        let mut buf = Buffer::new(1, 1);
1169        let mut cell = Cell::from_char('X');
1170        cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1171        buf.set(0, 0, cell);
1172
1173        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().italic());
1174
1175        let result = buf.get(0, 0).unwrap();
1176        assert!(result.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1177        assert!(
1178            result.attrs.has_flag(CellFlags::ITALIC),
1179            "ITALIC must be added"
1180        );
1181    }
1182
1183    #[test]
1184    fn set_style_area_applies_to_all_cells() {
1185        let mut buf = Buffer::new(3, 2);
1186        let area = Rect::new(0, 0, 3, 2);
1187        let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1188        set_style_area(&mut buf, area, style);
1189
1190        for y in 0..2 {
1191            for x in 0..3 {
1192                assert_eq!(
1193                    buf.get(x, y).unwrap().bg,
1194                    PackedRgba::rgb(10, 20, 30),
1195                    "cell ({x},{y}) should have style applied"
1196                );
1197            }
1198        }
1199    }
1200
1201    #[test]
1202    fn set_style_area_composites_alpha_bg_over_existing_bg() {
1203        let mut buf = Buffer::new(1, 1);
1204        let base = PackedRgba::rgb(200, 0, 0);
1205        buf.set(0, 0, Cell::default().with_bg(base));
1206
1207        let overlay = PackedRgba::rgba(0, 0, 200, 128);
1208        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(overlay));
1209
1210        let expected = overlay.over(base);
1211        assert_eq!(buf.get(0, 0).unwrap().bg, expected);
1212    }
1213
1214    #[test]
1215    fn set_style_area_partial_rect() {
1216        let mut buf = Buffer::new(5, 5);
1217        let area = Rect::new(1, 1, 2, 2);
1218        let style = Style::new().fg(PackedRgba::rgb(99, 99, 99));
1219        set_style_area(&mut buf, area, style);
1220
1221        // Inside area should be styled
1222        assert_eq!(buf.get(1, 1).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1223        assert_eq!(buf.get(2, 2).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1224
1225        // Outside area should be default
1226        assert_ne!(buf.get(0, 0).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1227    }
1228
1229    #[test]
1230    fn set_style_area_empty_style_is_noop() {
1231        let mut buf = Buffer::new(3, 3);
1232        buf.set(0, 0, Cell::from_char('A'));
1233        let original_fg = buf.get(0, 0).unwrap().fg;
1234
1235        set_style_area(&mut buf, Rect::new(0, 0, 3, 3), Style::default());
1236
1237        // Should not have changed
1238        assert_eq!(buf.get(0, 0).unwrap().fg, original_fg);
1239        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
1240    }
1241
1242    #[test]
1243    fn set_style_area_respects_scissor() {
1244        let mut buf = Buffer::new(3, 3);
1245        let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1246
1247        buf.push_scissor(Rect::new(1, 1, 1, 1));
1248        set_style_area(&mut buf, Rect::new(0, 0, 3, 3), style);
1249
1250        assert_eq!(buf.get(1, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1251        assert_ne!(buf.get(0, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1252        assert_ne!(buf.get(1, 0).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1253        assert_ne!(buf.get(2, 2).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1254    }
1255
1256    #[test]
1257    fn set_style_area_respects_opacity_stack() {
1258        let mut buf = Buffer::new(1, 1);
1259        let base_fg = PackedRgba::rgb(20, 30, 40);
1260        let base_bg = PackedRgba::rgb(50, 60, 70);
1261        buf.set(0, 0, Cell::from_char('X').with_fg(base_fg).with_bg(base_bg));
1262
1263        let overlay_fg = PackedRgba::rgb(200, 100, 0);
1264        let overlay_bg = PackedRgba::rgb(0, 0, 200);
1265        buf.push_opacity(0.5);
1266        set_style_area(
1267            &mut buf,
1268            Rect::new(0, 0, 1, 1),
1269            Style::new().fg(overlay_fg).bg(overlay_bg),
1270        );
1271
1272        let cell = buf.get(0, 0).unwrap();
1273        assert_eq!(cell.fg, overlay_fg.with_opacity(0.5));
1274        assert_eq!(cell.bg, overlay_bg.with_opacity(0.5).over(base_bg));
1275    }
1276
1277    #[test]
1278    fn draw_text_span_basic() {
1279        let mut pool = GraphemePool::new();
1280        let mut frame = Frame::new(10, 1, &mut pool);
1281        let end_x = draw_text_span(&mut frame, 0, 0, "ABC", Style::default(), 10);
1282
1283        assert_eq!(end_x, 3);
1284        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1285        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
1286        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1287    }
1288
1289    #[test]
1290    fn draw_text_span_clipped_at_max_x() {
1291        let mut pool = GraphemePool::new();
1292        let mut frame = Frame::new(10, 1, &mut pool);
1293        let end_x = draw_text_span(&mut frame, 0, 0, "ABCDEF", Style::default(), 3);
1294
1295        assert_eq!(end_x, 3);
1296        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1297        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1298        // 'D' should not be drawn
1299        assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1300    }
1301
1302    #[test]
1303    fn draw_text_span_starts_at_offset() {
1304        let mut pool = GraphemePool::new();
1305        let mut frame = Frame::new(10, 1, &mut pool);
1306        let end_x = draw_text_span(&mut frame, 5, 0, "XY", Style::default(), 10);
1307
1308        assert_eq!(end_x, 7);
1309        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('X'));
1310        assert_eq!(frame.buffer.get(6, 0).unwrap().content.as_char(), Some('Y'));
1311        assert!(frame.buffer.get(4, 0).unwrap().is_empty());
1312    }
1313
1314    #[test]
1315    fn draw_text_span_empty_string() {
1316        let mut pool = GraphemePool::new();
1317        let mut frame = Frame::new(5, 1, &mut pool);
1318        let end_x = draw_text_span(&mut frame, 0, 0, "", Style::default(), 5);
1319        assert_eq!(end_x, 0);
1320    }
1321
1322    #[test]
1323    fn draw_text_span_applies_style() {
1324        let mut pool = GraphemePool::new();
1325        let mut frame = Frame::new(5, 1, &mut pool);
1326        let style = Style::new().fg(PackedRgba::rgb(255, 128, 0));
1327        draw_text_span(&mut frame, 0, 0, "A", style, 5);
1328
1329        assert_eq!(
1330            frame.buffer.get(0, 0).unwrap().fg,
1331            PackedRgba::rgb(255, 128, 0)
1332        );
1333    }
1334
1335    #[test]
1336    fn draw_text_span_preserves_existing_overlay_fg_and_bg() {
1337        let mut pool = GraphemePool::new();
1338        let mut frame = Frame::new(3, 1, &mut pool);
1339        frame.buffer.set(
1340            0,
1341            0,
1342            Cell::from_char('x').with_fg(PackedRgba::rgb(200, 40, 10)),
1343        );
1344        set_style_area(
1345            &mut frame.buffer,
1346            Rect::new(0, 0, 1, 1),
1347            Style::new().bg(PackedRgba::rgb(20, 30, 40)),
1348        );
1349
1350        draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1351
1352        let cell = frame.buffer.get(0, 0).unwrap();
1353        assert_eq!(cell.content.as_char(), Some('A'));
1354        assert_eq!(cell.fg, PackedRgba::rgb(200, 40, 10));
1355        assert_eq!(cell.bg, PackedRgba::rgb(20, 30, 40));
1356    }
1357
1358    #[test]
1359    fn draw_text_span_drops_stale_link_id_but_keeps_style_flags() {
1360        use ftui_render::cell::{CellAttrs, StyleFlags as CellFlags};
1361
1362        let mut pool = GraphemePool::new();
1363        let mut frame = Frame::new(3, 1, &mut pool);
1364        frame.buffer.set(
1365            0,
1366            0,
1367            Cell::from_char('x').with_attrs(CellAttrs::new(CellFlags::UNDERLINE, 42)),
1368        );
1369
1370        draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1371
1372        let cell = frame.buffer.get(0, 0).unwrap();
1373        assert_eq!(cell.content.as_char(), Some('A'));
1374        assert!(cell.attrs.has_flag(CellFlags::UNDERLINE));
1375        assert_eq!(cell.attrs.link_id(), 0);
1376    }
1377
1378    #[test]
1379    fn draw_text_span_max_x_at_start_draws_nothing() {
1380        let mut pool = GraphemePool::new();
1381        let mut frame = Frame::new(5, 1, &mut pool);
1382        let end_x = draw_text_span(&mut frame, 3, 0, "ABC", Style::default(), 3);
1383        assert_eq!(end_x, 3);
1384        assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1385    }
1386
1387    #[test]
1388    fn widget_is_essential_default_false() {
1389        struct DummyWidget;
1390        impl Widget for DummyWidget {
1391            fn render(&self, _: Rect, _: &mut Frame) {}
1392        }
1393        assert!(!DummyWidget.is_essential());
1394    }
1395
1396    #[test]
1397    fn budgeted_new_and_inner() {
1398        struct TestW;
1399        impl Widget for TestW {
1400            fn render(&self, _: Rect, _: &mut Frame) {}
1401        }
1402        let b = Budgeted::new(42, TestW);
1403        assert_eq!(b.widget_id, 42);
1404        let _ = b.inner(); // Should not panic
1405    }
1406
1407    #[test]
1408    fn budgeted_with_signal() {
1409        struct TestW;
1410        impl Widget for TestW {
1411            fn render(&self, _: Rect, _: &mut Frame) {}
1412        }
1413        let sig = WidgetSignal::new(99);
1414        let b = Budgeted::new(42, TestW).with_signal(sig);
1415        // with_signal should override the signal's widget_id to match
1416        assert_eq!(b.signal.widget_id, 42);
1417    }
1418
1419    #[test]
1420    fn set_style_area_transparent_bg_is_noop() {
1421        let mut buf = Buffer::new(1, 1);
1422        let base = PackedRgba::rgb(100, 100, 100);
1423        buf.set(0, 0, Cell::default().with_bg(base));
1424
1425        // Alpha=0 means fully transparent, should leave bg unchanged
1426        let transparent = PackedRgba::rgba(255, 0, 0, 0);
1427        set_style_area(
1428            &mut buf,
1429            Rect::new(0, 0, 1, 1),
1430            Style::new().bg(transparent),
1431        );
1432        assert_eq!(buf.get(0, 0).unwrap().bg, base);
1433    }
1434
1435    #[test]
1436    fn set_style_area_opaque_bg_replaces() {
1437        let mut buf = Buffer::new(1, 1);
1438        buf.set(
1439            0,
1440            0,
1441            Cell::default().with_bg(PackedRgba::rgb(100, 100, 100)),
1442        );
1443
1444        let opaque = PackedRgba::rgba(0, 255, 0, 255);
1445        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(opaque));
1446        assert_eq!(buf.get(0, 0).unwrap().bg, opaque);
1447    }
1448
1449    #[test]
1450    fn draw_text_span_scrolled_skips_chars() {
1451        let mut pool = GraphemePool::new();
1452        let mut frame = Frame::new(10, 1, &mut pool);
1453        // Scroll past first 2 chars of "ABCDE"
1454        let end_x =
1455            draw_text_span_scrolled(&mut frame, 0, 0, "ABCDE", Style::default(), 10, 2, None);
1456
1457        assert_eq!(end_x, 3);
1458        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('C'));
1459        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('D'));
1460        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('E'));
1461    }
1462
1463    fn collect_a11y_from_render<F>(width: u16, height: u16, render: F) -> ftui_a11y::tree::A11yTree
1464    where
1465        F: FnOnce(&mut Frame),
1466    {
1467        let mut pool = GraphemePool::new();
1468        let mut builder = ftui_a11y::tree::A11yTreeBuilder::new();
1469        {
1470            let mut frame = Frame::new(width, height, &mut pool);
1471            frame.set_a11y(&mut builder);
1472            render(&mut frame);
1473            frame.finish_a11y();
1474        }
1475        builder.build()
1476    }
1477
1478    #[test]
1479    fn block_render_pushes_a11y_nodes() {
1480        use crate::block::Block;
1481        use crate::borders::Borders;
1482
1483        let block = Block::new().borders(Borders::ALL).title("Panel");
1484        let area = Rect::new(0, 0, 20, 6);
1485        let expected = ftui_a11y::Accessible::accessibility_nodes(&block, area);
1486        let tree = collect_a11y_from_render(20, 6, |frame| {
1487            block.render(area, frame);
1488        });
1489        assert_eq!(tree.node_count(), expected.len());
1490        let root = tree.node(expected[0].id).expect("block node present");
1491        assert_eq!(root.role, ftui_a11y::node::A11yRole::Group);
1492        assert_eq!(root.name.as_deref(), Some("Panel"));
1493    }
1494
1495    #[test]
1496    fn tabs_render_pushes_a11y_nodes() {
1497        use crate::tabs::{Tab, Tabs, TabsState};
1498
1499        let tabs = Tabs::new(vec![Tab::new("General"), Tab::new("Advanced")]);
1500        let area = Rect::new(0, 0, 30, 1);
1501        let expected = ftui_a11y::Accessible::accessibility_nodes(&tabs, area);
1502        let tree = collect_a11y_from_render(30, 1, |frame| {
1503            let mut state = TabsState::default();
1504            StatefulWidget::render(&tabs, area, frame, &mut state);
1505        });
1506        assert_eq!(tree.node_count(), expected.len());
1507        for node in &expected {
1508            assert!(tree.node(node.id).is_some(), "missing tab node {}", node.id);
1509        }
1510    }
1511
1512    #[test]
1513    fn progress_render_pushes_a11y_nodes() {
1514        use crate::progress::ProgressBar;
1515
1516        let bar = ProgressBar::new().ratio(0.6).label("60%");
1517        let area = Rect::new(0, 0, 20, 1);
1518        let expected = ftui_a11y::Accessible::accessibility_nodes(&bar, area);
1519        let tree = collect_a11y_from_render(20, 1, |frame| {
1520            bar.render(area, frame);
1521        });
1522        assert_eq!(tree.node_count(), expected.len());
1523        let node = tree.node(expected[0].id).expect("progress node present");
1524        assert_eq!(node.role, ftui_a11y::node::A11yRole::ProgressBar);
1525        assert_eq!(node.state.value_text.as_deref(), Some("60%"));
1526    }
1527
1528    #[test]
1529    fn input_render_pushes_a11y_nodes() {
1530        use crate::input::TextInput;
1531
1532        let input = TextInput::new()
1533            .with_value("alice")
1534            .with_placeholder("Username")
1535            .with_focused(true);
1536        let area = Rect::new(0, 0, 20, 1);
1537        let expected = ftui_a11y::Accessible::accessibility_nodes(&input, area);
1538        let tree = collect_a11y_from_render(20, 1, |frame| {
1539            input.render(area, frame);
1540        });
1541        assert_eq!(tree.node_count(), expected.len());
1542        let node = tree.node(expected[0].id).expect("input node present");
1543        assert_eq!(node.role, ftui_a11y::node::A11yRole::TextInput);
1544        assert!(node.state.focused);
1545        assert_eq!(tree.focused_id(), Some(expected[0].id));
1546    }
1547
1548    #[test]
1549    fn list_render_pushes_a11y_nodes() {
1550        use crate::list::{List, ListItem, ListState};
1551
1552        let list = List::new([ListItem::new("First"), ListItem::new("Second")]);
1553        let area = Rect::new(0, 0, 20, 4);
1554        let expected = ftui_a11y::Accessible::accessibility_nodes(&list, area);
1555        let tree = collect_a11y_from_render(20, 4, |frame| {
1556            let mut state = ListState::default();
1557            state.select(Some(1));
1558            StatefulWidget::render(&list, area, frame, &mut state);
1559        });
1560        assert_eq!(tree.node_count(), expected.len());
1561        let list_node = tree.node(expected[0].id).expect("list node present");
1562        assert_eq!(list_node.role, ftui_a11y::node::A11yRole::List);
1563        let second_child = tree
1564            .node(list_node.children[1])
1565            .expect("second list item node present");
1566        assert_eq!(second_child.name.as_deref(), Some("Second"));
1567        assert!(second_child.state.selected);
1568    }
1569
1570    #[test]
1571    fn table_render_pushes_a11y_nodes() {
1572        use crate::table::{Row, Table, TableState};
1573        use ftui_layout::Constraint;
1574
1575        let table = Table::new(
1576            [Row::new(["a", "1"]), Row::new(["b", "2"])],
1577            [Constraint::Fixed(8), Constraint::Fixed(8)],
1578        );
1579        let area = Rect::new(0, 0, 20, 4);
1580        let expected = ftui_a11y::Accessible::accessibility_nodes(&table, area);
1581        let tree = collect_a11y_from_render(20, 4, |frame| {
1582            let mut state = TableState::default();
1583            state.select(Some(0));
1584            StatefulWidget::render(&table, area, frame, &mut state);
1585        });
1586        assert_eq!(tree.node_count(), expected.len());
1587        let table_node = tree.node(expected[0].id).expect("table node present");
1588        assert_eq!(table_node.role, ftui_a11y::node::A11yRole::Table);
1589    }
1590
1591    #[test]
1592    fn spinner_render_pushes_a11y_nodes() {
1593        use crate::spinner::{Spinner, SpinnerState};
1594
1595        let spinner = Spinner::new().label("Loading");
1596        let area = Rect::new(0, 0, 20, 1);
1597        let expected = ftui_a11y::Accessible::accessibility_nodes(&spinner, area);
1598        let tree = collect_a11y_from_render(20, 1, |frame| {
1599            let mut state = SpinnerState::default();
1600            StatefulWidget::render(&spinner, area, frame, &mut state);
1601        });
1602        assert_eq!(tree.node_count(), expected.len());
1603        let node = tree.node(expected[0].id).expect("spinner node present");
1604        assert_eq!(node.name, expected[0].name);
1605        assert!(node.state.busy);
1606    }
1607
1608    #[test]
1609    fn scrollbar_render_pushes_a11y_nodes() {
1610        use crate::scrollbar::{Scrollbar, ScrollbarOrientation, ScrollbarState};
1611
1612        let sb = Scrollbar::new(ScrollbarOrientation::VerticalRight);
1613        let area = Rect::new(0, 0, 1, 10);
1614        let expected = ftui_a11y::Accessible::accessibility_nodes(&sb, area);
1615        let tree = collect_a11y_from_render(1, 10, |frame| {
1616            let mut state = ScrollbarState::new(100, 20, 10);
1617            StatefulWidget::render(&sb, area, frame, &mut state);
1618        });
1619        assert_eq!(tree.node_count(), expected.len());
1620        let node = tree.node(expected[0].id).expect("scrollbar node present");
1621        assert_eq!(node.role, ftui_a11y::node::A11yRole::ScrollBar);
1622    }
1623
1624    #[test]
1625    fn paragraph_render_pushes_a11y_nodes() {
1626        use crate::paragraph::Paragraph;
1627
1628        let p = Paragraph::new("Hello world");
1629        let area = Rect::new(0, 0, 20, 2);
1630        let expected = ftui_a11y::Accessible::accessibility_nodes(&p, area);
1631        let tree = collect_a11y_from_render(20, 2, |frame| {
1632            p.render(area, frame);
1633        });
1634        assert_eq!(tree.node_count(), expected.len());
1635        let node = tree.node(expected[0].id).expect("paragraph node present");
1636        assert_eq!(node.role, ftui_a11y::node::A11yRole::Label);
1637        assert_eq!(node.name.as_deref(), Some("Hello world"));
1638    }
1639
1640    #[test]
1641    fn block_render_with_children_nests_child_nodes() {
1642        use crate::block::Block;
1643        use crate::borders::Borders;
1644        use crate::input::TextInput;
1645        use crate::paragraph::Paragraph;
1646
1647        let block = Block::new().borders(Borders::ALL).title("Outer");
1648        let outer_area = Rect::new(0, 0, 30, 8);
1649        let inner_area = block.inner(outer_area);
1650        let p_area = Rect::new(inner_area.x, inner_area.y, inner_area.width, 1);
1651        let i_area = Rect::new(inner_area.x, inner_area.y + 1, inner_area.width, 1);
1652
1653        let tree = collect_a11y_from_render(30, 8, |frame| {
1654            block.render_with_children(outer_area, frame, |inner, frame| {
1655                assert_eq!(inner, inner_area);
1656                Paragraph::new("Prompt").render(p_area, frame);
1657                TextInput::new().with_value("abc").render(i_area, frame);
1658            });
1659        });
1660
1661        let block_id = a11y_node_id(outer_area);
1662        let p_id = a11y_node_id(p_area);
1663        let i_id = a11y_node_id(i_area);
1664        let block_node = tree.node(block_id).expect("block node");
1665        assert_eq!(block_node.children, vec![p_id, i_id]);
1666        assert_eq!(
1667            tree.node(p_id).expect("paragraph node").parent,
1668            Some(block_id)
1669        );
1670        assert_eq!(tree.node(i_id).expect("input node").parent, Some(block_id));
1671    }
1672
1673    #[test]
1674    fn render_without_builder_allocates_nothing() {
1675        use crate::block::Block;
1676        use crate::borders::Borders;
1677        use crate::input::TextInput;
1678        use crate::paragraph::Paragraph;
1679
1680        let mut pool = GraphemePool::new();
1681        let mut frame = Frame::new(30, 8, &mut pool);
1682        assert!(!frame.a11y_enabled());
1683
1684        let block = Block::new().borders(Borders::ALL).title("Outer");
1685        block.render_with_children(Rect::new(0, 0, 30, 8), &mut frame, |inner, frame| {
1686            Paragraph::new("Prompt").render(Rect::new(inner.x, inner.y, inner.width, 1), frame);
1687            TextInput::new()
1688                .with_value("abc")
1689                .render(Rect::new(inner.x, inner.y + 1, inner.width, 1), frame);
1690        });
1691        frame.finish_a11y();
1692        assert!(frame.take_a11y_order().is_empty());
1693    }
1694}