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 plain(text: impl Into<String>) -> Self {
198 Self::from_plain_text(text, DefaultTheme::default().body_text_style())
199 }
200
201 pub fn from_plain_text(text: impl Into<String>, style: TextStyle) -> Self {
202 Self::new(TextDocument::from_plain_text(text, style))
203 }
204
205 pub fn from_spans(spans: Vec<TextSpan>) -> Self {
206 Self::new(TextDocument {
207 paragraphs: vec![TextParagraph::from_spans(spans)],
208 })
209 }
210
211 pub fn document(&self) -> &TextDocument {
212 &self.document
213 }
214
215 pub fn set_document(&mut self, document: TextDocument) {
216 self.document = document;
217 self.document_reader = None;
218 self.layout = None;
219 self.source_map = None;
220 self.selection = TextSelection::new(TextCursor::default(), TextCursor::default());
221 self.dragging_selection = false;
222 }
223
224 pub fn document_when<F>(mut self, reader: F) -> Self
225 where
226 F: Fn() -> TextDocument + 'static,
227 {
228 self.document_reader = Some(Box::new(reader));
229 self
230 }
231
232 pub fn semantic_name(mut self, name: impl Into<String>) -> Self {
233 self.semantic_name = Some(name.into());
234 self
235 }
236
237 pub fn padding(mut self, padding: Insets) -> Self {
238 self.padding = padding;
239 self
240 }
241
242 pub fn min_width(mut self, width: f32) -> Self {
243 self.min_width = width.max(0.0);
244 self
245 }
246
247 pub fn min_height(mut self, height: f32) -> Self {
248 self.min_height = height.max(0.0);
249 self
250 }
251
252 pub fn selectable(mut self, scope: SelectionScope) -> Self {
254 self.selection_scope = Some(scope);
255 self
256 }
257
258 pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
259 self.clipboard_behavior = behavior;
260 self
261 }
262
263 pub fn copy_to_clipboard(self, enabled: bool) -> Self {
264 self.clipboard_behavior(if enabled {
265 SelectionClipboardBehavior::WidgetManaged
266 } else {
267 SelectionClipboardBehavior::AppManaged
268 })
269 }
270
271 pub fn source_map(mut self, source_map: RichTextSourceMap) -> Self {
273 self.source_map = Some(source_map);
274 self
275 }
276
277 pub fn selection_color(mut self, color: Color) -> Self {
278 self.selection_color = color;
279 self
280 }
281
282 fn current_document(&self) -> TextDocument {
283 self.document_reader
284 .as_ref()
285 .map(|reader| reader())
286 .unwrap_or_else(|| self.document.clone())
287 }
288
289 fn content_constraints(&self, constraints: Constraints) -> Constraints {
290 Constraints::new(
291 self.padding.inset(constraints.min),
292 self.padding.inset(constraints.max),
293 )
294 }
295
296 fn layout_request(
297 &self,
298 document: TextDocument,
299 content_constraints: Constraints,
300 ) -> TextLayoutRequest {
301 let max_width = content_constraints.max.width;
302 if max_width.is_finite() {
303 TextLayoutRequest::new(document).with_box_size(Size::new(max_width.max(1.0), 1.0))
304 } else {
305 TextLayoutRequest::new(document)
306 }
307 }
308
309 fn content_rect(&self, bounds: Rect) -> Rect {
310 Rect::new(
311 bounds.x() + self.padding.left,
312 bounds.y() + self.padding.top,
313 (bounds.width() - (self.padding.left + self.padding.right)).max(0.0),
314 (bounds.height() - (self.padding.top + self.padding.bottom)).max(0.0),
315 )
316 }
317
318 fn padded_size(&self, content_size: Size) -> Size {
319 Size::new(
320 (content_size.width + self.padding.left + self.padding.right).max(self.min_width),
321 (content_size.height + self.padding.top + self.padding.bottom).max(self.min_height),
322 )
323 }
324
325 fn text(&self) -> String {
326 self.current_document().plain_text()
327 }
328
329 fn selection_range(&self, text_len: usize) -> Range<usize> {
330 normalized_range(
331 self.selection.anchor.utf8_offset..self.selection.focus.utf8_offset,
332 text_len,
333 )
334 }
335
336 fn selected_text(&self, text: &str) -> String {
337 let range = self.selection_range(text.len());
338 if range.is_empty() {
339 return String::new();
340 }
341 self.source_map
342 .as_ref()
343 .map(|map| map.copy_range(range.clone()))
344 .unwrap_or_else(|| text.get(range).unwrap_or_default().to_string())
345 }
346
347 fn layout_origin(&self, bounds: Rect) -> Option<Point> {
348 let layout = self.layout.as_ref()?;
349 let content = self.content_rect(bounds);
350 let layout_bounds = layout.measurement().bounds;
351 Some(Point::new(content.x() - layout_bounds.x(), content.y()))
352 }
353
354 fn point_to_cursor(&self, bounds: Rect, point: Point) -> Option<TextCursor> {
355 let layout = self.layout.as_ref()?;
356 let origin = self.layout_origin(bounds)?;
357 Some(layout.hit_test_point(Point::new(point.x - origin.x, point.y - origin.y)))
358 }
359
360 fn publish_selection(&self, ctx: &mut EventCtx, text: &str) {
361 let Some(scope) = &self.selection_scope else {
362 return;
363 };
364 let owner = ctx.widget_id();
365 let range = self.selection_range(text.len());
366 let selected = self.selected_text(text);
367 if range.is_empty() || selected.is_empty() {
368 scope.clear_owner(owner);
369 } else {
370 scope.replace_text(owner, owner, range, text.len(), selected);
371 }
372 ctx.request_semantics();
373 }
374
375 fn set_selection(&mut self, ctx: &mut EventCtx, anchor: usize, focus: usize) {
376 let text = self.text();
377 let anchor = anchor.min(text.len());
378 let focus = focus.min(text.len());
379 let next = TextSelection::new(TextCursor::new(anchor), TextCursor::new(focus));
380 if self.selection == next {
381 return;
382 }
383 self.selection = next;
384 self.publish_selection(ctx, &text);
385 ctx.request_paint();
386 }
387
388 fn copy_selection(&self, ctx: &mut EventCtx) -> bool {
389 let selected = self.selected_text(&self.text());
390 if selected.is_empty() {
391 return false;
392 }
393 ctx.set_clipboard_text(selected);
394 true
395 }
396
397 fn handles_implicit_clipboard(&self) -> bool {
398 self.clipboard_behavior.is_widget_managed()
399 }
400}
401
402impl Default for RichText {
403 fn default() -> Self {
404 Self::plain("")
405 }
406}
407
408impl Widget for RichText {
409 fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
410 if self.selection_scope.is_none() {
411 return;
412 }
413 match event {
414 Event::Pointer(pointer)
415 if pointer.kind == PointerEventKind::Down
416 && pointer.button == Some(PointerButton::Primary)
417 && ctx.phase() != EventPhase::Capture
418 && ctx.bounds().contains(pointer.position) =>
419 {
420 if let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position) {
421 let anchor = if pointer.modifiers.shift {
422 self.selection.anchor.utf8_offset
423 } else {
424 cursor.utf8_offset
425 };
426 self.set_selection(ctx, anchor, cursor.utf8_offset);
427 self.dragging_selection = true;
428 ctx.request_focus();
429 ctx.request_pointer_capture(pointer.pointer_id);
430 ctx.set_handled();
431 }
432 }
433 Event::Pointer(pointer)
434 if pointer.kind == PointerEventKind::Move
435 && self.dragging_selection
436 && ctx.phase() != EventPhase::Capture
437 && pointer.buttons.contains(PointerButton::Primary) =>
438 {
439 if let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position) {
440 self.set_selection(ctx, self.selection.anchor.utf8_offset, cursor.utf8_offset);
441 ctx.set_handled();
442 }
443 }
444 Event::Pointer(pointer)
445 if pointer.kind == PointerEventKind::Up
446 && pointer.button == Some(PointerButton::Primary)
447 && self.dragging_selection =>
448 {
449 self.dragging_selection = false;
450 ctx.release_pointer_capture(pointer.pointer_id);
451 ctx.set_handled();
452 }
453 Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
454 if self.dragging_selection {
455 self.dragging_selection = false;
456 ctx.release_pointer_capture(pointer.pointer_id);
457 ctx.set_handled();
458 }
459 }
460 Event::Pointer(pointer)
461 if pointer.kind == PointerEventKind::Down
462 && pointer.button == Some(PointerButton::Secondary)
463 && ctx.phase() != EventPhase::Capture
464 && ctx.bounds().contains(pointer.position) =>
465 {
466 ctx.request_focus();
467 }
468 Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
469 let command = key.modifiers.control || key.modifiers.meta;
470 match key.key.as_str() {
471 "a" | "A" if command => {
472 let len = self.text().len();
473 self.set_selection(ctx, 0, len);
474 ctx.set_handled();
475 }
476 "c" | "C" if command && self.handles_implicit_clipboard() => {
477 if self.copy_selection(ctx) {
478 ctx.set_handled();
479 }
480 }
481 "Escape" => {
482 self.set_selection(ctx, 0, 0);
483 ctx.set_handled();
484 }
485 _ => {}
486 }
487 }
488 _ => {}
489 }
490 }
491
492 fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
493 let Some(command) = TextCommand::from_command(command) else {
494 return;
495 };
496 match command {
497 TextCommand::Copy => {
498 if self.copy_selection(ctx) {
499 ctx.set_handled();
500 }
501 }
502 TextCommand::SelectAll => {
503 let len = self.text().len();
504 self.set_selection(ctx, 0, len);
505 ctx.set_handled();
506 }
507 TextCommand::Cut | TextCommand::Paste => {}
508 }
509 }
510
511 fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
512 let document = self.current_document();
513 let content_constraints = self.content_constraints(constraints);
514 let request = self.layout_request(document, content_constraints);
515 let handle = self.layout.as_ref().map(|layout| layout.handle());
516 self.layout = ctx
517 .layout()
518 .layout_document_persistent(handle, request)
519 .ok();
520
521 let content_size = self
522 .layout
523 .as_ref()
524 .map(|layout| {
525 let measurement = layout.measurement();
526 Size::new(measurement.width.max(0.0), measurement.height.max(0.0))
527 })
528 .unwrap_or(Size::ZERO);
529
530 constraints.clamp(self.padded_size(content_size))
531 }
532
533 fn paint(&self, ctx: &mut PaintCtx) {
534 let Some(layout) = &self.layout else {
535 return;
536 };
537 let Some(origin) = self.layout_origin(ctx.bounds()) else {
538 return;
539 };
540 let text_len = layout.text().len();
541 let selection = self.selection_range(text_len);
542 if !selection.is_empty() {
543 for rect in layout.selection_rects(selection) {
544 ctx.fill_rect(
545 Rect::new(
546 origin.x + rect.x(),
547 origin.y + rect.y(),
548 rect.width(),
549 rect.height(),
550 ),
551 self.selection_color,
552 );
553 }
554 }
555 ctx.draw_persistent_text_layout(origin, layout);
556 }
557
558 fn accepts_focus(&self) -> bool {
559 self.selection_scope.is_some()
560 }
561
562 fn semantics(&self, ctx: &mut SemanticsCtx) {
563 let text = self.current_document().plain_text();
564 let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::Text, ctx.bounds());
565 node.name = Some(self.semantic_name.clone().unwrap_or_else(|| text.clone()));
566 if self.semantic_name.is_some() {
567 node.value = Some(SemanticsValue::Text(text));
568 }
569 ctx.push(node);
570 }
571}
572
573#[cfg(test)]
574mod tests {
575 use super::{RichText, RichTextSourceMap, RichTextSourceSpan};
576 use crate::SizedBox;
577 use sui_core::{Color, SemanticsRole, SemanticsValue};
578 use sui_runtime::{Application, RenderOutput, Widget, WindowBuilder};
579 use sui_scene::SceneCommand;
580 use sui_text::{FontStyle, FontWeight, TextDocument, TextParagraph, TextSpan, TextStyle};
581
582 fn render<W>(root: W) -> RenderOutput
583 where
584 W: Widget + 'static,
585 {
586 let mut runtime = Application::new()
587 .window(WindowBuilder::new().title("Rich text").root(root))
588 .build()
589 .unwrap();
590 let window_id = runtime.window_ids()[0];
591 runtime.render(window_id).unwrap()
592 }
593
594 fn two_span_document() -> TextDocument {
595 let mut strong = TextStyle::new(Color::rgba(0.84, 0.16, 0.18, 1.0));
596 strong.weight = FontWeight::BOLD;
597 let mut emphasis = TextStyle::new(Color::rgba(0.10, 0.38, 0.82, 1.0));
598 emphasis.style = FontStyle::Italic;
599 TextDocument {
600 paragraphs: vec![TextParagraph::from_spans(vec![
601 TextSpan::new("Warm", strong),
602 TextSpan::new(" cool", emphasis),
603 ])],
604 }
605 }
606
607 #[test]
608 fn rich_text_paints_document_spans_without_color_override() {
609 let output = render(RichText::new(two_span_document()));
610 let mut shaped = None;
611 output.frame.scene.visit_commands(&mut |command| {
612 if let SceneCommand::DrawShapedText(text) = command {
613 shaped = Some(text.clone());
614 }
615 });
616 let shaped = shaped.expect("rich text should emit shaped text");
617 assert_eq!(shaped.color_override, None);
618
619 let layout = shaped
620 .resolve(output.frame.text_layout_registry.as_ref())
621 .expect("rich text layout should resolve");
622 assert_eq!(layout.text(), "Warm cool");
623 assert_eq!(layout.runs().len(), 2);
624 assert_eq!(layout.run_style(0).weight, FontWeight::BOLD);
625 assert_eq!(layout.run_style(1).style, FontStyle::Italic);
626 assert_ne!(layout.run_style(0).color, layout.run_style(1).color);
627 }
628
629 #[test]
630 fn rich_text_exposes_plain_text_semantics_for_named_document() {
631 let document = TextDocument {
632 paragraphs: vec![
633 TextParagraph::new("First", TextStyle::new(Color::WHITE)),
634 TextParagraph::new("Second", TextStyle::new(Color::WHITE)),
635 ],
636 };
637 let output = render(RichText::new(document).semantic_name("Summary"));
638 let node = output
639 .semantics
640 .iter()
641 .find(|node| node.role == SemanticsRole::Text)
642 .expect("rich text should expose text semantics");
643
644 assert_eq!(node.name.as_deref(), Some("Summary"));
645 assert_eq!(
646 node.value,
647 Some(SemanticsValue::Text("First\nSecond".to_string()))
648 );
649 }
650
651 #[test]
652 fn rich_text_wraps_to_parent_constraints() {
653 let output = render(SizedBox::new().width(96.0).child(RichText::from_plain_text(
654 "alpha beta gamma delta epsilon",
655 TextStyle::new(Color::WHITE),
656 )));
657 let mut line_count = 0;
658 output.frame.scene.visit_commands(&mut |command| {
659 if let SceneCommand::DrawShapedText(text) = command
660 && let Some(layout) = text.resolve(output.frame.text_layout_registry.as_ref())
661 {
662 line_count = layout.lines().len();
663 }
664 });
665
666 assert!(line_count > 1, "expected constrained rich text to wrap");
667 }
668
669 #[test]
670 fn source_map_copies_complete_markdown_syntax_and_partial_content() {
671 let source = "Use **strong** and `code`.";
672 let rendered = "Use strong and code.";
673 let map = RichTextSourceMap::new(
674 source,
675 rendered,
676 vec![
677 RichTextSourceSpan::new(0..4, 0..4, 0..4),
678 RichTextSourceSpan::new(4..10, 4..14, 6..12),
679 RichTextSourceSpan::new(10..15, 14..19, 14..19),
680 RichTextSourceSpan::new(15..19, 19..25, 20..24),
681 RichTextSourceSpan::new(19..20, 25..26, 25..26),
682 ],
683 );
684
685 assert_eq!(map.copy_range(4..10), "**strong**");
686 assert_eq!(map.copy_range(6..9), "ron");
687 assert_eq!(map.copy_range(15..19), "`code`");
688 assert_eq!(map.copy_range(4..19), "**strong** and `code`");
689 }
690}