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#[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 #[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 #[must_use]
159 pub fn from_static_text(text: FtuiText<'static>) -> Self {
160 Self::with_static_text(text)
161 }
162
163 #[must_use]
165 pub fn from_static_str(text: &'static str) -> Self {
166 Self::from_static_text(FtuiText::raw(text))
167 }
168
169 #[must_use]
171 pub fn block(mut self, block: Block<'a>) -> Self {
172 self.block = Some(block);
173 self
174 }
175
176 #[must_use]
178 pub fn style(mut self, style: Style) -> Self {
179 self.style = style;
180 self
181 }
182
183 #[must_use]
185 pub fn wrap(mut self, wrap: WrapMode) -> Self {
186 self.wrap = Some(wrap);
187 self
188 }
189
190 #[must_use]
192 pub fn alignment(mut self, alignment: Alignment) -> Self {
193 self.alignment = alignment;
194 self
195 }
196
197 #[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 if frame.a11y_enabled() {
294 frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
295 }
296 #[cfg(feature = "tracing")]
297 let _span = tracing::debug_span!(
298 "widget_render",
299 widget = "Paragraph",
300 x = area.x,
301 y = area.y,
302 w = area.width,
303 h = area.height
304 )
305 .entered();
306
307 let deg = frame.buffer.degradation;
308
309 if !deg.render_content() {
311 clear_text_area(frame, area, Style::default());
312 return;
313 }
314
315 let style = if deg.apply_styling() {
319 self.style
320 } else {
321 Style::default()
322 };
323 if self.block.is_none() && self.text.is_empty() {
324 clear_text_area(frame, area, style);
325 return;
326 }
327
328 clear_text_area(frame, area, style);
329
330 let text_area = match self.block {
331 Some(ref b) => {
332 b.render(area, frame);
333 b.inner(area)
334 }
335 None => area,
336 };
337
338 if text_area.is_empty() {
339 return;
340 }
341
342 let mut text_style = style;
347 text_style.bg = None;
348
349 let mut y = text_area.y;
350 let mut current_visual_line = 0;
351 let scroll_offset = self.scroll.0 as usize;
352
353 let mut render_line = |line: &ftui_text::Line, line_width: usize, y: u16| {
354 let scroll_x = self.scroll.1;
355 let start_x = align_x(text_area, line_width, self.alignment);
356
357 let mut span_visual_offset = 0;
360
361 let alignment_offset = start_x.saturating_sub(text_area.x);
363
364 for span in line.spans() {
365 let span_width = span.width();
366
367 let line_rel_start = alignment_offset.saturating_add(span_visual_offset);
370
371 if line_rel_start.saturating_add(span_width as u16) <= scroll_x {
373 span_visual_offset = span_visual_offset.saturating_add(span_width as u16);
375 continue;
376 }
377
378 let (draw_x, local_scroll) = if line_rel_start < scroll_x {
380 (text_area.x, scroll_x - line_rel_start)
382 } else {
383 (text_area.x.saturating_add(line_rel_start - scroll_x), 0)
385 };
386
387 if draw_x >= text_area.right() {
388 break;
390 }
391
392 let span_style = if deg.apply_styling() {
394 match span.style {
395 Some(s) => s.merge(&text_style),
396 None => text_style,
397 }
398 } else {
399 text_style };
401
402 if local_scroll > 0 {
403 draw_text_span_scrolled(
404 frame,
405 draw_x,
406 y,
407 span.content.as_ref(),
408 span_style,
409 text_area.right(),
410 local_scroll,
411 span.link.as_deref(),
412 );
413 } else {
414 draw_text_span_with_link(
415 frame,
416 draw_x,
417 y,
418 span.content.as_ref(),
419 span_style,
420 text_area.right(),
421 span.link.as_deref(),
422 );
423 }
424
425 span_visual_offset = span_visual_offset.saturating_add(span_width as u16);
426 }
427 };
428
429 let metrics = self.cached_metrics();
430 let rendered_lines: Option<CachedWrappedParagraph> = self
431 .wrap
432 .map(|wrap_mode| self.cached_wrapped_lines(text_area.width as usize, wrap_mode));
433
434 if let Some(wrapped) = rendered_lines {
435 for (line, line_width) in wrapped.lines.iter().zip(wrapped.line_widths.iter()) {
436 if current_visual_line < scroll_offset {
437 current_visual_line += 1;
438 continue;
439 }
440 if y >= text_area.bottom() {
441 break;
442 }
443 render_line(line, *line_width, y);
444 y = y.saturating_add(1);
445 current_visual_line += 1;
446 }
447 } else {
448 for (line, line_width) in self.text.lines().iter().zip(metrics.line_widths.iter()) {
449 if current_visual_line < scroll_offset {
450 current_visual_line += 1;
451 continue;
452 }
453 if y >= text_area.bottom() {
454 break;
455 }
456 render_line(line, *line_width, y);
457 y = y.saturating_add(1);
458 current_visual_line += 1;
459 }
460 }
461 }
462}
463impl MeasurableWidget for Paragraph<'_> {
464 fn measure(&self, available: Size) -> SizeConstraints {
465 let metrics = self.cached_metrics();
466 let text_width = metrics.text_width;
467 let text_height = metrics.text_height;
468 let min_width = metrics.min_width;
469
470 let (chrome_width, chrome_height) = self
472 .block
473 .as_ref()
474 .map(|b| b.chrome_size())
475 .unwrap_or((0, 0));
476
477 let (preferred_width, preferred_height) =
479 if self.wrap.is_some_and(|mode| mode != WrapMode::None) {
480 let wrap_width = if available.width > chrome_width {
482 (available.width - chrome_width) as usize
483 } else {
484 1
485 };
486
487 let wrapped_height = self
488 .wrap
489 .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
490 .unwrap_or(text_height);
491
492 let pref_w = text_width.min(wrap_width);
494 (pref_w, wrapped_height)
495 } else {
496 (text_width, text_height)
498 };
499
500 let min_w = (min_width as u16).saturating_add(chrome_width);
502 let min_h = if preferred_height > 0 {
504 (1u16).saturating_add(chrome_height)
505 } else {
506 chrome_height
507 };
508
509 let pref_w = (preferred_width as u16).saturating_add(chrome_width);
510 let pref_h = (preferred_height as u16).saturating_add(chrome_height);
511
512 SizeConstraints {
513 min: Size::new(min_w, min_h),
514 preferred: Size::new(pref_w, pref_h),
515 max: None, }
517 }
518
519 fn has_intrinsic_size(&self) -> bool {
520 true
522 }
523}
524
525impl Paragraph<'_> {
526 #[cfg_attr(not(test), allow(dead_code))]
527 fn calculate_min_width(&self) -> usize {
528 self.cached_metrics().min_width
529 }
530
531 #[cfg_attr(not(test), allow(dead_code))]
532 fn estimate_wrapped_height(&self, wrap_width: usize) -> usize {
533 if wrap_width == 0 {
534 return self.cached_metrics().text_height;
535 }
536
537 self.wrap
538 .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
539 .unwrap_or_else(|| self.cached_metrics().text_height)
540 .max(1)
541 }
542}
543
544fn align_x(area: Rect, line_width: usize, alignment: Alignment) -> u16 {
546 let line_width_u16 = u16::try_from(line_width).unwrap_or(u16::MAX);
547 match alignment {
548 Alignment::Left => area.x,
549 Alignment::Center => area
550 .x
551 .saturating_add(area.width.saturating_sub(line_width_u16) / 2),
552 Alignment::Right => area
553 .x
554 .saturating_add(area.width.saturating_sub(line_width_u16)),
555 }
556}
557
558fn truncate_accessible_text(text: &str) -> String {
559 const ACCESSIBLE_TEXT_LIMIT: usize = 200;
560 const ACCESSIBLE_TEXT_PREFIX_LIMIT: usize = 197;
561
562 if text.chars().count() <= ACCESSIBLE_TEXT_LIMIT {
563 text.to_owned()
564 } else {
565 let mut prefix = String::new();
566 let mut prefix_chars = 0usize;
567
568 for grapheme in graphemes(text) {
569 let grapheme_chars = grapheme.chars().count();
570 if prefix_chars + grapheme_chars > ACCESSIBLE_TEXT_PREFIX_LIMIT {
571 break;
572 }
573 prefix.push_str(grapheme);
574 prefix_chars += grapheme_chars;
575 }
576
577 format!("{prefix}...")
578 }
579}
580
581impl ftui_a11y::Accessible for Paragraph<'_> {
586 fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
587 use ftui_a11y::node::{A11yNodeInfo, A11yRole};
588
589 let id = crate::a11y_node_id(area);
590
591 let name: String = self
593 .text
594 .lines()
595 .iter()
596 .map(|line| {
597 line.spans()
598 .iter()
599 .map(|span| span.content.as_ref())
600 .collect::<Vec<_>>()
601 .join("")
602 })
603 .collect::<Vec<_>>()
604 .join(" ");
605
606 let block_title = self.block.as_ref().and_then(|b| b.title_text());
607 let truncated_name = truncate_accessible_text(&name);
608
609 let mut node = A11yNodeInfo::new(id, A11yRole::Label, area);
610 if let Some(title) = block_title {
611 node = node.with_name(title);
612 if !name.is_empty() {
613 node = node.with_description(truncated_name);
614 }
615 } else if !name.is_empty() {
616 node = node.with_name(truncated_name);
617 }
618
619 vec![node]
620 }
621}
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626 use ftui_render::grapheme_pool::GraphemePool;
627
628 fn raw_row_text(frame: &Frame, y: u16) -> String {
629 let width = frame.buffer.width();
630 let mut actual = String::new();
631 for x in 0..width {
632 let ch = frame
633 .buffer
634 .get(x, y)
635 .and_then(|cell| cell.content.as_char())
636 .unwrap_or(' ');
637 actual.push(ch);
638 }
639 actual
640 }
641
642 #[test]
643 fn render_simple_text() {
644 let para = Paragraph::new(Text::raw("Hello"));
645 let area = Rect::new(0, 0, 10, 1);
646 let mut pool = GraphemePool::new();
647 let mut frame = Frame::new(10, 1, &mut pool);
648 para.render(area, &mut frame);
649
650 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
651 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('o'));
652 }
653
654 #[test]
655 fn from_static_str_preserves_rendering_without_owning_static_spans() {
656 let area = Rect::new(0, 0, 8, 2);
657
658 let fast = Paragraph::from_static_str("Hi\nthere").style(Style::new().bold());
659 let slow = Paragraph::new("Hi\nthere").style(Style::new().bold());
660
661 let mut fast_pool = GraphemePool::new();
662 let mut fast_frame = Frame::new(8, 2, &mut fast_pool);
663 fast.render(area, &mut fast_frame);
664
665 let mut slow_pool = GraphemePool::new();
666 let mut slow_frame = Frame::new(8, 2, &mut slow_pool);
667 slow.render(area, &mut slow_frame);
668
669 assert_eq!(raw_row_text(&fast_frame, 0), raw_row_text(&slow_frame, 0));
670 assert_eq!(raw_row_text(&fast_frame, 1), raw_row_text(&slow_frame, 1));
671
672 let first_span = &fast.text.lines()[0].spans()[0];
673 match &first_span.content {
674 std::borrow::Cow::Borrowed(text) => assert_eq!(*text, "Hi"),
675 std::borrow::Cow::Owned(_) => panic!("static paragraph text should stay borrowed"),
676 }
677 }
678
679 #[test]
680 fn render_multiline_text() {
681 let para = Paragraph::new(Text::raw("AB\nCD"));
682 let area = Rect::new(0, 0, 5, 3);
683 let mut pool = GraphemePool::new();
684 let mut frame = Frame::new(5, 3, &mut pool);
685 para.render(area, &mut frame);
686
687 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
688 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
689 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('C'));
690 assert_eq!(frame.buffer.get(1, 1).unwrap().content.as_char(), Some('D'));
691 }
692
693 #[test]
694 fn render_centered_text() {
695 let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Center);
696 let area = Rect::new(0, 0, 10, 1);
697 let mut pool = GraphemePool::new();
698 let mut frame = Frame::new(10, 1, &mut pool);
699 para.render(area, &mut frame);
700
701 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('H'));
703 assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('i'));
704 }
705
706 #[test]
707 fn render_with_scroll() {
708 let para = Paragraph::new(Text::raw("Line1\nLine2\nLine3")).scroll((1, 0));
709 let area = Rect::new(0, 0, 10, 2);
710 let mut pool = GraphemePool::new();
711 let mut frame = Frame::new(10, 2, &mut pool);
712 para.render(area, &mut frame);
713
714 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('L'));
716 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('2'));
717 }
718
719 #[test]
720 fn render_empty_area() {
721 let para = Paragraph::new(Text::raw("Hello"));
722 let area = Rect::new(0, 0, 0, 0);
723 let mut pool = GraphemePool::new();
724 let mut frame = Frame::new(1, 1, &mut pool);
725 para.render(area, &mut frame);
726 }
727
728 #[test]
729 fn line_min_width_tracks_words_across_spans() {
730 let line = Line::from_spans([
731 Span::raw("alpha"),
732 Span::styled(" ", Style::new().bold()),
733 Span::raw("beta"),
734 Span::raw(" "),
735 Span::raw("gamma"),
736 ]);
737
738 assert_eq!(line_min_width(&line), 5);
739 }
740
741 #[test]
742 fn measure_wrap_counts_cached_visual_lines() {
743 let para = Paragraph::new(Text::raw("hello world from cache")).wrap(WrapMode::Word);
744 let constraints = para.measure(Size::new(8, 10));
745
746 assert_eq!(constraints.preferred.height, 4);
747 assert_eq!(constraints.min.width, 5);
748 }
749
750 #[test]
751 fn measure_wrap_none_preserves_natural_width() {
752 let para = Paragraph::new(Text::raw("abcdef")).wrap(WrapMode::None);
753 let constraints = para.measure(Size::new(3, 10));
754
755 assert_eq!(constraints.preferred.width, 6);
756 assert_eq!(constraints.preferred.height, 1);
757 }
758
759 #[test]
760 fn render_empty_text_clears_content() {
761 let para = Paragraph::new("");
762 let area = Rect::new(0, 0, 3, 1);
763 let mut pool = GraphemePool::new();
764 let mut frame = Frame::new(3, 1, &mut pool);
765
766 frame
768 .buffer
769 .fill(area, ftui_render::cell::Cell::from_char('X'));
770
771 para.render(area, &mut frame);
772
773 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
774 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some(' '));
775 }
776
777 #[test]
778 fn render_right_aligned() {
779 let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Right);
780 let area = Rect::new(0, 0, 10, 1);
781 let mut pool = GraphemePool::new();
782 let mut frame = Frame::new(10, 1, &mut pool);
783 para.render(area, &mut frame);
784
785 assert_eq!(frame.buffer.get(8, 0).unwrap().content.as_char(), Some('H'));
787 assert_eq!(frame.buffer.get(9, 0).unwrap().content.as_char(), Some('i'));
788 }
789
790 #[test]
791 fn render_with_word_wrap() {
792 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
793 let area = Rect::new(0, 0, 6, 3);
794 let mut pool = GraphemePool::new();
795 let mut frame = Frame::new(6, 3, &mut pool);
796 para.render(area, &mut frame);
797
798 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('h'));
800 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('w'));
801 }
802
803 #[test]
804 fn render_with_char_wrap() {
805 let para = Paragraph::new(Text::raw("abcdefgh")).wrap(WrapMode::Char);
806 let area = Rect::new(0, 0, 4, 3);
807 let mut pool = GraphemePool::new();
808 let mut frame = Frame::new(4, 3, &mut pool);
809 para.render(area, &mut frame);
810
811 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
813 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some('d'));
814 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
816 }
817
818 #[test]
819 fn scroll_past_all_lines() {
820 let para = Paragraph::new(Text::raw("AB")).scroll((5, 0));
821 let area = Rect::new(0, 0, 5, 2);
822 let mut pool = GraphemePool::new();
823 let mut frame = Frame::new(5, 2, &mut pool);
824 para.render(area, &mut frame);
825
826 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
828 }
829
830 #[test]
831 fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
832 let area = Rect::new(0, 0, 8, 2);
833 let mut pool = GraphemePool::new();
834 let mut frame = Frame::new(8, 2, &mut pool);
835
836 Paragraph::new(Text::raw("Hello\nWorld")).render(area, &mut frame);
837 Paragraph::new(Text::raw("Hi")).render(area, &mut frame);
838
839 assert_eq!(raw_row_text(&frame, 0), "Hi ");
840 assert_eq!(raw_row_text(&frame, 1), " ");
841 }
842
843 #[test]
844 fn render_clipped_at_area_height() {
845 let para = Paragraph::new(Text::raw("A\nB\nC\nD\nE"));
846 let area = Rect::new(0, 0, 5, 2);
847 let mut pool = GraphemePool::new();
848 let mut frame = Frame::new(5, 2, &mut pool);
849 para.render(area, &mut frame);
850
851 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
853 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('B'));
854 }
855
856 #[test]
857 fn render_clipped_at_area_width() {
858 let para = Paragraph::new(Text::raw("ABCDEF"));
859 let area = Rect::new(0, 0, 3, 1);
860 let mut pool = GraphemePool::new();
861 let mut frame = Frame::new(3, 1, &mut pool);
862 para.render(area, &mut frame);
863
864 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
865 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
866 }
867
868 #[test]
869 fn align_x_left() {
870 let area = Rect::new(5, 0, 20, 1);
871 assert_eq!(align_x(area, 10, Alignment::Left), 5);
872 }
873
874 #[test]
875 fn align_x_center() {
876 let area = Rect::new(0, 0, 20, 1);
877 assert_eq!(align_x(area, 6, Alignment::Center), 7);
879 }
880
881 #[test]
882 fn align_x_right() {
883 let area = Rect::new(0, 0, 20, 1);
884 assert_eq!(align_x(area, 5, Alignment::Right), 15);
886 }
887
888 #[test]
889 fn align_x_wide_line_saturates() {
890 let area = Rect::new(0, 0, 10, 1);
891 assert_eq!(align_x(area, 20, Alignment::Right), 0);
893 assert_eq!(align_x(area, 20, Alignment::Center), 0);
894 }
895
896 #[test]
897 fn builder_methods_chain() {
898 let para = Paragraph::new(Text::raw("test"))
899 .style(Style::default())
900 .wrap(WrapMode::Word)
901 .alignment(Alignment::Center)
902 .scroll((1, 2));
903 let area = Rect::new(0, 0, 10, 5);
905 let mut pool = GraphemePool::new();
906 let mut frame = Frame::new(10, 5, &mut pool);
907 para.render(area, &mut frame);
908 }
909
910 #[test]
911 fn render_at_offset_area() {
912 let para = Paragraph::new(Text::raw("X"));
913 let area = Rect::new(3, 4, 5, 2);
914 let mut pool = GraphemePool::new();
915 let mut frame = Frame::new(10, 10, &mut pool);
916 para.render(area, &mut frame);
917
918 assert_eq!(frame.buffer.get(3, 4).unwrap().content.as_char(), Some('X'));
919 assert!(frame.buffer.get(0, 0).unwrap().is_empty());
921 }
922
923 #[test]
924 fn wrap_clipped_at_area_bottom() {
925 let para = Paragraph::new(Text::raw("abcdefghijklmnop")).wrap(WrapMode::Char);
927 let area = Rect::new(0, 0, 4, 2);
928 let mut pool = GraphemePool::new();
929 let mut frame = Frame::new(4, 2, &mut pool);
930 para.render(area, &mut frame);
931
932 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
934 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
935 }
936
937 #[test]
940 fn degradation_skeleton_skips_content() {
941 use ftui_render::budget::DegradationLevel;
942
943 let para = Paragraph::new(Text::raw("Hello"));
944 let area = Rect::new(0, 0, 10, 1);
945 let mut pool = GraphemePool::new();
946 let mut frame = Frame::new(10, 1, &mut pool);
947 Paragraph::new(Text::raw("Stale")).render(area, &mut frame);
948 frame.set_degradation(DegradationLevel::Skeleton);
949 para.render(area, &mut frame);
950
951 assert_eq!(raw_row_text(&frame, 0), " ");
953 }
954
955 #[test]
956 fn degradation_full_renders_content() {
957 use ftui_render::budget::DegradationLevel;
958
959 let para = Paragraph::new(Text::raw("Hello"));
960 let area = Rect::new(0, 0, 10, 1);
961 let mut pool = GraphemePool::new();
962 let mut frame = Frame::new(10, 1, &mut pool);
963 frame.set_degradation(DegradationLevel::Full);
964 para.render(area, &mut frame);
965
966 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
967 }
968
969 #[test]
970 fn degradation_essential_only_still_renders_text() {
971 use ftui_render::budget::DegradationLevel;
972
973 let para = Paragraph::new(Text::raw("Hello"));
974 let area = Rect::new(0, 0, 10, 1);
975 let mut pool = GraphemePool::new();
976 let mut frame = Frame::new(10, 1, &mut pool);
977 frame.set_degradation(DegradationLevel::EssentialOnly);
978 para.render(area, &mut frame);
979
980 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
982 }
983
984 #[test]
985 fn degradation_no_styling_ignores_span_styles() {
986 use ftui_render::budget::DegradationLevel;
987 use ftui_render::cell::PackedRgba;
988 use ftui_text::{Line, Span};
989
990 let styled_span = Span::styled("Hello", Style::new().fg(PackedRgba::RED));
992 let line = Line::from_spans([styled_span]);
993 let text = Text::from(line);
994 let para = Paragraph::new(text);
995 let area = Rect::new(0, 0, 10, 1);
996 let mut pool = GraphemePool::new();
997 let mut frame = Frame::new(10, 1, &mut pool);
998 frame.set_degradation(DegradationLevel::NoStyling);
999 para.render(area, &mut frame);
1000
1001 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1003 assert_ne!(
1005 frame.buffer.get(0, 0).unwrap().fg,
1006 PackedRgba::RED,
1007 "Span fg color should be ignored at NoStyling"
1008 );
1009 }
1010
1011 use crate::MeasurableWidget;
1014 use ftui_core::geometry::Size;
1015
1016 #[test]
1017 fn measure_simple_text() {
1018 let para = Paragraph::new(Text::raw("Hello"));
1019 let constraints = para.measure(Size::MAX);
1020
1021 assert_eq!(constraints.preferred, Size::new(5, 1));
1023 assert_eq!(constraints.min.height, 1);
1024 assert_eq!(constraints.min.width, 5);
1026 }
1027
1028 #[test]
1029 fn measure_multiline_text() {
1030 let para = Paragraph::new(Text::raw("Line1\nLine22\nL3"));
1031 let constraints = para.measure(Size::MAX);
1032
1033 assert_eq!(constraints.preferred, Size::new(6, 3));
1035 assert_eq!(constraints.min.height, 1);
1036 assert_eq!(constraints.min.width, 6);
1038 }
1039
1040 #[test]
1041 fn measure_with_block() {
1042 let block = crate::block::Block::bordered();
1043 let para = Paragraph::new(Text::raw("Hi")).block(block);
1044 let constraints = para.measure(Size::MAX);
1045
1046 assert_eq!(constraints.preferred, Size::new(6, 5));
1048 assert_eq!(constraints.min.width, 6);
1049 assert_eq!(constraints.min.height, 5);
1050 }
1051
1052 #[test]
1053 fn measure_with_word_wrap() {
1054 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1055 let constraints = para.measure(Size::new(6, 10));
1057
1058 assert_eq!(constraints.preferred.height, 2);
1061 assert_eq!(constraints.min.width, 5);
1063 }
1064
1065 #[test]
1066 fn measure_empty_text() {
1067 let para = Paragraph::new(Text::raw(""));
1068 let constraints = para.measure(Size::MAX);
1069
1070 assert_eq!(constraints.preferred.width, 0);
1072 assert_eq!(constraints.preferred.height, 0);
1073 assert_eq!(constraints.min.height, 0);
1076 }
1077
1078 #[test]
1079 fn calculate_min_width_single_long_word() {
1080 let para = Paragraph::new(Text::raw("supercalifragilistic"));
1081 assert_eq!(para.calculate_min_width(), 20);
1082 }
1083
1084 #[test]
1085 fn calculate_min_width_multiple_words() {
1086 let para = Paragraph::new(Text::raw("the quick brown fox"));
1087 assert_eq!(para.calculate_min_width(), 5);
1089 }
1090
1091 #[test]
1092 fn calculate_min_width_multiline() {
1093 let para = Paragraph::new(Text::raw("short\nlongword\na"));
1094 assert_eq!(para.calculate_min_width(), 8);
1096 }
1097
1098 #[test]
1099 fn estimate_wrapped_height_no_wrap_needed() {
1100 let para = Paragraph::new(Text::raw("short")).wrap(WrapMode::Word);
1101 assert_eq!(para.estimate_wrapped_height(10), 1);
1103 }
1104
1105 #[test]
1106 fn estimate_wrapped_height_needs_wrap() {
1107 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1108 assert_eq!(para.estimate_wrapped_height(6), 2);
1110 }
1111
1112 #[test]
1113 fn has_intrinsic_size() {
1114 let para = Paragraph::new(Text::raw("test"));
1115 assert!(para.has_intrinsic_size());
1116 }
1117
1118 #[test]
1119 fn measure_is_pure() {
1120 let para = Paragraph::new(Text::raw("Hello World"));
1121 let a = para.measure(Size::new(100, 50));
1122 let b = para.measure(Size::new(100, 50));
1123 assert_eq!(a, b);
1124 }
1125
1126 #[test]
1127 fn accessibility_truncates_long_unicode_without_panicking() {
1128 use ftui_a11y::Accessible;
1129
1130 let para = Paragraph::new(Text::raw("界".repeat(210)));
1131 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1132 let name = nodes[0]
1133 .name
1134 .as_deref()
1135 .expect("paragraph should have a name");
1136
1137 assert!(name.ends_with("..."));
1138 assert_eq!(name.chars().count(), 200);
1139 }
1140
1141 #[test]
1142 fn accessibility_truncates_description_when_block_title_present() {
1143 use ftui_a11y::Accessible;
1144
1145 let para =
1146 Paragraph::new(Text::raw("界".repeat(210))).block(Block::bordered().title("Body"));
1147 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1148 let node = &nodes[0];
1149
1150 assert_eq!(node.name.as_deref(), Some("Body"));
1151 let description = node
1152 .description
1153 .as_deref()
1154 .expect("paragraph should have a description");
1155 assert!(description.ends_with("..."));
1156 assert_eq!(description.chars().count(), 200);
1157 }
1158
1159 #[test]
1160 fn accessibility_preserves_exactly_200_chars_without_ellipsis() {
1161 use ftui_a11y::Accessible;
1162
1163 let para = Paragraph::new(Text::raw("界".repeat(200)));
1164 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1165 let name = nodes[0]
1166 .name
1167 .as_deref()
1168 .expect("paragraph should have a name");
1169
1170 assert!(!name.ends_with("..."));
1171 assert_eq!(name.chars().count(), 200);
1172 }
1173
1174 #[test]
1175 fn accessibility_truncates_on_grapheme_boundaries() {
1176 use ftui_a11y::Accessible;
1177
1178 let para = Paragraph::new(Text::raw("e\u{301}".repeat(210)));
1179 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1180 let name = nodes[0]
1181 .name
1182 .as_deref()
1183 .expect("paragraph should have a name");
1184
1185 let prefix = name
1186 .strip_suffix("...")
1187 .expect("paragraph should be truncated");
1188 assert!(name.chars().count() <= 200);
1189 assert_eq!(ftui_text::graphemes(prefix).count(), 98);
1190 assert!(prefix.ends_with("e\u{301}"));
1191 }
1192}