Skip to main content

cranpose_text/
annotated_string.rs

1use std::{ops::Range, rc::Rc, sync::Arc};
2
3use crate::{ParagraphStyle, SpanStyle};
4
5/// Mirrors Jetpack Compose's `LinkAnnotation` sealed class.
6///
7/// Attach to a text range via [`Builder::push_link`] or [`Builder::with_link`].
8/// `cranpose_ui::widgets::LinkedText` automatically opens URLs and invokes handlers
9/// when the user taps the annotated text.
10///
11/// # JC ref
12/// `androidx.compose.foundation.text.input.internal.selection.LinkAnnotation`
13///
14/// # Example
15///
16/// ```rust,ignore
17/// let text = AnnotatedString::builder()
18///     .append("Visit ")
19///     .with_link(
20///         LinkAnnotation::Url("https://developer.android.com".into()),
21///         |b| b.append("Android Developers"),
22///     )
23///     .to_annotated_string();
24/// ```
25#[derive(Clone)]
26pub enum LinkAnnotation {
27    /// Opens the given URL via the platform URI handler when clicked.
28    ///
29    /// JC parity: `LinkAnnotation.Url(url)`
30    Url(String),
31
32    /// Calls an arbitrary handler when clicked.
33    ///
34    /// JC parity: `LinkAnnotation.Clickable(tag, linkInteractionListener)`
35    Clickable {
36        /// Name that identifies the link.
37        tag: String,
38        /// Called when the user clicks the link.
39        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/// Mirrors Jetpack Compose's `AnnotatedString.Range<String>` — a tag+value
72/// annotation covering a byte range.
73///
74/// JC ref: `androidx.compose.ui.text.AnnotatedString.Range`
75#[derive(Debug, Clone, PartialEq)]
76pub struct StringAnnotation {
77    /// Name that groups annotations. Look annotations up by it with
78    /// `AnnotatedString::get_string_annotations`.
79    pub tag: String,
80    /// The value stored for the tag.
81    pub annotation: String,
82}
83
84/// Link identity without the link behavior: what rendering may know about a
85/// [`LinkAnnotation`]. URL links keep their URL, clickable links keep their
86/// tag — the handler stays UI-side.
87#[derive(Debug, Clone, PartialEq)]
88pub enum LinkKey {
89    /// Identity of a [`LinkAnnotation::Url`].
90    Url(String),
91    /// Identity of a [`LinkAnnotation::Clickable`] — its tag.
92    Clickable(String),
93}
94
95/// What rendering reads from an [`AnnotatedString`]: content, styles, and
96/// link identity — never the link handlers, which live UI-side only.
97///
98/// Unlike `AnnotatedString` this is plain owned data (`Send + Sync`), so a
99/// lowered scene that carries it can cross threads. An `AnnotatedString`
100/// keeps its content in one of these, which the renderer shares.
101///
102/// Built once and never changed, it hashes itself when built: renderers key
103/// caches by [`RenderString::render_hash`] every frame.
104#[derive(Debug, Clone)]
105pub struct RenderString {
106    text: String,
107    span_styles: Box<[RangeStyle<SpanStyle>]>,
108    // Paragraph styles, string annotations and links, which most text lacks.
109    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, &paragraph_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    // `text` with no styles, annotations or links.
170    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    // The bytes the string's text has room for, when it has no styles or
181    // annotations; `None` otherwise.
182    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    // Makes a plain string hold `text`, in the room its text has.
187    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    /// The characters.
194    pub fn text(&self) -> &str {
195        &self.text
196    }
197
198    /// Character styles with the byte ranges they cover.
199    pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
200        &self.span_styles
201    }
202
203    /// Paragraph styles with the byte ranges they cover.
204    pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
205        self.extras
206            .as_deref()
207            .map_or(&[], |extras| &extras.paragraph_styles)
208    }
209
210    /// Tag and value annotations with the byte ranges they cover.
211    pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
212        self.extras
213            .as_deref()
214            .map_or(&[], |extras| &extras.string_annotations)
215    }
216
217    /// Link ranges by identity (tag/url): enough to hash and to key caches,
218    /// never enough to invoke a link.
219    pub fn links(&self) -> &[RangeStyle<LinkKey>] {
220        self.extras.as_deref().map_or(&[], |extras| &extras.links)
221    }
222
223    /// Length of the text in bytes.
224    pub fn len(&self) -> usize {
225        self.text.len()
226    }
227
228    /// Returns true when the text is empty.
229    pub fn is_empty(&self) -> bool {
230        self.text.is_empty()
231    }
232
233    /// Returns a sorted list of unique byte indices where styles change.
234    pub fn span_boundaries(&self) -> SpanBoundaries {
235        span_boundaries_impl(&self.text, &self.span_styles)
236    }
237
238    /// Hash of the text and of the span and paragraph styles, as renderers
239    /// use it to key caches.
240    pub fn render_hash(&self) -> u64 {
241        self.hash
242    }
243
244    /// Returns a new `RenderString` containing a substring of the original
245    /// text and any styles that overlap with the new range, with indices
246    /// adjusted.
247    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
264// Compose's `intersect`: whether two ranges share a character, or one is
265// empty and the other contains it.
266fn 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
270// Compose's `contains`: whether `base` holds `target`; equal ends count only
271// when both ranges are empty or both are not.
272fn 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
297/// Byte offsets where a string's styles change, held inline for the few
298/// spans most text carries.
299pub 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
337// What a clickable link calls when it is clicked.
338type LinkHandler = Rc<dyn Fn()>;
339
340// The content every empty string shares, so an empty string allocates
341// nothing.
342static EMPTY: std::sync::LazyLock<Arc<RenderString>> =
343    std::sync::LazyLock::new(|| Arc::new(RenderString::plain(String::new())));
344
345/// The basic data structure of text with multiple styles: Compose's
346/// `AnnotatedString`. Its content, the text, styles, annotations and link
347/// identities, is shared with every layout and draw made from it, so a clone
348/// copies no text. The handlers of its clickable links stay with it.
349///
350/// To construct an `AnnotatedString` with styles you can use
351/// `AnnotatedString::builder()`.
352#[derive(Clone)]
353pub struct AnnotatedString {
354    content: Arc<RenderString>,
355    // The handler of each clickable link of `content`, in the links' order;
356    // `None` when it has none.
357    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/// A style applied to a range of an `AnnotatedString`.
396#[derive(Debug, Clone, PartialEq)]
397pub struct RangeStyle<T> {
398    /// The style or annotation that applies to the range.
399    pub item: T,
400    /// Byte range of the text the item covers. Both ends lie on character boundaries.
401    pub range: Range<usize>,
402}
403
404impl AnnotatedString {
405    // The string's content, when it has no link handlers.
406    pub(crate) fn into_plain_content(self) -> Option<Arc<RenderString>> {
407        self.handlers.is_none().then_some(self.content)
408    }
409
410    /// Creates a string holding `text` with no styles and no annotations.
411    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    // The string of `content`'s links, with `handlers` for its clickable
422    // ones in their order.
423    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    /// Starts a [`Builder`] for a string with styles and annotations.
431    pub fn builder() -> Builder {
432        Builder::new()
433    }
434
435    /// The characters.
436    pub fn text(&self) -> &str {
437        &self.content.text
438    }
439
440    /// Whether this is `text` with no styles, annotations or links: the
441    /// string [`AnnotatedString::new`] makes of `text`.
442    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    /// Character styles with the byte ranges they cover.
450    pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
451        &self.content.span_styles
452    }
453
454    /// Paragraph styles with the byte ranges they cover.
455    pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
456        self.content.paragraph_styles()
457    }
458
459    /// Tag and value annotations with the byte ranges they cover.
460    pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
461        self.content.string_annotations()
462    }
463
464    /// Whether a link annotation covers part of `[start, end)`.
465    ///
466    /// JC parity: `AnnotatedString.hasLinkAnnotations(start, end)`
467    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    /// Length of the text in bytes.
475    pub fn len(&self) -> usize {
476        self.content.text.len()
477    }
478
479    /// Returns true when the text is empty.
480    pub fn is_empty(&self) -> bool {
481        self.content.text.is_empty()
482    }
483
484    /// Returns a sorted list of unique byte indices where styles change.
485    pub fn span_boundaries(&self) -> SpanBoundaries {
486        self.content.span_boundaries()
487    }
488
489    /// The content as rendering reads it (text, styles, link identity), never
490    /// the link handlers. Shared: every clone of this string holds the same.
491    pub fn render_string(&self) -> &Arc<RenderString> {
492        &self.content
493    }
494
495    /// Hash of the span styles' ranges and the attributes that change how
496    /// the text measures: two strings with the same text and hash measure
497    /// alike, whatever their spans' colors, backgrounds or decorations.
498    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    /// Hash of the text and of the span and paragraph styles, as renderers use it to key caches.
512    pub fn render_hash(&self) -> u64 {
513        self.content.hash
514    }
515
516    /// This string with `map` applied to each of its span styles: the same
517    /// text, ranges, annotations and links.
518    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    /// Returns a new `AnnotatedString` containing a substring of the original text
535    /// and any styles that overlap with the new range, with indices adjusted.
536    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    /// Returns all string annotations with the given `tag` whose range overlaps `[start, end)`.
547    ///
548    /// JC parity: `AnnotatedString.getStringAnnotations(tag, start, end) -> List<Range<String>>`
549    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    /// Returns all link annotations whose range overlaps `[start, end)`.
562    ///
563    /// JC parity: `AnnotatedString.getLinkAnnotations(start, end)`
564    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    // Every link annotation in order, each clickable one with its handler.
575    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
598// The text and spans of `content`, shared, with no link handlers: what a
599// renderer draws of a text.
600impl 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/// A builder to construct `AnnotatedString`.
628#[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
665// The ranges a builder collected, each from its start to its end.
666fn 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    /// Creates a builder with no text.
697    pub fn new() -> Self {
698        Self::default()
699    }
700
701    /// Appends the given String to this Builder.
702    pub fn append(mut self, text: &str) -> Self {
703        self.text.push_str(text);
704        self
705    }
706
707    /// Appends the text of `annotated` together with its styles and annotations.
708    pub fn append_annotated(self, annotated: &AnnotatedString) -> Self {
709        self.append_annotated_subsequence(annotated, 0..annotated.len())
710    }
711
712    /// Appends the bytes of `annotated` in `range` with the styles and annotations that overlap
713    /// them. The range is clamped to the text and both ends must lie on character boundaries.
714    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    /// Applies the given `SpanStyle` to any appended text until a corresponding `pop` is called.
768    ///
769    /// Returns the index of the pushed style, which can be passed to `pop_to` or used as an ID.
770    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    /// Applies the given `ParagraphStyle` to any appended text until a corresponding `pop` is called.
785    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    /// Pushes a string annotation covering subsequent appended text until the matching `pop`.
800    ///
801    /// JC parity: `Builder.pushStringAnnotation(tag, annotation)`
802    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    /// Pushes a [`LinkAnnotation`] covering subsequent appended text.
820    /// Call `pop` when done, or use `with_link` for the block form.
821    ///
822    /// JC parity: `Builder.pushLink(link)`
823    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    /// Block form of `push_link` — mirrors JC's `withLink(link) { ... }` DSL.
838    ///
839    /// # Example
840    ///
841    /// ```rust,ignore
842    /// builder
843    ///     .append("Visit ")
844    ///     .with_link(
845    ///         LinkAnnotation::Url("https://developer.android.com".into()),
846    ///         |b| b.append("Android Developers"),
847    ///     )
848    ///     .append(".")
849    ///     .to_annotated_string()
850    /// ```
851    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    /// Ends the style that was most recently pushed.
858    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    /// Completes the builder, resolving open styles to the end of the text.
879    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    /// Applies `style` to the bytes of the text in `range`, as Compose's
925    /// `addStyle(style, start, end)`.
926    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;