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