Skip to main content

ftui_widgets/
paragraph.rs

1#![forbid(unsafe_code)]
2
3use crate::block::{Alignment, Block};
4use crate::measurable::{MeasurableWidget, SizeConstraints};
5use crate::{Widget, clear_text_area, draw_text_span_scrolled, draw_text_span_with_link};
6use ahash::AHashMap;
7use ftui_core::geometry::{Rect, Size};
8use ftui_render::frame::Frame;
9use ftui_style::Style;
10use ftui_text::{Line, Span, Text as FtuiText, WrapMode, display_width, graphemes};
11use std::cell::RefCell;
12use std::collections::VecDeque;
13use std::hash::{DefaultHasher, Hash, Hasher};
14use std::sync::Arc;
15
16type Text = FtuiText<'static>;
17
18const PARAGRAPH_METRICS_CACHE_CAPACITY: usize = 256;
19const PARAGRAPH_WRAP_CACHE_CAPACITY: usize = 256;
20
21#[derive(Debug, Clone)]
22struct CachedParagraphMetrics {
23    text_width: usize,
24    text_height: usize,
25    min_width: usize,
26    line_widths: Arc<[usize]>,
27}
28
29#[derive(Debug, Clone)]
30struct CachedWrappedParagraph {
31    lines: Arc<[Line<'static>]>,
32    line_widths: Arc<[usize]>,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36struct ParagraphWrapCacheKey {
37    text_hash: u64,
38    wrap_mode: WrapMode,
39    width: usize,
40}
41
42#[derive(Debug, Default)]
43struct ParagraphCacheState {
44    metrics: AHashMap<u64, CachedParagraphMetrics>,
45    metrics_fifo: VecDeque<u64>,
46    wrapped: AHashMap<ParagraphWrapCacheKey, CachedWrappedParagraph>,
47    wrapped_fifo: VecDeque<ParagraphWrapCacheKey>,
48}
49
50impl ParagraphCacheState {
51    fn insert_metrics(&mut self, key: u64, value: CachedParagraphMetrics) {
52        cache_insert(
53            &mut self.metrics,
54            &mut self.metrics_fifo,
55            PARAGRAPH_METRICS_CACHE_CAPACITY,
56            key,
57            value,
58        );
59    }
60
61    fn insert_wrapped(&mut self, key: ParagraphWrapCacheKey, value: CachedWrappedParagraph) {
62        cache_insert(
63            &mut self.wrapped,
64            &mut self.wrapped_fifo,
65            PARAGRAPH_WRAP_CACHE_CAPACITY,
66            key,
67            value,
68        );
69    }
70}
71
72thread_local! {
73    static PARAGRAPH_CACHE: RefCell<ParagraphCacheState> = RefCell::new(ParagraphCacheState::default());
74}
75
76fn cache_insert<K, V>(
77    map: &mut AHashMap<K, V>,
78    fifo: &mut VecDeque<K>,
79    capacity: usize,
80    key: K,
81    value: V,
82) where
83    K: Copy + Eq + Hash,
84{
85    if !map.contains_key(&key) {
86        if map.len() >= capacity
87            && let Some(oldest) = fifo.pop_front()
88        {
89            map.remove(&oldest);
90        }
91        fifo.push_back(key);
92    }
93    map.insert(key, value);
94}
95
96fn text_into_owned(text: FtuiText<'_>) -> FtuiText<'static> {
97    FtuiText::from_lines(
98        text.into_iter()
99            .map(|line| Line::from_spans(line.into_iter().map(Span::into_owned))),
100    )
101}
102
103/// A widget that renders multi-line styled text.
104#[derive(Debug, Clone, Default)]
105pub struct Paragraph<'a> {
106    text: Text,
107    block: Option<Block<'a>>,
108    style: Style,
109    wrap: Option<WrapMode>,
110    alignment: Alignment,
111    scroll: (u16, u16),
112}
113
114fn hash_value<T: Hash>(value: &T) -> u64 {
115    let mut hasher = DefaultHasher::new();
116    value.hash(&mut hasher);
117    hasher.finish()
118}
119
120fn line_min_width(line: &Line<'_>) -> usize {
121    let mut max_word_width = 0;
122    let mut current_word_width = 0;
123
124    for span in line.spans() {
125        for grapheme in graphemes(span.content.as_ref()) {
126            let grapheme_width = display_width(grapheme);
127            if grapheme.chars().all(char::is_whitespace) {
128                max_word_width = max_word_width.max(current_word_width);
129                current_word_width = 0;
130            } else {
131                current_word_width += grapheme_width;
132            }
133        }
134    }
135
136    max_word_width.max(current_word_width)
137}
138
139impl<'a> Paragraph<'a> {
140    fn with_static_text(text: FtuiText<'static>) -> Self {
141        Self {
142            text,
143            block: None,
144            style: Style::default(),
145            wrap: None,
146            alignment: Alignment::Left,
147            scroll: (0, 0),
148        }
149    }
150
151    /// Create a new paragraph from the given text.
152    #[must_use]
153    pub fn new<'t>(text: impl Into<FtuiText<'t>>) -> Self {
154        Self::with_static_text(text_into_owned(text.into()))
155    }
156
157    /// Create a new paragraph from text that is already valid for the widget's storage lifetime.
158    #[must_use]
159    pub fn from_static_text(text: FtuiText<'static>) -> Self {
160        Self::with_static_text(text)
161    }
162
163    /// Create a new paragraph from a static string without copying the string contents.
164    #[must_use]
165    pub fn from_static_str(text: &'static str) -> Self {
166        Self::from_static_text(FtuiText::raw(text))
167    }
168
169    /// Set the surrounding block.
170    #[must_use]
171    pub fn block(mut self, block: Block<'a>) -> Self {
172        self.block = Some(block);
173        self
174    }
175
176    /// Set the base text style.
177    #[must_use]
178    pub fn style(mut self, style: Style) -> Self {
179        self.style = style;
180        self
181    }
182
183    /// Set the text wrapping mode.
184    #[must_use]
185    pub fn wrap(mut self, wrap: WrapMode) -> Self {
186        self.wrap = Some(wrap);
187        self
188    }
189
190    /// Set the text alignment.
191    #[must_use]
192    pub fn alignment(mut self, alignment: Alignment) -> Self {
193        self.alignment = alignment;
194        self
195    }
196
197    /// Set the scroll offset as (vertical, horizontal).
198    #[must_use]
199    pub fn scroll(mut self, offset: (u16, u16)) -> Self {
200        self.scroll = offset;
201        self
202    }
203
204    fn text_hash(&self) -> u64 {
205        hash_value(&self.text)
206    }
207
208    fn cached_metrics(&self) -> CachedParagraphMetrics {
209        let text_hash = self.text_hash();
210        PARAGRAPH_CACHE.with(|cache| {
211            let mut cache = cache.borrow_mut();
212            if let Some(metrics) = cache.metrics.get(&text_hash) {
213                return metrics.clone();
214            }
215
216            let mut text_width = 0usize;
217            let mut min_width = 0usize;
218            let mut line_widths = Vec::with_capacity(self.text.lines().len());
219
220            for line in self.text.lines() {
221                let width = line.width();
222                text_width = text_width.max(width);
223                min_width = min_width.max(line_min_width(line));
224                line_widths.push(width);
225            }
226
227            let metrics = CachedParagraphMetrics {
228                text_width,
229                text_height: self.text.height(),
230                min_width: if min_width == 0 {
231                    text_width
232                } else {
233                    min_width
234                },
235                line_widths: Arc::from(line_widths),
236            };
237
238            cache.insert_metrics(text_hash, metrics.clone());
239            metrics
240        })
241    }
242
243    fn cached_wrapped_lines(&self, width: usize, wrap_mode: WrapMode) -> CachedWrappedParagraph {
244        let key = ParagraphWrapCacheKey {
245            text_hash: self.text_hash(),
246            wrap_mode,
247            width,
248        };
249
250        PARAGRAPH_CACHE.with(|cache| {
251            let mut cache = cache.borrow_mut();
252            if let Some(wrapped) = cache.wrapped.get(&key) {
253                return wrapped.clone();
254            }
255
256            let mut lines = Vec::new();
257            let mut line_widths = Vec::new();
258
259            for line in self.text.lines() {
260                let line_width = line.width();
261                if wrap_mode == WrapMode::None || line_width <= width {
262                    lines.push(line.clone());
263                    line_widths.push(line_width);
264                    continue;
265                }
266
267                let wrapped_lines = line.wrap(width, wrap_mode);
268                if wrapped_lines.is_empty() {
269                    lines.push(Line::new());
270                    line_widths.push(0);
271                    continue;
272                }
273
274                for wrapped_line in wrapped_lines {
275                    line_widths.push(wrapped_line.width());
276                    lines.push(wrapped_line);
277                }
278            }
279
280            let wrapped = CachedWrappedParagraph {
281                lines: Arc::from(lines),
282                line_widths: Arc::from(line_widths),
283            };
284
285            cache.insert_wrapped(key, wrapped.clone());
286            wrapped
287        })
288    }
289}
290
291impl Widget for Paragraph<'_> {
292    fn render(&self, area: Rect, frame: &mut Frame) {
293        #[cfg(feature = "tracing")]
294        let _span = tracing::debug_span!(
295            "widget_render",
296            widget = "Paragraph",
297            x = area.x,
298            y = area.y,
299            w = area.width,
300            h = area.height
301        )
302        .entered();
303
304        let deg = frame.buffer.degradation;
305
306        // Skeleton+: clear the owned area so previously rendered content does not linger.
307        if !deg.render_content() {
308            clear_text_area(frame, area, Style::default());
309            return;
310        }
311
312        // Special-case: an empty Paragraph with no Block is commonly used as a screen-clear.
313        // In that mode we must clear cell *content* (not just paint style), otherwise old
314        // borders/characters can bleed through Flex gaps.
315        let style = if deg.apply_styling() {
316            self.style
317        } else {
318            Style::default()
319        };
320        if self.block.is_none() && self.text.is_empty() {
321            clear_text_area(frame, area, style);
322            return;
323        }
324
325        clear_text_area(frame, area, style);
326
327        let text_area = match self.block {
328            Some(ref b) => {
329                b.render(area, frame);
330                b.inner(area)
331            }
332            None => area,
333        };
334
335        if text_area.is_empty() {
336            return;
337        }
338
339        // At NoStyling, render text without per-span styles
340        // Background is already applied for the whole area via `set_style_area()`. When drawing
341        // text we avoid re-applying the same background, otherwise semi-transparent BG colors
342        // get composited multiple times.
343        let mut text_style = style;
344        text_style.bg = None;
345
346        let mut y = text_area.y;
347        let mut current_visual_line = 0;
348        let scroll_offset = self.scroll.0 as usize;
349
350        let mut render_line = |line: &ftui_text::Line, line_width: usize, y: u16| {
351            let scroll_x = self.scroll.1;
352            let start_x = align_x(text_area, line_width, self.alignment);
353
354            // Let's iterate spans.
355            // `span_visual_offset`: relative to line start.
356            let mut span_visual_offset = 0;
357
358            // Alignment offset relative to text_area.x
359            let alignment_offset = start_x.saturating_sub(text_area.x);
360
361            for span in line.spans() {
362                let span_width = span.width();
363
364                // Effective position of this span relative to text_area.x
365                // pos = alignment_offset + span_visual_offset - scroll_x
366                let line_rel_start = alignment_offset.saturating_add(span_visual_offset);
367
368                // Check visibility
369                if line_rel_start.saturating_add(span_width as u16) <= scroll_x {
370                    // Fully scrolled out to the left
371                    span_visual_offset = span_visual_offset.saturating_add(span_width as u16);
372                    continue;
373                }
374
375                // Calculate actual draw position.
376                let (draw_x, local_scroll) = if line_rel_start < scroll_x {
377                    // Partially scrolled out left
378                    (text_area.x, scroll_x - line_rel_start)
379                } else {
380                    // Start is visible
381                    (text_area.x.saturating_add(line_rel_start - scroll_x), 0)
382                };
383
384                if draw_x >= text_area.right() {
385                    // Fully clipped to the right
386                    break;
387                }
388
389                // At NoStyling+, ignore span-level styles entirely
390                let span_style = if deg.apply_styling() {
391                    match span.style {
392                        Some(s) => s.merge(&text_style),
393                        None => text_style,
394                    }
395                } else {
396                    text_style // Style::default() at NoStyling
397                };
398
399                if local_scroll > 0 {
400                    draw_text_span_scrolled(
401                        frame,
402                        draw_x,
403                        y,
404                        span.content.as_ref(),
405                        span_style,
406                        text_area.right(),
407                        local_scroll,
408                        span.link.as_deref(),
409                    );
410                } else {
411                    draw_text_span_with_link(
412                        frame,
413                        draw_x,
414                        y,
415                        span.content.as_ref(),
416                        span_style,
417                        text_area.right(),
418                        span.link.as_deref(),
419                    );
420                }
421
422                span_visual_offset = span_visual_offset.saturating_add(span_width as u16);
423            }
424        };
425
426        let metrics = self.cached_metrics();
427        let rendered_lines: Option<CachedWrappedParagraph> = self
428            .wrap
429            .map(|wrap_mode| self.cached_wrapped_lines(text_area.width as usize, wrap_mode));
430
431        if let Some(wrapped) = rendered_lines {
432            for (line, line_width) in wrapped.lines.iter().zip(wrapped.line_widths.iter()) {
433                if current_visual_line < scroll_offset {
434                    current_visual_line += 1;
435                    continue;
436                }
437                if y >= text_area.bottom() {
438                    break;
439                }
440                render_line(line, *line_width, y);
441                y = y.saturating_add(1);
442                current_visual_line += 1;
443            }
444        } else {
445            for (line, line_width) in self.text.lines().iter().zip(metrics.line_widths.iter()) {
446                if current_visual_line < scroll_offset {
447                    current_visual_line += 1;
448                    continue;
449                }
450                if y >= text_area.bottom() {
451                    break;
452                }
453                render_line(line, *line_width, y);
454                y = y.saturating_add(1);
455                current_visual_line += 1;
456            }
457        }
458    }
459}
460impl MeasurableWidget for Paragraph<'_> {
461    fn measure(&self, available: Size) -> SizeConstraints {
462        let metrics = self.cached_metrics();
463        let text_width = metrics.text_width;
464        let text_height = metrics.text_height;
465        let min_width = metrics.min_width;
466
467        // Get block chrome if present
468        let (chrome_width, chrome_height) = self
469            .block
470            .as_ref()
471            .map(|b| b.chrome_size())
472            .unwrap_or((0, 0));
473
474        // If wrapping is enabled, calculate wrapped height
475        let (preferred_width, preferred_height) =
476            if self.wrap.is_some_and(|mode| mode != WrapMode::None) {
477                // When wrapping, preferred width is either the text width or available width
478                let wrap_width = if available.width > chrome_width {
479                    (available.width - chrome_width) as usize
480                } else {
481                    1
482                };
483
484                let wrapped_height = self
485                    .wrap
486                    .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
487                    .unwrap_or(text_height);
488
489                // Preferred width is min(text_width, available_width - chrome)
490                let pref_w = text_width.min(wrap_width);
491                (pref_w, wrapped_height)
492            } else {
493                // No wrapping: preferred is natural text dimensions
494                (text_width, text_height)
495            };
496
497        // Convert to u16, saturating at MAX
498        let min_w = (min_width as u16).saturating_add(chrome_width);
499        // Only require 1 line minimum if there's actual content
500        let min_h = if preferred_height > 0 {
501            (1u16).saturating_add(chrome_height)
502        } else {
503            chrome_height
504        };
505
506        let pref_w = (preferred_width as u16).saturating_add(chrome_width);
507        let pref_h = (preferred_height as u16).saturating_add(chrome_height);
508
509        SizeConstraints {
510            min: Size::new(min_w, min_h),
511            preferred: Size::new(pref_w, pref_h),
512            max: None, // Paragraph can use additional space for scrolling
513        }
514    }
515
516    fn has_intrinsic_size(&self) -> bool {
517        // Paragraph always has intrinsic size based on its text content
518        true
519    }
520}
521
522impl Paragraph<'_> {
523    #[cfg_attr(not(test), allow(dead_code))]
524    fn calculate_min_width(&self) -> usize {
525        self.cached_metrics().min_width
526    }
527
528    #[cfg_attr(not(test), allow(dead_code))]
529    fn estimate_wrapped_height(&self, wrap_width: usize) -> usize {
530        if wrap_width == 0 {
531            return self.cached_metrics().text_height;
532        }
533
534        self.wrap
535            .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
536            .unwrap_or_else(|| self.cached_metrics().text_height)
537            .max(1)
538    }
539}
540
541/// Calculate the starting x position for a line given alignment.
542fn align_x(area: Rect, line_width: usize, alignment: Alignment) -> u16 {
543    let line_width_u16 = u16::try_from(line_width).unwrap_or(u16::MAX);
544    match alignment {
545        Alignment::Left => area.x,
546        Alignment::Center => area
547            .x
548            .saturating_add(area.width.saturating_sub(line_width_u16) / 2),
549        Alignment::Right => area
550            .x
551            .saturating_add(area.width.saturating_sub(line_width_u16)),
552    }
553}
554
555fn truncate_accessible_text(text: &str) -> String {
556    const ACCESSIBLE_TEXT_LIMIT: usize = 200;
557    const ACCESSIBLE_TEXT_PREFIX_LIMIT: usize = 197;
558
559    if text.chars().count() <= ACCESSIBLE_TEXT_LIMIT {
560        text.to_owned()
561    } else {
562        let mut prefix = String::new();
563        let mut prefix_chars = 0usize;
564
565        for grapheme in graphemes(text) {
566            let grapheme_chars = grapheme.chars().count();
567            if prefix_chars + grapheme_chars > ACCESSIBLE_TEXT_PREFIX_LIMIT {
568                break;
569            }
570            prefix.push_str(grapheme);
571            prefix_chars += grapheme_chars;
572        }
573
574        format!("{prefix}...")
575    }
576}
577
578// ============================================================================
579// Accessibility
580// ============================================================================
581
582impl ftui_a11y::Accessible for Paragraph<'_> {
583    fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
584        use ftui_a11y::node::{A11yNodeInfo, A11yRole};
585
586        let id = crate::a11y_node_id(area);
587
588        // Extract the plain-text content for the accessible name.
589        let name: String = self
590            .text
591            .lines()
592            .iter()
593            .map(|line| {
594                line.spans()
595                    .iter()
596                    .map(|span| span.content.as_ref())
597                    .collect::<Vec<_>>()
598                    .join("")
599            })
600            .collect::<Vec<_>>()
601            .join(" ");
602
603        let block_title = self.block.as_ref().and_then(|b| b.title_text());
604        let truncated_name = truncate_accessible_text(&name);
605
606        let mut node = A11yNodeInfo::new(id, A11yRole::Label, area);
607        if let Some(title) = block_title {
608            node = node.with_name(title);
609            if !name.is_empty() {
610                node = node.with_description(truncated_name);
611            }
612        } else if !name.is_empty() {
613            node = node.with_name(truncated_name);
614        }
615
616        vec![node]
617    }
618}
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623    use ftui_render::grapheme_pool::GraphemePool;
624
625    fn raw_row_text(frame: &Frame, y: u16) -> String {
626        let width = frame.buffer.width();
627        let mut actual = String::new();
628        for x in 0..width {
629            let ch = frame
630                .buffer
631                .get(x, y)
632                .and_then(|cell| cell.content.as_char())
633                .unwrap_or(' ');
634            actual.push(ch);
635        }
636        actual
637    }
638
639    #[test]
640    fn render_simple_text() {
641        let para = Paragraph::new(Text::raw("Hello"));
642        let area = Rect::new(0, 0, 10, 1);
643        let mut pool = GraphemePool::new();
644        let mut frame = Frame::new(10, 1, &mut pool);
645        para.render(area, &mut frame);
646
647        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
648        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('o'));
649    }
650
651    #[test]
652    fn from_static_str_preserves_rendering_without_owning_static_spans() {
653        let area = Rect::new(0, 0, 8, 2);
654
655        let fast = Paragraph::from_static_str("Hi\nthere").style(Style::new().bold());
656        let slow = Paragraph::new("Hi\nthere").style(Style::new().bold());
657
658        let mut fast_pool = GraphemePool::new();
659        let mut fast_frame = Frame::new(8, 2, &mut fast_pool);
660        fast.render(area, &mut fast_frame);
661
662        let mut slow_pool = GraphemePool::new();
663        let mut slow_frame = Frame::new(8, 2, &mut slow_pool);
664        slow.render(area, &mut slow_frame);
665
666        assert_eq!(raw_row_text(&fast_frame, 0), raw_row_text(&slow_frame, 0));
667        assert_eq!(raw_row_text(&fast_frame, 1), raw_row_text(&slow_frame, 1));
668
669        let first_span = &fast.text.lines()[0].spans()[0];
670        match &first_span.content {
671            std::borrow::Cow::Borrowed(text) => assert_eq!(*text, "Hi"),
672            std::borrow::Cow::Owned(_) => panic!("static paragraph text should stay borrowed"),
673        }
674    }
675
676    #[test]
677    fn render_multiline_text() {
678        let para = Paragraph::new(Text::raw("AB\nCD"));
679        let area = Rect::new(0, 0, 5, 3);
680        let mut pool = GraphemePool::new();
681        let mut frame = Frame::new(5, 3, &mut pool);
682        para.render(area, &mut frame);
683
684        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
685        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
686        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('C'));
687        assert_eq!(frame.buffer.get(1, 1).unwrap().content.as_char(), Some('D'));
688    }
689
690    #[test]
691    fn render_centered_text() {
692        let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Center);
693        let area = Rect::new(0, 0, 10, 1);
694        let mut pool = GraphemePool::new();
695        let mut frame = Frame::new(10, 1, &mut pool);
696        para.render(area, &mut frame);
697
698        // "Hi" is 2 wide, area is 10, so starts at (10-2)/2 = 4
699        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('H'));
700        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('i'));
701    }
702
703    #[test]
704    fn render_with_scroll() {
705        let para = Paragraph::new(Text::raw("Line1\nLine2\nLine3")).scroll((1, 0));
706        let area = Rect::new(0, 0, 10, 2);
707        let mut pool = GraphemePool::new();
708        let mut frame = Frame::new(10, 2, &mut pool);
709        para.render(area, &mut frame);
710
711        // Should skip Line1, show Line2 and Line3
712        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('L'));
713        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('2'));
714    }
715
716    #[test]
717    fn render_empty_area() {
718        let para = Paragraph::new(Text::raw("Hello"));
719        let area = Rect::new(0, 0, 0, 0);
720        let mut pool = GraphemePool::new();
721        let mut frame = Frame::new(1, 1, &mut pool);
722        para.render(area, &mut frame);
723    }
724
725    #[test]
726    fn line_min_width_tracks_words_across_spans() {
727        let line = Line::from_spans([
728            Span::raw("alpha"),
729            Span::styled(" ", Style::new().bold()),
730            Span::raw("beta"),
731            Span::raw("  "),
732            Span::raw("gamma"),
733        ]);
734
735        assert_eq!(line_min_width(&line), 5);
736    }
737
738    #[test]
739    fn measure_wrap_counts_cached_visual_lines() {
740        let para = Paragraph::new(Text::raw("hello world from cache")).wrap(WrapMode::Word);
741        let constraints = para.measure(Size::new(8, 10));
742
743        assert_eq!(constraints.preferred.height, 4);
744        assert_eq!(constraints.min.width, 5);
745    }
746
747    #[test]
748    fn measure_wrap_none_preserves_natural_width() {
749        let para = Paragraph::new(Text::raw("abcdef")).wrap(WrapMode::None);
750        let constraints = para.measure(Size::new(3, 10));
751
752        assert_eq!(constraints.preferred.width, 6);
753        assert_eq!(constraints.preferred.height, 1);
754    }
755
756    #[test]
757    fn render_empty_text_clears_content() {
758        let para = Paragraph::new("");
759        let area = Rect::new(0, 0, 3, 1);
760        let mut pool = GraphemePool::new();
761        let mut frame = Frame::new(3, 1, &mut pool);
762
763        // Seed with non-space content; an empty Paragraph render should clear it.
764        frame
765            .buffer
766            .fill(area, ftui_render::cell::Cell::from_char('X'));
767
768        para.render(area, &mut frame);
769
770        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
771        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some(' '));
772    }
773
774    #[test]
775    fn render_right_aligned() {
776        let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Right);
777        let area = Rect::new(0, 0, 10, 1);
778        let mut pool = GraphemePool::new();
779        let mut frame = Frame::new(10, 1, &mut pool);
780        para.render(area, &mut frame);
781
782        // "Hi" is 2 wide, area is 10, so starts at 10-2 = 8
783        assert_eq!(frame.buffer.get(8, 0).unwrap().content.as_char(), Some('H'));
784        assert_eq!(frame.buffer.get(9, 0).unwrap().content.as_char(), Some('i'));
785    }
786
787    #[test]
788    fn render_with_word_wrap() {
789        let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
790        let area = Rect::new(0, 0, 6, 3);
791        let mut pool = GraphemePool::new();
792        let mut frame = Frame::new(6, 3, &mut pool);
793        para.render(area, &mut frame);
794
795        // "hello " fits in 6, " world" wraps to next line
796        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('h'));
797        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('w'));
798    }
799
800    #[test]
801    fn render_with_char_wrap() {
802        let para = Paragraph::new(Text::raw("abcdefgh")).wrap(WrapMode::Char);
803        let area = Rect::new(0, 0, 4, 3);
804        let mut pool = GraphemePool::new();
805        let mut frame = Frame::new(4, 3, &mut pool);
806        para.render(area, &mut frame);
807
808        // First line: abcd
809        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
810        assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some('d'));
811        // Second line: efgh
812        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
813    }
814
815    #[test]
816    fn scroll_past_all_lines() {
817        let para = Paragraph::new(Text::raw("AB")).scroll((5, 0));
818        let area = Rect::new(0, 0, 5, 2);
819        let mut pool = GraphemePool::new();
820        let mut frame = Frame::new(5, 2, &mut pool);
821        para.render(area, &mut frame);
822
823        // All lines skipped, but the paragraph still owns and clears its area.
824        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
825    }
826
827    #[test]
828    fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
829        let area = Rect::new(0, 0, 8, 2);
830        let mut pool = GraphemePool::new();
831        let mut frame = Frame::new(8, 2, &mut pool);
832
833        Paragraph::new(Text::raw("Hello\nWorld")).render(area, &mut frame);
834        Paragraph::new(Text::raw("Hi")).render(area, &mut frame);
835
836        assert_eq!(raw_row_text(&frame, 0), "Hi      ");
837        assert_eq!(raw_row_text(&frame, 1), "        ");
838    }
839
840    #[test]
841    fn render_clipped_at_area_height() {
842        let para = Paragraph::new(Text::raw("A\nB\nC\nD\nE"));
843        let area = Rect::new(0, 0, 5, 2);
844        let mut pool = GraphemePool::new();
845        let mut frame = Frame::new(5, 2, &mut pool);
846        para.render(area, &mut frame);
847
848        // Only first 2 lines should render
849        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
850        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('B'));
851    }
852
853    #[test]
854    fn render_clipped_at_area_width() {
855        let para = Paragraph::new(Text::raw("ABCDEF"));
856        let area = Rect::new(0, 0, 3, 1);
857        let mut pool = GraphemePool::new();
858        let mut frame = Frame::new(3, 1, &mut pool);
859        para.render(area, &mut frame);
860
861        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
862        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
863    }
864
865    #[test]
866    fn align_x_left() {
867        let area = Rect::new(5, 0, 20, 1);
868        assert_eq!(align_x(area, 10, Alignment::Left), 5);
869    }
870
871    #[test]
872    fn align_x_center() {
873        let area = Rect::new(0, 0, 20, 1);
874        // line_width=6, area=20, so (20-6)/2 = 7
875        assert_eq!(align_x(area, 6, Alignment::Center), 7);
876    }
877
878    #[test]
879    fn align_x_right() {
880        let area = Rect::new(0, 0, 20, 1);
881        // line_width=5, area=20, so 20-5 = 15
882        assert_eq!(align_x(area, 5, Alignment::Right), 15);
883    }
884
885    #[test]
886    fn align_x_wide_line_saturates() {
887        let area = Rect::new(0, 0, 10, 1);
888        // line wider than area: should saturate to area.x
889        assert_eq!(align_x(area, 20, Alignment::Right), 0);
890        assert_eq!(align_x(area, 20, Alignment::Center), 0);
891    }
892
893    #[test]
894    fn builder_methods_chain() {
895        let para = Paragraph::new(Text::raw("test"))
896            .style(Style::default())
897            .wrap(WrapMode::Word)
898            .alignment(Alignment::Center)
899            .scroll((1, 2));
900        // Verify it builds without panic
901        let area = Rect::new(0, 0, 10, 5);
902        let mut pool = GraphemePool::new();
903        let mut frame = Frame::new(10, 5, &mut pool);
904        para.render(area, &mut frame);
905    }
906
907    #[test]
908    fn render_at_offset_area() {
909        let para = Paragraph::new(Text::raw("X"));
910        let area = Rect::new(3, 4, 5, 2);
911        let mut pool = GraphemePool::new();
912        let mut frame = Frame::new(10, 10, &mut pool);
913        para.render(area, &mut frame);
914
915        assert_eq!(frame.buffer.get(3, 4).unwrap().content.as_char(), Some('X'));
916        // Cell at (0,0) should be empty
917        assert!(frame.buffer.get(0, 0).unwrap().is_empty());
918    }
919
920    #[test]
921    fn wrap_clipped_at_area_bottom() {
922        // Long wrapped text should stop at area height
923        let para = Paragraph::new(Text::raw("abcdefghijklmnop")).wrap(WrapMode::Char);
924        let area = Rect::new(0, 0, 4, 2);
925        let mut pool = GraphemePool::new();
926        let mut frame = Frame::new(4, 2, &mut pool);
927        para.render(area, &mut frame);
928
929        // Only 2 rows of 4 chars each
930        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
931        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
932    }
933
934    // --- Degradation tests ---
935
936    #[test]
937    fn degradation_skeleton_skips_content() {
938        use ftui_render::budget::DegradationLevel;
939
940        let para = Paragraph::new(Text::raw("Hello"));
941        let area = Rect::new(0, 0, 10, 1);
942        let mut pool = GraphemePool::new();
943        let mut frame = Frame::new(10, 1, &mut pool);
944        Paragraph::new(Text::raw("Stale")).render(area, &mut frame);
945        frame.set_degradation(DegradationLevel::Skeleton);
946        para.render(area, &mut frame);
947
948        // Skeleton clears previously rendered content instead of leaving it behind.
949        assert_eq!(raw_row_text(&frame, 0), "          ");
950    }
951
952    #[test]
953    fn degradation_full_renders_content() {
954        use ftui_render::budget::DegradationLevel;
955
956        let para = Paragraph::new(Text::raw("Hello"));
957        let area = Rect::new(0, 0, 10, 1);
958        let mut pool = GraphemePool::new();
959        let mut frame = Frame::new(10, 1, &mut pool);
960        frame.set_degradation(DegradationLevel::Full);
961        para.render(area, &mut frame);
962
963        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
964    }
965
966    #[test]
967    fn degradation_essential_only_still_renders_text() {
968        use ftui_render::budget::DegradationLevel;
969
970        let para = Paragraph::new(Text::raw("Hello"));
971        let area = Rect::new(0, 0, 10, 1);
972        let mut pool = GraphemePool::new();
973        let mut frame = Frame::new(10, 1, &mut pool);
974        frame.set_degradation(DegradationLevel::EssentialOnly);
975        para.render(area, &mut frame);
976
977        // EssentialOnly still renders content (< Skeleton)
978        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
979    }
980
981    #[test]
982    fn degradation_no_styling_ignores_span_styles() {
983        use ftui_render::budget::DegradationLevel;
984        use ftui_render::cell::PackedRgba;
985        use ftui_text::{Line, Span};
986
987        // Create text with a styled span
988        let styled_span = Span::styled("Hello", Style::new().fg(PackedRgba::RED));
989        let line = Line::from_spans([styled_span]);
990        let text = Text::from(line);
991        let para = Paragraph::new(text);
992        let area = Rect::new(0, 0, 10, 1);
993        let mut pool = GraphemePool::new();
994        let mut frame = Frame::new(10, 1, &mut pool);
995        frame.set_degradation(DegradationLevel::NoStyling);
996        para.render(area, &mut frame);
997
998        // Text should render but span style should be ignored
999        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1000        // Foreground color should NOT be red
1001        assert_ne!(
1002            frame.buffer.get(0, 0).unwrap().fg,
1003            PackedRgba::RED,
1004            "Span fg color should be ignored at NoStyling"
1005        );
1006    }
1007
1008    // --- MeasurableWidget tests ---
1009
1010    use crate::MeasurableWidget;
1011    use ftui_core::geometry::Size;
1012
1013    #[test]
1014    fn measure_simple_text() {
1015        let para = Paragraph::new(Text::raw("Hello"));
1016        let constraints = para.measure(Size::MAX);
1017
1018        // "Hello" is 5 chars wide, 1 line tall
1019        assert_eq!(constraints.preferred, Size::new(5, 1));
1020        assert_eq!(constraints.min.height, 1);
1021        // Min width is the longest word = "Hello" = 5
1022        assert_eq!(constraints.min.width, 5);
1023    }
1024
1025    #[test]
1026    fn measure_multiline_text() {
1027        let para = Paragraph::new(Text::raw("Line1\nLine22\nL3"));
1028        let constraints = para.measure(Size::MAX);
1029
1030        // Max width is "Line22" = 6, height = 3 lines
1031        assert_eq!(constraints.preferred, Size::new(6, 3));
1032        assert_eq!(constraints.min.height, 1);
1033        // Min width is longest word = "Line22" = 6
1034        assert_eq!(constraints.min.width, 6);
1035    }
1036
1037    #[test]
1038    fn measure_with_block() {
1039        let block = crate::block::Block::bordered();
1040        let para = Paragraph::new(Text::raw("Hi")).block(block);
1041        let constraints = para.measure(Size::MAX);
1042
1043        // "Hi" = 2 wide, 1 tall, plus chrome (borders + padding) = 4 on each axis.
1044        assert_eq!(constraints.preferred, Size::new(6, 5));
1045        assert_eq!(constraints.min.width, 6);
1046        assert_eq!(constraints.min.height, 5);
1047    }
1048
1049    #[test]
1050    fn measure_with_word_wrap() {
1051        let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1052        // Measure with narrow available width
1053        let constraints = para.measure(Size::new(6, 10));
1054
1055        // With 6 chars available, "hello" fits, "world" wraps
1056        // Preferred width = 6 (available), height = 2 lines
1057        assert_eq!(constraints.preferred.height, 2);
1058        // Min width is longest word = "hello" = 5
1059        assert_eq!(constraints.min.width, 5);
1060    }
1061
1062    #[test]
1063    fn measure_empty_text() {
1064        let para = Paragraph::new(Text::raw(""));
1065        let constraints = para.measure(Size::MAX);
1066
1067        // Empty text: 0 width, 0 height (no lines)
1068        assert_eq!(constraints.preferred.width, 0);
1069        assert_eq!(constraints.preferred.height, 0);
1070        // Min height is 0 for empty text (no content to display)
1071        // This ensures min <= preferred invariant holds
1072        assert_eq!(constraints.min.height, 0);
1073    }
1074
1075    #[test]
1076    fn calculate_min_width_single_long_word() {
1077        let para = Paragraph::new(Text::raw("supercalifragilistic"));
1078        assert_eq!(para.calculate_min_width(), 20);
1079    }
1080
1081    #[test]
1082    fn calculate_min_width_multiple_words() {
1083        let para = Paragraph::new(Text::raw("the quick brown fox"));
1084        // Longest word is "quick" or "brown" = 5
1085        assert_eq!(para.calculate_min_width(), 5);
1086    }
1087
1088    #[test]
1089    fn calculate_min_width_multiline() {
1090        let para = Paragraph::new(Text::raw("short\nlongword\na"));
1091        // Longest word is "longword" = 8
1092        assert_eq!(para.calculate_min_width(), 8);
1093    }
1094
1095    #[test]
1096    fn estimate_wrapped_height_no_wrap_needed() {
1097        let para = Paragraph::new(Text::raw("short")).wrap(WrapMode::Word);
1098        // Width 10 is enough for "short" (5 chars)
1099        assert_eq!(para.estimate_wrapped_height(10), 1);
1100    }
1101
1102    #[test]
1103    fn estimate_wrapped_height_needs_wrap() {
1104        let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1105        // Width 6: "hello " fits (6 chars), "world" (5 chars) wraps
1106        assert_eq!(para.estimate_wrapped_height(6), 2);
1107    }
1108
1109    #[test]
1110    fn has_intrinsic_size() {
1111        let para = Paragraph::new(Text::raw("test"));
1112        assert!(para.has_intrinsic_size());
1113    }
1114
1115    #[test]
1116    fn measure_is_pure() {
1117        let para = Paragraph::new(Text::raw("Hello World"));
1118        let a = para.measure(Size::new(100, 50));
1119        let b = para.measure(Size::new(100, 50));
1120        assert_eq!(a, b);
1121    }
1122
1123    #[test]
1124    fn accessibility_truncates_long_unicode_without_panicking() {
1125        use ftui_a11y::Accessible;
1126
1127        let para = Paragraph::new(Text::raw("界".repeat(210)));
1128        let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1129        let name = nodes[0]
1130            .name
1131            .as_deref()
1132            .expect("paragraph should have a name");
1133
1134        assert!(name.ends_with("..."));
1135        assert_eq!(name.chars().count(), 200);
1136    }
1137
1138    #[test]
1139    fn accessibility_truncates_description_when_block_title_present() {
1140        use ftui_a11y::Accessible;
1141
1142        let para =
1143            Paragraph::new(Text::raw("界".repeat(210))).block(Block::bordered().title("Body"));
1144        let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1145        let node = &nodes[0];
1146
1147        assert_eq!(node.name.as_deref(), Some("Body"));
1148        let description = node
1149            .description
1150            .as_deref()
1151            .expect("paragraph should have a description");
1152        assert!(description.ends_with("..."));
1153        assert_eq!(description.chars().count(), 200);
1154    }
1155
1156    #[test]
1157    fn accessibility_preserves_exactly_200_chars_without_ellipsis() {
1158        use ftui_a11y::Accessible;
1159
1160        let para = Paragraph::new(Text::raw("界".repeat(200)));
1161        let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1162        let name = nodes[0]
1163            .name
1164            .as_deref()
1165            .expect("paragraph should have a name");
1166
1167        assert!(!name.ends_with("..."));
1168        assert_eq!(name.chars().count(), 200);
1169    }
1170
1171    #[test]
1172    fn accessibility_truncates_on_grapheme_boundaries() {
1173        use ftui_a11y::Accessible;
1174
1175        let para = Paragraph::new(Text::raw("e\u{301}".repeat(210)));
1176        let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1177        let name = nodes[0]
1178            .name
1179            .as_deref()
1180            .expect("paragraph should have a name");
1181
1182        let prefix = name
1183            .strip_suffix("...")
1184            .expect("paragraph should be truncated");
1185        assert!(name.chars().count() <= 200);
1186        assert_eq!(ftui_text::graphemes(prefix).count(), 98);
1187        assert!(prefix.ends_with("e\u{301}"));
1188    }
1189}