1use std::ops::Range;
2
3use sui_core::{
4 Color, Event, KeyState, Point, PointerButton, PointerEventKind, Rect, SemanticsNode,
5 SemanticsRole, SemanticsValue, Size,
6};
7use sui_layout::{Constraints, Padding as Insets};
8use sui_runtime::{Command, EventCtx, EventPhase, MeasureCtx, PaintCtx, SemanticsCtx, Widget};
9use sui_text::{
10 PersistentTextLayout, TextCursor, TextDocument, TextLayoutRequest, TextParagraph,
11 TextSelection, TextSpan, TextStyle,
12};
13
14use crate::{DefaultTheme, SelectionClipboardBehavior, SelectionScope, TextCommand};
15
16#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct RichTextSourceSpan {
25 pub display_range: Range<usize>,
26 pub source_range: Range<usize>,
27 pub content_source_range: Range<usize>,
28}
29
30impl RichTextSourceSpan {
31 pub fn new(
32 display_range: Range<usize>,
33 source_range: Range<usize>,
34 content_source_range: Range<usize>,
35 ) -> Self {
36 Self {
37 display_range,
38 source_range,
39 content_source_range,
40 }
41 }
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
47pub struct RichTextSourceMap {
48 source: String,
49 rendered: String,
50 spans: Vec<RichTextSourceSpan>,
51}
52
53impl RichTextSourceMap {
54 pub fn new(
55 source: impl Into<String>,
56 rendered: impl Into<String>,
57 mut spans: Vec<RichTextSourceSpan>,
58 ) -> Self {
59 spans.sort_by_key(|span| (span.display_range.start, span.display_range.end));
60 Self {
61 source: source.into(),
62 rendered: rendered.into(),
63 spans,
64 }
65 }
66
67 pub fn identity(text: impl Into<String>) -> Self {
68 let text = text.into();
69 let len = text.len();
70 Self::new(
71 text.clone(),
72 text,
73 vec![RichTextSourceSpan::new(0..len, 0..len, 0..len)],
74 )
75 }
76
77 pub fn source(&self) -> &str {
78 &self.source
79 }
80
81 pub fn rendered(&self) -> &str {
82 &self.rendered
83 }
84
85 pub fn spans(&self) -> &[RichTextSourceSpan] {
86 &self.spans
87 }
88
89 pub fn copy_range(&self, range: Range<usize>) -> String {
91 let range = normalized_range(range, self.rendered.len());
92 if range.is_empty() {
93 return String::new();
94 }
95
96 let Some(first) = self
97 .spans
98 .iter()
99 .find(|span| ranges_overlap(&span.display_range, &range))
100 else {
101 return self.rendered.get(range).unwrap_or_default().to_string();
102 };
103 let last = self
104 .spans
105 .iter()
106 .rev()
107 .find(|span| ranges_overlap(&span.display_range, &range))
108 .unwrap_or(first);
109
110 let start = self.source_boundary(first, range.start, false);
111 let end = self.source_boundary(last, range.end, true);
112 self.source
113 .get(start.min(end)..end.max(start))
114 .unwrap_or_default()
115 .to_string()
116 }
117
118 fn source_boundary(&self, span: &RichTextSourceSpan, offset: usize, end: bool) -> usize {
119 let display = clamp_range(&span.display_range, self.rendered.len());
120 let source = clamp_range(&span.source_range, self.source.len());
121 let content = clamp_range(&span.content_source_range, self.source.len());
122 if offset <= display.start {
123 return if end { content.start } else { source.start };
124 }
125 if offset >= display.end {
126 return if end { source.end } else { content.end };
127 }
128
129 let display_text = self.rendered.get(display.clone()).unwrap_or_default();
130 let content_text = self.source.get(content.clone()).unwrap_or_default();
131 let relative = offset.saturating_sub(display.start).min(display.len());
132 let char_index = display_text
133 .get(..relative)
134 .map(str::chars)
135 .map(Iterator::count)
136 .unwrap_or(0);
137 content.start + nth_char_boundary(content_text, char_index)
138 }
139}
140
141fn normalized_range(range: Range<usize>, len: usize) -> Range<usize> {
142 let start = range.start.min(len);
143 let end = range.end.min(len);
144 start.min(end)..start.max(end)
145}
146
147fn clamp_range(range: &Range<usize>, len: usize) -> Range<usize> {
148 normalized_range(range.clone(), len)
149}
150
151fn ranges_overlap(left: &Range<usize>, right: &Range<usize>) -> bool {
152 left.start < right.end && right.start < left.end
153}
154
155fn nth_char_boundary(text: &str, index: usize) -> usize {
156 text.char_indices()
157 .map(|(offset, _)| offset)
158 .nth(index)
159 .unwrap_or(text.len())
160}
161
162pub struct RichText {
163 document: TextDocument,
164 document_reader: Option<Box<dyn Fn() -> TextDocument>>,
165 semantic_name: Option<String>,
166 padding: Insets,
167 min_width: f32,
168 min_height: f32,
169 layout: Option<PersistentTextLayout>,
170 selection_scope: Option<SelectionScope>,
171 clipboard_behavior: SelectionClipboardBehavior,
172 source_map: Option<RichTextSourceMap>,
173 selection: TextSelection,
174 selection_color: Color,
175 dragging_selection: bool,
176}
177
178impl RichText {
179 pub fn new(document: TextDocument) -> Self {
180 Self {
181 document,
182 document_reader: None,
183 semantic_name: None,
184 padding: Insets::ZERO,
185 min_width: 0.0,
186 min_height: 0.0,
187 layout: None,
188 selection_scope: None,
189 clipboard_behavior: SelectionClipboardBehavior::AppManaged,
190 source_map: None,
191 selection: TextSelection::new(TextCursor::default(), TextCursor::default()),
192 selection_color: Color::rgba(0.18, 0.62, 0.86, 0.32),
193 dragging_selection: false,
194 }
195 }
196
197 pub fn dynamic<F>(fallback: TextDocument, reader: F) -> Self
198 where
199 F: Fn() -> TextDocument + 'static,
200 {
201 Self::new(fallback).document_when(reader)
202 }
203
204 pub fn plain(text: impl Into<String>) -> Self {
205 Self::from_plain_text(text, DefaultTheme::default().body_text_style())
206 }
207
208 pub fn from_plain_text(text: impl Into<String>, style: TextStyle) -> Self {
209 Self::new(TextDocument::from_plain_text(text, style))
210 }
211
212 pub fn from_spans(spans: Vec<TextSpan>) -> Self {
213 Self::new(TextDocument {
214 paragraphs: vec![TextParagraph::from_spans(spans)],
215 })
216 }
217
218 pub fn document(&self) -> &TextDocument {
219 &self.document
220 }
221
222 pub fn set_document(&mut self, document: TextDocument) {
223 self.document = document;
224 self.document_reader = None;
225 self.layout = None;
226 self.source_map = None;
227 self.selection = TextSelection::new(TextCursor::default(), TextCursor::default());
228 self.dragging_selection = false;
229 }
230
231 pub fn document_when<F>(mut self, reader: F) -> Self
232 where
233 F: Fn() -> TextDocument + 'static,
234 {
235 self.document_reader = Some(Box::new(reader));
236 self
237 }
238
239 pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
240 self.semantic_name = Some(name.into());
241 self
242 }
243
244 pub fn padding(mut self, padding: Insets) -> Self {
245 self.padding = padding;
246 self
247 }
248
249 pub fn min_width(mut self, width: f32) -> Self {
250 self.min_width = width.max(0.0);
251 self
252 }
253
254 pub fn min_height(mut self, height: f32) -> Self {
255 self.min_height = height.max(0.0);
256 self
257 }
258
259 pub fn selectable(mut self, scope: SelectionScope) -> Self {
261 self.selection_scope = Some(scope);
262 self
263 }
264
265 pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
266 self.clipboard_behavior = behavior;
267 self
268 }
269
270 pub fn copy_to_clipboard(self, enabled: bool) -> Self {
271 self.clipboard_behavior(if enabled {
272 SelectionClipboardBehavior::WidgetManaged
273 } else {
274 SelectionClipboardBehavior::AppManaged
275 })
276 }
277
278 pub fn source_map(mut self, source_map: RichTextSourceMap) -> Self {
280 self.source_map = Some(source_map);
281 self
282 }
283
284 pub fn selection_color(mut self, color: Color) -> Self {
285 self.selection_color = color;
286 self
287 }
288
289 fn current_document(&self) -> TextDocument {
290 self.document_reader
291 .as_ref()
292 .map(|reader| reader())
293 .unwrap_or_else(|| self.document.clone())
294 }
295
296 fn content_constraints(&self, constraints: Constraints) -> Constraints {
297 Constraints::new(
298 self.padding.inset(constraints.min),
299 self.padding.inset(constraints.max),
300 )
301 }
302
303 fn layout_request(
304 &self,
305 document: TextDocument,
306 content_constraints: Constraints,
307 ) -> TextLayoutRequest {
308 let max_width = content_constraints.max.width;
309 if max_width.is_finite() {
310 TextLayoutRequest::new(document).with_box_size(Size::new(max_width.max(1.0), 1.0))
311 } else {
312 TextLayoutRequest::new(document)
313 }
314 }
315
316 fn content_rect(&self, bounds: Rect) -> Rect {
317 Rect::new(
318 bounds.x() + self.padding.left,
319 bounds.y() + self.padding.top,
320 (bounds.width() - (self.padding.left + self.padding.right)).max(0.0),
321 (bounds.height() - (self.padding.top + self.padding.bottom)).max(0.0),
322 )
323 }
324
325 fn padded_size(&self, content_size: Size) -> Size {
326 Size::new(
327 (content_size.width + self.padding.left + self.padding.right).max(self.min_width),
328 (content_size.height + self.padding.top + self.padding.bottom).max(self.min_height),
329 )
330 }
331
332 fn text(&self) -> String {
333 self.current_document().plain_text()
334 }
335
336 fn selection_range(&self, text_len: usize) -> Range<usize> {
337 normalized_range(
338 self.selection.anchor.utf8_offset..self.selection.focus.utf8_offset,
339 text_len,
340 )
341 }
342
343 fn selected_text(&self, text: &str) -> String {
344 let range = self.selection_range(text.len());
345 if range.is_empty() {
346 return String::new();
347 }
348 self.source_map
349 .as_ref()
350 .map(|map| map.copy_range(range.clone()))
351 .unwrap_or_else(|| text.get(range).unwrap_or_default().to_string())
352 }
353
354 fn layout_origin(&self, bounds: Rect) -> Option<Point> {
355 let layout = self.layout.as_ref()?;
356 let content = self.content_rect(bounds);
357 let layout_bounds = layout.measurement().bounds;
358 Some(Point::new(content.x() - layout_bounds.x(), content.y()))
359 }
360
361 fn point_to_cursor(&self, bounds: Rect, point: Point) -> Option<TextCursor> {
362 let layout = self.layout.as_ref()?;
363 let origin = self.layout_origin(bounds)?;
364 Some(layout.hit_test_point(Point::new(point.x - origin.x, point.y - origin.y)))
365 }
366
367 fn publish_selection(&self, ctx: &mut EventCtx, text: &str) {
368 let Some(scope) = &self.selection_scope else {
369 return;
370 };
371 let owner = ctx.widget_id();
372 let range = self.selection_range(text.len());
373 let selected = self.selected_text(text);
374 if range.is_empty() || selected.is_empty() {
375 scope.clear_owner(owner);
376 } else {
377 scope.replace_text(owner, owner, range, text.len(), selected);
378 }
379 ctx.request_semantics();
380 }
381
382 fn set_selection(&mut self, ctx: &mut EventCtx, anchor: usize, focus: usize) {
383 let text = self.text();
384 let anchor = anchor.min(text.len());
385 let focus = focus.min(text.len());
386 let next = TextSelection::new(TextCursor::new(anchor), TextCursor::new(focus));
387 if self.selection == next {
388 return;
389 }
390 self.selection = next;
391 self.publish_selection(ctx, &text);
392 ctx.request_paint();
393 }
394
395 fn copy_selection(&self, ctx: &mut EventCtx) -> bool {
396 let selected = self.selected_text(&self.text());
397 if selected.is_empty() {
398 return false;
399 }
400 ctx.set_clipboard_text(selected);
401 true
402 }
403
404 fn handles_implicit_clipboard(&self) -> bool {
405 self.clipboard_behavior.is_widget_managed()
406 }
407}
408
409impl Default for RichText {
410 fn default() -> Self {
411 Self::plain("")
412 }
413}
414
415impl Widget for RichText {
416 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
417 if self.selection_scope.is_none() {
418 return;
419 }
420 match event {
421 Event::Pointer(pointer)
422 if pointer.kind == PointerEventKind::Down
423 && pointer.button == Some(PointerButton::Primary)
424 && ctx.phase() != EventPhase::Capture
425 && ctx.bounds().contains(pointer.position) =>
426 {
427 if let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position) {
428 let anchor = if pointer.modifiers.shift {
429 self.selection.anchor.utf8_offset
430 } else {
431 cursor.utf8_offset
432 };
433 self.set_selection(ctx, anchor, cursor.utf8_offset);
434 self.dragging_selection = true;
435 ctx.request_focus();
436 ctx.request_pointer_capture(pointer.pointer_id);
437 ctx.set_handled();
438 }
439 }
440 Event::Pointer(pointer)
441 if pointer.kind == PointerEventKind::Move
442 && self.dragging_selection
443 && ctx.phase() != EventPhase::Capture
444 && pointer.buttons.contains(PointerButton::Primary) =>
445 {
446 if let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position) {
447 self.set_selection(ctx, self.selection.anchor.utf8_offset, cursor.utf8_offset);
448 ctx.set_handled();
449 }
450 }
451 Event::Pointer(pointer)
452 if pointer.kind == PointerEventKind::Up
453 && pointer.button == Some(PointerButton::Primary)
454 && self.dragging_selection =>
455 {
456 self.dragging_selection = false;
457 ctx.release_pointer_capture(pointer.pointer_id);
458 ctx.set_handled();
459 }
460 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
461 if self.dragging_selection {
462 self.dragging_selection = false;
463 ctx.release_pointer_capture(pointer.pointer_id);
464 ctx.set_handled();
465 }
466 }
467 Event::Pointer(pointer)
468 if pointer.kind == PointerEventKind::Down
469 && pointer.button == Some(PointerButton::Secondary)
470 && ctx.phase() != EventPhase::Capture
471 && ctx.bounds().contains(pointer.position) =>
472 {
473 ctx.request_focus();
474 }
475 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
476 let command = key.modifiers.control || key.modifiers.meta;
477 match key.key.as_str() {
478 "a" | "A" if command => {
479 let len = self.text().len();
480 self.set_selection(ctx, 0, len);
481 ctx.set_handled();
482 }
483 "c" | "C" if command && self.handles_implicit_clipboard() => {
484 if self.copy_selection(ctx) {
485 ctx.set_handled();
486 }
487 }
488 "Escape" => {
489 self.set_selection(ctx, 0, 0);
490 ctx.set_handled();
491 }
492 _ => {}
493 }
494 }
495 _ => {}
496 }
497 }
498
499 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
500 let Some(command) = TextCommand::from_command(command) else {
501 return;
502 };
503 match command {
504 TextCommand::Copy => {
505 if self.copy_selection(ctx) {
506 ctx.set_handled();
507 }
508 }
509 TextCommand::SelectAll => {
510 let len = self.text().len();
511 self.set_selection(ctx, 0, len);
512 ctx.set_handled();
513 }
514 TextCommand::Cut | TextCommand::Paste => {}
515 }
516 }
517
518 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
519 let document = self.current_document();
520 let content_constraints = self.content_constraints(constraints);
521 let request = self.layout_request(document, content_constraints);
522 let handle = self.layout.as_ref().map(|layout| layout.handle());
523 self.layout = ctx
524 .layout()
525 .layout_document_persistent(handle, request)
526 .ok();
527
528 let content_size = self
529 .layout
530 .as_ref()
531 .map(|layout| {
532 let measurement = layout.measurement();
533 Size::new(measurement.width.max(0.0), measurement.height.max(0.0))
534 })
535 .unwrap_or(Size::ZERO);
536
537 constraints.clamp(self.padded_size(content_size))
538 }
539
540 fn paint(&self, ctx: &mut PaintCtx) {
541 let Some(layout) = &self.layout else {
542 return;
543 };
544 let Some(origin) = self.layout_origin(ctx.bounds()) else {
545 return;
546 };
547 let text_len = layout.text().len();
548 let selection = self.selection_range(text_len);
549 if !selection.is_empty() {
550 for rect in layout.selection_rects(selection) {
551 ctx.fill_rect(
552 Rect::new(
553 origin.x + rect.x(),
554 origin.y + rect.y(),
555 rect.width(),
556 rect.height(),
557 ),
558 self.selection_color,
559 );
560 }
561 }
562 ctx.draw_persistent_text_layout(origin, layout);
563 }
564
565 fn accepts_focus(&self) -> bool {
566 self.selection_scope.is_some()
567 }
568
569 fn semantics(&self, ctx: &mut SemanticsCtx) {
570 let text = self.current_document().plain_text();
571 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
572 node.name = Some(self.semantic_name.clone().unwrap_or_else(|| text.clone()));
573 if self.semantic_name.is_some() {
574 node.value = Some(SemanticsValue::Text(text));
575 }
576 ctx.push(node);
577 }
578}
579
580#[cfg(test)]
581mod tests {
582 use super::{RichText, RichTextSourceMap, RichTextSourceSpan};
583 use crate::SizedBox;
584 use sui_core::{Color, SemanticsRole, SemanticsValue};
585 use sui_runtime::{Application, RenderOutput, Widget, WindowBuilder};
586 use sui_scene::SceneCommand;
587 use sui_text::{FontStyle, FontWeight, TextDocument, TextParagraph, TextSpan, TextStyle};
588
589 fn render<W>(root: W) -> RenderOutput
590 where
591 W: Widget + 'static,
592 {
593 let mut runtime = Application::new()
594 .window(WindowBuilder::new().title("Rich text").root(root))
595 .build()
596 .unwrap();
597 let window_id = runtime.window_ids()[0];
598 runtime.render(window_id).unwrap()
599 }
600
601 fn two_span_document() -> TextDocument {
602 let mut strong = TextStyle::new(Color::rgba(0.84, 0.16, 0.18, 1.0));
603 strong.weight = FontWeight::BOLD;
604 let mut emphasis = TextStyle::new(Color::rgba(0.10, 0.38, 0.82, 1.0));
605 emphasis.style = FontStyle::Italic;
606 TextDocument {
607 paragraphs: vec![TextParagraph::from_spans(vec![
608 TextSpan::new("Warm", strong),
609 TextSpan::new(" cool", emphasis),
610 ])],
611 }
612 }
613
614 #[test]
615 fn rich_text_paints_document_spans_without_color_override() {
616 let output = render(RichText::new(two_span_document()));
617 let mut shaped = None;
618 output.frame.scene.visit_commands(&mut |command| {
619 if let SceneCommand::DrawShapedText(text) = command {
620 shaped = Some(text.clone());
621 }
622 });
623 let shaped = shaped.expect("rich text should emit shaped text");
624 assert_eq!(shaped.color_override, None);
625
626 let layout = shaped
627 .resolve(output.frame.text_layout_registry.as_ref())
628 .expect("rich text layout should resolve");
629 assert_eq!(layout.text(), "Warm cool");
630 assert_eq!(layout.runs().len(), 2);
631 assert_eq!(layout.run_style(0).weight, FontWeight::BOLD);
632 assert_eq!(layout.run_style(1).style, FontStyle::Italic);
633 assert_ne!(layout.run_style(0).color, layout.run_style(1).color);
634 }
635
636 #[test]
637 fn rich_text_exposes_plain_text_semantics_for_named_document() {
638 let document = TextDocument {
639 paragraphs: vec![
640 TextParagraph::new("First", TextStyle::new(Color::WHITE)),
641 TextParagraph::new("Second", TextStyle::new(Color::WHITE)),
642 ],
643 };
644 let output = render(RichText::new(document).semantic_name("Summary"));
645 let node = output
646 .semantics
647 .iter()
648 .find(|node| node.role == SemanticsRole::Text)
649 .expect("rich text should expose text semantics");
650
651 assert_eq!(node.name.as_deref(), Some("Summary"));
652 assert_eq!(
653 node.value,
654 Some(SemanticsValue::Text("First\nSecond".to_string()))
655 );
656 }
657
658 #[test]
659 fn rich_text_wraps_to_parent_constraints() {
660 let output = render(
661 SizedBox::new()
662 .width(96.0)
663 .with_child(RichText::from_plain_text(
664 "alpha beta gamma delta epsilon",
665 TextStyle::new(Color::WHITE),
666 )),
667 );
668 let mut line_count = 0;
669 output.frame.scene.visit_commands(&mut |command| {
670 if let SceneCommand::DrawShapedText(text) = command
671 && let Some(layout) = text.resolve(output.frame.text_layout_registry.as_ref())
672 {
673 line_count = layout.lines().len();
674 }
675 });
676
677 assert!(line_count > 1, "expected constrained rich text to wrap");
678 }
679
680 #[test]
681 fn source_map_copies_complete_markdown_syntax_and_partial_content() {
682 let source = "Use **strong** and `code`.";
683 let rendered = "Use strong and code.";
684 let map = RichTextSourceMap::new(
685 source,
686 rendered,
687 vec![
688 RichTextSourceSpan::new(0..4, 0..4, 0..4),
689 RichTextSourceSpan::new(4..10, 4..14, 6..12),
690 RichTextSourceSpan::new(10..15, 14..19, 14..19),
691 RichTextSourceSpan::new(15..19, 19..25, 20..24),
692 RichTextSourceSpan::new(19..20, 25..26, 25..26),
693 ],
694 );
695
696 assert_eq!(map.copy_range(4..10), "**strong**");
697 assert_eq!(map.copy_range(6..9), "ron");
698 assert_eq!(map.copy_range(15..19), "`code`");
699 assert_eq!(map.copy_range(4..19), "**strong** and `code`");
700 }
701}