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 fn text(&self) -> &str {
195 &self.text
196 }
197
198 pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
200 &self.span_styles
201 }
202
203 pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
205 self.extras
206 .as_deref()
207 .map_or(&[], |extras| &extras.paragraph_styles)
208 }
209
210 pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
212 self.extras
213 .as_deref()
214 .map_or(&[], |extras| &extras.string_annotations)
215 }
216
217 pub fn links(&self) -> &[RangeStyle<LinkKey>] {
220 self.extras.as_deref().map_or(&[], |extras| &extras.links)
221 }
222
223 pub fn len(&self) -> usize {
225 self.text.len()
226 }
227
228 pub fn is_empty(&self) -> bool {
230 self.text.is_empty()
231 }
232
233 pub fn span_boundaries(&self) -> SpanBoundaries {
235 span_boundaries_impl(&self.text, &self.span_styles)
236 }
237
238 pub fn render_hash(&self) -> u64 {
241 self.hash
242 }
243
244 pub fn subsequence(&self, range: Range<usize>) -> Self {
248 let start = range.start.min(self.text.len());
249 let end = range.end.max(start).min(self.text.len());
250 if start == end {
251 return Self::default();
252 }
253
254 Self::from_parts(
255 self.text[start..end].to_string(),
256 clip_range_styles(&self.span_styles, start, end),
257 clip_range_styles(self.paragraph_styles(), start, end),
258 clip_range_styles(self.string_annotations(), start, end),
259 clip_range_styles(self.links(), start, end),
260 )
261 }
262}
263
264fn intersect(a: &Range<usize>, b: &Range<usize>) -> bool {
267 a.start.max(b.start) < a.end.min(b.end) || contains(a, b) || contains(b, a)
268}
269
270fn contains(base: &Range<usize>, target: &Range<usize>) -> bool {
273 base.start <= target.start
274 && target.end <= base.end
275 && (base.end != target.end || (target.start == target.end) == (base.start == base.end))
276}
277
278fn clip_range_styles<T: Clone>(
279 styles: &[RangeStyle<T>],
280 start: usize,
281 end: usize,
282) -> Vec<RangeStyle<T>> {
283 let mut clipped = Vec::new();
284 for style in styles {
285 let intersection_start = style.range.start.max(start);
286 let intersection_end = style.range.end.min(end);
287 if intersection_start < intersection_end {
288 clipped.push(RangeStyle {
289 item: style.item.clone(),
290 range: (intersection_start - start)..(intersection_end - start),
291 });
292 }
293 }
294 clipped
295}
296
297pub type SpanBoundaries = smallvec::SmallVec<[usize; 8]>;
300
301fn span_boundaries_impl(text: &str, span_styles: &[RangeStyle<SpanStyle>]) -> SpanBoundaries {
302 let mut boundaries: SpanBoundaries = smallvec::smallvec![0, text.len()];
303 for span in span_styles {
304 boundaries.push(span.range.start);
305 boundaries.push(span.range.end);
306 }
307 boundaries.sort_unstable();
308 boundaries.dedup();
309 boundaries.retain(|boundary| *boundary <= text.len() && text.is_char_boundary(*boundary));
310 boundaries
311}
312
313fn render_hash_impl(
314 text: &str,
315 span_styles: &[RangeStyle<SpanStyle>],
316 paragraph_styles: &[RangeStyle<ParagraphStyle>],
317) -> u64 {
318 use std::hash::{Hash, Hasher};
319
320 let mut hasher = cranpose_ui_graphics::FxHasher::default();
321 text.hash(&mut hasher);
322 span_styles.len().hash(&mut hasher);
323 for span in span_styles {
324 span.range.start.hash(&mut hasher);
325 span.range.end.hash(&mut hasher);
326 span.item.render_hash().hash(&mut hasher);
327 }
328 paragraph_styles.len().hash(&mut hasher);
329 for paragraph in paragraph_styles {
330 paragraph.range.start.hash(&mut hasher);
331 paragraph.range.end.hash(&mut hasher);
332 paragraph.item.render_hash().hash(&mut hasher);
333 }
334 hasher.finish()
335}
336
337type LinkHandler = Rc<dyn Fn()>;
339
340static EMPTY: std::sync::LazyLock<Arc<RenderString>> =
343 std::sync::LazyLock::new(|| Arc::new(RenderString::plain(String::new())));
344
345#[derive(Clone)]
353pub struct AnnotatedString {
354 content: Arc<RenderString>,
355 handlers: Option<Rc<[LinkHandler]>>,
358}
359
360impl Default for AnnotatedString {
361 fn default() -> Self {
362 Self {
363 content: Arc::clone(&EMPTY),
364 handlers: None,
365 }
366 }
367}
368
369impl std::fmt::Debug for AnnotatedString {
370 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
371 f.debug_struct("AnnotatedString")
372 .field("content", &self.content)
373 .field(
374 "handlers",
375 &self.handlers.as_ref().map_or(0, |handlers| handlers.len()),
376 )
377 .finish()
378 }
379}
380
381impl PartialEq for AnnotatedString {
382 fn eq(&self, other: &Self) -> bool {
383 let same_handlers = match (&self.handlers, &other.handlers) {
384 (None, None) => true,
385 (Some(a), Some(b)) => {
386 a.len() == b.len() && a.iter().zip(b.iter()).all(|(a, b)| Rc::ptr_eq(a, b))
387 }
388 _ => false,
389 };
390 (Arc::ptr_eq(&self.content, &other.content) || *self.content == *other.content)
391 && same_handlers
392 }
393}
394
395#[derive(Debug, Clone, PartialEq)]
397pub struct RangeStyle<T> {
398 pub item: T,
400 pub range: Range<usize>,
402}
403
404impl AnnotatedString {
405 pub(crate) fn into_plain_content(self) -> Option<Arc<RenderString>> {
407 self.handlers.is_none().then_some(self.content)
408 }
409
410 pub fn new(text: String) -> Self {
412 if text.is_empty() {
413 return Self::default();
414 }
415 Self {
416 content: Arc::new(RenderString::plain(text)),
417 handlers: None,
418 }
419 }
420
421 fn of_parts(content: RenderString, handlers: Vec<LinkHandler>) -> Self {
424 Self {
425 content: Arc::new(content),
426 handlers: (!handlers.is_empty()).then(|| Rc::from(handlers)),
427 }
428 }
429
430 pub fn builder() -> Builder {
432 Builder::new()
433 }
434
435 pub fn text(&self) -> &str {
437 &self.content.text
438 }
439
440 pub fn is_plain(&self, text: &str) -> bool {
443 self.handlers.is_none()
444 && self.content.span_styles.is_empty()
445 && self.content.extras.is_none()
446 && self.content.text == text
447 }
448
449 pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
451 &self.content.span_styles
452 }
453
454 pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
456 self.content.paragraph_styles()
457 }
458
459 pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
461 self.content.string_annotations()
462 }
463
464 pub fn has_link_annotations(&self, start: usize, end: usize) -> bool {
468 self.content
469 .links()
470 .iter()
471 .any(|link| intersect(&link.range, &(start..end)))
472 }
473
474 pub fn len(&self) -> usize {
476 self.content.text.len()
477 }
478
479 pub fn is_empty(&self) -> bool {
481 self.content.text.is_empty()
482 }
483
484 pub fn span_boundaries(&self) -> SpanBoundaries {
486 self.content.span_boundaries()
487 }
488
489 pub fn render_string(&self) -> &Arc<RenderString> {
492 &self.content
493 }
494
495 pub fn span_measurement_hash(&self) -> u64 {
499 use std::hash::Hasher;
500 let spans = self.span_styles();
501 let mut hasher = cranpose_ui_graphics::FxHasher::default();
502 hasher.write_usize(spans.len());
503 for span in spans {
504 hasher.write_usize(span.range.start);
505 hasher.write_usize(span.range.end);
506 crate::style::hash_span_measurement(&span.item, &mut hasher);
507 }
508 hasher.finish()
509 }
510
511 pub fn render_hash(&self) -> u64 {
513 self.content.hash
514 }
515
516 pub fn map_span_styles(&self, mut map: impl FnMut(&mut SpanStyle)) -> Self {
519 let mut content = RenderString::clone(&self.content);
520 for span in &mut content.span_styles {
521 map(&mut span.item);
522 }
523 content.hash = render_hash_impl(
524 &content.text,
525 &content.span_styles,
526 content.paragraph_styles(),
527 );
528 Self {
529 content: Arc::new(content),
530 handlers: self.handlers.clone(),
531 }
532 }
533
534 pub fn subsequence(&self, range: Range<usize>) -> Self {
537 let range = clamp_subsequence_range(self.text(), range);
538 if range.is_empty() {
539 return Self::default();
540 }
541 Builder::new()
542 .append_annotated_subsequence(self, range)
543 .to_annotated_string()
544 }
545
546 pub fn get_string_annotations(
550 &self,
551 tag: &str,
552 start: usize,
553 end: usize,
554 ) -> Vec<&RangeStyle<StringAnnotation>> {
555 self.string_annotations()
556 .iter()
557 .filter(|ann| ann.item.tag == tag && intersect(&ann.range, &(start..end)))
558 .collect()
559 }
560
561 pub fn get_link_annotations(
565 &self,
566 start: usize,
567 end: usize,
568 ) -> Vec<RangeStyle<LinkAnnotation>> {
569 self.link_annotations()
570 .filter(|ann| intersect(&ann.range, &(start..end)))
571 .collect()
572 }
573
574 fn link_annotations(&self) -> impl Iterator<Item = RangeStyle<LinkAnnotation>> + '_ {
576 let mut handlers = self.handlers.iter().flat_map(|handlers| handlers.iter());
577 self.content.links().iter().map(move |link| RangeStyle {
578 item: match &link.item {
579 LinkKey::Url(url) => LinkAnnotation::Url(url.clone()),
580 LinkKey::Clickable(tag) => LinkAnnotation::Clickable {
581 tag: tag.clone(),
582 handler: Rc::clone(
583 handlers.next().expect("a clickable link holds its handler"),
584 ),
585 },
586 },
587 range: link.range.clone(),
588 })
589 }
590}
591
592impl From<String> for AnnotatedString {
593 fn from(text: String) -> Self {
594 Self::new(text)
595 }
596}
597
598impl From<Arc<RenderString>> for AnnotatedString {
601 fn from(content: Arc<RenderString>) -> Self {
602 Self {
603 content,
604 handlers: None,
605 }
606 }
607}
608
609impl From<&str> for AnnotatedString {
610 fn from(text: &str) -> Self {
611 Self::new(text.to_owned())
612 }
613}
614
615impl From<&String> for AnnotatedString {
616 fn from(text: &String) -> Self {
617 Self::new(text.clone())
618 }
619}
620
621impl From<&mut String> for AnnotatedString {
622 fn from(text: &mut String) -> Self {
623 Self::new(text.clone())
624 }
625}
626
627#[derive(Debug, Default, Clone)]
629pub struct Builder {
630 text: String,
631 span_styles: Vec<MutableRange<SpanStyle>>,
632 paragraph_styles: Vec<MutableRange<ParagraphStyle>>,
633 string_annotations: Vec<MutableRange<StringAnnotation>>,
634 link_annotations: Vec<MutableRange<LinkAnnotation>>,
635 style_stack: Vec<StyleStackRecord>,
636}
637
638#[derive(Debug, Clone)]
639struct MutableRange<T> {
640 item: T,
641 start: usize,
642 end: usize,
643}
644
645#[derive(Debug, Clone)]
646struct StyleStackRecord {
647 style_type: StyleType,
648 index: usize,
649}
650
651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
652enum StyleType {
653 Span,
654 Paragraph,
655 StringAnnotation,
656 LinkAnnotation,
657}
658
659fn clamp_subsequence_range(text: &str, range: Range<usize>) -> Range<usize> {
660 let start = range.start.min(text.len());
661 let end = range.end.max(start).min(text.len());
662 start..end
663}
664
665fn finished_ranges<T>(ranges: Vec<MutableRange<T>>) -> Vec<RangeStyle<T>> {
667 ranges
668 .into_iter()
669 .map(|range| RangeStyle {
670 item: range.item,
671 range: range.start..range.end,
672 })
673 .collect()
674}
675
676fn append_clipped_ranges<T: Clone>(
677 target: &mut Vec<MutableRange<T>>,
678 source: &[RangeStyle<T>],
679 source_range: Range<usize>,
680 target_offset: usize,
681) {
682 for style in source {
683 let intersection_start = style.range.start.max(source_range.start);
684 let intersection_end = style.range.end.min(source_range.end);
685 if intersection_start < intersection_end {
686 target.push(MutableRange {
687 item: style.item.clone(),
688 start: (intersection_start - source_range.start) + target_offset,
689 end: (intersection_end - source_range.start) + target_offset,
690 });
691 }
692 }
693}
694
695impl Builder {
696 pub fn new() -> Self {
698 Self::default()
699 }
700
701 pub fn append(mut self, text: &str) -> Self {
703 self.text.push_str(text);
704 self
705 }
706
707 pub fn append_annotated(self, annotated: &AnnotatedString) -> Self {
709 self.append_annotated_subsequence(annotated, 0..annotated.len())
710 }
711
712 pub fn append_annotated_subsequence(
715 mut self,
716 annotated: &AnnotatedString,
717 range: Range<usize>,
718 ) -> Self {
719 let range = clamp_subsequence_range(annotated.text(), range);
720 if range.is_empty() {
721 return self;
722 }
723
724 debug_assert!(
725 annotated.text().is_char_boundary(range.start),
726 "the clamped range starts on a character"
727 );
728 debug_assert!(
729 annotated.text().is_char_boundary(range.end),
730 "the clamped range ends on a character"
731 );
732
733 let target_offset = self.text.len();
734 self.text.push_str(&annotated.text()[range.clone()]);
735 append_clipped_ranges(
736 &mut self.span_styles,
737 annotated.span_styles(),
738 range.clone(),
739 target_offset,
740 );
741 append_clipped_ranges(
742 &mut self.paragraph_styles,
743 annotated.paragraph_styles(),
744 range.clone(),
745 target_offset,
746 );
747 append_clipped_ranges(
748 &mut self.string_annotations,
749 annotated.string_annotations(),
750 range.clone(),
751 target_offset,
752 );
753 for link in annotated.link_annotations() {
754 let start = link.range.start.max(range.start);
755 let end = link.range.end.min(range.end);
756 if start < end {
757 self.link_annotations.push(MutableRange {
758 item: link.item,
759 start: start - range.start + target_offset,
760 end: end - range.start + target_offset,
761 });
762 }
763 }
764 self
765 }
766
767 pub fn push_style(mut self, style: SpanStyle) -> Self {
771 let index = self.span_styles.len();
772 self.span_styles.push(MutableRange {
773 item: style,
774 start: self.text.len(),
775 end: usize::MAX,
776 });
777 self.style_stack.push(StyleStackRecord {
778 style_type: StyleType::Span,
779 index,
780 });
781 self
782 }
783
784 pub fn push_paragraph_style(mut self, style: ParagraphStyle) -> Self {
786 let index = self.paragraph_styles.len();
787 self.paragraph_styles.push(MutableRange {
788 item: style,
789 start: self.text.len(),
790 end: usize::MAX,
791 });
792 self.style_stack.push(StyleStackRecord {
793 style_type: StyleType::Paragraph,
794 index,
795 });
796 self
797 }
798
799 pub fn push_string_annotation(mut self, tag: &str, annotation: &str) -> Self {
803 let index = self.string_annotations.len();
804 self.string_annotations.push(MutableRange {
805 item: StringAnnotation {
806 tag: tag.to_string(),
807 annotation: annotation.to_string(),
808 },
809 start: self.text.len(),
810 end: usize::MAX,
811 });
812 self.style_stack.push(StyleStackRecord {
813 style_type: StyleType::StringAnnotation,
814 index,
815 });
816 self
817 }
818
819 pub fn push_link(mut self, link: LinkAnnotation) -> Self {
824 let index = self.link_annotations.len();
825 self.link_annotations.push(MutableRange {
826 item: link,
827 start: self.text.len(),
828 end: usize::MAX,
829 });
830 self.style_stack.push(StyleStackRecord {
831 style_type: StyleType::LinkAnnotation,
832 index,
833 });
834 self
835 }
836
837 pub fn with_link(self, link: LinkAnnotation, block: impl FnOnce(Self) -> Self) -> Self {
852 let b = self.push_link(link);
853 let b = block(b);
854 b.pop()
855 }
856
857 pub fn pop(mut self) -> Self {
859 if let Some(record) = self.style_stack.pop() {
860 match record.style_type {
861 StyleType::Span => {
862 self.span_styles[record.index].end = self.text.len();
863 }
864 StyleType::Paragraph => {
865 self.paragraph_styles[record.index].end = self.text.len();
866 }
867 StyleType::StringAnnotation => {
868 self.string_annotations[record.index].end = self.text.len();
869 }
870 StyleType::LinkAnnotation => {
871 self.link_annotations[record.index].end = self.text.len();
872 }
873 }
874 }
875 self
876 }
877
878 pub fn to_annotated_string(mut self) -> AnnotatedString {
880 while let Some(record) = self.style_stack.pop() {
881 match record.style_type {
882 StyleType::Span => {
883 self.span_styles[record.index].end = self.text.len();
884 }
885 StyleType::Paragraph => {
886 self.paragraph_styles[record.index].end = self.text.len();
887 }
888 StyleType::StringAnnotation => {
889 self.string_annotations[record.index].end = self.text.len();
890 }
891 StyleType::LinkAnnotation => {
892 self.link_annotations[record.index].end = self.text.len();
893 }
894 }
895 }
896
897 let mut handlers = Vec::new();
898 let links = self
899 .link_annotations
900 .into_iter()
901 .map(|link| RangeStyle {
902 item: match link.item {
903 LinkAnnotation::Url(url) => LinkKey::Url(url),
904 LinkAnnotation::Clickable { tag, handler } => {
905 handlers.push(handler);
906 LinkKey::Clickable(tag)
907 }
908 },
909 range: link.start..link.end,
910 })
911 .collect();
912 AnnotatedString::of_parts(
913 RenderString::from_parts(
914 self.text,
915 finished_ranges(self.span_styles),
916 finished_ranges(self.paragraph_styles),
917 finished_ranges(self.string_annotations),
918 links,
919 ),
920 handlers,
921 )
922 }
923
924 pub fn add_style(mut self, style: SpanStyle, range: Range<usize>) -> Self {
927 self.span_styles.push(MutableRange {
928 item: style,
929 start: range.start,
930 end: range.end,
931 });
932 self
933 }
934}
935
936#[cfg(test)]
937#[path = "tests/annotated_string_tests.rs"]
938mod tests;