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 arena = frame.arena();
413 let mut render_spans = |spans: &[ftui_text::Span], line_width: usize, y: u16| {
414 let scroll_x = usize::from(self.scroll.1);
415 let start_x = align_x(text_area, line_width, effective_alignment);
416
417 let mut span_visual_offset: usize = 0;
419
420 let alignment_offset = usize::from(start_x.saturating_sub(text_area.x));
422 let visible_width = usize::from(text_area.right().saturating_sub(text_area.x));
423
424 for span in spans {
425 let span_width = span.width();
426
427 let line_rel_start = alignment_offset.saturating_add(span_visual_offset);
430
431 if line_rel_start.saturating_add(span_width) <= scroll_x {
433 span_visual_offset = span_visual_offset.saturating_add(span_width);
435 continue;
436 }
437
438 let draw_offset = line_rel_start.saturating_sub(scroll_x);
439 if draw_offset >= visible_width {
440 break;
442 }
443
444 let draw_x = text_area.x
447 + u16::try_from(draw_offset).expect("visible paragraph offset fits u16");
448 let local_scroll = u16::try_from(scroll_x.saturating_sub(line_rel_start))
449 .expect("local paragraph scroll is bounded by u16 scroll");
450
451 let span_style = if deg.apply_styling() {
453 match span.style {
454 Some(s) => s.merge(&text_style),
455 None => text_style,
456 }
457 } else {
458 text_style };
460
461 if local_scroll > 0 {
462 draw_text_span_scrolled(
463 frame,
464 draw_x,
465 y,
466 span.content.as_ref(),
467 span_style,
468 text_area.right(),
469 local_scroll,
470 span.link.as_deref(),
471 );
472 } else {
473 draw_text_span_with_link(
474 frame,
475 draw_x,
476 y,
477 span.content.as_ref(),
478 span_style,
479 text_area.right(),
480 span.link.as_deref(),
481 );
482 }
483
484 span_visual_offset = span_visual_offset.saturating_add(span_width);
485 }
486 };
487
488 #[cfg(feature = "bidi")]
489 let para_dir = match text_direction {
490 ftui_render::TextDirection::Rtl => ftui_text::bidi::ParagraphDirection::Rtl,
491 ftui_render::TextDirection::Ltr => ftui_text::bidi::ParagraphDirection::Ltr,
492 };
493
494 let width = text_area.width as usize;
495 if let Some(wrap_mode) = self.wrap {
496 let can_use_arena_wrap = arena.is_some()
497 && self.text.lines().iter().all(|line| {
498 line.spans().len() <= 1
499 && line
500 .spans()
501 .first()
502 .is_none_or(|s| !s.as_str().starts_with(char::is_whitespace))
503 });
504
505 if let Some(arena) = arena.filter(|_| can_use_arena_wrap) {
506 let effective_mode = match wrap_mode {
507 WrapMode::Optimal => WrapMode::Word,
508 other => other,
509 };
510 for line in self.text.lines() {
511 let line_width = line.width();
512 if wrap_mode == WrapMode::None || line_width <= width {
513 if current_visual_line < scroll_offset {
514 current_visual_line += 1;
515 continue;
516 }
517 if y >= text_area.bottom() {
518 break;
519 }
520 #[cfg(feature = "bidi")]
521 if line_has_rtl(line.spans()) {
522 let (reordered_line, reordered_width) =
523 reorder_line_bidi(line, para_dir);
524 render_spans(reordered_line.spans(), reordered_width, y);
525 } else {
526 render_spans(line.spans(), line_width, y);
527 }
528 #[cfg(not(feature = "bidi"))]
529 render_spans(line.spans(), line_width, y);
530
531 y = y.saturating_add(1);
532 current_visual_line += 1;
533 continue;
534 }
535
536 let Some(span) = line.spans().first() else {
537 if current_visual_line < scroll_offset {
538 current_visual_line += 1;
539 continue;
540 }
541 if y >= text_area.bottom() {
542 break;
543 }
544 render_spans(&[], 0, y);
545 y = y.saturating_add(1);
546 current_visual_line += 1;
547 continue;
548 };
549
550 let wrapped_slices =
551 ftui_text::wrap::wrap_text_in(arena, span.as_str(), width, effective_mode);
552 if wrapped_slices.is_empty() {
553 if current_visual_line < scroll_offset {
554 current_visual_line += 1;
555 continue;
556 }
557 if y >= text_area.bottom() {
558 break;
559 }
560 render_spans(&[], 0, y);
561 y = y.saturating_add(1);
562 current_visual_line += 1;
563 continue;
564 }
565
566 for &slice in wrapped_slices {
567 if current_visual_line < scroll_offset {
568 current_visual_line += 1;
569 continue;
570 }
571 if y >= text_area.bottom() {
572 break;
573 }
574 let w_span = ftui_text::Span {
575 content: std::borrow::Cow::Borrowed(slice),
576 style: span.style,
577 link: span.link.clone(),
578 };
579 let w_width = w_span.width();
580 #[cfg(feature = "bidi")]
581 if ftui_text::bidi::has_rtl(slice) {
582 let tmp_line = ftui_text::Line::from_spans([w_span]);
583 let (reordered_line, reordered_width) =
584 reorder_line_bidi(&tmp_line, para_dir);
585 render_spans(reordered_line.spans(), reordered_width, y);
586 } else {
587 render_spans(std::slice::from_ref(&w_span), w_width, y);
588 }
589 #[cfg(not(feature = "bidi"))]
590 render_spans(std::slice::from_ref(&w_span), w_width, y);
591
592 y = y.saturating_add(1);
593 current_visual_line += 1;
594 }
595 }
596 } else {
597 let wrapped = self.cached_wrapped_lines(width, wrap_mode);
598 for (line, _line_width) in wrapped.lines.iter().zip(wrapped.line_widths.iter()) {
599 if current_visual_line < scroll_offset {
600 current_visual_line += 1;
601 continue;
602 }
603 if y >= text_area.bottom() {
604 break;
605 }
606 #[cfg(feature = "bidi")]
607 if line_has_rtl(line.spans()) {
608 let (reordered_line, reordered_width) = reorder_line_bidi(line, para_dir);
609 render_spans(reordered_line.spans(), reordered_width, y);
610 } else {
611 render_spans(line.spans(), *_line_width, y);
612 }
613 #[cfg(not(feature = "bidi"))]
614 render_spans(line.spans(), *_line_width, y);
615
616 y = y.saturating_add(1);
617 current_visual_line += 1;
618 }
619 }
620 } else if arena.is_some() {
621 for line in self.text.lines() {
622 if current_visual_line < scroll_offset {
623 current_visual_line += 1;
624 continue;
625 }
626 if y >= text_area.bottom() {
627 break;
628 }
629 let line_width = line.width();
630 #[cfg(feature = "bidi")]
631 if line_has_rtl(line.spans()) {
632 let (reordered_line, reordered_width) = reorder_line_bidi(line, para_dir);
633 render_spans(reordered_line.spans(), reordered_width, y);
634 } else {
635 render_spans(line.spans(), line_width, y);
636 }
637 #[cfg(not(feature = "bidi"))]
638 render_spans(line.spans(), line_width, y);
639
640 y = y.saturating_add(1);
641 current_visual_line += 1;
642 }
643 } else {
644 let metrics = self.cached_metrics(false);
645 for (line, _line_width) in self.text.lines().iter().zip(metrics.line_widths.iter()) {
646 if current_visual_line < scroll_offset {
647 current_visual_line += 1;
648 continue;
649 }
650 if y >= text_area.bottom() {
651 break;
652 }
653 #[cfg(feature = "bidi")]
654 if line_has_rtl(line.spans()) {
655 let (reordered_line, reordered_width) = reorder_line_bidi(line, para_dir);
656 render_spans(reordered_line.spans(), reordered_width, y);
657 } else {
658 render_spans(line.spans(), *_line_width, y);
659 }
660 #[cfg(not(feature = "bidi"))]
661 render_spans(line.spans(), *_line_width, y);
662
663 y = y.saturating_add(1);
664 current_visual_line += 1;
665 }
666 }
667 }
668}
669
670#[cfg(feature = "bidi")]
671#[inline]
672fn line_has_rtl(spans: &[ftui_text::Span]) -> bool {
673 spans
674 .iter()
675 .any(|s| ftui_text::bidi::has_rtl(s.content.as_ref()))
676}
677
678#[cfg(feature = "bidi")]
679fn reorder_line_bidi(
680 line: &ftui_text::Line,
681 para_dir: ftui_text::bidi::ParagraphDirection,
682) -> (ftui_text::Line<'static>, usize) {
683 let full_text: String = line.spans().iter().map(|s| s.content.as_ref()).collect();
684 if full_text.is_empty() || !ftui_text::bidi::has_rtl(&full_text) {
685 let width = line.width();
686 let spans: Vec<ftui_text::Span<'static>> = line
687 .spans()
688 .iter()
689 .cloned()
690 .map(ftui_text::Span::into_owned)
691 .collect();
692 return (ftui_text::Line::from_spans(spans), width);
693 }
694 let level = match para_dir {
700 ftui_text::bidi::ParagraphDirection::Ltr => Some(unicode_bidi::Level::ltr()),
701 ftui_text::bidi::ParagraphDirection::Rtl => Some(unicode_bidi::Level::rtl()),
702 ftui_text::bidi::ParagraphDirection::Auto => None,
703 };
704 let bidi_info = unicode_bidi::BidiInfo::new(&full_text, level);
705 let mut byte_styles: Vec<Option<Style>> = Vec::with_capacity(full_text.len());
706 for span in line.spans() {
707 byte_styles.extend(std::iter::repeat_n(span.style, span.content.len()));
708 }
709
710 let mut new_spans: Vec<ftui_text::Span<'static>> = Vec::new();
711 let mut current_str = String::new();
712 let mut current_style: Option<Style> = None;
713 let mut push_cluster = |cluster: &str, style: Option<Style>| {
714 if !current_str.is_empty() && current_style != style {
715 let text = std::mem::take(&mut current_str);
716 new_spans.push(match current_style {
717 Some(st) => ftui_text::Span::styled(text, st),
718 None => ftui_text::Span::raw(text),
719 });
720 }
721 current_style = style;
722 current_str.push_str(cluster);
723 };
724 for para in &bidi_info.paragraphs {
725 let (levels, runs) = bidi_info.visual_runs(para, para.range.clone());
726 for run in runs {
727 let run_text = &full_text[run.clone()];
728 let clusters: Vec<(usize, &str)> =
729 unicode_segmentation::UnicodeSegmentation::grapheme_indices(run_text, true)
730 .collect();
731 let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl());
732 let style_at = |off: usize| byte_styles.get(run.start + off).copied().flatten();
733 if rtl {
734 for &(off, g) in clusters.iter().rev() {
735 push_cluster(g, style_at(off));
736 }
737 } else {
738 for &(off, g) in &clusters {
739 push_cluster(g, style_at(off));
740 }
741 }
742 }
743 }
744 if !current_str.is_empty() {
745 new_spans.push(match current_style {
746 Some(st) => ftui_text::Span::styled(current_str, st),
747 None => ftui_text::Span::raw(current_str),
748 });
749 }
750 let line = ftui_text::Line::from_spans(new_spans);
751 let width = line.width();
752 (line, width)
753}
754impl MeasurableWidget for Paragraph<'_> {
755 fn measure(&self, available: Size) -> SizeConstraints {
756 let metrics = self.cached_metrics(true);
757 let text_width = metrics.text_width;
758 let text_height = metrics.text_height;
759 let min_width = match self.wrap {
766 Some(WrapMode::Char | WrapMode::WordChar) => metrics.widest_grapheme,
767 _ => metrics.min_width,
768 };
769
770 let (chrome_width, chrome_height) = self
772 .block
773 .as_ref()
774 .map(|b| b.chrome_size())
775 .unwrap_or((0, 0));
776
777 let (preferred_width, preferred_height) =
779 if self.wrap.is_some_and(|mode| mode != WrapMode::None) {
780 let wrap_width = if available.width > chrome_width {
782 (available.width - chrome_width) as usize
783 } else {
784 1
785 };
786
787 let wrapped_height = self
788 .wrap
789 .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
790 .unwrap_or(text_height);
791
792 let pref_w = text_width.min(wrap_width);
794 (pref_w, wrapped_height)
795 } else {
796 (text_width, text_height)
798 };
799
800 let min_w = u16::try_from(min_width)
802 .unwrap_or(u16::MAX)
803 .saturating_add(chrome_width);
804 let min_h = if preferred_height > 0 {
806 (1u16).saturating_add(chrome_height)
807 } else {
808 chrome_height
809 };
810
811 let pref_w = u16::try_from(preferred_width)
818 .unwrap_or(u16::MAX)
819 .saturating_add(chrome_width)
820 .max(min_w);
821 let pref_h = u16::try_from(preferred_height)
822 .unwrap_or(u16::MAX)
823 .saturating_add(chrome_height);
824
825 SizeConstraints {
826 min: Size::new(min_w, min_h),
827 preferred: Size::new(pref_w, pref_h),
828 max: None, }
830 }
831
832 fn has_intrinsic_size(&self) -> bool {
833 true
835 }
836}
837
838impl Paragraph<'_> {
839 #[cfg_attr(not(test), allow(dead_code))]
840 fn calculate_min_width(&self) -> usize {
841 self.cached_metrics(true).min_width
842 }
843
844 #[cfg_attr(not(test), allow(dead_code))]
845 fn estimate_wrapped_height(&self, wrap_width: usize) -> usize {
846 if wrap_width == 0 {
847 return self.cached_metrics(false).text_height;
848 }
849
850 self.wrap
851 .map(|wrap_mode| self.cached_wrapped_lines(wrap_width, wrap_mode).lines.len())
852 .unwrap_or_else(|| self.cached_metrics(false).text_height)
853 .max(1)
854 }
855}
856
857fn align_x(area: Rect, line_width: usize, alignment: Alignment) -> u16 {
859 let line_width_u16 = u16::try_from(line_width).unwrap_or(u16::MAX);
860 match alignment {
861 Alignment::Left => area.x,
862 Alignment::Center => area
863 .x
864 .saturating_add(area.width.saturating_sub(line_width_u16) / 2),
865 Alignment::Right => area
866 .x
867 .saturating_add(area.width.saturating_sub(line_width_u16)),
868 }
869}
870
871fn truncate_accessible_text(text: &str) -> String {
872 const ACCESSIBLE_TEXT_LIMIT: usize = 200;
873 const ACCESSIBLE_TEXT_PREFIX_LIMIT: usize = 197;
874
875 if text.chars().count() <= ACCESSIBLE_TEXT_LIMIT {
876 text.to_owned()
877 } else {
878 let mut prefix = String::new();
879 let mut prefix_chars = 0usize;
880
881 for grapheme in graphemes(text) {
882 let grapheme_chars = grapheme.chars().count();
883 if prefix_chars + grapheme_chars > ACCESSIBLE_TEXT_PREFIX_LIMIT {
884 break;
885 }
886 prefix.push_str(grapheme);
887 prefix_chars += grapheme_chars;
888 }
889
890 format!("{prefix}...")
891 }
892}
893
894impl ftui_a11y::Accessible for Paragraph<'_> {
899 fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
900 use ftui_a11y::node::{A11yNodeInfo, A11yRole};
901
902 let id = crate::a11y_node_id(area);
903
904 let name: String = self
906 .text
907 .lines()
908 .iter()
909 .map(|line| {
910 line.spans()
911 .iter()
912 .map(|span| span.content.as_ref())
913 .collect::<Vec<_>>()
914 .join("")
915 })
916 .collect::<Vec<_>>()
917 .join(" ");
918
919 let block_title = self.block.as_ref().and_then(|b| b.title_text());
920 let truncated_name = truncate_accessible_text(&name);
921
922 let mut node = A11yNodeInfo::new(id, A11yRole::Label, area);
923 if let Some(title) = block_title {
924 node = node.with_name(title);
925 if !name.is_empty() {
926 node = node.with_description(truncated_name);
927 }
928 } else if !name.is_empty() {
929 node = node.with_name(truncated_name);
930 }
931
932 vec![node]
933 }
934}
935
936#[cfg(test)]
937mod tests {
938 use super::*;
939 use ftui_render::grapheme_pool::GraphemePool;
940
941 fn raw_row_text(frame: &Frame, y: u16) -> String {
942 let width = frame.buffer.width();
943 let mut actual = String::new();
944 for x in 0..width {
945 let cell = match frame.buffer.get(x, y) {
946 Some(c) => c,
947 None => {
948 actual.push(' ');
949 continue;
950 }
951 };
952 if cell.content.is_empty() {
953 actual.push(' ');
954 } else if let Some(ch) = cell.content.as_char() {
955 actual.push(ch);
956 } else if let Some(gid) = cell.content.grapheme_id() {
957 if let Some(s) = frame.pool.get(gid) {
958 actual.push_str(s);
959 } else {
960 actual.push(' ');
961 }
962 } else {
963 actual.push(' ');
964 }
965 }
966 actual
967 }
968
969 #[test]
970 fn render_simple_text() {
971 let para = Paragraph::new(Text::raw("Hello"));
972 let area = Rect::new(0, 0, 10, 1);
973 let mut pool = GraphemePool::new();
974 let mut frame = Frame::new(10, 1, &mut pool);
975 para.render(area, &mut frame);
976
977 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
978 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('o'));
979 }
980
981 #[test]
982 fn from_static_str_preserves_rendering_without_owning_static_spans() {
983 let area = Rect::new(0, 0, 8, 2);
984
985 let fast = Paragraph::from_static_str("Hi\nthere").style(Style::new().bold());
986 let slow = Paragraph::new("Hi\nthere").style(Style::new().bold());
987
988 let mut fast_pool = GraphemePool::new();
989 let mut fast_frame = Frame::new(8, 2, &mut fast_pool);
990 fast.render(area, &mut fast_frame);
991
992 let mut slow_pool = GraphemePool::new();
993 let mut slow_frame = Frame::new(8, 2, &mut slow_pool);
994 slow.render(area, &mut slow_frame);
995
996 assert_eq!(raw_row_text(&fast_frame, 0), raw_row_text(&slow_frame, 0));
997 assert_eq!(raw_row_text(&fast_frame, 1), raw_row_text(&slow_frame, 1));
998
999 let first_span = &fast.text.lines()[0].spans()[0];
1000 match &first_span.content {
1001 std::borrow::Cow::Borrowed(text) => assert_eq!(*text, "Hi"),
1002 std::borrow::Cow::Owned(_) => panic!("static paragraph text should stay borrowed"),
1003 }
1004 }
1005
1006 #[test]
1007 fn render_multiline_text() {
1008 let para = Paragraph::new(Text::raw("AB\nCD"));
1009 let area = Rect::new(0, 0, 5, 3);
1010 let mut pool = GraphemePool::new();
1011 let mut frame = Frame::new(5, 3, &mut pool);
1012 para.render(area, &mut frame);
1013
1014 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1015 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('B'));
1016 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('C'));
1017 assert_eq!(frame.buffer.get(1, 1).unwrap().content.as_char(), Some('D'));
1018 }
1019
1020 #[test]
1021 fn render_centered_text() {
1022 let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Center);
1023 let area = Rect::new(0, 0, 10, 1);
1024 let mut pool = GraphemePool::new();
1025 let mut frame = Frame::new(10, 1, &mut pool);
1026 para.render(area, &mut frame);
1027
1028 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('H'));
1030 assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('i'));
1031 }
1032
1033 #[test]
1034 fn render_with_scroll() {
1035 let para = Paragraph::new(Text::raw("Line1\nLine2\nLine3")).scroll((1, 0));
1036 let area = Rect::new(0, 0, 10, 2);
1037 let mut pool = GraphemePool::new();
1038 let mut frame = Frame::new(10, 2, &mut pool);
1039 para.render(area, &mut frame);
1040
1041 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('L'));
1043 assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('2'));
1044 }
1045
1046 #[test]
1047 fn render_long_span_visible_prefix_at_u16_boundaries() {
1048 for width in [65_535, 65_536, 65_537, 131_072] {
1049 let content = format!("ABCDE{}", "x".repeat(width - 5));
1050 let paragraph = Paragraph::new(content);
1051 let mut pool = GraphemePool::new();
1052 let mut frame = Frame::new(7, 1, &mut pool);
1053 paragraph.render(Rect::new(1, 0, 5, 1), &mut frame);
1054
1055 assert_eq!(raw_row_text(&frame, 0), " ABCDE ", "width {width}");
1056 }
1057 }
1058
1059 #[test]
1060 fn render_long_span_at_max_horizontal_scroll() {
1061 for (tail, expected) in [
1062 ("", " "),
1063 ("A", "A "),
1064 ("ABCDE", "ABCDE "),
1065 ("ABCDEFGH", "ABCDEF"),
1066 ] {
1067 let content = format!("{}{tail}", "x".repeat(65_535));
1068 let paragraph = Paragraph::new(content).scroll((0, u16::MAX));
1069 let mut pool = GraphemePool::new();
1070 let mut frame = Frame::new(6, 1, &mut pool);
1071 paragraph.render(Rect::new(0, 0, 6, 1), &mut frame);
1072
1073 assert_eq!(raw_row_text(&frame, 0), expected, "tail {tail:?}");
1074 }
1075 }
1076
1077 #[test]
1078 fn render_max_horizontal_scroll_preserves_span_positions_and_styles() {
1079 use ftui_render::cell::PackedRgba;
1080
1081 for (prefix_width, expected, red_start, green_start) in [
1082 (65_534, " BCD ", 1, 2),
1083 (65_535, " ABCD ", 1, 3),
1084 (65_536, " xABCD ", 2, 4),
1085 ] {
1086 let paragraph = Paragraph::new(Text::from(Line::from_spans([
1087 Span::raw("x".repeat(prefix_width)),
1088 Span::styled("AB", Style::new().fg(PackedRgba::RED)),
1089 Span::styled("CD", Style::new().fg(PackedRgba::GREEN)),
1090 ])))
1091 .scroll((0, u16::MAX));
1092 let mut pool = GraphemePool::new();
1093 let mut frame = Frame::new(7, 1, &mut pool);
1094 paragraph.render(Rect::new(1, 0, 5, 1), &mut frame);
1095
1096 assert_eq!(raw_row_text(&frame, 0), expected, "prefix {prefix_width}");
1097 for x in red_start..green_start {
1098 assert_eq!(frame.buffer.get(x, 0).unwrap().fg, PackedRgba::RED);
1099 }
1100 for x in green_start..green_start + 2 {
1101 assert_eq!(frame.buffer.get(x, 0).unwrap().fg, PackedRgba::GREEN);
1102 }
1103 }
1104 }
1105
1106 #[test]
1107 fn render_long_wide_span_clips_at_viewport_edge() {
1108 let paragraph = Paragraph::new("界".repeat(32_768));
1109 let mut pool = GraphemePool::new();
1110 let mut frame = Frame::new(5, 1, &mut pool);
1111 paragraph.render(Rect::new(1, 0, 3, 1), &mut frame);
1112
1113 let wide = frame
1114 .buffer
1115 .get(1, 0)
1116 .unwrap()
1117 .content
1118 .grapheme_id()
1119 .expect("the visible whole wide grapheme must be rendered");
1120 assert_eq!(frame.pool.get(wide), Some("界"));
1121 assert!(frame.buffer.get(2, 0).unwrap().is_continuation());
1122 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some(' '));
1123 for x in [0, 4] {
1124 assert_eq!(
1125 *frame.buffer.get(x, 0).unwrap(),
1126 ftui_render::cell::Cell::default()
1127 );
1128 }
1129 }
1130
1131 #[test]
1132 fn render_max_horizontal_scroll_clips_whole_wide_graphemes() {
1133 let content = format!("{}界A界B", "x".repeat(65_535));
1134 let paragraph = Paragraph::new(content).scroll((0, u16::MAX));
1135 let mut pool = GraphemePool::new();
1136 let mut frame = Frame::new(4, 1, &mut pool);
1137 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1138
1139 let wide = frame
1140 .buffer
1141 .get(0, 0)
1142 .unwrap()
1143 .content
1144 .grapheme_id()
1145 .expect("a wide grapheme beginning at the scroll offset must remain visible");
1146 assert_eq!(frame.pool.get(wide), Some("界"));
1147 assert!(frame.buffer.get(1, 0).unwrap().is_continuation());
1148 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('A'));
1149 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some(' '));
1150
1151 let content = format!("{}界AB", "x".repeat(65_534));
1154 let paragraph = Paragraph::new(content).scroll((0, u16::MAX));
1155 let mut pool = GraphemePool::new();
1156 let mut frame = Frame::new(4, 1, &mut pool);
1157 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1158 assert_eq!(raw_row_text(&frame, 0), "AB ");
1159 }
1160
1161 #[test]
1162 fn render_empty_area() {
1163 let para = Paragraph::new(Text::raw("Hello"));
1164 let area = Rect::new(0, 0, 0, 0);
1165 let mut pool = GraphemePool::new();
1166 let mut frame = Frame::new(1, 1, &mut pool);
1167 para.render(area, &mut frame);
1168 }
1169
1170 #[test]
1171 fn line_min_width_tracks_words_across_spans() {
1172 let line = Line::from_spans([
1173 Span::raw("alpha"),
1174 Span::styled(" ", Style::new().bold()),
1175 Span::raw("beta"),
1176 Span::raw(" "),
1177 Span::raw("gamma"),
1178 ]);
1179
1180 assert_eq!(line_min_width(&line), 5);
1181 }
1182
1183 #[test]
1184 fn intrinsic_minimum_preserves_whitespace_unicode_and_span_boundaries() {
1185 let cases = [
1186 (Text::raw(""), 0),
1187 (Text::raw(" "), 3),
1188 (Text::raw(" \na"), 1),
1189 (Text::raw("e\u{301} x"), 1),
1190 (Text::raw("ab\tc"), 2),
1191 (Text::raw("a\0b\x7fc"), 3),
1192 (
1193 Text::from(Line::from_spans([
1194 Span::raw("hel"),
1195 Span::styled("lo", Style::new().bold()),
1196 ])),
1197 5,
1198 ),
1199 (
1200 Text::from(Line::from_spans([Span::raw("ab"), Span::raw("界")])),
1201 4,
1202 ),
1203 ];
1204 let area = Rect::new(0, 0, 16, 3);
1205 for (text, expected_minimum) in cases {
1206 let paragraph = Paragraph::new(text);
1207 for render_first in [true, false] {
1208 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1209 let mut pool = GraphemePool::new();
1210 let mut frame = Frame::new(area.width, area.height, &mut pool);
1211 if render_first {
1212 paragraph.render(area, &mut frame);
1213 }
1214 let measured = paragraph.measure(Size::new(area.width, area.height));
1215 assert_eq!(measured.min.width, expected_minimum, "{paragraph:?}");
1216 paragraph.render(area, &mut frame);
1217 assert_eq!(paragraph.measure(Size::new(1, 1)), measured);
1218 }
1219 }
1220 }
1221
1222 #[test]
1223 fn intrinsic_measurement_is_independent_of_render_order_and_chrome() {
1224 let paragraph = Paragraph::new("hello world").wrap(WrapMode::Word);
1225 let area = Rect::new(0, 0, 6, 2);
1226 for render_first in [true, false] {
1227 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1228 let mut pool = GraphemePool::new();
1229 let mut frame = Frame::new(6, 2, &mut pool);
1230 if render_first {
1231 paragraph.render(area, &mut frame);
1232 }
1233 let measured = paragraph.measure(Size::new(6, 2));
1234 assert_eq!(measured.min, Size::new(5, 1));
1235 assert_eq!(measured.preferred, Size::new(6, 2));
1236 paragraph.render(area, &mut frame);
1237 assert_eq!(raw_row_text(&frame, 0), "hello ");
1238 assert_eq!(raw_row_text(&frame, 1), "world ");
1239
1240 let bordered = paragraph.clone().block(Block::bordered());
1241 let measured = bordered.measure(Size::new(10, 6));
1242 assert_eq!(measured.min, Size::new(9, 5));
1243 assert_eq!(measured.preferred, Size::new(10, 6));
1244 let unwrapped = paragraph.clone().wrap(WrapMode::None);
1245 assert_eq!(
1246 unwrapped.measure(Size::new(6, 2)).preferred,
1247 Size::new(11, 1)
1248 );
1249 }
1250 }
1251
1252 #[test]
1253 fn intrinsic_minimum_survives_actual_metrics_eviction() {
1254 let original = Paragraph::new("hello world");
1255 let available = Size::new(16, 2);
1256 let area = Rect::new(0, 0, 16, 2);
1257 for measure_first in [true, false] {
1258 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1259 let mut pool = GraphemePool::new();
1260 let mut frame = Frame::new(16, 2, &mut pool);
1261 original.render(area, &mut frame);
1262 if measure_first {
1263 assert_eq!(original.measure(available).min.width, 5);
1264 }
1265 for index in 0..PARAGRAPH_METRICS_CACHE_CAPACITY {
1266 Paragraph::new(format!("entry{index} xxxx")).render(area, &mut frame);
1267 }
1268 PARAGRAPH_CACHE.with(|cache| {
1269 let cache = cache.borrow();
1270 assert_eq!(cache.metrics.len(), PARAGRAPH_METRICS_CACHE_CAPACITY);
1271 assert!(!cache.metrics.contains_key(&original.text_hash()));
1272 });
1273 let measured = original.measure(available);
1274 assert_eq!(measured.min, Size::new(5, 1));
1275 assert_eq!(measured.preferred, Size::new(11, 1));
1276 original.render(area, &mut frame);
1277 assert_eq!(raw_row_text(&frame, 0), "hello world ");
1278 }
1279 }
1280
1281 #[test]
1282 fn render_skips_min_width_scan_until_intrinsic_measure_requests_it() {
1283 let paragraph = Paragraph::new("alpha beta supercalifragilistic");
1284 let area = Rect::new(0, 0, 20, 2);
1285 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1286
1287 let mut pool = GraphemePool::new();
1288 let mut frame = Frame::new(20, 2, &mut pool);
1289 paragraph.render(area, &mut frame);
1290
1291 PARAGRAPH_CACHE.with(|cache| {
1292 let cache = cache.borrow();
1293 let entry = cache
1294 .metrics
1295 .get(¶graph.text_hash())
1296 .expect("render should populate line-width metrics");
1297 assert!(
1298 !entry.min_width_computed,
1299 "render must not compute min_width/widest_grapheme eagerly"
1300 );
1301 assert_eq!(entry.text_width, 31);
1302 });
1303
1304 let measured = paragraph.measure(Size::new(20, 2));
1305 assert_eq!(measured.min, Size::new(20, 1));
1306 assert_eq!(measured.preferred, Size::new(31, 1));
1307
1308 PARAGRAPH_CACHE.with(|cache| {
1309 let cache = cache.borrow();
1310 let entry = cache
1311 .metrics
1312 .get(¶graph.text_hash())
1313 .expect("metrics entry should remain cached");
1314 assert!(
1315 entry.min_width_computed,
1316 "measure() must lazily populate min_width on the cached entry"
1317 );
1318 assert_eq!(entry.min_width, 20);
1319 assert_eq!(entry.widest_grapheme, 1);
1320 });
1321 }
1322
1323 #[test]
1324 fn intrinsic_measurement_preserves_resolved_unicode_rendering() {
1325 let paragraph = Paragraph::new("e\u{301} 界");
1326 for render_first in [true, false] {
1327 PARAGRAPH_CACHE.with(|cache| *cache.borrow_mut() = ParagraphCacheState::default());
1328 let mut pool = GraphemePool::new();
1329 let mut frame = Frame::new(4, 1, &mut pool);
1330 if render_first {
1331 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1332 }
1333 let measured = paragraph.measure(Size::new(4, 1));
1334 assert_eq!(measured.min, Size::new(2, 1));
1335 assert_eq!(measured.preferred, Size::new(4, 1));
1336 paragraph.render(Rect::new(0, 0, 4, 1), &mut frame);
1337 let accent = frame
1338 .buffer
1339 .get(0, 0)
1340 .unwrap()
1341 .content
1342 .grapheme_id()
1343 .unwrap();
1344 assert_eq!(frame.pool.get(accent), Some("e\u{301}"));
1345 assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some(' '));
1346 let wide = frame
1347 .buffer
1348 .get(2, 0)
1349 .unwrap()
1350 .content
1351 .grapheme_id()
1352 .unwrap();
1353 assert_eq!(frame.pool.get(wide), Some("界"));
1354 assert!(frame.buffer.get(3, 0).unwrap().content.is_continuation());
1355 }
1356 }
1357
1358 #[test]
1359 fn intrinsic_width_saturates_before_adding_chrome() {
1360 for (width, expected_plain, expected_bordered) in [
1361 (65_534, 65_534, 65_535),
1362 (65_535, 65_535, 65_535),
1363 (65_536, 65_535, 65_535),
1364 (131_071, 65_535, 65_535),
1365 ] {
1366 let paragraph = Paragraph::new("x".repeat(width));
1367 let measured = paragraph.measure(Size::new(80, 24));
1368 assert_eq!(measured.min, Size::new(expected_plain, 1));
1369 assert_eq!(measured.preferred, Size::new(expected_plain, 1));
1370
1371 let bordered = paragraph.block(Block::bordered());
1372 let measured = bordered.measure(Size::new(80, 24));
1373 assert_eq!(measured.min, Size::new(expected_bordered, 5));
1374 assert_eq!(measured.preferred, Size::new(expected_bordered, 5));
1375 }
1376 }
1377
1378 #[test]
1379 fn intrinsic_height_saturates_before_adding_chrome() {
1380 for (height, expected_plain) in [(65_534, 65_534), (65_535, 65_535), (65_536, 65_535)] {
1381 let paragraph = Paragraph::new(Text::from_lines(vec![Line::raw("x"); height]));
1382 let measured = paragraph.measure(Size::new(80, 24));
1383 assert_eq!(measured.min, Size::new(1, 1));
1384 assert_eq!(measured.preferred, Size::new(1, expected_plain));
1385
1386 let bordered = paragraph.block(Block::bordered());
1387 let measured = bordered.measure(Size::new(80, 24));
1388 assert_eq!(measured.min, Size::new(5, 5));
1389 assert_eq!(measured.preferred, Size::new(5, u16::MAX));
1390 }
1391 }
1392
1393 #[test]
1394 fn intrinsic_wrapped_height_saturates_at_terminal_dimension_limit() {
1395 let paragraph = Paragraph::new("x".repeat(65_536)).wrap(WrapMode::Char);
1396 let measured = paragraph.measure(Size::new(1, 24));
1397 assert_eq!(measured.min, Size::new(1, 1));
1402 assert_eq!(measured.preferred, Size::new(1, u16::MAX));
1403
1404 let bordered = paragraph.block(Block::bordered());
1407 let measured = bordered.measure(Size::new(5, 24));
1408 assert_eq!(measured.min, Size::new(5, 5));
1409 assert_eq!(measured.preferred, Size::new(5, u16::MAX));
1410 }
1411
1412 #[test]
1413 fn measure_wrap_counts_cached_visual_lines() {
1414 let para = Paragraph::new(Text::raw("hello world from cache")).wrap(WrapMode::Word);
1415 let constraints = para.measure(Size::new(8, 10));
1416
1417 assert_eq!(constraints.preferred.height, 4);
1418 assert_eq!(constraints.min.width, 5);
1419 }
1420
1421 #[test]
1422 fn measure_wrap_none_preserves_natural_width() {
1423 let para = Paragraph::new(Text::raw("abcdef")).wrap(WrapMode::None);
1424 let constraints = para.measure(Size::new(3, 10));
1425
1426 assert_eq!(constraints.preferred.width, 6);
1427 assert_eq!(constraints.preferred.height, 1);
1428 }
1429
1430 #[test]
1431 fn render_empty_text_clears_content() {
1432 let para = Paragraph::new("");
1433 let area = Rect::new(0, 0, 3, 1);
1434 let mut pool = GraphemePool::new();
1435 let mut frame = Frame::new(3, 1, &mut pool);
1436
1437 frame
1439 .buffer
1440 .fill(area, ftui_render::cell::Cell::from_char('X'));
1441
1442 para.render(area, &mut frame);
1443
1444 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
1445 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some(' '));
1446 }
1447
1448 #[test]
1449 fn render_right_aligned() {
1450 let para = Paragraph::new(Text::raw("Hi")).alignment(Alignment::Right);
1451 let area = Rect::new(0, 0, 10, 1);
1452 let mut pool = GraphemePool::new();
1453 let mut frame = Frame::new(10, 1, &mut pool);
1454 para.render(area, &mut frame);
1455
1456 assert_eq!(frame.buffer.get(8, 0).unwrap().content.as_char(), Some('H'));
1458 assert_eq!(frame.buffer.get(9, 0).unwrap().content.as_char(), Some('i'));
1459 }
1460
1461 #[test]
1462 fn render_with_word_wrap() {
1463 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1464 let area = Rect::new(0, 0, 6, 3);
1465 let mut pool = GraphemePool::new();
1466 let mut frame = Frame::new(6, 3, &mut pool);
1467 para.render(area, &mut frame);
1468
1469 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('h'));
1471 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('w'));
1472 }
1473
1474 #[test]
1475 fn render_with_char_wrap() {
1476 let para = Paragraph::new(Text::raw("abcdefgh")).wrap(WrapMode::Char);
1477 let area = Rect::new(0, 0, 4, 3);
1478 let mut pool = GraphemePool::new();
1479 let mut frame = Frame::new(4, 3, &mut pool);
1480 para.render(area, &mut frame);
1481
1482 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
1484 assert_eq!(frame.buffer.get(3, 0).unwrap().content.as_char(), Some('d'));
1485 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
1487 }
1488
1489 #[test]
1490 fn scroll_past_all_lines() {
1491 let para = Paragraph::new(Text::raw("AB")).scroll((5, 0));
1492 let area = Rect::new(0, 0, 5, 2);
1493 let mut pool = GraphemePool::new();
1494 let mut frame = Frame::new(5, 2, &mut pool);
1495 para.render(area, &mut frame);
1496
1497 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some(' '));
1499 }
1500
1501 #[test]
1502 fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
1503 let area = Rect::new(0, 0, 8, 2);
1504 let mut pool = GraphemePool::new();
1505 let mut frame = Frame::new(8, 2, &mut pool);
1506
1507 Paragraph::new(Text::raw("Hello\nWorld")).render(area, &mut frame);
1508 Paragraph::new(Text::raw("Hi")).render(area, &mut frame);
1509
1510 assert_eq!(raw_row_text(&frame, 0), "Hi ");
1511 assert_eq!(raw_row_text(&frame, 1), " ");
1512 }
1513
1514 #[test]
1515 fn render_clipped_at_area_height() {
1516 let para = Paragraph::new(Text::raw("A\nB\nC\nD\nE"));
1517 let area = Rect::new(0, 0, 5, 2);
1518 let mut pool = GraphemePool::new();
1519 let mut frame = Frame::new(5, 2, &mut pool);
1520 para.render(area, &mut frame);
1521
1522 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1524 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('B'));
1525 }
1526
1527 #[test]
1528 fn render_clipped_at_area_width() {
1529 let para = Paragraph::new(Text::raw("ABCDEF"));
1530 let area = Rect::new(0, 0, 3, 1);
1531 let mut pool = GraphemePool::new();
1532 let mut frame = Frame::new(3, 1, &mut pool);
1533 para.render(area, &mut frame);
1534
1535 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
1536 assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('C'));
1537 }
1538
1539 #[test]
1540 fn align_x_left() {
1541 let area = Rect::new(5, 0, 20, 1);
1542 assert_eq!(align_x(area, 10, Alignment::Left), 5);
1543 }
1544
1545 #[test]
1546 fn align_x_center() {
1547 let area = Rect::new(0, 0, 20, 1);
1548 assert_eq!(align_x(area, 6, Alignment::Center), 7);
1550 }
1551
1552 #[test]
1553 fn align_x_right() {
1554 let area = Rect::new(0, 0, 20, 1);
1555 assert_eq!(align_x(area, 5, Alignment::Right), 15);
1557 }
1558
1559 #[test]
1560 fn align_x_wide_line_saturates() {
1561 let area = Rect::new(0, 0, 10, 1);
1562 assert_eq!(align_x(area, 20, Alignment::Right), 0);
1564 assert_eq!(align_x(area, 20, Alignment::Center), 0);
1565 }
1566
1567 #[test]
1568 fn builder_methods_chain() {
1569 let para = Paragraph::new(Text::raw("test"))
1570 .style(Style::default())
1571 .wrap(WrapMode::Word)
1572 .alignment(Alignment::Center)
1573 .scroll((1, 2));
1574 let area = Rect::new(0, 0, 10, 5);
1576 let mut pool = GraphemePool::new();
1577 let mut frame = Frame::new(10, 5, &mut pool);
1578 para.render(area, &mut frame);
1579 }
1580
1581 #[test]
1582 fn render_at_offset_area() {
1583 let para = Paragraph::new(Text::raw("X"));
1584 let area = Rect::new(3, 4, 5, 2);
1585 let mut pool = GraphemePool::new();
1586 let mut frame = Frame::new(10, 10, &mut pool);
1587 para.render(area, &mut frame);
1588
1589 assert_eq!(frame.buffer.get(3, 4).unwrap().content.as_char(), Some('X'));
1590 assert!(frame.buffer.get(0, 0).unwrap().is_empty());
1592 }
1593
1594 #[test]
1595 fn wrap_clipped_at_area_bottom() {
1596 let para = Paragraph::new(Text::raw("abcdefghijklmnop")).wrap(WrapMode::Char);
1598 let area = Rect::new(0, 0, 4, 2);
1599 let mut pool = GraphemePool::new();
1600 let mut frame = Frame::new(4, 2, &mut pool);
1601 para.render(area, &mut frame);
1602
1603 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
1605 assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('e'));
1606 }
1607
1608 #[test]
1611 fn degradation_skeleton_skips_content() {
1612 use ftui_render::budget::DegradationLevel;
1613
1614 let para = Paragraph::new(Text::raw("Hello"));
1615 let area = Rect::new(0, 0, 10, 1);
1616 let mut pool = GraphemePool::new();
1617 let mut frame = Frame::new(10, 1, &mut pool);
1618 Paragraph::new(Text::raw("Stale")).render(area, &mut frame);
1619 frame.set_degradation(DegradationLevel::Skeleton);
1620 para.render(area, &mut frame);
1621
1622 assert_eq!(raw_row_text(&frame, 0), " ");
1624 }
1625
1626 #[test]
1627 fn degradation_full_renders_content() {
1628 use ftui_render::budget::DegradationLevel;
1629
1630 let para = Paragraph::new(Text::raw("Hello"));
1631 let area = Rect::new(0, 0, 10, 1);
1632 let mut pool = GraphemePool::new();
1633 let mut frame = Frame::new(10, 1, &mut pool);
1634 frame.set_degradation(DegradationLevel::Full);
1635 para.render(area, &mut frame);
1636
1637 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1638 }
1639
1640 #[test]
1641 fn degradation_essential_only_still_renders_text() {
1642 use ftui_render::budget::DegradationLevel;
1643
1644 let para = Paragraph::new(Text::raw("Hello"));
1645 let area = Rect::new(0, 0, 10, 1);
1646 let mut pool = GraphemePool::new();
1647 let mut frame = Frame::new(10, 1, &mut pool);
1648 frame.set_degradation(DegradationLevel::EssentialOnly);
1649 para.render(area, &mut frame);
1650
1651 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1653 }
1654
1655 #[test]
1656 fn degradation_no_styling_ignores_span_styles() {
1657 use ftui_render::budget::DegradationLevel;
1658 use ftui_render::cell::PackedRgba;
1659 use ftui_text::{Line, Span};
1660
1661 let styled_span = Span::styled("Hello", Style::new().fg(PackedRgba::RED));
1663 let line = Line::from_spans([styled_span]);
1664 let text = Text::from(line);
1665 let para = Paragraph::new(text);
1666 let area = Rect::new(0, 0, 10, 1);
1667 let mut pool = GraphemePool::new();
1668 let mut frame = Frame::new(10, 1, &mut pool);
1669 frame.set_degradation(DegradationLevel::NoStyling);
1670 para.render(area, &mut frame);
1671
1672 assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('H'));
1674 assert_ne!(
1676 frame.buffer.get(0, 0).unwrap().fg,
1677 PackedRgba::RED,
1678 "Span fg color should be ignored at NoStyling"
1679 );
1680 }
1681
1682 use crate::MeasurableWidget;
1685 use ftui_core::geometry::Size;
1686
1687 #[test]
1688 fn measure_simple_text() {
1689 let para = Paragraph::new(Text::raw("Hello"));
1690 let constraints = para.measure(Size::MAX);
1691
1692 assert_eq!(constraints.preferred, Size::new(5, 1));
1694 assert_eq!(constraints.min.height, 1);
1695 assert_eq!(constraints.min.width, 5);
1697 }
1698
1699 #[test]
1700 fn measure_multiline_text() {
1701 let para = Paragraph::new(Text::raw("Line1\nLine22\nL3"));
1702 let constraints = para.measure(Size::MAX);
1703
1704 assert_eq!(constraints.preferred, Size::new(6, 3));
1706 assert_eq!(constraints.min.height, 1);
1707 assert_eq!(constraints.min.width, 6);
1709 }
1710
1711 #[test]
1712 fn measure_with_block() {
1713 let block = crate::block::Block::bordered();
1714 let para = Paragraph::new(Text::raw("Hi")).block(block);
1715 let constraints = para.measure(Size::MAX);
1716
1717 assert_eq!(constraints.preferred, Size::new(6, 5));
1719 assert_eq!(constraints.min.width, 6);
1720 assert_eq!(constraints.min.height, 5);
1721 }
1722
1723 #[test]
1724 fn measure_with_word_wrap() {
1725 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1726 let constraints = para.measure(Size::new(6, 10));
1728
1729 assert_eq!(constraints.preferred.height, 2);
1732 assert_eq!(constraints.min.width, 5);
1734 }
1735
1736 #[test]
1737 fn measure_empty_text() {
1738 let para = Paragraph::new(Text::raw(""));
1739 let constraints = para.measure(Size::MAX);
1740
1741 assert_eq!(constraints.preferred.width, 0);
1743 assert_eq!(constraints.preferred.height, 0);
1744 assert_eq!(constraints.min.height, 0);
1747 }
1748
1749 #[test]
1750 fn calculate_min_width_single_long_word() {
1751 let para = Paragraph::new(Text::raw("supercalifragilistic"));
1752 assert_eq!(para.calculate_min_width(), 20);
1753 }
1754
1755 #[test]
1756 fn calculate_min_width_multiple_words() {
1757 let para = Paragraph::new(Text::raw("the quick brown fox"));
1758 assert_eq!(para.calculate_min_width(), 5);
1760 }
1761
1762 #[test]
1763 fn calculate_min_width_multiline() {
1764 let para = Paragraph::new(Text::raw("short\nlongword\na"));
1765 assert_eq!(para.calculate_min_width(), 8);
1767 }
1768
1769 #[test]
1770 fn estimate_wrapped_height_no_wrap_needed() {
1771 let para = Paragraph::new(Text::raw("short")).wrap(WrapMode::Word);
1772 assert_eq!(para.estimate_wrapped_height(10), 1);
1774 }
1775
1776 #[test]
1777 fn estimate_wrapped_height_needs_wrap() {
1778 let para = Paragraph::new(Text::raw("hello world")).wrap(WrapMode::Word);
1779 assert_eq!(para.estimate_wrapped_height(6), 2);
1781 }
1782
1783 #[test]
1784 fn has_intrinsic_size() {
1785 let para = Paragraph::new(Text::raw("test"));
1786 assert!(para.has_intrinsic_size());
1787 }
1788
1789 #[test]
1790 fn measure_is_pure() {
1791 let para = Paragraph::new(Text::raw("Hello World"));
1792 let a = para.measure(Size::new(100, 50));
1793 let b = para.measure(Size::new(100, 50));
1794 assert_eq!(a, b);
1795 }
1796
1797 #[test]
1798 fn a_blocks_group_does_not_overwrite_the_paragraph_node() {
1799 use ftui_a11y::tree::A11yTreeBuilder;
1800
1801 let mut builder = A11yTreeBuilder::new();
1808 let area = Rect::new(0, 0, 40, 6);
1809 {
1810 let mut pool = GraphemePool::new();
1811 let mut frame = Frame::new(40, 6, &mut pool);
1812 frame.set_a11y(&mut builder);
1813 Paragraph::new("hello world")
1814 .block(Block::bordered().title("Notes"))
1815 .render(area, &mut frame);
1816 frame.finish_a11y();
1817 }
1818 let tree = builder.build();
1819
1820 let inventory: Vec<_> = tree
1821 .nodes()
1822 .map(|n| (n.role, n.name.clone(), n.description.clone()))
1823 .collect();
1824 assert_eq!(tree.node_count(), 1, "tree was {inventory:#?}");
1825 let node = tree.nodes().next().expect("one node");
1826 assert_ne!(
1827 node.role,
1828 ftui_a11y::node::A11yRole::Group,
1829 "the block's Group must not be what survived: {inventory:#?}"
1830 );
1831 assert_eq!(node.name.as_deref(), Some("Notes"));
1832 assert_eq!(
1833 node.description.as_deref(),
1834 Some("hello world"),
1835 "the paragraph's text must reach the tree: {inventory:#?}"
1836 );
1837 }
1838
1839 #[test]
1840 fn accessibility_truncates_long_unicode_without_panicking() {
1841 use ftui_a11y::Accessible;
1842
1843 let para = Paragraph::new(Text::raw("界".repeat(210)));
1844 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1845 let name = nodes[0]
1846 .name
1847 .as_deref()
1848 .expect("paragraph should have a name");
1849
1850 assert!(name.ends_with("..."));
1851 assert_eq!(name.chars().count(), 200);
1852 }
1853
1854 #[test]
1855 fn accessibility_truncates_description_when_block_title_present() {
1856 use ftui_a11y::Accessible;
1857
1858 let para =
1859 Paragraph::new(Text::raw("界".repeat(210))).block(Block::bordered().title("Body"));
1860 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1861 let node = &nodes[0];
1862
1863 assert_eq!(node.name.as_deref(), Some("Body"));
1864 let description = node
1865 .description
1866 .as_deref()
1867 .expect("paragraph should have a description");
1868 assert!(description.ends_with("..."));
1869 assert_eq!(description.chars().count(), 200);
1870 }
1871
1872 #[test]
1873 fn accessibility_preserves_exactly_200_chars_without_ellipsis() {
1874 use ftui_a11y::Accessible;
1875
1876 let para = Paragraph::new(Text::raw("界".repeat(200)));
1877 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1878 let name = nodes[0]
1879 .name
1880 .as_deref()
1881 .expect("paragraph should have a name");
1882
1883 assert!(!name.ends_with("..."));
1884 assert_eq!(name.chars().count(), 200);
1885 }
1886
1887 #[test]
1888 fn accessibility_truncates_on_grapheme_boundaries() {
1889 use ftui_a11y::Accessible;
1890
1891 let para = Paragraph::new(Text::raw("e\u{301}".repeat(210)));
1892 let nodes = para.accessibility_nodes(Rect::new(0, 0, 10, 1));
1893 let name = nodes[0]
1894 .name
1895 .as_deref()
1896 .expect("paragraph should have a name");
1897
1898 let prefix = name
1899 .strip_suffix("...")
1900 .expect("paragraph should be truncated");
1901 assert!(name.chars().count() <= 200);
1902 assert_eq!(ftui_text::graphemes(prefix).count(), 98);
1903 assert!(prefix.ends_with("e\u{301}"));
1904 }
1905
1906 #[test]
1907 fn paragraph_rtl_default_alignment_right() {
1908 let sample = "مرحبا بالعالم";
1909 let para = Paragraph::new(sample);
1910 let mut pool = GraphemePool::new();
1911 let mut frame = Frame::new(40, 3, &mut pool);
1912 frame.set_text_direction(ftui_render::TextDirection::Rtl);
1913 let area = Rect::new(0, 0, 40, 3);
1914 para.render(area, &mut frame);
1915
1916 let row = raw_row_text(&frame, 0);
1917 assert!(
1918 !row.ends_with(' '),
1919 "RTL frame paragraph should right-align by default: {:?}",
1920 row
1921 );
1922
1923 let para_left = Paragraph::new(sample).alignment(Alignment::Left);
1924 let mut frame_left = Frame::new(40, 3, &mut pool);
1925 frame_left.set_text_direction(ftui_render::TextDirection::Rtl);
1926 para_left.render(area, &mut frame_left);
1927
1928 let row_left = raw_row_text(&frame_left, 0);
1929 assert!(
1930 !row_left.starts_with(' '),
1931 "Explicit Alignment::Left should left-align: {:?}",
1932 row_left
1933 );
1934 }
1935
1936 #[cfg(feature = "bidi")]
1937 #[test]
1938 fn paragraph_rtl_visual_order_matches_unicode_bidi() {
1939 let corpus = [
1940 "مرحبا بكم",
1941 "السلام عليكم",
1942 "اللغة العربية جميلة",
1943 "صباح الخير",
1944 "استخدم Rust للبرمجة",
1945 "مرحبا بكم في FrankenTUI",
1946 "جرب Linux اليوم",
1947 "تطبيق Terminal جديد",
1948 "العدد هو 12345",
1949 "سعر المنتج 50 دولار",
1950 "عام 2026 الحالي",
1951 "رقم 42 هو الجواب",
1952 "هل أنت بخير؟",
1953 "نعم، بالتأكيد!",
1954 "واحد، اثنان، ثلاثة.",
1955 "مرحبا يا عالم",
1956 "שלום עולם",
1957 "עברית ו-Rust",
1958 "בוקר טוב ישראל",
1959 "מספר 100 כאן",
1960 ];
1961
1962 for sample in corpus {
1963 let para = Paragraph::new(sample).alignment(Alignment::Left);
1964 let width = 60;
1965 let mut pool = GraphemePool::new();
1966 let mut frame = Frame::new(width, 1, &mut pool);
1967 frame.set_text_direction(ftui_render::TextDirection::Rtl);
1968 let area = Rect::new(0, 0, width, 1);
1969 para.render(area, &mut frame);
1970
1971 let bidi_info = unicode_bidi::BidiInfo::new(sample, Some(unicode_bidi::Level::rtl()));
1972 let oracle_reordered =
1973 bidi_info.reorder_line(&bidi_info.paragraphs[0], 0..sample.len());
1974
1975 let row = raw_row_text(&frame, 0);
1976 let rendered_trimmed = row.trim_end();
1977 assert_eq!(
1978 rendered_trimmed,
1979 oracle_reordered.as_ref(),
1980 "Mismatch for sample {:?}: got {:?}, expected oracle {:?}",
1981 sample,
1982 rendered_trimmed,
1983 oracle_reordered
1984 );
1985 }
1986 }
1987
1988 #[cfg(feature = "bidi")]
1992 #[test]
1993 fn paragraph_rtl_reorder_keeps_grapheme_clusters_whole() {
1994 let cases = [
1995 (
1996 "\u{05E9}\u{05B8}\u{05C1}\u{05DC}\u{05D5}\u{05B9}\u{05DD}",
1997 "\u{05DD}\u{05D5}\u{05B9}\u{05DC}\u{05E9}\u{05B8}\u{05C1}",
1998 ),
1999 (
2000 "\u{0628}\u{0650}\u{0633}\u{0652}\u{0645}\u{0650}",
2001 "\u{0645}\u{0650}\u{0633}\u{0652}\u{0628}\u{0650}",
2002 ),
2003 ("a\u{0301} \u{05D0}\u{05D1}", "a\u{0301} \u{05D1}\u{05D0}"),
2004 ];
2005 for (logical, visual) in cases {
2006 for styled in [false, true] {
2007 let text = if styled {
2008 let mid = logical.char_indices().nth(1).unwrap().0;
2011 FtuiText::from_spans([
2012 Span::styled(&logical[..mid], Style::new().bold()),
2013 Span::raw(&logical[mid..]),
2014 ])
2015 } else {
2016 FtuiText::raw(logical)
2017 };
2018 let (line, width) =
2019 reorder_line_bidi(&text.lines()[0], ftui_text::bidi::ParagraphDirection::Auto);
2020 let got: String = line.spans().iter().map(|s| s.content.as_ref()).collect();
2021 assert_eq!(got, visual, "logical={logical:?} styled={styled}");
2022 assert_eq!(width, display_width(logical), "logical={logical:?}");
2023 }
2024 }
2025 }
2026
2027 #[cfg(feature = "bidi")]
2028 #[test]
2029 fn paragraph_wrap_then_reorder_per_line() {
2030 let text = "هذا نص عربي طويل جدا لتجربة تقسيم الأسطر وإعادة الترتيب بشكل مستقل لكل سطر";
2031 let width = 25;
2032 let para = Paragraph::new(text)
2033 .wrap(WrapMode::Word)
2034 .alignment(Alignment::Left);
2035 let mut pool = GraphemePool::new();
2036 let mut frame = Frame::new(width, 5, &mut pool);
2037 frame.set_text_direction(ftui_render::TextDirection::Rtl);
2038 let area = Rect::new(0, 0, width, 5);
2039 para.render(area, &mut frame);
2040
2041 let cached = para.cached_wrapped_lines(width as usize, WrapMode::Word);
2042 for (y, wrapped_line) in cached.lines.iter().take(3).enumerate() {
2043 let logical_text: String = wrapped_line
2044 .spans()
2045 .iter()
2046 .map(|s| s.content.as_ref())
2047 .collect();
2048 let expected =
2049 ftui_text::bidi::reorder(&logical_text, ftui_text::bidi::ParagraphDirection::Rtl);
2050 let row = raw_row_text(&frame, y as u16);
2051 assert_eq!(
2052 row.trim_end(),
2053 expected.as_str(),
2054 "Line {} mismatch against independently reordered wrapped line",
2055 y
2056 );
2057 }
2058 }
2059
2060 #[cfg(feature = "bidi")]
2061 proptest::proptest! {
2062 #[test]
2063 fn paragraph_ltr_text_is_unchanged_by_direction_rtl(s in "[a-zA-Z0-9 _-]{1,30}") {
2064 let area = Rect::new(0, 0, 40, 1);
2065 let mut pool = GraphemePool::new();
2066
2067 let mut ltr_frame = Frame::new(40, 1, &mut pool);
2068 ltr_frame.set_text_direction(ftui_render::TextDirection::Ltr);
2069 Paragraph::new(s.as_str()).alignment(Alignment::Left).render(area, &mut ltr_frame);
2070 let ltr_row = raw_row_text(<r_frame, 0);
2071
2072 let mut rtl_frame = Frame::new(40, 1, &mut pool);
2073 rtl_frame.set_text_direction(ftui_render::TextDirection::Rtl);
2074 Paragraph::new(s.as_str()).alignment(Alignment::Left).render(area, &mut rtl_frame);
2075 let rtl_row = raw_row_text(&rtl_frame, 0);
2076
2077 proptest::prop_assert_eq!(ltr_row.trim_end(), rtl_row.trim_end());
2078 }
2079 }
2080
2081 #[cfg(not(feature = "bidi"))]
2082 #[test]
2083 fn paragraph_rtl_without_bidi_only_aligns_right() {
2084 let sample = "مرحبا بالعالم";
2085 let para = Paragraph::new(sample);
2086 let mut pool = GraphemePool::new();
2087 let mut frame = Frame::new(40, 1, &mut pool);
2088 frame.set_text_direction(ftui_render::TextDirection::Rtl);
2089 let area = Rect::new(0, 0, 40, 1);
2090 para.render(area, &mut frame);
2091
2092 let row = raw_row_text(&frame, 0);
2093 assert!(
2094 !row.ends_with(' '),
2095 "RTL frame paragraph should right-align even without bidi feature"
2096 );
2097 assert!(row.trim().starts_with("مرحبا"));
2098 }
2099
2100 #[test]
2101 fn paragraph_uses_arena_when_present() {
2102 let text = "FrankenTUI deterministic buffer diffing and per-frame bump arena wrapping across multiple wrapped lines in an 80x24 viewport.";
2103 let para = Paragraph::new(text).wrap(WrapMode::Word);
2104 let area = Rect::new(0, 0, 28, 6);
2105
2106 let mut pool_no_arena = GraphemePool::new();
2107 let mut frame_no_arena = Frame::new(28, 6, &mut pool_no_arena);
2108 para.render(area, &mut frame_no_arena);
2109
2110 let arena = ftui_render::arena::FrameArena::new(0);
2111 let mut pool_arena = GraphemePool::new();
2112 let mut frame_arena = Frame::new(28, 6, &mut pool_arena);
2113 frame_arena.set_arena(&arena);
2114 para.render(area, &mut frame_arena);
2115
2116 assert!(
2117 arena.allocated_bytes() > 0,
2118 "Paragraph::render with WrapMode::Word must allocate in FrameArena when present"
2119 );
2120 for y in 0..6 {
2121 assert_eq!(
2122 raw_row_text(&frame_arena, y),
2123 raw_row_text(&frame_no_arena, y),
2124 "row {y} must match between arena and non-arena paragraph paths"
2125 );
2126 }
2127 }
2128}