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    // Makes a plain string hold `text` in `text`'s own room.
194    pub(crate) fn replace_plain(&mut self, text: String) {
195        self.hash = render_hash_impl(&text, &[], &[]);
196        self.text = text;
197    }
198
199    /// The characters.
200    pub fn text(&self) -> &str {
201        &self.text
202    }
203
204    /// Character styles with the byte ranges they cover.
205    pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
206        &self.span_styles
207    }
208
209    /// Paragraph styles with the byte ranges they cover.
210    pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
211        self.extras
212            .as_deref()
213            .map_or(&[], |extras| &extras.paragraph_styles)
214    }
215
216    /// Tag and value annotations with the byte ranges they cover.
217    pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
218        self.extras
219            .as_deref()
220            .map_or(&[], |extras| &extras.string_annotations)
221    }
222
223    /// Link ranges by identity (tag/url): enough to hash and to key caches,
224    /// never enough to invoke a link.
225    pub fn links(&self) -> &[RangeStyle<LinkKey>] {
226        self.extras.as_deref().map_or(&[], |extras| &extras.links)
227    }
228
229    /// Length of the text in bytes.
230    pub fn len(&self) -> usize {
231        self.text.len()
232    }
233
234    /// Returns true when the text is empty.
235    pub fn is_empty(&self) -> bool {
236        self.text.is_empty()
237    }
238
239    /// Returns a sorted list of unique byte indices where styles change.
240    pub fn span_boundaries(&self) -> SpanBoundaries {
241        span_boundaries_impl(&self.text, &self.span_styles)
242    }
243
244    /// Hash of the text and of the span and paragraph styles, as renderers
245    /// use it to key caches.
246    pub fn render_hash(&self) -> u64 {
247        self.hash
248    }
249
250    /// Returns a new `RenderString` containing a substring of the original
251    /// text and any styles that overlap with the new range, with indices
252    /// adjusted.
253    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
270// Compose's `intersect`: whether two ranges share a character, or one is
271// empty and the other contains it.
272fn 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
276// Compose's `contains`: whether `base` holds `target`; equal ends count only
277// when both ranges are empty or both are not.
278fn 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
303/// Byte offsets where a string's styles change, held inline for the few
304/// spans most text carries.
305pub 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
343// What a clickable link calls when it is clicked.
344type LinkHandler = Rc<dyn Fn()>;
345
346// The content every empty string shares, so an empty string allocates
347// nothing.
348static EMPTY: std::sync::LazyLock<Arc<RenderString>> =
349    std::sync::LazyLock::new(|| Arc::new(RenderString::plain(String::new())));
350
351/// The basic data structure of text with multiple styles: Compose's
352/// `AnnotatedString`. Its content, the text, styles, annotations and link
353/// identities, is shared with every layout and draw made from it, so a clone
354/// copies no text. The handlers of its clickable links stay with it.
355///
356/// To construct an `AnnotatedString` with styles you can use
357/// `AnnotatedString::builder()`.
358#[derive(Clone)]
359pub struct AnnotatedString {
360    content: Arc<RenderString>,
361    // The handler of each clickable link of `content`, in the links' order;
362    // `None` when it has none.
363    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/// A style applied to a range of an `AnnotatedString`.
402#[derive(Debug, Clone, PartialEq)]
403pub struct RangeStyle<T> {
404    /// The style or annotation that applies to the range.
405    pub item: T,
406    /// Byte range of the text the item covers. Both ends lie on character boundaries.
407    pub range: Range<usize>,
408}
409
410impl AnnotatedString {
411    // The string's content, when it has no link handlers.
412    pub(crate) fn into_plain_content(self) -> Option<Arc<RenderString>> {
413        self.handlers.is_none().then_some(self.content)
414    }
415
416    /// Creates a string holding `text` with no styles and no annotations.
417    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    // The string of `content`'s links, with `handlers` for its clickable
428    // ones in their order.
429    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    /// Starts a [`Builder`] for a string with styles and annotations.
437    pub fn builder() -> Builder {
438        Builder::new()
439    }
440
441    /// The characters.
442    pub fn text(&self) -> &str {
443        &self.content.text
444    }
445
446    /// Whether this is `text` with no styles, annotations or links: the
447    /// string [`AnnotatedString::new`] makes of `text`.
448    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    /// Character styles with the byte ranges they cover.
456    pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
457        &self.content.span_styles
458    }
459
460    /// Paragraph styles with the byte ranges they cover.
461    pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
462        self.content.paragraph_styles()
463    }
464
465    /// Tag and value annotations with the byte ranges they cover.
466    pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
467        self.content.string_annotations()
468    }
469
470    /// Whether a link annotation covers part of `[start, end)`.
471    ///
472    /// JC parity: `AnnotatedString.hasLinkAnnotations(start, end)`
473    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    /// Length of the text in bytes.
481    pub fn len(&self) -> usize {
482        self.content.text.len()
483    }
484
485    /// Returns true when the text is empty.
486    pub fn is_empty(&self) -> bool {
487        self.content.text.is_empty()
488    }
489
490    /// Returns a sorted list of unique byte indices where styles change.
491    pub fn span_boundaries(&self) -> SpanBoundaries {
492        self.content.span_boundaries()
493    }
494
495    /// The content as rendering reads it (text, styles, link identity), never
496    /// the link handlers. Shared: every clone of this string holds the same.
497    pub fn render_string(&self) -> &Arc<RenderString> {
498        &self.content
499    }
500
501    /// Hash of the span styles' ranges and the attributes that change how
502    /// the text measures: two strings with the same text and hash measure
503    /// alike, whatever their spans' colors, backgrounds or decorations.
504    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    /// Hash of the text and of the span and paragraph styles, as renderers use it to key caches.
518    pub fn render_hash(&self) -> u64 {
519        self.content.hash
520    }
521
522    /// This string with `map` applied to each of its span styles: the same
523    /// text, ranges, annotations and links.
524    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    /// Returns a new `AnnotatedString` containing a substring of the original text
541    /// and any styles that overlap with the new range, with indices adjusted.
542    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    /// Returns all string annotations with the given `tag` whose range overlaps `[start, end)`.
553    ///
554    /// JC parity: `AnnotatedString.getStringAnnotations(tag, start, end) -> List<Range<String>>`
555    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    /// Returns all link annotations whose range overlaps `[start, end)`.
568    ///
569    /// JC parity: `AnnotatedString.getLinkAnnotations(start, end)`
570    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    // Every link annotation in order, each clickable one with its handler.
581    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
604// The text and spans of `content`, shared, with no link handlers: what a
605// renderer draws of a text.
606impl 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/// A builder to construct `AnnotatedString`.
634#[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
671// The ranges a builder collected, each from its start to its end.
672fn 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    /// Creates a builder with no text.
703    pub fn new() -> Self {
704        Self::default()
705    }
706
707    /// Appends the given String to this Builder.
708    pub fn append(mut self, text: &str) -> Self {
709        self.text.push_str(text);
710        self
711    }
712
713    /// Appends the text of `annotated` together with its styles and annotations.
714    pub fn append_annotated(self, annotated: &AnnotatedString) -> Self {
715        self.append_annotated_subsequence(annotated, 0..annotated.len())
716    }
717
718    /// Appends the bytes of `annotated` in `range` with the styles and annotations that overlap
719    /// them. The range is clamped to the text and both ends must lie on character boundaries.
720    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    /// Applies the given `SpanStyle` to any appended text until a corresponding `pop` is called.
774    ///
775    /// Returns the index of the pushed style, which can be passed to `pop_to` or used as an ID.
776    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    /// Applies the given `ParagraphStyle` to any appended text until a corresponding `pop` is called.
791    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    /// Pushes a string annotation covering subsequent appended text until the matching `pop`.
806    ///
807    /// JC parity: `Builder.pushStringAnnotation(tag, annotation)`
808    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    /// Pushes a [`LinkAnnotation`] covering subsequent appended text.
826    /// Call `pop` when done, or use `with_link` for the block form.
827    ///
828    /// JC parity: `Builder.pushLink(link)`
829    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    /// Block form of `push_link` — mirrors JC's `withLink(link) { ... }` DSL.
844    ///
845    /// # Example
846    ///
847    /// ```rust,ignore
848    /// builder
849    ///     .append("Visit ")
850    ///     .with_link(
851    ///         LinkAnnotation::Url("https://developer.android.com".into()),
852    ///         |b| b.append("Android Developers"),
853    ///     )
854    ///     .append(".")
855    ///     .to_annotated_string()
856    /// ```
857    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    /// Ends the style that was most recently pushed.
864    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    /// Completes the builder, resolving open styles to the end of the text.
885    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    /// Applies `style` to the bytes of the text in `range`, as Compose's
931    /// `addStyle(style, start, end)`.
932    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;