1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use crate::{ParagraphStyle, SpanStyle};
4
5#[derive(Clone)]
26pub enum LinkAnnotation {
27 Url(String),
31
32 Clickable {
36 tag: String,
38 handler: Rc<dyn Fn()>,
40 },
41}
42
43impl std::fmt::Debug for LinkAnnotation {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 Self::Url(url) => f.debug_tuple("Url").field(url).finish(),
47 Self::Clickable { tag, .. } => f.debug_struct("Clickable").field("tag", tag).finish(),
48 }
49 }
50}
51
52impl PartialEq for LinkAnnotation {
53 fn eq(&self, other: &Self) -> bool {
54 match (self, other) {
55 (Self::Url(a), Self::Url(b)) => a == b,
56 (
57 Self::Clickable {
58 tag: ta,
59 handler: ha,
60 },
61 Self::Clickable {
62 tag: tb,
63 handler: hb,
64 },
65 ) => ta == tb && Rc::ptr_eq(ha, hb),
66 _ => false,
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq)]
76pub struct StringAnnotation {
77 pub tag: String,
80 pub annotation: String,
82}
83
84#[derive(Debug, Clone, PartialEq)]
88pub enum LinkKey {
89 Url(String),
91 Clickable(String),
93}
94
95#[derive(Debug, Clone)]
105pub struct RenderString {
106 text: String,
107 span_styles: Box<[RangeStyle<SpanStyle>]>,
108 extras: Option<Box<RenderExtras>>,
110 hash: u64,
111}
112
113#[derive(Debug, Clone, Default, PartialEq)]
114struct RenderExtras {
115 paragraph_styles: Box<[RangeStyle<ParagraphStyle>]>,
116 string_annotations: Box<[RangeStyle<StringAnnotation>]>,
117 links: Box<[RangeStyle<LinkKey>]>,
118}
119
120impl Default for RenderString {
121 fn default() -> Self {
122 Self::plain(String::new())
123 }
124}
125
126impl PartialEq for RenderString {
127 fn eq(&self, other: &Self) -> bool {
128 self.hash == other.hash
129 && self.text == other.text
130 && self.span_styles == other.span_styles
131 && self.extras == other.extras
132 }
133}
134
135const _: () = {
136 fn assert_send<T: Send + Sync>() {}
137 #[expect(dead_code, reason = "a compile-time check that is never called")]
138 fn assert_render_string_is_send_sync() {
139 assert_send::<RenderString>();
140 }
141};
142
143impl RenderString {
144 fn from_parts(
145 text: String,
146 span_styles: Vec<RangeStyle<SpanStyle>>,
147 paragraph_styles: Vec<RangeStyle<ParagraphStyle>>,
148 string_annotations: Vec<RangeStyle<StringAnnotation>>,
149 links: Vec<RangeStyle<LinkKey>>,
150 ) -> Self {
151 let hash = render_hash_impl(&text, &span_styles, ¶graph_styles);
152 let extras =
153 (!paragraph_styles.is_empty() || !string_annotations.is_empty() || !links.is_empty())
154 .then(|| {
155 Box::new(RenderExtras {
156 paragraph_styles: paragraph_styles.into_boxed_slice(),
157 string_annotations: string_annotations.into_boxed_slice(),
158 links: links.into_boxed_slice(),
159 })
160 });
161 Self {
162 text,
163 span_styles: span_styles.into_boxed_slice(),
164 extras,
165 hash,
166 }
167 }
168
169 pub(crate) fn plain(text: String) -> Self {
171 let hash = render_hash_impl(&text, &[], &[]);
172 Self {
173 text,
174 span_styles: Box::default(),
175 extras: None,
176 hash,
177 }
178 }
179
180 pub(crate) fn plain_capacity(&self) -> Option<usize> {
183 (self.span_styles.is_empty() && self.extras.is_none()).then_some(self.text.capacity())
184 }
185
186 pub(crate) fn refill_plain(&mut self, text: &str) {
188 self.text.clear();
189 self.text.push_str(text);
190 self.hash = render_hash_impl(&self.text, &[], &[]);
191 }
192
193 pub(crate) fn replace_plain(&mut self, text: String) {
195 self.hash = render_hash_impl(&text, &[], &[]);
196 self.text = text;
197 }
198
199 pub fn text(&self) -> &str {
201 &self.text
202 }
203
204 pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
206 &self.span_styles
207 }
208
209 pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
211 self.extras
212 .as_deref()
213 .map_or(&[], |extras| &extras.paragraph_styles)
214 }
215
216 pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
218 self.extras
219 .as_deref()
220 .map_or(&[], |extras| &extras.string_annotations)
221 }
222
223 pub fn links(&self) -> &[RangeStyle<LinkKey>] {
226 self.extras.as_deref().map_or(&[], |extras| &extras.links)
227 }
228
229 pub fn len(&self) -> usize {
231 self.text.len()
232 }
233
234 pub fn is_empty(&self) -> bool {
236 self.text.is_empty()
237 }
238
239 pub fn span_boundaries(&self) -> SpanBoundaries {
241 span_boundaries_impl(&self.text, &self.span_styles)
242 }
243
244 pub fn render_hash(&self) -> u64 {
247 self.hash
248 }
249
250 pub fn subsequence(&self, range: Range<usize>) -> Self {
254 let start = range.start.min(self.text.len());
255 let end = range.end.max(start).min(self.text.len());
256 if start == end {
257 return Self::default();
258 }
259
260 Self::from_parts(
261 self.text[start..end].to_string(),
262 clip_range_styles(&self.span_styles, start, end),
263 clip_range_styles(self.paragraph_styles(), start, end),
264 clip_range_styles(self.string_annotations(), start, end),
265 clip_range_styles(self.links(), start, end),
266 )
267 }
268}
269
270fn intersect(a: &Range<usize>, b: &Range<usize>) -> bool {
273 a.start.max(b.start) < a.end.min(b.end) || contains(a, b) || contains(b, a)
274}
275
276fn contains(base: &Range<usize>, target: &Range<usize>) -> bool {
279 base.start <= target.start
280 && target.end <= base.end
281 && (base.end != target.end || (target.start == target.end) == (base.start == base.end))
282}
283
284fn clip_range_styles<T: Clone>(
285 styles: &[RangeStyle<T>],
286 start: usize,
287 end: usize,
288) -> Vec<RangeStyle<T>> {
289 let mut clipped = Vec::new();
290 for style in styles {
291 let intersection_start = style.range.start.max(start);
292 let intersection_end = style.range.end.min(end);
293 if intersection_start < intersection_end {
294 clipped.push(RangeStyle {
295 item: style.item.clone(),
296 range: (intersection_start - start)..(intersection_end - start),
297 });
298 }
299 }
300 clipped
301}
302
303pub type SpanBoundaries = smallvec::SmallVec<[usize; 8]>;
306
307fn span_boundaries_impl(text: &str, span_styles: &[RangeStyle<SpanStyle>]) -> SpanBoundaries {
308 let mut boundaries: SpanBoundaries = smallvec::smallvec![0, text.len()];
309 for span in span_styles {
310 boundaries.push(span.range.start);
311 boundaries.push(span.range.end);
312 }
313 boundaries.sort_unstable();
314 boundaries.dedup();
315 boundaries.retain(|boundary| *boundary <= text.len() && text.is_char_boundary(*boundary));
316 boundaries
317}
318
319fn render_hash_impl(
320 text: &str,
321 span_styles: &[RangeStyle<SpanStyle>],
322 paragraph_styles: &[RangeStyle<ParagraphStyle>],
323) -> u64 {
324 use std::hash::{Hash, Hasher};
325
326 let mut hasher = cranpose_ui_graphics::FxHasher::default();
327 text.hash(&mut hasher);
328 span_styles.len().hash(&mut hasher);
329 for span in span_styles {
330 span.range.start.hash(&mut hasher);
331 span.range.end.hash(&mut hasher);
332 span.item.render_hash().hash(&mut hasher);
333 }
334 paragraph_styles.len().hash(&mut hasher);
335 for paragraph in paragraph_styles {
336 paragraph.range.start.hash(&mut hasher);
337 paragraph.range.end.hash(&mut hasher);
338 paragraph.item.render_hash().hash(&mut hasher);
339 }
340 hasher.finish()
341}
342
343type LinkHandler = Rc<dyn Fn()>;
345
346static EMPTY: std::sync::LazyLock<Arc<RenderString>> =
349 std::sync::LazyLock::new(|| Arc::new(RenderString::plain(String::new())));
350
351#[derive(Clone)]
359pub struct AnnotatedString {
360 content: Arc<RenderString>,
361 handlers: Option<Rc<[LinkHandler]>>,
364}
365
366impl Default for AnnotatedString {
367 fn default() -> Self {
368 Self {
369 content: Arc::clone(&EMPTY),
370 handlers: None,
371 }
372 }
373}
374
375impl std::fmt::Debug for AnnotatedString {
376 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377 f.debug_struct("AnnotatedString")
378 .field("content", &self.content)
379 .field(
380 "handlers",
381 &self.handlers.as_ref().map_or(0, |handlers| handlers.len()),
382 )
383 .finish()
384 }
385}
386
387impl PartialEq for AnnotatedString {
388 fn eq(&self, other: &Self) -> bool {
389 let same_handlers = match (&self.handlers, &other.handlers) {
390 (None, None) => true,
391 (Some(a), Some(b)) => {
392 a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| Rc::ptr_eq(a, b))
393 }
394 _ => false,
395 };
396 (Arc::ptr_eq(&self.content, &other.content) || *self.content == *other.content)
397 && same_handlers
398 }
399}
400
401#[derive(Debug, Clone, PartialEq)]
403pub struct RangeStyle<T> {
404 pub item: T,
406 pub range: Range<usize>,
408}
409
410impl AnnotatedString {
411 pub(crate) fn into_plain_content(self) -> Option<Arc<RenderString>> {
413 self.handlers.is_none().then_some(self.content)
414 }
415
416 pub fn new(text: String) -> Self {
418 if text.is_empty() {
419 return Self::default();
420 }
421 Self {
422 content: Arc::new(RenderString::plain(text)),
423 handlers: None,
424 }
425 }
426
427 fn of_parts(content: RenderString, handlers: Vec<LinkHandler>) -> Self {
430 Self {
431 content: Arc::new(content),
432 handlers: (!handlers.is_empty()).then(|| Rc::from(handlers)),
433 }
434 }
435
436 pub fn builder() -> Builder {
438 Builder::new()
439 }
440
441 pub fn text(&self) -> &str {
443 &self.content.text
444 }
445
446 pub fn is_plain(&self, text: &str) -> bool {
449 self.handlers.is_none()
450 && self.content.span_styles.is_empty()
451 && self.content.extras.is_none()
452 && self.content.text == text
453 }
454
455 pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
457 &self.content.span_styles
458 }
459
460 pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
462 self.content.paragraph_styles()
463 }
464
465 pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
467 self.content.string_annotations()
468 }
469
470 pub fn has_link_annotations(&self, start: usize, end: usize) -> bool {
474 self.content
475 .links()
476 .iter()
477 .any(|link| intersect(&link.range, &(start..end)))
478 }
479
480 pub fn len(&self) -> usize {
482 self.content.text.len()
483 }
484
485 pub fn is_empty(&self) -> bool {
487 self.content.text.is_empty()
488 }
489
490 pub fn span_boundaries(&self) -> SpanBoundaries {
492 self.content.span_boundaries()
493 }
494
495 pub fn render_string(&self) -> &Arc<RenderString> {
498 &self.content
499 }
500
501 pub fn span_measurement_hash(&self) -> u64 {
505 use std::hash::Hasher;
506 let spans = self.span_styles();
507 let mut hasher = cranpose_ui_graphics::FxHasher::default();
508 hasher.write_usize(spans.len());
509 for span in spans {
510 hasher.write_usize(span.range.start);
511 hasher.write_usize(span.range.end);
512 crate::style::hash_span_measurement(&span.item, &mut hasher);
513 }
514 hasher.finish()
515 }
516
517 pub fn render_hash(&self) -> u64 {
519 self.content.hash
520 }
521
522 pub fn map_span_styles(&self, mut map: impl FnMut(&mut SpanStyle)) -> Self {
525 let mut content = RenderString::clone(&self.content);
526 for span in &mut content.span_styles {
527 map(&mut span.item);
528 }
529 content.hash = render_hash_impl(
530 &content.text,
531 &content.span_styles,
532 content.paragraph_styles(),
533 );
534 Self {
535 content: Arc::new(content),
536 handlers: self.handlers.clone(),
537 }
538 }
539
540 pub fn subsequence(&self, range: Range<usize>) -> Self {
543 let range = clamp_subsequence_range(self.text(), range);
544 if range.is_empty() {
545 return Self::default();
546 }
547 Builder::new()
548 .append_annotated_subsequence(self, range)
549 .to_annotated_string()
550 }
551
552 pub fn get_string_annotations(
556 &self,
557 tag: &str,
558 start: usize,
559 end: usize,
560 ) -> Vec<&RangeStyle<StringAnnotation>> {
561 self.string_annotations()
562 .iter()
563 .filter(|ann| ann.item.tag == tag && intersect(&ann.range, &(start..end)))
564 .collect()
565 }
566
567 pub fn get_link_annotations(
571 &self,
572 start: usize,
573 end: usize,
574 ) -> Vec<RangeStyle<LinkAnnotation>> {
575 self.link_annotations()
576 .filter(|ann| intersect(&ann.range, &(start..end)))
577 .collect()
578 }
579
580 fn link_annotations(&self) -> impl Iterator<Item = RangeStyle<LinkAnnotation>> + '_ {
582 let mut handlers = self.handlers.iter().flat_map(|handlers| handlers.iter());
583 self.content.links().iter().map(move |link| RangeStyle {
584 item: match &link.item {
585 LinkKey::Url(url) => LinkAnnotation::Url(url.clone()),
586 LinkKey::Clickable(tag) => LinkAnnotation::Clickable {
587 tag: tag.clone(),
588 handler: Rc::clone(
589 handlers.next().expect("a clickable link holds its handler"),
590 ),
591 },
592 },
593 range: link.range.clone(),
594 })
595 }
596}
597
598impl From<String> for AnnotatedString {
599 fn from(text: String) -> Self {
600 Self::new(text)
601 }
602}
603
604impl From<Arc<RenderString>> for AnnotatedString {
607 fn from(content: Arc<RenderString>) -> Self {
608 Self {
609 content,
610 handlers: None,
611 }
612 }
613}
614
615impl From<&str> for AnnotatedString {
616 fn from(text: &str) -> Self {
617 Self::new(text.to_owned())
618 }
619}
620
621impl From<&String> for AnnotatedString {
622 fn from(text: &String) -> Self {
623 Self::new(text.clone())
624 }
625}
626
627impl From<&mut String> for AnnotatedString {
628 fn from(text: &mut String) -> Self {
629 Self::new(text.clone())
630 }
631}
632
633#[derive(Debug, Default, Clone)]
635pub struct Builder {
636 text: String,
637 span_styles: Vec<MutableRange<SpanStyle>>,
638 paragraph_styles: Vec<MutableRange<ParagraphStyle>>,
639 string_annotations: Vec<MutableRange<StringAnnotation>>,
640 link_annotations: Vec<MutableRange<LinkAnnotation>>,
641 style_stack: Vec<StyleStackRecord>,
642}
643
644#[derive(Debug, Clone)]
645struct MutableRange<T> {
646 item: T,
647 start: usize,
648 end: usize,
649}
650
651#[derive(Debug, Clone)]
652struct StyleStackRecord {
653 style_type: StyleType,
654 index: usize,
655}
656
657#[derive(Debug, Clone, Copy, PartialEq, Eq)]
658enum StyleType {
659 Span,
660 Paragraph,
661 StringAnnotation,
662 LinkAnnotation,
663}
664
665fn clamp_subsequence_range(text: &str, range: Range<usize>) -> Range<usize> {
666 let start = range.start.min(text.len());
667 let end = range.end.max(start).min(text.len());
668 start..end
669}
670
671fn finished_ranges<T>(ranges: Vec<MutableRange<T>>) -> Vec<RangeStyle<T>> {
673 ranges
674 .into_iter()
675 .map(|range| RangeStyle {
676 item: range.item,
677 range: range.start..range.end,
678 })
679 .collect()
680}
681
682fn append_clipped_ranges<T: Clone>(
683 target: &mut Vec<MutableRange<T>>,
684 source: &[RangeStyle<T>],
685 source_range: Range<usize>,
686 target_offset: usize,
687) {
688 for style in source {
689 let intersection_start = style.range.start.max(source_range.start);
690 let intersection_end = style.range.end.min(source_range.end);
691 if intersection_start < intersection_end {
692 target.push(MutableRange {
693 item: style.item.clone(),
694 start: (intersection_start - source_range.start) + target_offset,
695 end: (intersection_end - source_range.start) + target_offset,
696 });
697 }
698 }
699}
700
701impl Builder {
702 pub fn new() -> Self {
704 Self::default()
705 }
706
707 pub fn append(mut self, text: &str) -> Self {
709 self.text.push_str(text);
710 self
711 }
712
713 pub fn append_annotated(self, annotated: &AnnotatedString) -> Self {
715 self.append_annotated_subsequence(annotated, 0..annotated.len())
716 }
717
718 pub fn append_annotated_subsequence(
721 mut self,
722 annotated: &AnnotatedString,
723 range: Range<usize>,
724 ) -> Self {
725 let range = clamp_subsequence_range(annotated.text(), range);
726 if range.is_empty() {
727 return self;
728 }
729
730 debug_assert!(
731 annotated.text().is_char_boundary(range.start),
732 "the clamped range starts on a character"
733 );
734 debug_assert!(
735 annotated.text().is_char_boundary(range.end),
736 "the clamped range ends on a character"
737 );
738
739 let target_offset = self.text.len();
740 self.text.push_str(&annotated.text()[range.clone()]);
741 append_clipped_ranges(
742 &mut self.span_styles,
743 annotated.span_styles(),
744 range.clone(),
745 target_offset,
746 );
747 append_clipped_ranges(
748 &mut self.paragraph_styles,
749 annotated.paragraph_styles(),
750 range.clone(),
751 target_offset,
752 );
753 append_clipped_ranges(
754 &mut self.string_annotations,
755 annotated.string_annotations(),
756 range.clone(),
757 target_offset,
758 );
759 for link in annotated.link_annotations() {
760 let start = link.range.start.max(range.start);
761 let end = link.range.end.min(range.end);
762 if start < end {
763 self.link_annotations.push(MutableRange {
764 item: link.item,
765 start: start - range.start + target_offset,
766 end: end - range.start + target_offset,
767 });
768 }
769 }
770 self
771 }
772
773 pub fn push_style(mut self, style: SpanStyle) -> Self {
777 let index = self.span_styles.len();
778 self.span_styles.push(MutableRange {
779 item: style,
780 start: self.text.len(),
781 end: usize::MAX,
782 });
783 self.style_stack.push(StyleStackRecord {
784 style_type: StyleType::Span,
785 index,
786 });
787 self
788 }
789
790 pub fn push_paragraph_style(mut self, style: ParagraphStyle) -> Self {
792 let index = self.paragraph_styles.len();
793 self.paragraph_styles.push(MutableRange {
794 item: style,
795 start: self.text.len(),
796 end: usize::MAX,
797 });
798 self.style_stack.push(StyleStackRecord {
799 style_type: StyleType::Paragraph,
800 index,
801 });
802 self
803 }
804
805 pub fn push_string_annotation(mut self, tag: &str, annotation: &str) -> Self {
809 let index = self.string_annotations.len();
810 self.string_annotations.push(MutableRange {
811 item: StringAnnotation {
812 tag: tag.to_string(),
813 annotation: annotation.to_string(),
814 },
815 start: self.text.len(),
816 end: usize::MAX,
817 });
818 self.style_stack.push(StyleStackRecord {
819 style_type: StyleType::StringAnnotation,
820 index,
821 });
822 self
823 }
824
825 pub fn push_link(mut self, link: LinkAnnotation) -> Self {
830 let index = self.link_annotations.len();
831 self.link_annotations.push(MutableRange {
832 item: link,
833 start: self.text.len(),
834 end: usize::MAX,
835 });
836 self.style_stack.push(StyleStackRecord {
837 style_type: StyleType::LinkAnnotation,
838 index,
839 });
840 self
841 }
842
843 pub fn with_link(self, link: LinkAnnotation, block: impl FnOnce(Self) -> Self) -> Self {
858 let b = self.push_link(link);
859 let b = block(b);
860 b.pop()
861 }
862
863 pub fn pop(mut self) -> Self {
865 if let Some(record) = self.style_stack.pop() {
866 match record.style_type {
867 StyleType::Span => {
868 self.span_styles[record.index].end = self.text.len();
869 }
870 StyleType::Paragraph => {
871 self.paragraph_styles[record.index].end = self.text.len();
872 }
873 StyleType::StringAnnotation => {
874 self.string_annotations[record.index].end = self.text.len();
875 }
876 StyleType::LinkAnnotation => {
877 self.link_annotations[record.index].end = self.text.len();
878 }
879 }
880 }
881 self
882 }
883
884 pub fn to_annotated_string(mut self) -> AnnotatedString {
886 while let Some(record) = self.style_stack.pop() {
887 match record.style_type {
888 StyleType::Span => {
889 self.span_styles[record.index].end = self.text.len();
890 }
891 StyleType::Paragraph => {
892 self.paragraph_styles[record.index].end = self.text.len();
893 }
894 StyleType::StringAnnotation => {
895 self.string_annotations[record.index].end = self.text.len();
896 }
897 StyleType::LinkAnnotation => {
898 self.link_annotations[record.index].end = self.text.len();
899 }
900 }
901 }
902
903 let mut handlers = Vec::new();
904 let links = self
905 .link_annotations
906 .into_iter()
907 .map(|link| RangeStyle {
908 item: match link.item {
909 LinkAnnotation::Url(url) => LinkKey::Url(url),
910 LinkAnnotation::Clickable { tag, handler } => {
911 handlers.push(handler);
912 LinkKey::Clickable(tag)
913 }
914 },
915 range: link.start..link.end,
916 })
917 .collect();
918 AnnotatedString::of_parts(
919 RenderString::from_parts(
920 self.text,
921 finished_ranges(self.span_styles),
922 finished_ranges(self.paragraph_styles),
923 finished_ranges(self.string_annotations),
924 links,
925 ),
926 handlers,
927 )
928 }
929
930 pub fn add_style(mut self, style: SpanStyle, range: Range<usize>) -> Self {
933 self.span_styles.push(MutableRange {
934 item: style,
935 start: range.start,
936 end: range.end,
937 });
938 self
939 }
940}
941
942#[cfg(test)]
943#[path = "tests/annotated_string_tests.rs"]
944mod tests;