Skip to main content

cranpose_ui/text/
annotated_string.rs

1use std::{ops::Range, rc::Rc};
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/// [`crate::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 { tag: String, handler: Rc<dyn Fn()> },
36}
37
38impl std::fmt::Debug for LinkAnnotation {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        match self {
41            Self::Url(url) => f.debug_tuple("Url").field(url).finish(),
42            Self::Clickable { tag, .. } => f.debug_struct("Clickable").field("tag", tag).finish(),
43        }
44    }
45}
46
47impl PartialEq for LinkAnnotation {
48    fn eq(&self, other: &Self) -> bool {
49        match (self, other) {
50            (Self::Url(a), Self::Url(b)) => a == b,
51            (
52                Self::Clickable {
53                    tag: ta,
54                    handler: ha,
55                },
56                Self::Clickable {
57                    tag: tb,
58                    handler: hb,
59                },
60            ) => ta == tb && Rc::ptr_eq(ha, hb),
61            _ => false,
62        }
63    }
64}
65
66/// Mirrors Jetpack Compose's `AnnotatedString.Range<String>` — a tag+value
67/// annotation covering a byte range.
68///
69/// JC ref: `androidx.compose.ui.text.AnnotatedString.Range`
70#[derive(Debug, Clone, PartialEq)]
71pub struct StringAnnotation {
72    pub tag: String,
73    pub annotation: String,
74}
75
76/// Link identity without the link behavior: what rendering may know about a
77/// [`LinkAnnotation`]. URL links keep their URL, clickable links keep their
78/// tag — the handler stays UI-side.
79#[derive(Debug, Clone, PartialEq)]
80pub enum LinkKey {
81    /// Identity of a [`LinkAnnotation::Url`].
82    Url(String),
83    /// Identity of a [`LinkAnnotation::Clickable`] — its tag.
84    Clickable(String),
85}
86
87/// What rendering reads from an [`AnnotatedString`]: content, styles, and
88/// link identity — never the link handlers, which live UI-side only.
89///
90/// Unlike `AnnotatedString` this is plain owned data (`Send + Sync`), so a
91/// lowered scene that carries it can cross threads.
92///
93/// Built once and never changed, it hashes itself when built: renderers key
94/// caches by [`RenderString::render_hash`] every frame.
95#[derive(Debug, Clone, PartialEq)]
96pub struct RenderString {
97    text: String,
98    span_styles: Vec<RangeStyle<SpanStyle>>,
99    paragraph_styles: Vec<RangeStyle<ParagraphStyle>>,
100    string_annotations: Vec<RangeStyle<StringAnnotation>>,
101    links: Vec<RangeStyle<LinkKey>>,
102    hash: u64,
103}
104
105impl Default for RenderString {
106    fn default() -> Self {
107        Self::from_parts(
108            String::new(),
109            Vec::new(),
110            Vec::new(),
111            Vec::new(),
112            Vec::new(),
113        )
114    }
115}
116
117const _: () = {
118    fn assert_send<T: Send + Sync>() {}
119    #[expect(dead_code)]
120    fn assert_render_string_is_send_sync() {
121        assert_send::<RenderString>();
122    }
123};
124
125impl RenderString {
126    fn from_parts(
127        text: String,
128        span_styles: Vec<RangeStyle<SpanStyle>>,
129        paragraph_styles: Vec<RangeStyle<ParagraphStyle>>,
130        string_annotations: Vec<RangeStyle<StringAnnotation>>,
131        links: Vec<RangeStyle<LinkKey>>,
132    ) -> Self {
133        let hash = render_hash_impl(&text, &span_styles, &paragraph_styles);
134        Self {
135            text,
136            span_styles,
137            paragraph_styles,
138            string_annotations,
139            links,
140            hash,
141        }
142    }
143
144    /// The characters.
145    pub fn text(&self) -> &str {
146        &self.text
147    }
148
149    pub fn span_styles(&self) -> &[RangeStyle<SpanStyle>] {
150        &self.span_styles
151    }
152
153    pub fn paragraph_styles(&self) -> &[RangeStyle<ParagraphStyle>] {
154        &self.paragraph_styles
155    }
156
157    pub fn string_annotations(&self) -> &[RangeStyle<StringAnnotation>] {
158        &self.string_annotations
159    }
160
161    /// Link ranges by identity (tag/url): enough to hash and to key caches,
162    /// never enough to invoke a link.
163    pub fn links(&self) -> &[RangeStyle<LinkKey>] {
164        &self.links
165    }
166
167    pub fn len(&self) -> usize {
168        self.text.len()
169    }
170
171    pub fn is_empty(&self) -> bool {
172        self.text.is_empty()
173    }
174
175    /// Returns a sorted list of unique byte indices where styles change.
176    ///
177    /// Mirrors [`AnnotatedString::span_boundaries`].
178    pub fn span_boundaries(&self) -> SpanBoundaries {
179        span_boundaries_impl(&self.text, &self.span_styles)
180    }
181
182    /// Mirrors [`AnnotatedString::render_hash`]: hashes the exact same fields
183    /// with the exact same formula, so a cache keyed by either stays keyed by
184    /// the same distinctions.
185    pub fn render_hash(&self) -> u64 {
186        self.hash
187    }
188
189    /// Returns a new `RenderString` containing a substring of the original
190    /// text and any styles that overlap with the new range, with indices
191    /// adjusted. Mirrors [`AnnotatedString::subsequence`].
192    pub fn subsequence(&self, range: std::ops::Range<usize>) -> Self {
193        let start = range.start.min(self.text.len());
194        let end = range.end.max(start).min(self.text.len());
195        if start == end {
196            return Self::default();
197        }
198
199        Self::from_parts(
200            self.text[start..end].to_string(),
201            clip_range_styles(&self.span_styles, start, end),
202            clip_range_styles(&self.paragraph_styles, start, end),
203            clip_range_styles(&self.string_annotations, start, end),
204            clip_range_styles(&self.links, start, end),
205        )
206    }
207}
208
209fn clip_range_styles<T: Clone>(
210    styles: &[RangeStyle<T>],
211    start: usize,
212    end: usize,
213) -> Vec<RangeStyle<T>> {
214    let mut clipped = Vec::new();
215    for style in styles {
216        let intersection_start = style.range.start.max(start);
217        let intersection_end = style.range.end.min(end);
218        if intersection_start < intersection_end {
219            clipped.push(RangeStyle {
220                item: style.item.clone(),
221                range: (intersection_start - start)..(intersection_end - start),
222            });
223        }
224    }
225    clipped
226}
227
228/// Byte offsets where a string's styles change, held inline for the few
229/// spans most text carries.
230pub type SpanBoundaries = smallvec::SmallVec<[usize; 8]>;
231
232fn span_boundaries_impl(text: &str, span_styles: &[RangeStyle<SpanStyle>]) -> SpanBoundaries {
233    let mut boundaries: SpanBoundaries = smallvec::smallvec![0, text.len()];
234    for span in span_styles {
235        boundaries.push(span.range.start);
236        boundaries.push(span.range.end);
237    }
238    boundaries.sort_unstable();
239    boundaries.dedup();
240    boundaries.retain(|boundary| *boundary <= text.len() && text.is_char_boundary(*boundary));
241    boundaries
242}
243
244fn render_hash_impl(
245    text: &str,
246    span_styles: &[RangeStyle<SpanStyle>],
247    paragraph_styles: &[RangeStyle<ParagraphStyle>],
248) -> u64 {
249    use std::hash::{Hash, Hasher};
250
251    let mut hasher = cranpose_ui_graphics::FxHasher::default();
252    text.hash(&mut hasher);
253    span_styles.len().hash(&mut hasher);
254    for span in span_styles {
255        span.range.start.hash(&mut hasher);
256        span.range.end.hash(&mut hasher);
257        span.item.render_hash().hash(&mut hasher);
258    }
259    paragraph_styles.len().hash(&mut hasher);
260    for paragraph in paragraph_styles {
261        paragraph.range.start.hash(&mut hasher);
262        paragraph.range.end.hash(&mut hasher);
263        paragraph.item.render_hash().hash(&mut hasher);
264    }
265    hasher.finish()
266}
267
268/// The basic data structure of text with multiple styles.
269///
270/// To construct an `AnnotatedString` you can use `AnnotatedString::builder()`.
271#[derive(Debug, Clone, PartialEq, Default)]
272pub struct AnnotatedString {
273    pub text: String,
274    pub span_styles: Vec<RangeStyle<SpanStyle>>,
275    pub paragraph_styles: Vec<RangeStyle<ParagraphStyle>>,
276    /// Arbitrary tag+value annotations. Used for e.g. clickable link URLs.
277    /// Mirrors JC `AnnotatedString.getStringAnnotations(tag, start, end)`.
278    pub string_annotations: Vec<RangeStyle<StringAnnotation>>,
279    /// Link annotations — URLs and clickable actions.
280    /// Mirrors JC `AnnotatedString.getLinkAnnotations(start, end)`.
281    pub link_annotations: Vec<RangeStyle<LinkAnnotation>>,
282}
283
284/// A style applied to a range of an `AnnotatedString`.
285#[derive(Debug, Clone, PartialEq)]
286pub struct RangeStyle<T> {
287    pub item: T,
288    pub range: Range<usize>,
289}
290
291/// Returns the shared [`AnnotatedString`] for a plain, style-free string,
292/// reusing the copy made on an earlier frame when the content matches.
293///
294/// Draw scopes lower every `draw_text*` call through an `AnnotatedString` on
295/// every frame — once to measure and once to emit — and a HUD label or score
296/// counter has the same characters frame after frame. Without this pool each
297/// pass re-copied a string it had copied the frame before, only to hash it and
298/// hit a layout cache that is keyed by content anyway. Entries are verified by
299/// content on hit, so a hash collision costs a fresh copy, never wrong text.
300/// The pool clears itself when full; a live scene re-warms within one frame.
301pub fn shared_plain_annotated_string(text: &str) -> Rc<AnnotatedString> {
302    with_shared_plain_text(text, |shared| Rc::clone(&shared.annotated))
303}
304
305/// The [`RenderString`] of [`shared_plain_annotated_string`]'s string for
306/// `text`, converted once while the pool holds it, so a canvas redrawing the
307/// same characters hands the renderer the same allocation every frame.
308pub fn shared_plain_render_string(text: &str) -> std::sync::Arc<RenderString> {
309    with_shared_plain_text(text, |shared| {
310        std::sync::Arc::clone(
311            shared
312                .render
313                .get_or_init(|| std::sync::Arc::new(shared.annotated.render_string())),
314        )
315    })
316}
317
318pub(crate) struct SharedPlainText {
319    annotated: Rc<AnnotatedString>,
320    render: std::cell::OnceCell<std::sync::Arc<RenderString>>,
321}
322
323fn with_shared_plain_text<R>(text: &str, read: impl FnOnce(&SharedPlainText) -> R) -> R {
324    use std::hash::{Hash, Hasher};
325
326    const POOL_CAPACITY: usize = 256;
327
328    let mut hasher = cranpose_ui_graphics::FxHasher::default();
329    text.hash(&mut hasher);
330    let key = hasher.finish();
331
332    crate::thread_state::with(|state| {
333        let mut pool = state.shared_plain_texts.borrow_mut();
334        if let Some(shared) = pool.get(&key)
335            && shared.annotated.text == text
336        {
337            return read(shared);
338        }
339        if pool.len() >= POOL_CAPACITY {
340            pool.clear();
341        }
342        let shared = pool.entry(key).insert_entry(SharedPlainText {
343            annotated: Rc::new(AnnotatedString::new(text.to_owned())),
344            render: std::cell::OnceCell::new(),
345        });
346        read(shared.get())
347    })
348}
349
350impl AnnotatedString {
351    pub fn new(text: String) -> Self {
352        Self {
353            text,
354            span_styles: vec![],
355            paragraph_styles: vec![],
356            string_annotations: vec![],
357            link_annotations: vec![],
358        }
359    }
360
361    pub fn builder() -> Builder {
362        Builder::new()
363    }
364
365    pub fn len(&self) -> usize {
366        self.text.len()
367    }
368
369    pub fn is_empty(&self) -> bool {
370        self.text.is_empty()
371    }
372
373    /// Returns a sorted list of unique byte indices where styles change.
374    pub fn span_boundaries(&self) -> SpanBoundaries {
375        span_boundaries_impl(&self.text, &self.span_styles)
376    }
377
378    /// Returns the [`RenderString`] view of this string: everything rendering
379    /// reads (content, styles, link identity), nothing it must not touch
380    /// (link handlers). A clone-conversion — memoize at the call site when
381    /// the same `AnnotatedString` lowers every frame.
382    pub fn render_string(&self) -> RenderString {
383        RenderString::from_parts(
384            self.text.clone(),
385            self.span_styles.clone(),
386            self.paragraph_styles.clone(),
387            self.string_annotations.clone(),
388            self.link_annotations
389                .iter()
390                .map(|link| RangeStyle {
391                    item: match &link.item {
392                        LinkAnnotation::Url(url) => LinkKey::Url(url.clone()),
393                        LinkAnnotation::Clickable { tag, .. } => LinkKey::Clickable(tag.clone()),
394                    },
395                    range: link.range.clone(),
396                })
397                .collect(),
398        )
399    }
400
401    /// Hash of the span styles' ranges and the attributes that change how
402    /// the text measures: two strings with the same text and hash measure
403    /// alike, whatever their spans' colors, backgrounds or decorations.
404    pub fn span_measurement_hash(&self) -> u64 {
405        use std::hash::Hasher;
406        let mut hasher = cranpose_ui_graphics::FxHasher::default();
407        hasher.write_usize(self.span_styles.len());
408        for span in &self.span_styles {
409            hasher.write_usize(span.range.start);
410            hasher.write_usize(span.range.end);
411            crate::text::style::hash_span_measurement(&span.item, &mut hasher);
412        }
413        hasher.finish()
414    }
415
416    pub fn render_hash(&self) -> u64 {
417        render_hash_impl(&self.text, &self.span_styles, &self.paragraph_styles)
418    }
419
420    /// Returns a new `AnnotatedString` containing a substring of the original text
421    /// and any styles that overlap with the new range, with indices adjusted.
422    pub fn subsequence(&self, range: std::ops::Range<usize>) -> Self {
423        if range.is_empty() {
424            return Self::new(String::new());
425        }
426
427        let start = range.start.min(self.text.len());
428        let end = range.end.max(start).min(self.text.len());
429
430        if start == end {
431            return Self::new(String::new());
432        }
433
434        let mut new_spans = Vec::new();
435        for span in &self.span_styles {
436            let intersection_start = span.range.start.max(start);
437            let intersection_end = span.range.end.min(end);
438            if intersection_start < intersection_end {
439                new_spans.push(RangeStyle {
440                    item: span.item.clone(),
441                    range: (intersection_start - start)..(intersection_end - start),
442                });
443            }
444        }
445
446        let mut new_paragraphs = Vec::new();
447        for span in &self.paragraph_styles {
448            let intersection_start = span.range.start.max(start);
449            let intersection_end = span.range.end.min(end);
450            if intersection_start < intersection_end {
451                new_paragraphs.push(RangeStyle {
452                    item: span.item.clone(),
453                    range: (intersection_start - start)..(intersection_end - start),
454                });
455            }
456        }
457
458        let mut new_string_annotations = Vec::new();
459        for ann in &self.string_annotations {
460            let intersection_start = ann.range.start.max(start);
461            let intersection_end = ann.range.end.min(end);
462            if intersection_start < intersection_end {
463                new_string_annotations.push(RangeStyle {
464                    item: ann.item.clone(),
465                    range: (intersection_start - start)..(intersection_end - start),
466                });
467            }
468        }
469
470        let mut new_link_annotations = Vec::new();
471        for ann in &self.link_annotations {
472            let intersection_start = ann.range.start.max(start);
473            let intersection_end = ann.range.end.min(end);
474            if intersection_start < intersection_end {
475                new_link_annotations.push(RangeStyle {
476                    item: ann.item.clone(),
477                    range: (intersection_start - start)..(intersection_end - start),
478                });
479            }
480        }
481
482        Self {
483            text: self.text[start..end].to_string(),
484            span_styles: new_spans,
485            paragraph_styles: new_paragraphs,
486            string_annotations: new_string_annotations,
487            link_annotations: new_link_annotations,
488        }
489    }
490
491    /// Returns all string annotations with the given `tag` whose range overlaps `[start, end)`.
492    ///
493    /// JC parity: `AnnotatedString.getStringAnnotations(tag, start, end) -> List<Range<String>>`
494    pub fn get_string_annotations(
495        &self,
496        tag: &str,
497        start: usize,
498        end: usize,
499    ) -> Vec<&RangeStyle<StringAnnotation>> {
500        self.string_annotations
501            .iter()
502            .filter(|ann| ann.item.tag == tag && ann.range.start < end && ann.range.end > start)
503            .collect()
504    }
505
506    /// Returns all link annotations whose range overlaps `[start, end)`.
507    ///
508    /// JC parity: `AnnotatedString.getLinkAnnotations(start, end)`
509    pub fn get_link_annotations(
510        &self,
511        start: usize,
512        end: usize,
513    ) -> Vec<&RangeStyle<LinkAnnotation>> {
514        self.link_annotations
515            .iter()
516            .filter(|ann| ann.range.start < end && ann.range.end > start)
517            .collect()
518    }
519}
520
521impl From<String> for AnnotatedString {
522    fn from(text: String) -> Self {
523        Self::new(text)
524    }
525}
526
527impl From<&str> for AnnotatedString {
528    fn from(text: &str) -> Self {
529        Self::new(text.to_owned())
530    }
531}
532
533impl From<&String> for AnnotatedString {
534    fn from(text: &String) -> Self {
535        Self::new(text.clone())
536    }
537}
538
539impl From<&mut String> for AnnotatedString {
540    fn from(text: &mut String) -> Self {
541        Self::new(text.clone())
542    }
543}
544
545/// A builder to construct `AnnotatedString`.
546#[derive(Debug, Default, Clone)]
547pub struct Builder {
548    text: String,
549    span_styles: Vec<MutableRange<SpanStyle>>,
550    paragraph_styles: Vec<MutableRange<ParagraphStyle>>,
551    string_annotations: Vec<MutableRange<StringAnnotation>>,
552    link_annotations: Vec<MutableRange<LinkAnnotation>>,
553    style_stack: Vec<StyleStackRecord>,
554}
555
556#[derive(Debug, Clone)]
557struct MutableRange<T> {
558    item: T,
559    start: usize,
560    end: usize,
561}
562
563#[derive(Debug, Clone)]
564struct StyleStackRecord {
565    style_type: StyleType,
566    index: usize,
567}
568
569#[derive(Debug, Clone, Copy, PartialEq, Eq)]
570enum StyleType {
571    Span,
572    Paragraph,
573    StringAnnotation,
574    LinkAnnotation,
575}
576
577fn clamp_subsequence_range(text: &str, range: Range<usize>) -> Range<usize> {
578    let start = range.start.min(text.len());
579    let end = range.end.max(start).min(text.len());
580    start..end
581}
582
583/// The ranges a builder collected, in a vector that keeps no room past
584/// them: a string outlives its builder, and a span style is 296 bytes, so
585/// the room growth left for four took 1,184 bytes for a string of one or
586/// two spans.
587fn finished_ranges<T>(ranges: Vec<MutableRange<T>>) -> Vec<RangeStyle<T>> {
588    let mut finished: Vec<RangeStyle<T>> = ranges
589        .into_iter()
590        .map(|range| RangeStyle {
591            item: range.item,
592            range: range.start..range.end,
593        })
594        .collect();
595    finished.shrink_to_fit();
596    finished
597}
598
599fn append_clipped_ranges<T: Clone>(
600    target: &mut Vec<MutableRange<T>>,
601    source: &[RangeStyle<T>],
602    source_range: Range<usize>,
603    target_offset: usize,
604) {
605    for style in source {
606        let intersection_start = style.range.start.max(source_range.start);
607        let intersection_end = style.range.end.min(source_range.end);
608        if intersection_start < intersection_end {
609            target.push(MutableRange {
610                item: style.item.clone(),
611                start: (intersection_start - source_range.start) + target_offset,
612                end: (intersection_end - source_range.start) + target_offset,
613            });
614        }
615    }
616}
617
618impl Builder {
619    pub fn new() -> Self {
620        Self::default()
621    }
622
623    /// Appends the given String to this Builder.
624    pub fn append(mut self, text: &str) -> Self {
625        self.text.push_str(text);
626        self
627    }
628
629    pub fn append_annotated(self, annotated: &AnnotatedString) -> Self {
630        self.append_annotated_subsequence(annotated, 0..annotated.text.len())
631    }
632
633    pub fn append_annotated_subsequence(
634        mut self,
635        annotated: &AnnotatedString,
636        range: Range<usize>,
637    ) -> Self {
638        let range = clamp_subsequence_range(annotated.text.as_str(), range);
639        if range.is_empty() {
640            return self;
641        }
642
643        debug_assert!(annotated.text.is_char_boundary(range.start));
644        debug_assert!(annotated.text.is_char_boundary(range.end));
645
646        let target_offset = self.text.len();
647        self.text.push_str(&annotated.text[range.clone()]);
648        append_clipped_ranges(
649            &mut self.span_styles,
650            &annotated.span_styles,
651            range.clone(),
652            target_offset,
653        );
654        append_clipped_ranges(
655            &mut self.paragraph_styles,
656            &annotated.paragraph_styles,
657            range.clone(),
658            target_offset,
659        );
660        append_clipped_ranges(
661            &mut self.string_annotations,
662            &annotated.string_annotations,
663            range.clone(),
664            target_offset,
665        );
666        append_clipped_ranges(
667            &mut self.link_annotations,
668            &annotated.link_annotations,
669            range,
670            target_offset,
671        );
672        self
673    }
674
675    /// Applies the given `SpanStyle` to any appended text until a corresponding `pop` is called.
676    ///
677    /// Returns the index of the pushed style, which can be passed to `pop_to` or used as an ID.
678    pub fn push_style(mut self, style: SpanStyle) -> Self {
679        let index = self.span_styles.len();
680        self.span_styles.push(MutableRange {
681            item: style,
682            start: self.text.len(),
683            end: usize::MAX,
684        });
685        self.style_stack.push(StyleStackRecord {
686            style_type: StyleType::Span,
687            index,
688        });
689        self
690    }
691
692    /// Applies the given `ParagraphStyle` to any appended text until a corresponding `pop` is called.
693    pub fn push_paragraph_style(mut self, style: ParagraphStyle) -> Self {
694        let index = self.paragraph_styles.len();
695        self.paragraph_styles.push(MutableRange {
696            item: style,
697            start: self.text.len(),
698            end: usize::MAX,
699        });
700        self.style_stack.push(StyleStackRecord {
701            style_type: StyleType::Paragraph,
702            index,
703        });
704        self
705    }
706
707    /// Pushes a string annotation covering subsequent appended text until the matching `pop`.
708    ///
709    /// JC parity: `Builder.pushStringAnnotation(tag, annotation)`
710    pub fn push_string_annotation(mut self, tag: &str, annotation: &str) -> Self {
711        let index = self.string_annotations.len();
712        self.string_annotations.push(MutableRange {
713            item: StringAnnotation {
714                tag: tag.to_string(),
715                annotation: annotation.to_string(),
716            },
717            start: self.text.len(),
718            end: usize::MAX,
719        });
720        self.style_stack.push(StyleStackRecord {
721            style_type: StyleType::StringAnnotation,
722            index,
723        });
724        self
725    }
726
727    /// Pushes a [`LinkAnnotation`] covering subsequent appended text.
728    /// Call `pop` when done, or use `with_link` for the block form.
729    ///
730    /// JC parity: `Builder.pushLink(link)`
731    pub fn push_link(mut self, link: LinkAnnotation) -> Self {
732        let index = self.link_annotations.len();
733        self.link_annotations.push(MutableRange {
734            item: link,
735            start: self.text.len(),
736            end: usize::MAX,
737        });
738        self.style_stack.push(StyleStackRecord {
739            style_type: StyleType::LinkAnnotation,
740            index,
741        });
742        self
743    }
744
745    /// Block form of `push_link` — mirrors JC's `withLink(link) { ... }` DSL.
746    ///
747    /// # Example
748    ///
749    /// ```rust,ignore
750    /// builder
751    ///     .append("Visit ")
752    ///     .with_link(
753    ///         LinkAnnotation::Url("https://developer.android.com".into()),
754    ///         |b| b.append("Android Developers"),
755    ///     )
756    ///     .append(".")
757    ///     .to_annotated_string()
758    /// ```
759    pub fn with_link(self, link: LinkAnnotation, block: impl FnOnce(Self) -> Self) -> Self {
760        let b = self.push_link(link);
761        let b = block(b);
762        b.pop()
763    }
764
765    /// Ends the style that was most recently pushed.
766    pub fn pop(mut self) -> Self {
767        if let Some(record) = self.style_stack.pop() {
768            match record.style_type {
769                StyleType::Span => {
770                    self.span_styles[record.index].end = self.text.len();
771                }
772                StyleType::Paragraph => {
773                    self.paragraph_styles[record.index].end = self.text.len();
774                }
775                StyleType::StringAnnotation => {
776                    self.string_annotations[record.index].end = self.text.len();
777                }
778                StyleType::LinkAnnotation => {
779                    self.link_annotations[record.index].end = self.text.len();
780                }
781            }
782        }
783        self
784    }
785
786    /// Completes the builder, resolving open styles to the end of the text.
787    pub fn to_annotated_string(mut self) -> AnnotatedString {
788        while let Some(record) = self.style_stack.pop() {
789            match record.style_type {
790                StyleType::Span => {
791                    self.span_styles[record.index].end = self.text.len();
792                }
793                StyleType::Paragraph => {
794                    self.paragraph_styles[record.index].end = self.text.len();
795                }
796                StyleType::StringAnnotation => {
797                    self.string_annotations[record.index].end = self.text.len();
798                }
799                StyleType::LinkAnnotation => {
800                    self.link_annotations[record.index].end = self.text.len();
801                }
802            }
803        }
804
805        AnnotatedString {
806            text: self.text,
807            span_styles: finished_ranges(self.span_styles),
808            paragraph_styles: finished_ranges(self.paragraph_styles),
809            string_annotations: finished_ranges(self.string_annotations),
810            link_annotations: finished_ranges(self.link_annotations),
811        }
812    }
813}
814
815#[cfg(test)]
816#[path = "tests/annotated_string_tests.rs"]
817mod tests;