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#[cfg(all(test, feature = "tracing"))]
225pub(crate) mod tracing_test_support {
226    use std::sync::{Mutex, MutexGuard, OnceLock};
227
228    /// Serialize tests that install tracing subscribers and rebuild the
229    /// callsite interest cache.
230    pub(crate) struct TraceTestGuard {
231        _lock: MutexGuard<'static, ()>,
232    }
233
234    impl Drop for TraceTestGuard {
235        fn drop(&mut self) {
236            tracing::callsite::rebuild_interest_cache();
237        }
238    }
239
240    pub(crate) fn acquire() -> TraceTestGuard {
241        static TRACE_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
242
243        // Preserve serialization even if an earlier tracing assertion panicked.
244        let lock = TRACE_TEST_LOCK
245            .get_or_init(|| Mutex::new(()))
246            .lock()
247            .unwrap_or_else(|e| e.into_inner());
248        tracing::callsite::rebuild_interest_cache();
249        TraceTestGuard { _lock: lock }
250    }
251}
252
253pub use align::{Align, VerticalAlignment};
254pub use badge::Badge;
255pub use cached::{CacheKey, CachedWidget, CachedWidgetState, FnKey, HashKey, NoCacheKey};
256pub use columns::{Column, Columns};
257pub use constraint_overlay::{ConstraintOverlay, ConstraintOverlayStyle};
258#[cfg(feature = "debug-overlay")]
259pub use debug_overlay::{
260    DebugOverlay, DebugOverlayOptions, DebugOverlayState, DebugOverlayStateful,
261    DebugOverlayStatefulState,
262};
263pub use decision_card::DecisionCard;
264pub use group::Group;
265pub use help_registry::{HelpContent, HelpId, HelpRegistry, Keybinding};
266pub use history_panel::{HistoryEntry, HistoryPanel, HistoryPanelMode};
267pub use layout_debugger::{LayoutConstraints, LayoutDebugger, LayoutRecord};
268pub use log_ring::LogRing;
269pub use log_viewer::{LogViewer, LogViewerState, LogWrapMode, SearchConfig, SearchMode};
270pub use paginator::{Paginator, PaginatorMode};
271pub use panel::Panel;
272pub use sparkline::{Sparkline, SparklineMarkers};
273pub use status_line::{StatusItem, StatusLine};
274pub use tabs::{Tab, Tabs, TabsState};
275pub use virtualized::{
276    HeightCache, ItemHeight, RenderItem, Virtualized, VirtualizedList, VirtualizedListState,
277    VirtualizedStorage,
278};
279pub use voi_debug_overlay::{
280    VoiDebugOverlay, VoiDecisionSummary, VoiLedgerEntry, VoiObservationSummary, VoiOverlayData,
281    VoiOverlayStyle, VoiPosteriorSummary,
282};
283
284// Toast notification widget
285pub use toast::{
286    KeyEvent as ToastKeyEvent, Toast, ToastAction, ToastAnimationConfig, ToastAnimationPhase,
287    ToastAnimationState, ToastConfig, ToastContent, ToastEasing, ToastEntranceAnimation,
288    ToastEvent, ToastExitAnimation, ToastIcon, ToastId, ToastPosition, ToastState, ToastStyle,
289};
290
291// Notification queue manager
292pub use notification_queue::{
293    NotificationPriority, NotificationQueue, QueueAction, QueueConfig, QueueStats,
294};
295
296// Re-export accessibility trait and types for widget implementations.
297pub use ftui_a11y::Accessible;
298
299// Shared mouse result type for widget mouse handling
300pub use mouse::MouseResult;
301
302// Measurable widget support for intrinsic sizing
303pub use measurable::{MeasurableWidget, SizeConstraints};
304
305// Measure cache for memoizing measure() results
306pub use measure_cache::{CacheStats, MeasureCache, WidgetId};
307pub use modal::{
308    BackdropConfig, MODAL_HIT_BACKDROP, MODAL_HIT_CONTENT, Modal, ModalAction, ModalConfig,
309    ModalPosition, ModalSizeConstraints, ModalState,
310};
311
312// UI Inspector for debugging
313pub use inspector::{
314    DiagnosticEntry, DiagnosticEventKind, DiagnosticLog, HitInfo, InspectorMode, InspectorOverlay,
315    InspectorState, InspectorStyle, TelemetryCallback, TelemetryHooks, WidgetInfo,
316    diagnostics_enabled, init_diagnostics, is_deterministic_mode, reset_event_counter,
317    set_diagnostics_enabled,
318};
319
320// Focus management
321pub use focus::{
322    FocusEvent, FocusGraph, FocusGroup, FocusId, FocusIndicator, FocusIndicatorKind, FocusManager,
323    FocusNode, FocusTrap, NavDirection,
324};
325
326// Drag-and-drop protocol (source + target)
327pub use drag::{
328    DragConfig, DragPayload, DragState, Draggable, DropPosition, DropResult, DropTarget,
329};
330
331// Stateful persistence trait
332pub use stateful::{StateKey, Stateful, VersionedState};
333
334// Widget persist state types for state-persistence
335pub use list::ListPersistState;
336pub use table::TablePersistState;
337pub use tree::TreePersistState;
338pub use virtualized::VirtualizedListPersistState;
339
340// Undo support for widgets
341pub use undo_support::{
342    ListOperation, ListUndoExt, SelectionOperation, TableOperation, TableUndoExt,
343    TextEditOperation, TextInputUndoExt, TreeOperation, TreeUndoExt, UndoSupport, UndoWidgetId,
344    WidgetTextEditCmd,
345};
346
347// Inline validation error display
348pub use validation_error::{
349    ANIMATION_DURATION_MS, ERROR_BG_DEFAULT, ERROR_FG_DEFAULT, ERROR_ICON_DEFAULT,
350    ValidationErrorDisplay, ValidationErrorState,
351};
352
353use ftui_core::geometry::Rect;
354use ftui_render::buffer::Buffer;
355use ftui_render::cell::Cell;
356use ftui_render::frame::{Frame, WidgetSignal};
357use ftui_style::Style;
358use ftui_text::grapheme_width;
359
360/// Generate a deterministic accessibility node ID from a widget's bounding rect.
361///
362/// Uses FNV-1a to hash the area coordinates. Stable across frames for widgets
363/// rendered at the same position, enabling efficient A11yTree diffing.
364#[must_use]
365pub(crate) fn a11y_node_id(area: Rect) -> u64 {
366    // FNV-1a 64-bit
367    const FNV_OFFSET: u64 = 14_695_981_039_346_656_037;
368    const FNV_PRIME: u64 = 1_099_511_628_211;
369    let mut h = FNV_OFFSET;
370    for byte in area
371        .x
372        .to_le_bytes()
373        .iter()
374        .chain(&area.y.to_le_bytes())
375        .chain(&area.width.to_le_bytes())
376        .chain(&area.height.to_le_bytes())
377    {
378        h ^= u64::from(*byte);
379        h = h.wrapping_mul(FNV_PRIME);
380    }
381    h
382}
383
384/// A widget that can render itself into a [`Frame`].
385///
386/// # Frame vs Buffer
387///
388/// Widgets render into a `Frame` rather than directly into a `Buffer`. This provides:
389///
390/// - **Buffer access**: `frame.buffer` for drawing cells
391/// - **Hit testing**: `frame.register_hit()` for mouse interaction
392/// - **Cursor control**: `frame.cursor_position` for input widgets
393/// - **Performance hints**: `frame.buffer.degradation` for adaptive rendering
394///
395/// # Implementation Guide
396///
397/// Most widgets only need buffer access:
398///
399/// ```ignore
400/// fn render(&self, area: Rect, frame: &mut Frame) {
401///     for y in area.y..area.bottom() {
402///         for x in area.x..area.right() {
403///             frame.buffer.set(x, y, Cell::from_char('.'));
404///         }
405///     }
406/// }
407/// ```
408///
409/// Interactive widgets should register hit regions when a `hit_id` is set.
410/// Input widgets should set `frame.cursor_position` when focused.
411///
412/// # Degradation Levels
413///
414/// Check `frame.buffer.degradation` to adapt rendering:
415///
416/// - `Full`: All features enabled
417/// - `SimpleBorders`: Skip fancy borders, use ASCII
418/// - `NoStyling`: Skip colors and attributes
419/// - `EssentialOnly`: Only render essential widgets
420/// - `Skeleton`: Minimal placeholder rendering
421///
422/// [`Frame`]: ftui_render::frame::Frame
423pub trait Widget {
424    /// Render the widget into the frame at the given area.
425    ///
426    /// The `area` defines the bounding rectangle within which the widget
427    /// should render. Widgets should respect the area bounds and not
428    /// draw outside them (the buffer's scissor stack enforces this).
429    fn render(&self, area: Rect, frame: &mut Frame);
430
431    /// Whether this widget is essential and should always render.
432    ///
433    /// Essential widgets render even at `EssentialOnly` degradation level.
434    /// Override this to return `true` for:
435    ///
436    /// - Text inputs (user needs to see what they're typing)
437    /// - Primary content areas (main information display)
438    /// - Critical status indicators
439    ///
440    /// Returns `false` by default, appropriate for decorative widgets.
441    fn is_essential(&self) -> bool {
442        false
443    }
444}
445
446/// Frame-side rendering helpers so `view()` code reads top-down:
447/// `frame.render_widget(&sidebar, left)` instead of `sidebar.render(left, frame)`.
448///
449/// This is an extension trait because [`Frame`] lives in `ftui-render`, which
450/// does not know the widget traits; import it through `ftui::prelude::*` or
451/// `use ftui_widgets::FrameExt`.
452pub trait FrameExt {
453    /// Render a stateless widget into `area`.
454    fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect);
455
456    /// Render a stateful widget into `area`, giving it mutable access to its
457    /// state for the duration of the render.
458    fn render_stateful_widget<W: StatefulWidget + ?Sized>(
459        &mut self,
460        widget: &W,
461        area: Rect,
462        state: &mut W::State,
463    );
464}
465
466impl FrameExt for Frame<'_> {
467    #[inline]
468    fn render_widget<W: Widget + ?Sized>(&mut self, widget: &W, area: Rect) {
469        widget.render(area, self);
470    }
471
472    #[inline]
473    fn render_stateful_widget<W: StatefulWidget + ?Sized>(
474        &mut self,
475        widget: &W,
476        area: Rect,
477        state: &mut W::State,
478    ) {
479        widget.render(area, self, state);
480    }
481}
482
483/// Budget-aware wrapper that registers widget signals and respects refresh budgets.
484pub struct Budgeted<W> {
485    widget_id: u64,
486    signal: WidgetSignal,
487    inner: W,
488}
489
490impl<W> Budgeted<W> {
491    /// Wrap a widget with a stable identifier and default signal values.
492    #[must_use]
493    pub fn new(widget_id: u64, inner: W) -> Self {
494        Self {
495            widget_id,
496            signal: WidgetSignal::new(widget_id),
497            inner,
498        }
499    }
500
501    /// Override the widget signal template.
502    #[must_use]
503    pub fn with_signal(mut self, mut signal: WidgetSignal) -> Self {
504        signal.widget_id = self.widget_id;
505        self.signal = signal;
506        self
507    }
508
509    /// Access the wrapped widget.
510    #[must_use]
511    pub fn inner(&self) -> &W {
512        &self.inner
513    }
514}
515
516impl<W: Widget> Widget for Budgeted<W> {
517    fn render(&self, area: Rect, frame: &mut Frame) {
518        let mut signal = self.signal.clone();
519        signal.widget_id = self.widget_id;
520        signal.essential = self.inner.is_essential();
521        signal.area_cells = area.width as u32 * area.height as u32;
522        frame.register_widget_signal(signal);
523
524        if frame.should_render_widget(self.widget_id, self.inner.is_essential()) {
525            self.inner.render(area, frame);
526        }
527    }
528
529    fn is_essential(&self) -> bool {
530        self.inner.is_essential()
531    }
532}
533
534impl<W: StatefulWidget + Widget> StatefulWidget for Budgeted<W> {
535    type State = W::State;
536
537    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
538        let mut signal = self.signal.clone();
539        signal.widget_id = self.widget_id;
540        signal.essential = self.inner.is_essential();
541        signal.area_cells = area.width as u32 * area.height as u32;
542        frame.register_widget_signal(signal);
543
544        if frame.should_render_widget(self.widget_id, self.inner.is_essential()) {
545            StatefulWidget::render(&self.inner, area, frame, state);
546        }
547    }
548}
549
550/// A widget that renders based on mutable state.
551///
552/// Use `StatefulWidget` when the widget needs to:
553///
554/// - Update scroll position during render
555/// - Track selection state
556/// - Cache computed layout information
557/// - Synchronize view with external model
558///
559/// # Example
560///
561/// ```ignore
562/// pub struct ListState {
563///     pub selected: Option<usize>,
564///     pub offset: usize,
565/// }
566///
567/// impl StatefulWidget for List<'_> {
568///     type State = ListState;
569///
570///     fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
571///         // Adjust offset to keep selection visible
572///         if let Some(sel) = state.selected {
573///             if sel < state.offset {
574///                 state.offset = sel;
575///             }
576///         }
577///         // Render items starting from offset...
578///     }
579/// }
580/// ```
581///
582/// # Stateful vs Stateless
583///
584/// Prefer stateless [`Widget`] when possible. Use `StatefulWidget` only when
585/// the render pass genuinely needs to modify state (e.g., scroll adjustment).
586pub trait StatefulWidget {
587    /// The state type associated with this widget.
588    type State;
589
590    /// Render the widget into the frame, potentially modifying state.
591    ///
592    /// State modifications should be limited to:
593    /// - Scroll offset adjustments
594    /// - Selection clamping
595    /// - Layout caching
596    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State);
597}
598
599/// Merge a [`Style`] into a cell, preserving existing properties for unset fields.
600///
601/// - **Foreground / Background:** Only overwritten when the style explicitly sets
602///   the field (`Some`).  Background colours with alpha < 255 are composited via
603///   Porter-Duff SourceOver so semi-transparent overlays blend correctly.
604/// - **Attributes:** New flags are OR-ed on top of existing flags (never cleared).
605pub(crate) fn apply_style(cell: &mut Cell, style: Style) {
606    if let Some(fg) = style.fg {
607        cell.fg = fg;
608    }
609    if let Some(bg) = style.bg {
610        match bg.a() {
611            0 => {}                          // Fully transparent: no-op
612            255 => cell.bg = bg,             // Fully opaque: replace
613            _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
614        }
615    }
616    if let Some(attrs) = style.attrs {
617        let cell_flags: ftui_render::cell::StyleFlags = attrs.into();
618        cell.attrs = cell.attrs.merged_flags(cell_flags);
619    }
620}
621
622/// Apply a style to all cells in a rectangular area using **merge** semantics.
623///
624/// Only fields that are explicitly set in `style` (i.e. `Some`) are applied;
625/// unset fields leave the existing cell values intact.  This is the correct
626/// behaviour for selection / highlight overlays that specify only a background
627/// colour — per-cell foreground colours from earlier text rendering are preserved.
628///
629/// - **Background:** Alpha-aware compositing (Porter-Duff SourceOver).
630/// - **Attributes:** OR-ed on top of existing flags (never cleared).
631pub(crate) fn set_style_area(buf: &mut Buffer, area: Rect, style: Style) {
632    if style.is_empty() {
633        return;
634    }
635    let clipped = area.intersection(&buf.current_scissor());
636    if clipped.is_empty() {
637        return;
638    }
639
640    let opacity = buf.current_opacity();
641    let fg = style.fg.map(|fg| fg.with_opacity(opacity));
642    let bg = style.bg.map(|bg| bg.with_opacity(opacity));
643    let attrs = style.attrs.map(ftui_render::cell::StyleFlags::from);
644    for y in clipped.y..clipped.bottom() {
645        let Some(row) = buf.row_cells_mut_span(y, clipped.x, clipped.right()) else {
646            continue;
647        };
648        for cell in row {
649            if let Some(fg) = fg {
650                cell.fg = fg;
651            }
652            if let Some(bg) = bg {
653                match bg.a() {
654                    0 => {}                          // Fully transparent: no-op
655                    255 => cell.bg = bg,             // Fully opaque: replace
656                    _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
657                }
658            }
659            if let Some(attrs) = attrs {
660                cell.attrs = cell.attrs.merged_flags(attrs);
661            }
662        }
663    }
664}
665
666/// Clear a text area with styled spaces before rendering new content.
667pub(crate) fn clear_text_area(frame: &mut Frame, area: Rect, style: Style) {
668    if area.width == 0 || area.height == 0 {
669        return;
670    }
671
672    let mut cell = Cell::from_char(' ');
673    apply_style(&mut cell, style);
674    frame.buffer.fill(area, cell);
675}
676
677/// Clear a single text row with styled spaces before rendering new content.
678pub(crate) fn clear_text_row(frame: &mut Frame, area: Rect, style: Style) {
679    clear_text_area(frame, Rect::new(area.x, area.y, area.width, 1), style);
680}
681
682/// Build a text cell that inherits existing visual styling from the buffer.
683///
684/// This preserves foreground/background/style flags applied by prior area-wide
685/// overlays (for example selection/highlight passes) while intentionally
686/// dropping any stale hyperlink ID before new text is written.
687fn inherited_text_cell(
688    frame: &Frame,
689    x: u16,
690    y: u16,
691    content: ftui_render::cell::CellContent,
692) -> Cell {
693    let mut cell = frame.buffer.get(x, y).copied().unwrap_or_default();
694    cell.content = content;
695    cell.attrs = ftui_render::cell::CellAttrs::new(cell.attrs.flags(), 0);
696    cell
697}
698
699/// Draw a text span into a frame at the given position.
700///
701/// Returns the x position after the last drawn character.
702/// Stops at `max_x` (exclusive).
703pub(crate) fn draw_text_span(
704    frame: &mut Frame,
705    mut x: u16,
706    y: u16,
707    content: &str,
708    style: Style,
709    max_x: u16,
710) -> u16 {
711    use unicode_segmentation::UnicodeSegmentation;
712
713    for grapheme in content.graphemes(true) {
714        if x >= max_x {
715            break;
716        }
717        let w = grapheme_width(grapheme);
718        if w == 0 {
719            continue;
720        }
721        if x.saturating_add(w as u16) > max_x {
722            break;
723        }
724
725        // Intern grapheme if needed
726        let cell_content = if w > 1 || grapheme.chars().count() > 1 {
727            let id = frame.intern_with_width(grapheme, w as u8);
728            ftui_render::cell::CellContent::from_grapheme(id)
729        } else if let Some(c) = grapheme.chars().next() {
730            ftui_render::cell::CellContent::from_char(c)
731        } else {
732            continue;
733        };
734
735        let mut cell = inherited_text_cell(frame, x, y, cell_content);
736        apply_style(&mut cell, style);
737
738        // set_fast() skips scissor/opacity/compositing checks for common
739        // single-width opaque cells; falls back to set() otherwise.
740        frame.buffer.set_fast(x, y, cell);
741
742        x = x.saturating_add(w as u16);
743    }
744    x
745}
746
747/// Draw a text span, optionally attaching a hyperlink.
748#[allow(dead_code)]
749pub(crate) fn draw_text_span_with_link(
750    frame: &mut Frame,
751    x: u16,
752    y: u16,
753    content: &str,
754    style: Style,
755    max_x: u16,
756    link_url: Option<&str>,
757) -> u16 {
758    draw_text_span_scrolled(frame, x, y, content, style, max_x, 0, link_url)
759}
760
761/// Draw a text span with horizontal scrolling (skip first `scroll_x` visual cells).
762#[allow(dead_code, clippy::too_many_arguments)]
763pub(crate) fn draw_text_span_scrolled(
764    frame: &mut Frame,
765    mut x: u16,
766    y: u16,
767    content: &str,
768    style: Style,
769    max_x: u16,
770    scroll_x: u16,
771    link_url: Option<&str>,
772) -> u16 {
773    use unicode_segmentation::UnicodeSegmentation;
774
775    // Register link if present
776    let link_id = if let Some(url) = link_url {
777        frame.register_link(url)
778    } else {
779        0
780    };
781
782    let mut visual_pos: u16 = 0;
783
784    for grapheme in content.graphemes(true) {
785        if x >= max_x {
786            break;
787        }
788        let w = grapheme_width(grapheme);
789        if w == 0 {
790            continue;
791        }
792
793        let next_visual_pos = visual_pos.saturating_add(w as u16);
794
795        // Check if this grapheme is visible
796        if next_visual_pos <= scroll_x {
797            // Fully scrolled out
798            visual_pos = next_visual_pos;
799            continue;
800        }
801
802        if visual_pos < scroll_x {
803            // Partially scrolled out (e.g. wide char starting at scroll_x - 1)
804            // We skip the whole character because we can't render half a cell.
805            visual_pos = next_visual_pos;
806            continue;
807        }
808
809        if x.saturating_add(w as u16) > max_x {
810            break;
811        }
812
813        // Intern grapheme if needed
814        let cell_content = if w > 1 || grapheme.chars().count() > 1 {
815            let id = frame.intern_with_width(grapheme, w as u8);
816            ftui_render::cell::CellContent::from_grapheme(id)
817        } else if let Some(c) = grapheme.chars().next() {
818            ftui_render::cell::CellContent::from_char(c)
819        } else {
820            continue;
821        };
822
823        let mut cell = inherited_text_cell(frame, x, y, cell_content);
824        apply_style(&mut cell, style);
825
826        // Apply link ID if present
827        if link_id != 0 {
828            cell.attrs = cell.attrs.with_link(link_id);
829        }
830
831        frame.buffer.set_fast(x, y, cell);
832
833        x = x.saturating_add(w as u16);
834        visual_pos = next_visual_pos;
835    }
836    x
837}
838
839/// Helper for allocation-free case-insensitive containment check.
840pub(crate) fn contains_ignore_case(haystack: &str, needle_lower: &str) -> bool {
841    if needle_lower.is_empty() {
842        return true;
843    }
844    // Fast path for ASCII
845    if haystack.is_ascii() && needle_lower.is_ascii() {
846        let haystack_bytes = haystack.as_bytes();
847        let needle_bytes = needle_lower.as_bytes();
848        if needle_bytes.len() > haystack_bytes.len() {
849            return false;
850        }
851        // Naive byte-by-byte scan is fast enough for short strings (UI labels)
852        for i in 0..=haystack_bytes.len() - needle_bytes.len() {
853            let mut match_found = true;
854            for (j, &b) in needle_bytes.iter().enumerate() {
855                if haystack_bytes[i + j].to_ascii_lowercase() != b {
856                    match_found = false;
857                    break;
858                }
859            }
860            if match_found {
861                return true;
862            }
863        }
864        return false;
865    }
866    // Fallback for Unicode (allocates, but correct)
867    haystack.to_lowercase().contains(needle_lower)
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873    use ftui_render::cell::PackedRgba;
874    use ftui_render::grapheme_pool::GraphemePool;
875
876    /// `frame.render_widget(&w, area)` must be exactly `w.render(area, frame)`:
877    /// same cells, same clipping, no extra state.
878    #[test]
879    fn frame_ext_render_widget_matches_direct_render() {
880        struct Fill(char);
881        impl Widget for Fill {
882            fn render(&self, area: Rect, frame: &mut Frame) {
883                for y in area.y..area.y + area.height {
884                    for x in area.x..area.x + area.width {
885                        frame.buffer.set_raw(x, y, Cell::from_char(self.0));
886                    }
887                }
888            }
889        }
890
891        let mut pool_a = GraphemePool::new();
892        let mut direct = Frame::new(6, 2, &mut pool_a);
893        Fill('d').render(Rect::new(1, 0, 3, 2), &mut direct);
894
895        let mut pool_b = GraphemePool::new();
896        let mut via_ext = Frame::new(6, 2, &mut pool_b);
897        via_ext.render_widget(&Fill('d'), Rect::new(1, 0, 3, 2));
898        assert_eq!(via_ext.area(), Rect::new(0, 0, 6, 2));
899
900        for y in 0..2 {
901            for x in 0..6 {
902                assert_eq!(
903                    direct.buffer.get(x, y).map(|cell| cell.content),
904                    via_ext.buffer.get(x, y).map(|cell| cell.content),
905                    "cell ({x},{y}) differs between direct render and FrameExt"
906                );
907            }
908        }
909        assert_eq!(
910            via_ext.buffer.get(1, 0).map(|cell| cell.content),
911            Some(Cell::from_char('d').content)
912        );
913        assert_eq!(
914            via_ext.buffer.get(0, 0).map(|cell| cell.content),
915            Some(Cell::default().content)
916        );
917    }
918
919    /// With a tree builder attached to the frame, rendering an `Accessible`
920    /// widget pushes its nodes (a list with items, a titled block, a
921    /// paragraph) so the runtime can build the tree; without one nothing is
922    /// collected and rendering is unchanged.
923    #[test]
924    fn rendering_accessible_widgets_pushes_their_nodes_into_the_frame() {
925        use crate::block::Block;
926        use crate::list::{List, ListState};
927        use crate::paragraph::Paragraph;
928        use ftui_a11y::node::A11yRole;
929        use ftui_a11y::tree::A11yTreeBuilder;
930
931        let mut pool = GraphemePool::new();
932        let mut builder = A11yTreeBuilder::new();
933        let mut frame = Frame::new(30, 8, &mut pool);
934        frame.set_a11y(&mut builder);
935
936        let mut list_state = ListState::default();
937        let list = List::new(["alpha", "beta"]);
938        StatefulWidget::render(&list, Rect::new(0, 0, 30, 3), &mut frame, &mut list_state);
939        Block::new()
940            .title("Details")
941            .render(Rect::new(0, 3, 30, 3), &mut frame);
942        Paragraph::new("hello").render(Rect::new(0, 6, 30, 1), &mut frame);
943        frame.finish_a11y();
944        let order = frame.take_a11y_order();
945        drop(frame);
946
947        let tree = builder.build();
948        assert_eq!(order.len(), tree.node_count());
949        assert!(
950            order.len() >= 5,
951            "list + 2 items + block + paragraph: {order:?}"
952        );
953        let roles: Vec<A11yRole> = order
954            .iter()
955            .filter_map(|id| tree.node(*id).map(|n| n.role))
956            .collect();
957        assert_eq!(roles[0], A11yRole::List);
958        assert_eq!(roles[1], A11yRole::ListItem);
959        assert_eq!(roles[2], A11yRole::ListItem);
960        assert!(roles.contains(&A11yRole::Group), "{roles:?}");
961        let list_id = order[0];
962        assert_eq!(
963            tree.node(list_id).map(|n| n.children.len()),
964            Some(2),
965            "list items are the list's children"
966        );
967        assert_eq!(
968            tree.root_id(),
969            Some(list_id),
970            "first parentless node is the root"
971        );
972        let text = tree.dump_text(&order);
973        assert!(text.contains("ListItem \"alpha\""), "{text}");
974        assert!(text.contains("Group \"Details\""), "{text}");
975
976        // No builder: nothing collected, rendering still works.
977        let mut pool = GraphemePool::new();
978        let mut frame = Frame::new(30, 8, &mut pool);
979        Paragraph::new("hello").render(Rect::new(0, 0, 30, 1), &mut frame);
980        assert!(frame.a11y_order().is_empty());
981    }
982
983    /// The stateful helper hands the widget its state and keeps mutations.
984    #[test]
985    fn frame_ext_render_stateful_widget_passes_state() {
986        struct Counter;
987        impl StatefulWidget for Counter {
988            type State = u32;
989            fn render(&self, _area: Rect, _frame: &mut Frame, state: &mut u32) {
990                *state += 1;
991            }
992        }
993        let mut pool = GraphemePool::new();
994        let mut frame = Frame::new(4, 1, &mut pool);
995        let mut count = 0;
996        frame.render_stateful_widget(&Counter, frame.area(), &mut count);
997        frame.render_stateful_widget(&Counter, Rect::new(0, 0, 1, 1), &mut count);
998        assert_eq!(count, 2);
999    }
1000
1001    #[test]
1002    fn apply_style_sets_fg() {
1003        let mut cell = Cell::default();
1004        let style = Style::new().fg(PackedRgba::rgb(255, 0, 0));
1005        apply_style(&mut cell, style);
1006        assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
1007    }
1008
1009    #[test]
1010    fn apply_style_sets_bg() {
1011        let mut cell = Cell::default();
1012        let style = Style::new().bg(PackedRgba::rgb(0, 255, 0));
1013        apply_style(&mut cell, style);
1014        assert_eq!(cell.bg, PackedRgba::rgb(0, 255, 0));
1015    }
1016
1017    #[test]
1018    fn apply_style_preserves_content() {
1019        let mut cell = Cell::from_char('Z');
1020        let style = Style::new().fg(PackedRgba::rgb(1, 2, 3));
1021        apply_style(&mut cell, style);
1022        assert_eq!(cell.content.as_char(), Some('Z'));
1023    }
1024
1025    #[test]
1026    fn apply_style_empty_is_noop() {
1027        let original = Cell::default();
1028        let mut cell = Cell::default();
1029        apply_style(&mut cell, Style::default());
1030        assert_eq!(cell.fg, original.fg);
1031        assert_eq!(cell.bg, original.bg);
1032    }
1033
1034    #[test]
1035    fn apply_style_bg_only_preserves_fg() {
1036        // Simulate: cell already has syntax-highlighted fg, selection overlay sets only bg.
1037        let mut cell = Cell::from_char('x').with_fg(PackedRgba::rgb(0, 200, 0));
1038        let selection = Style::new().bg(PackedRgba::rgb(0, 0, 180));
1039        apply_style(&mut cell, selection);
1040        // fg must survive — the selection style didn't set a fg.
1041        assert_eq!(cell.fg, PackedRgba::rgb(0, 200, 0));
1042        assert_eq!(cell.bg, PackedRgba::rgb(0, 0, 180));
1043    }
1044
1045    #[test]
1046    fn apply_style_composites_alpha_bg() {
1047        let base_bg = PackedRgba::rgb(200, 0, 0);
1048        let mut cell = Cell::default().with_bg(base_bg);
1049        let overlay = PackedRgba::rgba(0, 0, 200, 128);
1050        apply_style(&mut cell, Style::new().bg(overlay));
1051        assert_eq!(cell.bg, overlay.over(base_bg));
1052    }
1053
1054    #[test]
1055    fn apply_style_transparent_bg_is_noop() {
1056        let base_bg = PackedRgba::rgb(100, 100, 100);
1057        let mut cell = Cell::default().with_bg(base_bg);
1058        apply_style(&mut cell, Style::new().bg(PackedRgba::rgba(255, 0, 0, 0)));
1059        assert_eq!(cell.bg, base_bg);
1060    }
1061
1062    #[test]
1063    fn apply_style_merges_attrs_not_replaces() {
1064        use ftui_render::cell::StyleFlags as CellFlags;
1065        // Cell starts with BOLD.
1066        let mut cell = Cell::default();
1067        cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1068        // Overlay adds ITALIC — should NOT clear BOLD.
1069        let overlay = Style::new().italic();
1070        apply_style(&mut cell, overlay);
1071        assert!(cell.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1072        assert!(
1073            cell.attrs.has_flag(CellFlags::ITALIC),
1074            "ITALIC must be added"
1075        );
1076    }
1077
1078    #[test]
1079    fn set_style_area_bg_only_preserves_per_cell_fg() {
1080        // A 3-cell buffer where each cell has a distinct fg.
1081        let mut buf = Buffer::new(3, 1);
1082        buf.set(0, 0, Cell::from_char('R').with_fg(PackedRgba::RED));
1083        buf.set(1, 0, Cell::from_char('G').with_fg(PackedRgba::GREEN));
1084        buf.set(2, 0, Cell::from_char('B').with_fg(PackedRgba::BLUE));
1085
1086        // Selection highlight sets only bg.
1087        let highlight = Style::new().bg(PackedRgba::rgb(40, 40, 40));
1088        set_style_area(&mut buf, Rect::new(0, 0, 3, 1), highlight);
1089
1090        // All fg colours must be preserved.
1091        assert_eq!(buf.get(0, 0).unwrap().fg, PackedRgba::RED);
1092        assert_eq!(buf.get(1, 0).unwrap().fg, PackedRgba::GREEN);
1093        assert_eq!(buf.get(2, 0).unwrap().fg, PackedRgba::BLUE);
1094        // bg should be the highlight colour.
1095        assert_eq!(buf.get(0, 0).unwrap().bg, PackedRgba::rgb(40, 40, 40));
1096    }
1097
1098    #[test]
1099    fn set_style_area_merges_attrs_not_replaces() {
1100        use ftui_render::cell::StyleFlags as CellFlags;
1101        let mut buf = Buffer::new(1, 1);
1102        let mut cell = Cell::from_char('X');
1103        cell.attrs = cell.attrs.with_flags(CellFlags::BOLD);
1104        buf.set(0, 0, cell);
1105
1106        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().italic());
1107
1108        let result = buf.get(0, 0).unwrap();
1109        assert!(result.attrs.has_flag(CellFlags::BOLD), "BOLD must survive");
1110        assert!(
1111            result.attrs.has_flag(CellFlags::ITALIC),
1112            "ITALIC must be added"
1113        );
1114    }
1115
1116    #[test]
1117    fn set_style_area_applies_to_all_cells() {
1118        let mut buf = Buffer::new(3, 2);
1119        let area = Rect::new(0, 0, 3, 2);
1120        let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1121        set_style_area(&mut buf, area, style);
1122
1123        for y in 0..2 {
1124            for x in 0..3 {
1125                assert_eq!(
1126                    buf.get(x, y).unwrap().bg,
1127                    PackedRgba::rgb(10, 20, 30),
1128                    "cell ({x},{y}) should have style applied"
1129                );
1130            }
1131        }
1132    }
1133
1134    #[test]
1135    fn set_style_area_composites_alpha_bg_over_existing_bg() {
1136        let mut buf = Buffer::new(1, 1);
1137        let base = PackedRgba::rgb(200, 0, 0);
1138        buf.set(0, 0, Cell::default().with_bg(base));
1139
1140        let overlay = PackedRgba::rgba(0, 0, 200, 128);
1141        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(overlay));
1142
1143        let expected = overlay.over(base);
1144        assert_eq!(buf.get(0, 0).unwrap().bg, expected);
1145    }
1146
1147    #[test]
1148    fn set_style_area_partial_rect() {
1149        let mut buf = Buffer::new(5, 5);
1150        let area = Rect::new(1, 1, 2, 2);
1151        let style = Style::new().fg(PackedRgba::rgb(99, 99, 99));
1152        set_style_area(&mut buf, area, style);
1153
1154        // Inside area should be styled
1155        assert_eq!(buf.get(1, 1).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1156        assert_eq!(buf.get(2, 2).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1157
1158        // Outside area should be default
1159        assert_ne!(buf.get(0, 0).unwrap().fg, PackedRgba::rgb(99, 99, 99));
1160    }
1161
1162    #[test]
1163    fn set_style_area_empty_style_is_noop() {
1164        let mut buf = Buffer::new(3, 3);
1165        buf.set(0, 0, Cell::from_char('A'));
1166        let original_fg = buf.get(0, 0).unwrap().fg;
1167
1168        set_style_area(&mut buf, Rect::new(0, 0, 3, 3), Style::default());
1169
1170        // Should not have changed
1171        assert_eq!(buf.get(0, 0).unwrap().fg, original_fg);
1172        assert_eq!(buf.get(0, 0).unwrap().content.as_char(), Some('A'));
1173    }
1174
1175    #[test]
1176    fn set_style_area_respects_scissor() {
1177        let mut buf = Buffer::new(3, 3);
1178        let style = Style::new().bg(PackedRgba::rgb(10, 20, 30));
1179
1180        buf.push_scissor(Rect::new(1, 1, 1, 1));
1181        set_style_area(&mut buf, Rect::new(0, 0, 3, 3), style);
1182
1183        assert_eq!(buf.get(1, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1184        assert_ne!(buf.get(0, 1).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1185        assert_ne!(buf.get(1, 0).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1186        assert_ne!(buf.get(2, 2).unwrap().bg, PackedRgba::rgb(10, 20, 30));
1187    }
1188
1189    #[test]
1190    fn set_style_area_respects_opacity_stack() {
1191        let mut buf = Buffer::new(1, 1);
1192        let base_fg = PackedRgba::rgb(20, 30, 40);
1193        let base_bg = PackedRgba::rgb(50, 60, 70);
1194        buf.set(0, 0, Cell::from_char('X').with_fg(base_fg).with_bg(base_bg));
1195
1196        let overlay_fg = PackedRgba::rgb(200, 100, 0);
1197        let overlay_bg = PackedRgba::rgb(0, 0, 200);
1198        buf.push_opacity(0.5);
1199        set_style_area(
1200            &mut buf,
1201            Rect::new(0, 0, 1, 1),
1202            Style::new().fg(overlay_fg).bg(overlay_bg),
1203        );
1204
1205        let cell = buf.get(0, 0).unwrap();
1206        assert_eq!(cell.fg, overlay_fg.with_opacity(0.5));
1207        assert_eq!(cell.bg, overlay_bg.with_opacity(0.5).over(base_bg));
1208    }
1209
1210    #[test]
1211    fn draw_text_span_basic() {
1212        let mut pool = GraphemePool::new();
1213        let mut frame = Frame::new(10, 1, &mut pool);
1214        let end_x = draw_text_span(&mut frame, 0, 0, "ABC", Style::default(), 10);
1215
1216        assert_eq!(end_x, 3);
1217        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1218        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
1219        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1220    }
1221
1222    #[test]
1223    fn draw_text_span_clipped_at_max_x() {
1224        let mut pool = GraphemePool::new();
1225        let mut frame = Frame::new(10, 1, &mut pool);
1226        let end_x = draw_text_span(&mut frame, 0, 0, "ABCDEF", Style::default(), 3);
1227
1228        assert_eq!(end_x, 3);
1229        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1230        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1231        // 'D' should not be drawn
1232        assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1233    }
1234
1235    #[test]
1236    fn draw_text_span_starts_at_offset() {
1237        let mut pool = GraphemePool::new();
1238        let mut frame = Frame::new(10, 1, &mut pool);
1239        let end_x = draw_text_span(&mut frame, 5, 0, "XY", Style::default(), 10);
1240
1241        assert_eq!(end_x, 7);
1242        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('X'));
1243        assert_eq!(frame.buffer.get(6, 0).unwrap().content.as_char(), Some('Y'));
1244        assert!(frame.buffer.get(4, 0).unwrap().is_empty());
1245    }
1246
1247    #[test]
1248    fn draw_text_span_empty_string() {
1249        let mut pool = GraphemePool::new();
1250        let mut frame = Frame::new(5, 1, &mut pool);
1251        let end_x = draw_text_span(&mut frame, 0, 0, "", Style::default(), 5);
1252        assert_eq!(end_x, 0);
1253    }
1254
1255    #[test]
1256    fn draw_text_span_applies_style() {
1257        let mut pool = GraphemePool::new();
1258        let mut frame = Frame::new(5, 1, &mut pool);
1259        let style = Style::new().fg(PackedRgba::rgb(255, 128, 0));
1260        draw_text_span(&mut frame, 0, 0, "A", style, 5);
1261
1262        assert_eq!(
1263            frame.buffer.get(0, 0).unwrap().fg,
1264            PackedRgba::rgb(255, 128, 0)
1265        );
1266    }
1267
1268    #[test]
1269    fn draw_text_span_preserves_existing_overlay_fg_and_bg() {
1270        let mut pool = GraphemePool::new();
1271        let mut frame = Frame::new(3, 1, &mut pool);
1272        frame.buffer.set(
1273            0,
1274            0,
1275            Cell::from_char('x').with_fg(PackedRgba::rgb(200, 40, 10)),
1276        );
1277        set_style_area(
1278            &mut frame.buffer,
1279            Rect::new(0, 0, 1, 1),
1280            Style::new().bg(PackedRgba::rgb(20, 30, 40)),
1281        );
1282
1283        draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1284
1285        let cell = frame.buffer.get(0, 0).unwrap();
1286        assert_eq!(cell.content.as_char(), Some('A'));
1287        assert_eq!(cell.fg, PackedRgba::rgb(200, 40, 10));
1288        assert_eq!(cell.bg, PackedRgba::rgb(20, 30, 40));
1289    }
1290
1291    #[test]
1292    fn draw_text_span_drops_stale_link_id_but_keeps_style_flags() {
1293        use ftui_render::cell::{CellAttrs, StyleFlags as CellFlags};
1294
1295        let mut pool = GraphemePool::new();
1296        let mut frame = Frame::new(3, 1, &mut pool);
1297        frame.buffer.set(
1298            0,
1299            0,
1300            Cell::from_char('x').with_attrs(CellAttrs::new(CellFlags::UNDERLINE, 42)),
1301        );
1302
1303        draw_text_span(&mut frame, 0, 0, "A", Style::default(), 1);
1304
1305        let cell = frame.buffer.get(0, 0).unwrap();
1306        assert_eq!(cell.content.as_char(), Some('A'));
1307        assert!(cell.attrs.has_flag(CellFlags::UNDERLINE));
1308        assert_eq!(cell.attrs.link_id(), 0);
1309    }
1310
1311    #[test]
1312    fn draw_text_span_max_x_at_start_draws_nothing() {
1313        let mut pool = GraphemePool::new();
1314        let mut frame = Frame::new(5, 1, &mut pool);
1315        let end_x = draw_text_span(&mut frame, 3, 0, "ABC", Style::default(), 3);
1316        assert_eq!(end_x, 3);
1317        assert!(frame.buffer.get(3, 0).unwrap().is_empty());
1318    }
1319
1320    #[test]
1321    fn widget_is_essential_default_false() {
1322        struct DummyWidget;
1323        impl Widget for DummyWidget {
1324            fn render(&self, _: Rect, _: &mut Frame) {}
1325        }
1326        assert!(!DummyWidget.is_essential());
1327    }
1328
1329    #[test]
1330    fn budgeted_new_and_inner() {
1331        struct TestW;
1332        impl Widget for TestW {
1333            fn render(&self, _: Rect, _: &mut Frame) {}
1334        }
1335        let b = Budgeted::new(42, TestW);
1336        assert_eq!(b.widget_id, 42);
1337        let _ = b.inner(); // Should not panic
1338    }
1339
1340    #[test]
1341    fn budgeted_with_signal() {
1342        struct TestW;
1343        impl Widget for TestW {
1344            fn render(&self, _: Rect, _: &mut Frame) {}
1345        }
1346        let sig = WidgetSignal::new(99);
1347        let b = Budgeted::new(42, TestW).with_signal(sig);
1348        // with_signal should override the signal's widget_id to match
1349        assert_eq!(b.signal.widget_id, 42);
1350    }
1351
1352    #[test]
1353    fn set_style_area_transparent_bg_is_noop() {
1354        let mut buf = Buffer::new(1, 1);
1355        let base = PackedRgba::rgb(100, 100, 100);
1356        buf.set(0, 0, Cell::default().with_bg(base));
1357
1358        // Alpha=0 means fully transparent, should leave bg unchanged
1359        let transparent = PackedRgba::rgba(255, 0, 0, 0);
1360        set_style_area(
1361            &mut buf,
1362            Rect::new(0, 0, 1, 1),
1363            Style::new().bg(transparent),
1364        );
1365        assert_eq!(buf.get(0, 0).unwrap().bg, base);
1366    }
1367
1368    #[test]
1369    fn set_style_area_opaque_bg_replaces() {
1370        let mut buf = Buffer::new(1, 1);
1371        buf.set(
1372            0,
1373            0,
1374            Cell::default().with_bg(PackedRgba::rgb(100, 100, 100)),
1375        );
1376
1377        let opaque = PackedRgba::rgba(0, 255, 0, 255);
1378        set_style_area(&mut buf, Rect::new(0, 0, 1, 1), Style::new().bg(opaque));
1379        assert_eq!(buf.get(0, 0).unwrap().bg, opaque);
1380    }
1381
1382    #[test]
1383    fn draw_text_span_scrolled_skips_chars() {
1384        let mut pool = GraphemePool::new();
1385        let mut frame = Frame::new(10, 1, &mut pool);
1386        // Scroll past first 2 chars of "ABCDE"
1387        let end_x =
1388            draw_text_span_scrolled(&mut frame, 0, 0, "ABCDE", Style::default(), 10, 2, None);
1389
1390        assert_eq!(end_x, 3);
1391        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('C'));
1392        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('D'));
1393        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('E'));
1394    }
1395}