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,
28 widest_grapheme: usize,
31 min_width_computed: bool,
32 line_widths: Arc<[usize]>,
33}
34
35#[derive(Debug, Clone)]
36struct CachedWrappedParagraph {
37 lines: Arc<[Line<'static>]>,
38 line_widths: Arc<[usize]>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42struct ParagraphWrapCacheKey {
43 text_hash: u64,
44 wrap_mode: WrapMode,
45 width: usize,
46}
47
48#[derive(Debug, Default)]
49struct ParagraphCacheState {
50 metrics: AHashMap<u64, CachedParagraphMetrics>,
51 metrics_fifo: VecDeque<u64>,
52 wrapped: AHashMap<ParagraphWrapCacheKey, CachedWrappedParagraph>,
53 wrapped_fifo: VecDeque<ParagraphWrapCacheKey>,
54}
55
56impl ParagraphCacheState {
57 fn insert_metrics(&mut self, key: u64, value: CachedParagraphMetrics) {
58 cache_insert(
59 &mut self.metrics,
60 &mut self.metrics_fifo,
61 PARAGRAPH_METRICS_CACHE_CAPACITY,
62 key,
63 value,
64 );
65 }
66
67 fn insert_wrapped(&mut self, key: ParagraphWrapCacheKey, value: CachedWrappedParagraph) {
68 cache_insert(
69 &mut self.wrapped,
70 &mut self.wrapped_fifo,
71 PARAGRAPH_WRAP_CACHE_CAPACITY,
72 key,
73 value,
74 );
75 }
76}
77
78thread_local! {
79 static PARAGRAPH_CACHE: RefCell<ParagraphCacheState> = RefCell::new(ParagraphCacheState::default());
80}
81
82fn cache_insert<K, V>(
83 map: &mut AHashMap<K, V>,
84 fifo: &mut VecDeque<K>,
85 capacity: usize,
86 key: K,
87 value: V,
88) where
89 K: Copy + Eq + Hash,
90{
91 if !map.contains_key(&key) {
92 if map.len() >= capacity
93 && let Some(oldest) = fifo.pop_front()
94 {
95 map.remove(&oldest);
96 }
97 fifo.push_back(key);
98 }
99 map.insert(key, value);
100}
101
102fn text_into_owned(text: FtuiText<'_>) -> FtuiText<'static> {
103 FtuiText::from_lines(
104 text.into_iter()
105 .map(|line| Line::from_spans(line.into_iter().map(Span::into_owned))),
106 )
107}
108
109#[derive(Debug, Clone, Default)]
111pub struct Paragraph<'a> {
112 text: Text,
113 block: Option<Block<'a>>,
114 style: Style,
115 wrap: Option<WrapMode>,
116 alignment: Option<Alignment>,
117 scroll: (u16, u16),
118}
119
120fn hash_value<T: Hash>(value: &T) -> u64 {
121 let mut hasher = DefaultHasher::new();
122 value.hash(&mut hasher);
123 hasher.finish()
124}
125
126fn line_min_width(line: &Line<'_>) -> usize {
127 let mut max_word_width = 0;
128 let mut current_word_width = 0;
129
130 for span in line.spans() {
131 for grapheme in graphemes(span.content.as_ref()) {
132 let grapheme_width = display_width(grapheme);
133 if grapheme.chars().all(char::is_whitespace) {
134 max_word_width = max_word_width.max(current_word_width);
135 current_word_width = 0;
136 } else {
137 current_word_width += grapheme_width;
138 }
139 }
140 }
141
142 max_word_width.max(current_word_width)
143}
144
145fn line_widest_grapheme(line: &Line<'_>) -> usize {
146 line.spans()
147 .iter()
148 .flat_map(|span| graphemes(span.content.as_ref()))
149 .filter(|grapheme| !grapheme.chars().all(char::is_whitespace))
150 .map(display_width)
151 .max()
152 .unwrap_or(0)
153}
154
155impl<'a> Paragraph<'a> {
156 fn with_static_text(text: FtuiText<'static>) -> Self {
157 Self {
158 text,
159 block: None,
160 style: Style::default(),
161 wrap: None,
162 alignment: None,
163 scroll: (0, 0),
164 }
165 }
166
167 #[must_use]
169 pub fn new<'t>(text: impl Into<FtuiText<'t>>) -> Self {
170 Self::with_static_text(text_into_owned(text.into()))
171 }
172
173 #[must_use]
175 pub fn from_static_text(text: FtuiText<'static>) -> Self {
176 Self::with_static_text(text)
177 }
178
179 #[must_use]
181 pub fn from_static_str(text: &'static str) -> Self {
182 Self::from_static_text(FtuiText::raw(text))
183 }
184
185 #[must_use]
187 pub fn block(mut self, block: Block<'a>) -> Self {
188 self.block = Some(block);
189 self
190 }
191
192 #[must_use]
194 pub fn style(mut self, style: Style) -> Self {
195 self.style = style;
196 self
197 }
198
199 #[must_use]
201 pub fn wrap(mut self, wrap: WrapMode) -> Self {
202 self.wrap = Some(wrap);
203 self
204 }
205
206 #[must_use]
208 pub fn alignment(mut self, alignment: Alignment) -> Self {
209 self.alignment = Some(alignment);
210 self
211 }
212
213 #[must_use]
215 pub fn scroll(mut self, offset: (u16, u16)) -> Self {
216 self.scroll = offset;
217 self
218 }
219
220 fn text_hash(&self) -> u64 {
221 hash_value(&self.text)
222 }
223
224 fn cached_metrics(&self, include_min_width: bool) -> CachedParagraphMetrics {
225 let text_hash = self.text_hash();
226 PARAGRAPH_CACHE.with(|cache| {
227 let mut cache = cache.borrow_mut();
228 if let Some(metrics) = cache.metrics.get_mut(&text_hash) {
229 if include_min_width && !metrics.min_width_computed {
232 let min_width = self
233 .text
234 .lines()
235 .iter()
236 .map(line_min_width)
237 .max()
238 .unwrap_or(0);
239 metrics.min_width = if min_width == 0 {
240 metrics.text_width
241 } else {
242 min_width
243 };
244 metrics.widest_grapheme = self
245 .text
246 .lines()
247 .iter()
248 .map(line_widest_grapheme)
249 .max()
250 .unwrap_or(0);
251 metrics.min_width_computed = true;
252 }
253 return metrics.clone();
254 }
255
256 let mut text_width = 0usize;
257 let mut min_width = 0usize;
258 let mut widest_grapheme = 0usize;
259 let mut line_widths = Vec::with_capacity(self.text.lines().len());
260
261 for line in self.text.lines() {
262 let width = line.width();
263 text_width = text_width.max(width);
264 if include_min_width {
265 min_width = min_width.max(line_min_width(line));
266 widest_grapheme = widest_grapheme.max(line_widest_grapheme(line));
267 }
268 line_widths.push(width);
269 }
270
271 let metrics = CachedParagraphMetrics {
272 text_width,
273 text_height: self.text.height(),
274 min_width: if min_width == 0 {
275 text_width
276 } else {
277 min_width
278 },
279 widest_grapheme,
280 min_width_computed: include_min_width,
281 line_widths: Arc::from(line_widths),
282 };
283
284 cache.insert_metrics(text_hash, metrics.clone());
285 metrics
286 })
287 }
288
289 fn cached_wrapped_lines(&self, width: usize, wrap_mode: WrapMode) -> CachedWrappedParagraph {
290 let key = ParagraphWrapCacheKey {
291 text_hash: self.text_hash(),
292 wrap_mode,
293 width,
294 };
295
296 PARAGRAPH_CACHE.with(|cache| {
297 let mut cache = cache.borrow_mut();
298 if let Some(wrapped) = cache.wrapped.get(&key) {
299 return wrapped.clone();
300 }
301
302 let mut lines = Vec::new();
303 let mut line_widths = Vec::new();
304
305 for line in self.text.lines() {
306 let line_width = line.width();
307 if wrap_mode == WrapMode::None || line_width <= width {
308 lines.push(line.clone());
309 line_widths.push(line_width);
310 continue;
311 }
312
313 let wrapped_lines = line.wrap(width, wrap_mode);
314 if wrapped_lines.is_empty() {
315 lines.push(Line::new());
316 line_widths.push(0);
317 continue;
318 }
319
320 for wrapped_line in wrapped_lines {
321 line_widths.push(wrapped_line.width());
322 lines.push(wrapped_line);
323 }
324 }
325
326 let wrapped = CachedWrappedParagraph {
327 lines: Arc::from(lines),
328 line_widths: Arc::from(line_widths),
329 };
330
331 cache.insert_wrapped(key, wrapped.clone());
332 wrapped
333 })
334 }
335}
336
337impl Widget for Paragraph<'_> {
338 fn render(&self, area: Rect, frame: &mut Frame) {
339 if frame.a11y_enabled() && !area.is_empty() {
344 frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
345 }
346 #[cfg(feature = "tracing")]
347 let _span = tracing::debug_span!(
348 "widget_render",
349 widget = "Paragraph",
350 x = area.x,
351 y = area.y,
352 w = area.width,
353 h = area.height
354 )
355 .entered();
356
357 let deg = frame.buffer.degradation;
358
359 if !deg.render_content() {
361 clear_text_area(frame, area, Style::default());
362 return;
363 }
364
365 let style = if deg.apply_styling() {
369 self.style
370 } else {
371 Style::default()
372 };
373 if self.block.is_none() && self.text.is_empty() {
374 clear_text_area(frame, area, style);
375 return;
376 }
377
378 clear_text_area(frame, area, style);
379
380 let text_area = match self.block {
381 Some(ref b) => {
382 crate::render_block_without_a11y(b, area, frame);
383 b.inner(area)
384 }
385 None => area,
386 };
387
388 if text_area.is_empty() {
389 return;
390 }
391
392 let mut text_style = style;
397 text_style.bg = None;
398
399 let mut y = text_area.y;
400 let mut current_visual_line = 0;
401 let scroll_offset = self.scroll.0 as usize;
402
403 let text_direction = frame.text_direction;
404 let effective_alignment = self.alignment.unwrap_or_else(|| {
405 if text_direction.is_rtl() {
406 Alignment::Right
407 } else {
408 Alignment::Left
409 }
410 });
411
412 let mut render_line = |line: &ftui_text::Line, line_width: usize, y: u16| {
413 let scroll_x = usize::from(self.scroll.1);
414 let start_x = align_x(text_area, line_width, effective_alignment);
415
416 let mut span_visual_offset: usize = 0;
418
419 let alignment_offset = usize::from(start_x.saturating_sub(text_area.x));
421 let visible_width = usize::from(text_area.right().saturating_sub(text_area.x));
422
423 for span in line.spans() {
424 let span_width = span.width();
425
426 let line_rel_start = alignment_offset.saturating_add(span_visual_offset);
429
430 if line_rel_start.saturating_add(span_width) <= scroll_x {
432 span_visual_offset = span_visual_offset.saturating_add(span_width);
434 continue;
435 }
436
437 let draw_offset = line_rel_start.saturating_sub(scroll_x);
438 if draw_offset >= visible_width {
439 break;
441 }
442
443 let draw_x = text_area.x
446 + u16::try_from(draw_offset).expect("visible paragraph offset fits u16");
447 let local_scroll = u16::try_from(scroll_x.saturating_sub(line_rel_start))
448 .expect("local paragraph scroll is bounded by u16 scroll");
449
450 let span_style = if deg.apply_styling() {
452 match span.style {
453 Some(s) => s.merge(&text_style),
454 None => text_style,
455 }
456 } else {
457 text_style };
459
460 if local_scroll > 0 {
461 draw_text_span_scrolled(
462 frame,
463 draw_x,
464 y,
465 span.content.as_ref(),
466 span_style,
467 text_area.right(),
468 local_scroll,
469 span.link.as_deref(),
470 );
471 } else {
472 draw_text_span_with_link(
473 frame,
474 draw_x,
475 y,
476 span.content.as_ref(),
477 span_style,
478 text_area.right(),
479 span.link.as_deref(),
480 );
481 }
482
483 span_visual_offset = span_visual_offset.saturating_add(span_width);
484 }
485 };
486
487 #[cfg(feature = "bidi")]
488 let para_dir = match text_direction {
489 ftui_render::TextDirection::Rtl => ftui_text::bidi::ParagraphDirection::Rtl,
490 ftui_render::TextDirection::Ltr => ftui_text::bidi::ParagraphDirection::Ltr,
491 };
492
493 let metrics = self.cached_metrics(false);
494 let rendered_lines: Option<CachedWrappedParagraph> = self
495 .wrap
496 .map(|wrap_mode| self.cached_wrapped_lines(text_area.width as usize, wrap_mode));
497
498 if let Some(wrapped) = rendered_lines {
499 for (line, _line_width) in wrapped.lines.iter().zip(wrapped.line_widths.iter()) {
500 if current_visual_line < scroll_offset {
501 current_visual_line += 1;
502 continue;
503 }
504 if y >= text_area.bottom() {
505 break;
506 }
507 #[cfg(feature = "bidi")]
508 {
509 let (reordered_line, reordered_width) = reorder_line_bidi(line, para_dir);
510 render_line(&reordered_line, reordered_width, y);
511 }
512 #[cfg(not(feature = "bidi"))]
513 render_line(line, *_line_width, y);
514
515 y = y.saturating_add(1);
516 current_visual_line += 1;
517 }
518 } else {
519 for (line, _line_width) in self.text.lines().iter().zip(metrics.line_widths.iter()) {
520 if current_visual_line < scroll_offset {
521 current_visual_line += 1;
522 continue;
523 }
524 if y >= text_area.bottom() {
525 break;
526 }
527 #[cfg(feature = "bidi")]
528 {
529 let (reordered_line, reordered_width) = reorder_line_bidi(line, para_dir);
530 render_line(&reordered_line, reordered_width, y);
531 }
532 #[cfg(not(feature = "bidi"))]
533 render_line(line, *_line_width, y);
534
535 y = y.saturating_add(1);
536 current_visual_line += 1;
537 }
538 }
539 }
540}
541
542#[cfg(feature = "bidi")]
543fn reorder_line_bidi(
544 line: &ftui_text::Line,
545 para_dir: ftui_text::bidi::ParagraphDirection,
546) -> (ftui_text::Line<'static>, usize) {
547 let full_text: String = line.spans().iter().map(|s| s.content.as_ref()).collect();
548 if full_text.is_empty() || !ftui_text::bidi::has_rtl(&full_text) {
549 let width = line.width();
550 let spans: Vec<ftui_text::Span<'static>> = line
551 .spans()
552 .iter()
553 .cloned()
554 .map(ftui_text::Span::into_owned)
555 .collect();
556 return (ftui_text::Line::from_spans(spans), width);
557 }
558 let level = match para_dir {
564 ftui_text::bidi::ParagraphDirection::Ltr => Some(unicode_bidi::Level::ltr()),
565 ftui_text::bidi::ParagraphDirection::Rtl => Some(unicode_bidi::Level::rtl()),
566 ftui_text::bidi::ParagraphDirection::Auto => None,
567 };
568 let bidi_info = unicode_bidi::BidiInfo::new(&full_text, level);
569 let mut byte_styles: Vec<Option<Style>> = Vec::with_capacity(full_text.len());
570 for span in line.spans() {
571 byte_styles.extend(std::iter::repeat_n(span.style, span.content.len()));
572 }
573
574 let mut new_spans: Vec<ftui_text::Span<'static>> = Vec::new();
575 let mut current_str = String::new();
576 let mut current_style: Option<Style> = None;
577 let mut push_cluster = |cluster: &str, style: Option<Style>| {
578 if !current_str.is_empty() && current_style != style {
579 let text = std::mem::take(&mut current_str);
580 new_spans.push(match current_style {
581 Some(st) => ftui_text::Span::styled(text, st),
582 None => ftui_text::Span::raw(text),
583 });
584 }
585 current_style = style;
586 current_str.push_str(cluster);
587 };
588 for para in &bidi_info.paragraphs {
589 let (levels, runs) = bidi_info.visual_runs(para, para.range.clone());
590 for run in runs {
591 let run_text = &full_text[run.clone()];
592 let clusters: Vec<(usize, &str)> =
593 unicode_segmentation::UnicodeSegmentation::grapheme_indices(run_text, true)
594 .collect();
595 let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl());
596 let style_at = |off: usize| byte_styles.get(run.start + off).copied().flatten();
597 if rtl {
598 for &(off, g) in clusters.iter().rev() {
599 push_cluster(g, style_at(off));
600 }
601 } else {
602 for &(off, g) in &clusters {
603 push_cluster(g, style_at(off));
604 }
605 }
606 }
607 }
608 if !current_str.is_empty() {
609 new_spans.push(match current_style {
610 Some(st) => ftui_text::Span::styled(current_str, st),
611 None => ftui_text::Span::raw(current_str),
612 });
613 }
614 let line = ftui_text::Line::from_spans(new_spans);
615 let width = line.width();
616 (line, width)
617}
618impl MeasurableWidget for Paragraph<'_> {
619 fn measure(&self, available: Size) -> SizeConstraints {
620 let metrics = self.cached_metrics(true);
621 let text_width = metrics.text_width;
622 let text_height = metrics.text_height;
623 let min_width = match self.wrap {
630 Some(WrapMode::Char | WrapMode::WordChar) => metrics.widest_grapheme,
631 _ => metrics.min_width,
632 };
633
634 let (chrome_width, chrome_height) = self
636 .block
637 .as_ref()
638 .map(|b| b.chrome_size())
639 .unwrap_or((0, 0));
640
641 let (preferred_width, preferred_height) =
643 if self.wrap.is_some_and(|mode| mode != WrapMode::None) {
644 let wrap_width = if available.width > chrome_width {
646 (available.width - chrome_width) as usize
647 } else {
648 1
649 };
650
651 let wrapped_height = self
652 .wrap
653 .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
654 .unwrap_or(text_height);
655
656 let pref_w = text_width.min(wrap_width);
658 (pref_w, wrapped_height)
659 } else {
660 (text_width, text_height)
662 };
663
664 let min_w = u16::try_from(min_width)
666 .unwrap_or(u16::MAX)
667 .saturating_add(chrome_width);
668 let min_h = if preferred_height > 0 {
670 (1u16).saturating_add(chrome_height)
671 } else {
672 chrome_height
673 };
674
675 let pref_w = u16::try_from(preferred_width)
682 .unwrap_or(u16::MAX)
683 .saturating_add(chrome_width)
684 .max(min_w);
685 let pref_h = u16::try_from(preferred_height)
686 .unwrap_or(u16::MAX)
687 .saturating_add(chrome_height);
688
689 SizeConstraints {
690 min: Size::new(min_w, min_h),
691 preferred: Size::new(pref_w, pref_h),
692 max: None, }
694 }
695
696 fn has_intrinsic_size(&self) -> bool {
697 true
699 }
700}
701
702impl Paragraph<'_> {
703 #[cfg_attr(not(test), allow(dead_code))]
704 fn calculate_min_width(&self) -> usize {
705 self.cached_metrics(true).min_width
706 }
707
708 #[cfg_attr(not(test), allow(dead_code))]
709 fn estimate_wrapped_height(&self, wrap_width: usize) -> usize {
710 if wrap_width == 0 {
711 return self.cached_metrics(false).text_height;
712 }
713
714 self.wrap
715 .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
716 .unwrap_or_else(|| self.cached_metrics(false).text_height)
717 .max(1)
718 }
719}
720
721fn align_x(area: Rect, line_width: usize, alignment: Alignment) -> u16 {
723 let line_width_u16 = u16::try_from(line_width).unwrap_or(u16::MAX);
724 match alignment {
725 Alignment::Left => area.x,
726 Alignment::Center => area
727 .x
728 .saturating_add(area.width.saturating_sub(line_width_u16) / 2),
729 Alignment::Right => area
730 .x
731 .saturating_add(area.width.saturating_sub(line_width_u16)),
732 }
733}
734
735fn truncate_accessible_text(text: &str) -> String {
736 const ACCESSIBLE_TEXT_LIMIT: usize = 200;
737 const ACCESSIBLE_TEXT_PREFIX_LIMIT: usize = 197;
738
739 if text.chars().count() <= ACCESSIBLE_TEXT_LIMIT {
740 text.to_owned()
741 } else {
742 let mut prefix = String::new();
743 let mut prefix_chars = 0usize;
744
745 for grapheme in graphemes(text) {
746 let grapheme_chars = grapheme.chars().count();
747 if prefix_chars + grapheme_chars > ACCESSIBLE_TEXT_PREFIX_LIMIT {
748 break;
749 }
750 prefix.push_str(grapheme);
751 prefix_chars += grapheme_chars;
752 }
753
754 format!("{prefix}...")
755 }
756}
757
758impl ftui_a11y::Accessible for Paragraph<'_> {
763 fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
764 use ftui_a11y::node::{A11yNodeInfo, A11yRole};
765
766 let id = crate::a11y_node_id(area);
767
768 let name: String = self
770 .text
771 .lines()
772 .iter()
773 .map(|line| {
774 line.spans()
775 .iter()
776 .map(|span| span.content.as_ref())
777 .collect::<Vec<_>>()
778 .join("")
779 })
780 .collect::<Vec<_>>()
781 .join(" ");
782
783 let block_title = self.block.as_ref().and_then(|b| b.title_text());
784 let truncated_name = truncate_accessible_text(&name);
785
786 let mut node = A11yNodeInfo::new(id, A11yRole::Label, area);
787 if let Some(title) = block_title {
788 node = node.with_name(title);
789 if !name.is_empty() {
790 node = node.with_description(truncated_name);
791 }
792 } else if !name.is_empty() {
793 node = node.with_name(truncated_name);
794 }
795
796 vec![node]
797 }
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803 use ftui_render::grapheme_pool::GraphemePool;
804
805 fn raw_row_text(frame: &Frame, y: u16) -> String {
806 let width = frame.buffer.width();
807 let mut actual = String::new();
808 for x in 0..width {
809 let cell = match frame.buffer.get(x, y) {
810 Some(c) => c,
811 None => {
812 actual.push(' ');
813 continue;
814 }
815 };
816 if cell.content.is_empty() {
817 actual.push(' ');
818 } else if let Some(ch) = cell.content.as_char() {
819 actual.push(ch);
820 } else if let Some(gid) = cell.content.grapheme_id() {
821 if let Some(s) = frame.pool.get(gid) {
822 actual.push_str(s);
823 } else {
824 actual.push(' ');
825 }
826 } else {
827 actual.push(' ');
828 }
829 }
830 actual
831 }
832
833 #[test]
834 fn render_simple_text() {
835 let para = Paragraph::new(Text::raw("Hello"));
836 let area = Rect::new(0, 0, 10, 1);
837 let mut pool = GraphemePool::new();
838 let mut frame = Frame::new(10, 1, &mut pool);
839 para.render(area, &mut frame);
840
841 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
842 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('o'));
843 }
844
845 #[test]
846 fn from_static_str_preserves_rendering_without_owning_static_spans() {
847 let area = Rect::new(0, 0, 8, 2);
848
849 let fast = Paragraph::from_static_str("Hi\nthere").style(Style::new().bold());
850 let slow = Paragraph::new("Hi\nthere").style(Style::new().bold());
851
852 let mut fast_pool = GraphemePool::new();
853 let mut fast_frame = Frame::new(8, 2, &mut fast_pool);
854 fast.render(area, &mut fast_frame);
855
856 let mut slow_pool = GraphemePool::new();
857 let mut slow_frame = Frame::new(8, 2, &mut slow_pool);
858 slow.render(area, &mut slow_frame);
859
860 assert_eq!(raw_row_text(&fast_frame, 0), raw_row_text(&slow_frame, 0));
861 assert_eq!(raw_row_text(&fast_frame, 1), raw_row_text(&slow_frame, 1));
862
863 let first_span = &fast.text.lines()[0].spans()[0];
864 match &first_span.content {
865 std::borrow::Cow::Borrowed(text) => assert_eq!(*text, "Hi"),
866 std::borrow::Cow::Owned(_) => panic!("static paragraph text should stay borrowed"),
867 }
868 }
869
870 #[test]
871 fn render_multiline_text() {
872 let para = Paragraph::new(Text::raw("AB\nCD"));
873 let area = Rect::new(0, 0, 5, 3);
874 let mut pool = GraphemePool::new();
875 let mut frame = Frame::new(5, 3, &mut pool);
876 para.render(area, &mut frame);
877
878 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
879 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
880 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('C'));
881 assert_eq!(frame.buffer.get(1, 1).unwrap().content.as_char(), Some('D'));
882 }
883
884 #[test]
885 fn render_centered_text() {
886 let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Center);
887 let area = Rect::new(0, 0, 10, 1);
888 let mut pool = GraphemePool::new();
889 let mut frame = Frame::new(10, 1, &mut pool);
890 para.render(area, &mut frame);
891
892 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('H'));
894 assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('i'));
895 }
896
897 #[test]
898 fn render_with_scroll() {
899 let para = Paragraph::new(Text::raw("Line1\nLine2\nLine3")).scroll((1, 0));
900 let area = Rect::new(0, 0, 10, 2);
901 let mut pool = GraphemePool::new();
902 let mut frame = Frame::new(10, 2, &mut pool);
903 para.render(area, &mut frame);
904
905 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('L'));
907 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('2'));
908 }
909
910 #[test]
911 fn render_long_span_visible_prefix_at_u16_boundaries() {
912 for width in [65_535, 65_536, 65_537, 131_072] {
913 let content = format!("ABCDE{}", "x".repeat(width - 5));
914 let paragraph = Paragraph::new(content);
915 let mut pool = GraphemePool::new();
916 let mut frame = Frame::new(7, 1, &mut pool);
917 paragraph.render(Rect::new(1, 0, 5, 1), &mut frame);
918
919 assert_eq!(raw_row_text(&frame, 0), " ABCDE ", "width {width}");
920 }
921 }
922
923 #[test]
924 fn render_long_span_at_max_horizontal_scroll() {
925 for (tail, expected) in [
926 ("", " "),
927 ("A", "A "),
928 ("ABCDE", "ABCDE "),
929 ("ABCDEFGH", "ABCDEF"),
930 ] {
931 let content = format!("{}{tail}", "x".repeat(65_535));
932 let paragraph = Paragraph::new(content).scroll((0, u16::MAX));
933 let mut pool = GraphemePool::new();
934 let mut frame = Frame::new(6, 1, &mut pool);
935 paragraph.render(Rect::new(0, 0, 6, 1), &mut frame);
936
937 assert_eq!(raw_row_text(&frame, 0), expected, "tail {tail:?}");
938 }
939 }
940
941 #[test]
942 fn render_max_horizontal_scroll_preserves_span_positions_and_styles() {
943 use ftui_render::cell::PackedRgba;
944
945 for (prefix_width, expected, red_start, green_start) in [
946 (65_534, " BCD ", 1, 2),
947 (65_535, " ABCD ", 1, 3),
948 (65_536, " xABCD ", 2, 4),
949 ] {
950 let paragraph = Paragraph::new(Text::from(Line::from_spans([
951 Span::raw("x".repeat(prefix_width)),
952 Span::styled("AB", Style::new().fg(PackedRgba::RED)),
953 Span::styled("CD", Style::new().fg(PackedRgba::GREEN)),
954 ])))
955 .scroll((0, u16::MAX));
956 let mut pool = GraphemePool::new();
957 let mut frame = Frame::new(7, 1, &mut pool);
958 paragraph.render(Rect::new(1, 0, 5, 1), &mut frame);
959
960 assert_eq!(raw_row_text(&frame, 0), expected, "prefix {prefix_width}");
961 for x in red_start..green_start {
962 assert_eq!(frame.buffer.get(x, 0).unwrap().fg, PackedRgba::RED);
963 }
964 for x in green_start..green_start + 2 {
965 assert_eq!(frame.buffer.get(x, 0).unwrap().fg, PackedRgba::GREEN);
966 }
967 }
968 }
969
970 #[test]
971 fn render_long_wide_span_clips_at_viewport_edge() {
972 let paragraph = Paragraph::new("界".repeat(32_768));
973 let mut pool = GraphemePool::new();
974 let mut frame = Frame::new(5, 1, &mut pool);
975 paragraph.render(Rect::new(1, 0, 3, 1), &mut frame);
976
977 let wide = frame
978 .buffer
979 .get(1, 0)
980 .unwrap()
981 .content
982 .grapheme_id()
983 .expect("the visible whole wide grapheme must be rendered");
984 assert_eq!(frame.pool.get(wide), Some("界"));
985 assert!(frame.buffer.get(2, 0).unwrap().is_continuation());
986 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some(' '));
987 for x in [0, 4] {
988 assert_eq!(
989 *frame.buffer.get(x, 0).unwrap(),
990 ftui_render::cell::Cell::default()
991 );
992 }
993 }
994
995 #[test]
996 fn render_max_horizontal_scroll_clips_whole_wide_graphemes() {
997 let content = format!("{}界A界B", "x".repeat(65_535));
998 let paragraph = Paragraph::new(content).scroll((0, u16::MAX));
999 let mut pool = GraphemePool::new();
1000 let mut frame = Frame::new(4, 1, &mut pool);
1001 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1002
1003 let wide = frame
1004 .buffer
1005 .get(0, 0)
1006 .unwrap()
1007 .content
1008 .grapheme_id()
1009 .expect("a wide grapheme beginning at the scroll offset must remain visible");
1010 assert_eq!(frame.pool.get(wide), Some("界"));
1011 assert!(frame.buffer.get(1, 0).unwrap().is_continuation());
1012 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('A'));
1013 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some(' '));
1014
1015 let content = format!("{}界AB", "x".repeat(65_534));
1018 let paragraph = Paragraph::new(content).scroll((0, u16::MAX));
1019 let mut pool = GraphemePool::new();
1020 let mut frame = Frame::new(4, 1, &mut pool);
1021 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1022 assert_eq!(raw_row_text(&frame, 0), "AB ");
1023 }
1024
1025 #[test]
1026 fn render_empty_area() {
1027 let para = Paragraph::new(Text::raw("Hello"));
1028 let area = Rect::new(0, 0, 0, 0);
1029 let mut pool = GraphemePool::new();
1030 let mut frame = Frame::new(1, 1, &mut pool);
1031 para.render(area, &mut frame);
1032 }
1033
1034 #[test]
1035 fn line_min_width_tracks_words_across_spans() {
1036 let line = Line::from_spans([
1037 Span::raw("alpha"),
1038 Span::styled(" ", Style::new().bold()),
1039 Span::raw("beta"),
1040 Span::raw(" "),
1041 Span::raw("gamma"),
1042 ]);
1043
1044 assert_eq!(line_min_width(&line), 5);
1045 }
1046
1047 #[test]
1048 fn intrinsic_minimum_preserves_whitespace_unicode_and_span_boundaries() {
1049 let cases = [
1050 (Text::raw(""), 0),
1051 (Text::raw(" "), 3),
1052 (Text::raw(" \na"), 1),
1053 (Text::raw("e\u{301} x"), 1),
1054 (Text::raw("ab\tc"), 2),
1055 (Text::raw("a\0b\x7fc"), 3),
1056 (
1057 Text::from(Line::from_spans([
1058 Span::raw("hel"),
1059 Span::styled("lo", Style::new().bold()),
1060 ])),
1061 5,
1062 ),
1063 (
1064 Text::from(Line::from_spans([Span::raw("ab"), Span::raw("界")])),
1065 4,
1066 ),
1067 ];
1068 let area = Rect::new(0, 0, 16, 3);
1069 for (text, expected_minimum) in cases {
1070 let paragraph = Paragraph::new(text);
1071 for render_first in [true, false] {
1072 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1073 let mut pool = GraphemePool::new();
1074 let mut frame = Frame::new(area.width, area.height, &mut pool);
1075 if render_first {
1076 paragraph.render(area, &mut frame);
1077 }
1078 let measured = paragraph.measure(Size::new(area.width, area.height));
1079 assert_eq!(measured.min.width, expected_minimum, "{paragraph:?}");
1080 paragraph.render(area, &mut frame);
1081 assert_eq!(paragraph.measure(Size::new(1, 1)), measured);
1082 }
1083 }
1084 }
1085
1086 #[test]
1087 fn intrinsic_measurement_is_independent_of_render_order_and_chrome() {
1088 let paragraph = Paragraph::new("hello world").wrap(WrapMode::Word);
1089 let area = Rect::new(0, 0, 6, 2);
1090 for render_first in [true, false] {
1091 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1092 let mut pool = GraphemePool::new();
1093 let mut frame = Frame::new(6, 2, &mut pool);
1094 if render_first {
1095 paragraph.render(area, &mut frame);
1096 }
1097 let measured = paragraph.measure(Size::new(6, 2));
1098 assert_eq!(measured.min, Size::new(5, 1));
1099 assert_eq!(measured.preferred, Size::new(6, 2));
1100 paragraph.render(area, &mut frame);
1101 assert_eq!(raw_row_text(&frame, 0), "hello ");
1102 assert_eq!(raw_row_text(&frame, 1), "world ");
1103
1104 let bordered = paragraph.clone().block(Block::bordered());
1105 let measured = bordered.measure(Size::new(10, 6));
1106 assert_eq!(measured.min, Size::new(9, 5));
1107 assert_eq!(measured.preferred, Size::new(10, 6));
1108 let unwrapped = paragraph.clone().wrap(WrapMode::None);
1109 assert_eq!(
1110 unwrapped.measure(Size::new(6, 2)).preferred,
1111 Size::new(11, 1)
1112 );
1113 }
1114 }
1115
1116 #[test]
1117 fn intrinsic_minimum_survives_actual_metrics_eviction() {
1118 let original = Paragraph::new("hello world");
1119 let available = Size::new(16, 2);
1120 let area = Rect::new(0, 0, 16, 2);
1121 for measure_first in [true, false] {
1122 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1123 let mut pool = GraphemePool::new();
1124 let mut frame = Frame::new(16, 2, &mut pool);
1125 original.render(area, &mut frame);
1126 if measure_first {
1127 assert_eq!(original.measure(available).min.width, 5);
1128 }
1129 for index in 0..PARAGRAPH_METRICS_CACHE_CAPACITY {
1130 Paragraph::new(format!("entry{index} xxxx")).render(area, &mut frame);
1131 }
1132 PARAGRAPH_CACHE.with(|cache| {
1133 let cache = cache.borrow();
1134 assert_eq!(cache.metrics.len(), PARAGRAPH_METRICS_CACHE_CAPACITY);
1135 assert!(!cache.metrics.contains_key(&original.text_hash()));
1136 });
1137 let measured = original.measure(available);
1138 assert_eq!(measured.min, Size::new(5, 1));
1139 assert_eq!(measured.preferred, Size::new(11, 1));
1140 original.render(area, &mut frame);
1141 assert_eq!(raw_row_text(&frame, 0), "hello world ");
1142 }
1143 }
1144
1145 #[test]
1146 fn intrinsic_measurement_preserves_resolved_unicode_rendering() {
1147 let paragraph = Paragraph::new("e\u{301} 界");
1148 for render_first in [true, false] {
1149 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1150 let mut pool = GraphemePool::new();
1151 let mut frame = Frame::new(4, 1, &mut pool);
1152 if render_first {
1153 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1154 }
1155 let measured = paragraph.measure(Size::new(4, 1));
1156 assert_eq!(measured.min, Size::new(2, 1));
1157 assert_eq!(measured.preferred, Size::new(4, 1));
1158 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1159 let accent = frame
1160 .buffer
1161 .get(0, 0)
1162 .unwrap()
1163 .content
1164 .grapheme_id()
1165 .unwrap();
1166 assert_eq!(frame.pool.get(accent), Some("e\u{301}"));
1167 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some(' '));
1168 let wide = frame
1169 .buffer
1170 .get(2, 0)
1171 .unwrap()
1172 .content
1173 .grapheme_id()
1174 .unwrap();
1175 assert_eq!(frame.pool.get(wide), Some("界"));
1176 assert!(frame.buffer.get(3, 0).unwrap().content.is_continuation());
1177 }
1178 }
1179
1180 #[test]
1181 fn intrinsic_width_saturates_before_adding_chrome() {
1182 for (width, expected_plain, expected_bordered) in [
1183 (65_534, 65_534, 65_535),
1184 (65_535, 65_535, 65_535),
1185 (65_536, 65_535, 65_535),
1186 (131_071, 65_535, 65_535),
1187 ] {
1188 let paragraph = Paragraph::new("x".repeat(width));
1189 let measured = paragraph.measure(Size::new(80, 24));
1190 assert_eq!(measured.min, Size::new(expected_plain, 1));
1191 assert_eq!(measured.preferred, Size::new(expected_plain, 1));
1192
1193 let bordered = paragraph.block(Block::bordered());
1194 let measured = bordered.measure(Size::new(80, 24));
1195 assert_eq!(measured.min, Size::new(expected_bordered, 5));
1196 assert_eq!(measured.preferred, Size::new(expected_bordered, 5));
1197 }
1198 }
1199
1200 #[test]
1201 fn intrinsic_height_saturates_before_adding_chrome() {
1202 for (height, expected_plain) in [(65_534, 65_534), (65_535, 65_535), (65_536, 65_535)] {
1203 let paragraph = Paragraph::new(Text::from_lines(vec![Line::raw("x"); height]));
1204 let measured = paragraph.measure(Size::new(80, 24));
1205 assert_eq!(measured.min, Size::new(1, 1));
1206 assert_eq!(measured.preferred, Size::new(1, expected_plain));
1207
1208 let bordered = paragraph.block(Block::bordered());
1209 let measured = bordered.measure(Size::new(80, 24));
1210 assert_eq!(measured.min, Size::new(5, 5));
1211 assert_eq!(measured.preferred, Size::new(5, u16::MAX));
1212 }
1213 }
1214
1215 #[test]
1216 fn intrinsic_wrapped_height_saturates_at_terminal_dimension_limit() {
1217 let paragraph = Paragraph::new("x".repeat(65_536)).wrap(WrapMode::Char);
1218 let measured = paragraph.measure(Size::new(1, 24));
1219 assert_eq!(measured.min, Size::new(1, 1));
1224 assert_eq!(measured.preferred, Size::new(1, u16::MAX));
1225
1226 let bordered = paragraph.block(Block::bordered());
1229 let measured = bordered.measure(Size::new(5, 24));
1230 assert_eq!(measured.min, Size::new(5, 5));
1231 assert_eq!(measured.preferred, Size::new(5, u16::MAX));
1232 }
1233
1234 #[test]
1235 fn measure_wrap_counts_cached_visual_lines() {
1236 let para = Paragraph::new(Text::raw("hello world from cache")).wrap(WrapMode::Word);
1237 let constraints = para.measure(Size::new(8, 10));
1238
1239 assert_eq!(constraints.preferred.height, 4);
1240 assert_eq!(constraints.min.width, 5);
1241 }
1242
1243 #[test]
1244 fn measure_wrap_none_preserves_natural_width() {
1245 let para = Paragraph::new(Text::raw("abcdef")).wrap(WrapMode::None);
1246 let constraints = para.measure(Size::new(3, 10));
1247
1248 assert_eq!(constraints.preferred.width, 6);
1249 assert_eq!(constraints.preferred.height, 1);
1250 }
1251
1252 #[test]
1253 fn render_empty_text_clears_content() {
1254 let para = Paragraph::new("");
1255 let area = Rect::new(0, 0, 3, 1);
1256 let mut pool = GraphemePool::new();
1257 let mut frame = Frame::new(3, 1, &mut pool);
1258
1259 frame
1261 .buffer
1262 .fill(area, ftui_render::cell::Cell::from_char('X'));
1263
1264 para.render(area, &mut frame);
1265
1266 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
1267 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some(' '));
1268 }
1269
1270 #[test]
1271 fn render_right_aligned() {
1272 let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Right);
1273 let area = Rect::new(0, 0, 10, 1);
1274 let mut pool = GraphemePool::new();
1275 let mut frame = Frame::new(10, 1, &mut pool);
1276 para.render(area, &mut frame);
1277
1278 assert_eq!(frame.buffer.get(8, 0).unwrap().content.as_char(), Some('H'));
1280 assert_eq!(frame.buffer.get(9, 0).unwrap().content.as_char(), Some('i'));
1281 }
1282
1283 #[test]
1284 fn render_with_word_wrap() {
1285 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1286 let area = Rect::new(0, 0, 6, 3);
1287 let mut pool = GraphemePool::new();
1288 let mut frame = Frame::new(6, 3, &mut pool);
1289 para.render(area, &mut frame);
1290
1291 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('h'));
1293 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('w'));
1294 }
1295
1296 #[test]
1297 fn render_with_char_wrap() {
1298 let para = Paragraph::new(Text::raw("abcdefgh")).wrap(WrapMode::Char);
1299 let area = Rect::new(0, 0, 4, 3);
1300 let mut pool = GraphemePool::new();
1301 let mut frame = Frame::new(4, 3, &mut pool);
1302 para.render(area, &mut frame);
1303
1304 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
1306 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some('d'));
1307 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
1309 }
1310
1311 #[test]
1312 fn scroll_past_all_lines() {
1313 let para = Paragraph::new(Text::raw("AB")).scroll((5, 0));
1314 let area = Rect::new(0, 0, 5, 2);
1315 let mut pool = GraphemePool::new();
1316 let mut frame = Frame::new(5, 2, &mut pool);
1317 para.render(area, &mut frame);
1318
1319 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
1321 }
1322
1323 #[test]
1324 fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
1325 let area = Rect::new(0, 0, 8, 2);
1326 let mut pool = GraphemePool::new();
1327 let mut frame = Frame::new(8, 2, &mut pool);
1328
1329 Paragraph::new(Text::raw("Hello\nWorld")).render(area, &mut frame);
1330 Paragraph::new(Text::raw("Hi")).render(area, &mut frame);
1331
1332 assert_eq!(raw_row_text(&frame, 0), "Hi ");
1333 assert_eq!(raw_row_text(&frame, 1), " ");
1334 }
1335
1336 #[test]
1337 fn render_clipped_at_area_height() {
1338 let para = Paragraph::new(Text::raw("A\nB\nC\nD\nE"));
1339 let area = Rect::new(0, 0, 5, 2);
1340 let mut pool = GraphemePool::new();
1341 let mut frame = Frame::new(5, 2, &mut pool);
1342 para.render(area, &mut frame);
1343
1344 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1346 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('B'));
1347 }
1348
1349 #[test]
1350 fn render_clipped_at_area_width() {
1351 let para = Paragraph::new(Text::raw("ABCDEF"));
1352 let area = Rect::new(0, 0, 3, 1);
1353 let mut pool = GraphemePool::new();
1354 let mut frame = Frame::new(3, 1, &mut pool);
1355 para.render(area, &mut frame);
1356
1357 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1358 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1359 }
1360
1361 #[test]
1362 fn align_x_left() {
1363 let area = Rect::new(5, 0, 20, 1);
1364 assert_eq!(align_x(area, 10, Alignment::Left), 5);
1365 }
1366
1367 #[test]
1368 fn align_x_center() {
1369 let area = Rect::new(0, 0, 20, 1);
1370 assert_eq!(align_x(area, 6, Alignment::Center), 7);
1372 }
1373
1374 #[test]
1375 fn align_x_right() {
1376 let area = Rect::new(0, 0, 20, 1);
1377 assert_eq!(align_x(area, 5, Alignment::Right), 15);
1379 }
1380
1381 #[test]
1382 fn align_x_wide_line_saturates() {
1383 let area = Rect::new(0, 0, 10, 1);
1384 assert_eq!(align_x(area, 20, Alignment::Right), 0);
1386 assert_eq!(align_x(area, 20, Alignment::Center), 0);
1387 }
1388
1389 #[test]
1390 fn builder_methods_chain() {
1391 let para = Paragraph::new(Text::raw("test"))
1392 .style(Style::default())
1393 .wrap(WrapMode::Word)
1394 .alignment(Alignment::Center)
1395 .scroll((1, 2));
1396 let area = Rect::new(0, 0, 10, 5);
1398 let mut pool = GraphemePool::new();
1399 let mut frame = Frame::new(10, 5, &mut pool);
1400 para.render(area, &mut frame);
1401 }
1402
1403 #[test]
1404 fn render_at_offset_area() {
1405 let para = Paragraph::new(Text::raw("X"));
1406 let area = Rect::new(3, 4, 5, 2);
1407 let mut pool = GraphemePool::new();
1408 let mut frame = Frame::new(10, 10, &mut pool);
1409 para.render(area, &mut frame);
1410
1411 assert_eq!(frame.buffer.get(3, 4).unwrap().content.as_char(), Some('X'));
1412 assert!(frame.buffer.get(0, 0).unwrap().is_empty());
1414 }
1415
1416 #[test]
1417 fn wrap_clipped_at_area_bottom() {
1418 let para = Paragraph::new(Text::raw("abcdefghijklmnop")).wrap(WrapMode::Char);
1420 let area = Rect::new(0, 0, 4, 2);
1421 let mut pool = GraphemePool::new();
1422 let mut frame = Frame::new(4, 2, &mut pool);
1423 para.render(area, &mut frame);
1424
1425 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
1427 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
1428 }
1429
1430 #[test]
1433 fn degradation_skeleton_skips_content() {
1434 use ftui_render::budget::DegradationLevel;
1435
1436 let para = Paragraph::new(Text::raw("Hello"));
1437 let area = Rect::new(0, 0, 10, 1);
1438 let mut pool = GraphemePool::new();
1439 let mut frame = Frame::new(10, 1, &mut pool);
1440 Paragraph::new(Text::raw("Stale")).render(area, &mut frame);
1441 frame.set_degradation(DegradationLevel::Skeleton);
1442 para.render(area, &mut frame);
1443
1444 assert_eq!(raw_row_text(&frame, 0), " ");
1446 }
1447
1448 #[test]
1449 fn degradation_full_renders_content() {
1450 use ftui_render::budget::DegradationLevel;
1451
1452 let para = Paragraph::new(Text::raw("Hello"));
1453 let area = Rect::new(0, 0, 10, 1);
1454 let mut pool = GraphemePool::new();
1455 let mut frame = Frame::new(10, 1, &mut pool);
1456 frame.set_degradation(DegradationLevel::Full);
1457 para.render(area, &mut frame);
1458
1459 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1460 }
1461
1462 #[test]
1463 fn degradation_essential_only_still_renders_text() {
1464 use ftui_render::budget::DegradationLevel;
1465
1466 let para = Paragraph::new(Text::raw("Hello"));
1467 let area = Rect::new(0, 0, 10, 1);
1468 let mut pool = GraphemePool::new();
1469 let mut frame = Frame::new(10, 1, &mut pool);
1470 frame.set_degradation(DegradationLevel::EssentialOnly);
1471 para.render(area, &mut frame);
1472
1473 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1475 }
1476
1477 #[test]
1478 fn degradation_no_styling_ignores_span_styles() {
1479 use ftui_render::budget::DegradationLevel;
1480 use ftui_render::cell::PackedRgba;
1481 use ftui_text::{Line, Span};
1482
1483 let styled_span = Span::styled("Hello", Style::new().fg(PackedRgba::RED));
1485 let line = Line::from_spans([styled_span]);
1486 let text = Text::from(line);
1487 let para = Paragraph::new(text);
1488 let area = Rect::new(0, 0, 10, 1);
1489 let mut pool = GraphemePool::new();
1490 let mut frame = Frame::new(10, 1, &mut pool);
1491 frame.set_degradation(DegradationLevel::NoStyling);
1492 para.render(area, &mut frame);
1493
1494 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1496 assert_ne!(
1498 frame.buffer.get(0, 0).unwrap().fg,
1499 PackedRgba::RED,
1500 "Span fg color should be ignored at NoStyling"
1501 );
1502 }
1503
1504 use crate::MeasurableWidget;
1507 use ftui_core::geometry::Size;
1508
1509 #[test]
1510 fn measure_simple_text() {
1511 let para = Paragraph::new(Text::raw("Hello"));
1512 let constraints = para.measure(Size::MAX);
1513
1514 assert_eq!(constraints.preferred, Size::new(5, 1));
1516 assert_eq!(constraints.min.height, 1);
1517 assert_eq!(constraints.min.width, 5);
1519 }
1520
1521 #[test]
1522 fn measure_multiline_text() {
1523 let para = Paragraph::new(Text::raw("Line1\nLine22\nL3"));
1524 let constraints = para.measure(Size::MAX);
1525
1526 assert_eq!(constraints.preferred, Size::new(6, 3));
1528 assert_eq!(constraints.min.height, 1);
1529 assert_eq!(constraints.min.width, 6);
1531 }
1532
1533 #[test]
1534 fn measure_with_block() {
1535 let block = crate::block::Block::bordered();
1536 let para = Paragraph::new(Text::raw("Hi")).block(block);
1537 let constraints = para.measure(Size::MAX);
1538
1539 assert_eq!(constraints.preferred, Size::new(6, 5));
1541 assert_eq!(constraints.min.width, 6);
1542 assert_eq!(constraints.min.height, 5);
1543 }
1544
1545 #[test]
1546 fn measure_with_word_wrap() {
1547 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1548 let constraints = para.measure(Size::new(6, 10));
1550
1551 assert_eq!(constraints.preferred.height, 2);
1554 assert_eq!(constraints.min.width, 5);
1556 }
1557
1558 #[test]
1559 fn measure_empty_text() {
1560 let para = Paragraph::new(Text::raw(""));
1561 let constraints = para.measure(Size::MAX);
1562
1563 assert_eq!(constraints.preferred.width, 0);
1565 assert_eq!(constraints.preferred.height, 0);
1566 assert_eq!(constraints.min.height, 0);
1569 }
1570
1571 #[test]
1572 fn calculate_min_width_single_long_word() {
1573 let para = Paragraph::new(Text::raw("supercalifragilistic"));
1574 assert_eq!(para.calculate_min_width(), 20);
1575 }
1576
1577 #[test]
1578 fn calculate_min_width_multiple_words() {
1579 let para = Paragraph::new(Text::raw("the quick brown fox"));
1580 assert_eq!(para.calculate_min_width(), 5);
1582 }
1583
1584 #[test]
1585 fn calculate_min_width_multiline() {
1586 let para = Paragraph::new(Text::raw("short\nlongword\na"));
1587 assert_eq!(para.calculate_min_width(), 8);
1589 }
1590
1591 #[test]
1592 fn estimate_wrapped_height_no_wrap_needed() {
1593 let para = Paragraph::new(Text::raw("short")).wrap(WrapMode::Word);
1594 assert_eq!(para.estimate_wrapped_height(10), 1);
1596 }
1597
1598 #[test]
1599 fn estimate_wrapped_height_needs_wrap() {
1600 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1601 assert_eq!(para.estimate_wrapped_height(6), 2);
1603 }
1604
1605 #[test]
1606 fn has_intrinsic_size() {
1607 let para = Paragraph::new(Text::raw("test"));
1608 assert!(para.has_intrinsic_size());
1609 }
1610
1611 #[test]
1612 fn measure_is_pure() {
1613 let para = Paragraph::new(Text::raw("Hello World"));
1614 let a = para.measure(Size::new(100, 50));
1615 let b = para.measure(Size::new(100, 50));
1616 assert_eq!(a, b);
1617 }
1618
1619 #[test]
1620 fn a_blocks_group_does_not_overwrite_the_paragraph_node() {
1621 use ftui_a11y::tree::A11yTreeBuilder;
1622
1623 let mut builder = A11yTreeBuilder::new();
1630 let area = Rect::new(0, 0, 40, 6);
1631 {
1632 let mut pool = GraphemePool::new();
1633 let mut frame = Frame::new(40, 6, &mut pool);
1634 frame.set_a11y(&mut builder);
1635 Paragraph::new("hello world")
1636 .block(Block::bordered().title("Notes"))
1637 .render(area, &mut frame);
1638 frame.finish_a11y();
1639 }
1640 let tree = builder.build();
1641
1642 let inventory: Vec<_> = tree
1643 .nodes()
1644 .map(|n| (n.role, n.name.clone(), n.description.clone()))
1645 .collect();
1646 assert_eq!(tree.node_count(), 1, "tree was {inventory:#?}");
1647 let node = tree.nodes().next().expect("one node");
1648 assert_ne!(
1649 node.role,
1650 ftui_a11y::node::A11yRole::Group,
1651 "the block's Group must not be what survived: {inventory:#?}"
1652 );
1653 assert_eq!(node.name.as_deref(), Some("Notes"));
1654 assert_eq!(
1655 node.description.as_deref(),
1656 Some("hello world"),
1657 "the paragraph's text must reach the tree: {inventory:#?}"
1658 );
1659 }
1660
1661 #[test]
1662 fn accessibility_truncates_long_unicode_without_panicking() {
1663 use ftui_a11y::Accessible;
1664
1665 let para = Paragraph::new(Text::raw("界".repeat(210)));
1666 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1667 let name = nodes[0]
1668 .name
1669 .as_deref()
1670 .expect("paragraph should have a name");
1671
1672 assert!(name.ends_with("..."));
1673 assert_eq!(name.chars().count(), 200);
1674 }
1675
1676 #[test]
1677 fn accessibility_truncates_description_when_block_title_present() {
1678 use ftui_a11y::Accessible;
1679
1680 let para =
1681 Paragraph::new(Text::raw("界".repeat(210))).block(Block::bordered().title("Body"));
1682 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1683 let node = &nodes[0];
1684
1685 assert_eq!(node.name.as_deref(), Some("Body"));
1686 let description = node
1687 .description
1688 .as_deref()
1689 .expect("paragraph should have a description");
1690 assert!(description.ends_with("..."));
1691 assert_eq!(description.chars().count(), 200);
1692 }
1693
1694 #[test]
1695 fn accessibility_preserves_exactly_200_chars_without_ellipsis() {
1696 use ftui_a11y::Accessible;
1697
1698 let para = Paragraph::new(Text::raw("界".repeat(200)));
1699 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1700 let name = nodes[0]
1701 .name
1702 .as_deref()
1703 .expect("paragraph should have a name");
1704
1705 assert!(!name.ends_with("..."));
1706 assert_eq!(name.chars().count(), 200);
1707 }
1708
1709 #[test]
1710 fn accessibility_truncates_on_grapheme_boundaries() {
1711 use ftui_a11y::Accessible;
1712
1713 let para = Paragraph::new(Text::raw("e\u{301}".repeat(210)));
1714 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1715 let name = nodes[0]
1716 .name
1717 .as_deref()
1718 .expect("paragraph should have a name");
1719
1720 let prefix = name
1721 .strip_suffix("...")
1722 .expect("paragraph should be truncated");
1723 assert!(name.chars().count() <= 200);
1724 assert_eq!(ftui_text::graphemes(prefix).count(), 98);
1725 assert!(prefix.ends_with("e\u{301}"));
1726 }
1727
1728 #[test]
1729 fn paragraph_rtl_default_alignment_right() {
1730 let sample = "مرحبا بالعالم";
1731 let para = Paragraph::new(sample);
1732 let mut pool = GraphemePool::new();
1733 let mut frame = Frame::new(40, 3, &mut pool);
1734 frame.set_text_direction(ftui_render::TextDirection::Rtl);
1735 let area = Rect::new(0, 0, 40, 3);
1736 para.render(area, &mut frame);
1737
1738 let row = raw_row_text(&frame, 0);
1739 assert!(
1740 !row.ends_with(' '),
1741 "RTL frame paragraph should right-align by default: {:?}",
1742 row
1743 );
1744
1745 let para_left = Paragraph::new(sample).alignment(Alignment::Left);
1746 let mut frame_left = Frame::new(40, 3, &mut pool);
1747 frame_left.set_text_direction(ftui_render::TextDirection::Rtl);
1748 para_left.render(area, &mut frame_left);
1749
1750 let row_left = raw_row_text(&frame_left, 0);
1751 assert!(
1752 !row_left.starts_with(' '),
1753 "Explicit Alignment::Left should left-align: {:?}",
1754 row_left
1755 );
1756 }
1757
1758 #[cfg(feature = "bidi")]
1759 #[test]
1760 fn paragraph_rtl_visual_order_matches_unicode_bidi() {
1761 let corpus = [
1762 "مرحبا بكم",
1763 "السلام عليكم",
1764 "اللغة العربية جميلة",
1765 "صباح الخير",
1766 "استخدم Rust للبرمجة",
1767 "مرحبا بكم في FrankenTUI",
1768 "جرب Linux اليوم",
1769 "تطبيق Terminal جديد",
1770 "العدد هو 12345",
1771 "سعر المنتج 50 دولار",
1772 "عام 2026 الحالي",
1773 "رقم 42 هو الجواب",
1774 "هل أنت بخير؟",
1775 "نعم، بالتأكيد!",
1776 "واحد، اثنان، ثلاثة.",
1777 "مرحبا يا عالم",
1778 "שלום עולם",
1779 "עברית ו-Rust",
1780 "בוקר טוב ישראל",
1781 "מספר 100 כאן",
1782 ];
1783
1784 for sample in corpus {
1785 let para = Paragraph::new(sample).alignment(Alignment::Left);
1786 let width = 60;
1787 let mut pool = GraphemePool::new();
1788 let mut frame = Frame::new(width, 1, &mut pool);
1789 frame.set_text_direction(ftui_render::TextDirection::Rtl);
1790 let area = Rect::new(0, 0, width, 1);
1791 para.render(area, &mut frame);
1792
1793 let bidi_info = unicode_bidi::BidiInfo::new(sample, Some(unicode_bidi::Level::rtl()));
1794 let oracle_reordered =
1795 bidi_info.reorder_line(&bidi_info.paragraphs[0], 0..sample.len());
1796
1797 let row = raw_row_text(&frame, 0);
1798 let rendered_trimmed = row.trim_end();
1799 assert_eq!(
1800 rendered_trimmed,
1801 oracle_reordered.as_ref(),
1802 "Mismatch for sample {:?}: got {:?}, expected oracle {:?}",
1803 sample,
1804 rendered_trimmed,
1805 oracle_reordered
1806 );
1807 }
1808 }
1809
1810 #[cfg(feature = "bidi")]
1814 #[test]
1815 fn paragraph_rtl_reorder_keeps_grapheme_clusters_whole() {
1816 let cases = [
1817 (
1818 "\u{05E9}\u{05B8}\u{05C1}\u{05DC}\u{05D5}\u{05B9}\u{05DD}",
1819 "\u{05DD}\u{05D5}\u{05B9}\u{05DC}\u{05E9}\u{05B8}\u{05C1}",
1820 ),
1821 (
1822 "\u{0628}\u{0650}\u{0633}\u{0652}\u{0645}\u{0650}",
1823 "\u{0645}\u{0650}\u{0633}\u{0652}\u{0628}\u{0650}",
1824 ),
1825 ("a\u{0301} \u{05D0}\u{05D1}", "a\u{0301} \u{05D1}\u{05D0}"),
1826 ];
1827 for (logical, visual) in cases {
1828 for styled in [false, true] {
1829 let text = if styled {
1830 let mid = logical.char_indices().nth(1).unwrap().0;
1833 FtuiText::from_spans([
1834 Span::styled(&logical[..mid], Style::new().bold()),
1835 Span::raw(&logical[mid..]),
1836 ])
1837 } else {
1838 FtuiText::raw(logical)
1839 };
1840 let (line, width) =
1841 reorder_line_bidi(&text.lines()[0], ftui_text::bidi::ParagraphDirection::Auto);
1842 let got: String = line.spans().iter().map(|s| s.content.as_ref()).collect();
1843 assert_eq!(got, visual, "logical={logical:?} styled={styled}");
1844 assert_eq!(width, display_width(logical), "logical={logical:?}");
1845 }
1846 }
1847 }
1848
1849 #[cfg(feature = "bidi")]
1850 #[test]
1851 fn paragraph_wrap_then_reorder_per_line() {
1852 let text = "هذا نص عربي طويل جدا لتجربة تقسيم الأسطر وإعادة الترتيب بشكل مستقل لكل سطر";
1853 let width = 25;
1854 let para = Paragraph::new(text)
1855 .wrap(WrapMode::Word)
1856 .alignment(Alignment::Left);
1857 let mut pool = GraphemePool::new();
1858 let mut frame = Frame::new(width, 5, &mut pool);
1859 frame.set_text_direction(ftui_render::TextDirection::Rtl);
1860 let area = Rect::new(0, 0, width, 5);
1861 para.render(area, &mut frame);
1862
1863 let cached = para.cached_wrapped_lines(width as usize, WrapMode::Word);
1864 for (y, wrapped_line) in cached.lines.iter().take(3).enumerate() {
1865 let logical_text: String = wrapped_line
1866 .spans()
1867 .iter()
1868 .map(|s| s.content.as_ref())
1869 .collect();
1870 let expected =
1871 ftui_text::bidi::reorder(&logical_text, ftui_text::bidi::ParagraphDirection::Rtl);
1872 let row = raw_row_text(&frame, y as u16);
1873 assert_eq!(
1874 row.trim_end(),
1875 expected.as_str(),
1876 "Line {} mismatch against independently reordered wrapped line",
1877 y
1878 );
1879 }
1880 }
1881
1882 #[cfg(feature = "bidi")]
1883 proptest::proptest! {
1884 #[test]
1885 fn paragraph_ltr_text_is_unchanged_by_direction_rtl(s in "[a-zA-Z0-9 _-]{1,30}") {
1886 let area = Rect::new(0, 0, 40, 1);
1887 let mut pool = GraphemePool::new();
1888
1889 let mut ltr_frame = Frame::new(40, 1, &mut pool);
1890 ltr_frame.set_text_direction(ftui_render::TextDirection::Ltr);
1891 Paragraph::new(s.as_str()).alignment(Alignment::Left).render(area, &mut ltr_frame);
1892 let ltr_row = raw_row_text(<r_frame, 0);
1893
1894 let mut rtl_frame = Frame::new(40, 1, &mut pool);
1895 rtl_frame.set_text_direction(ftui_render::TextDirection::Rtl);
1896 Paragraph::new(s.as_str()).alignment(Alignment::Left).render(area, &mut rtl_frame);
1897 let rtl_row = raw_row_text(&rtl_frame, 0);
1898
1899 proptest::prop_assert_eq!(ltr_row.trim_end(), rtl_row.trim_end());
1900 }
1901 }
1902
1903 #[cfg(not(feature = "bidi"))]
1904 #[test]
1905 fn paragraph_rtl_without_bidi_only_aligns_right() {
1906 let sample = "مرحبا بالعالم";
1907 let para = Paragraph::new(sample);
1908 let mut pool = GraphemePool::new();
1909 let mut frame = Frame::new(40, 1, &mut pool);
1910 frame.set_text_direction(ftui_render::TextDirection::Rtl);
1911 let area = Rect::new(0, 0, 40, 1);
1912 para.render(area, &mut frame);
1913
1914 let row = raw_row_text(&frame, 0);
1915 assert!(
1916 !row.ends_with(' '),
1917 "RTL frame paragraph should right-align even without bidi feature"
1918 );
1919 assert!(row.trim().starts_with("مرحبا"));
1920 }
1921}