Skip to main content

repose_core/
text.rs

1use crate::Color;
2use crate::units::Sp;
3use std::fmt::Debug;
4use std::rc::Rc;
5use std::sync::Arc;
6
7/// A range of text measured in byte offsets, matching Compose's `TextRange`.
8///
9/// When `start == end`, the range is collapsed (cursor position).
10/// When `start > end`, the range is reversed (selection direction matters).
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub struct TextRange {
13    pub start: usize,
14    pub end: usize,
15}
16
17impl TextRange {
18    pub const ZERO: TextRange = TextRange { start: 0, end: 0 };
19
20    pub fn new(start: usize, end: usize) -> Self {
21        Self { start, end }
22    }
23
24    pub fn collapsed(at: usize) -> Self {
25        Self { start: at, end: at }
26    }
27
28    pub fn min(self) -> usize {
29        self.start.min(self.end)
30    }
31
32    pub fn max(self) -> usize {
33        self.start.max(self.end)
34    }
35
36    pub fn is_collapsed(self) -> bool {
37        self.start == self.end
38    }
39
40    pub fn reversed(self) -> bool {
41        self.start > self.end
42    }
43
44    pub fn length(self) -> usize {
45        self.max() - self.min()
46    }
47
48    pub fn intersects(self, other: TextRange) -> bool {
49        self.min() < other.max() && other.min() < self.max()
50    }
51
52    pub fn contains(self, offset: usize) -> bool {
53        self.min() <= offset && offset < self.max()
54    }
55
56    pub fn coerce_in(self, min: usize, max: usize) -> Self {
57        Self {
58            start: self.start.clamp(min, max),
59            end: self.end.clamp(min, max),
60        }
61    }
62}
63
64impl From<(usize, usize)> for TextRange {
65    fn from((start, end): (usize, usize)) -> Self {
66        Self { start, end }
67    }
68}
69
70/// Geometry the layout engine measured for a selectable `Text` node.
71///
72/// Published so hit testing wraps and measures lines exactly like the paint
73/// pass does, instead of re-deriving them from font size alone.
74#[derive(Clone, Copy, Debug, Default, PartialEq)]
75pub struct TextLayoutGeometry {
76    /// Width the text was wrapped into, in px.
77    pub wrap_width_px: f32,
78    /// Distance between consecutive line tops, in px.
79    pub line_height_px: f32,
80    /// Top-left of the text block, relative to the node's top-left, in px.
81    pub origin: (f32, f32),
82}
83
84/// Selected range of a `Text` node, drawn by the layout engine behind the
85/// glyphs the way Compose's `SelectionController` draws from a
86/// `TextLayoutResult`.
87///
88/// A range with `start > end` is reversed (the anchor sits at `end`);
89/// painting normalizes it.
90#[derive(Clone, Default)]
91pub struct TextSelection {
92    range: Rc<std::cell::RefCell<Option<TextRange>>>,
93    geometry: Rc<std::cell::RefCell<TextLayoutGeometry>>,
94}
95
96impl TextSelection {
97    pub fn range(&self) -> Option<TextRange> {
98        *self.range.borrow()
99    }
100
101    pub fn set_range(&self, range: Option<TextRange>) {
102        *self.range.borrow_mut() = range;
103    }
104
105    pub fn geometry(&self) -> TextLayoutGeometry {
106        *self.geometry.borrow()
107    }
108
109    /// Called by the layout engine after measuring the node.
110    pub fn set_geometry(&self, geometry: TextLayoutGeometry) {
111        *self.geometry.borrow_mut() = geometry;
112    }
113
114    /// Stable identity: the pointer of the shared state Rc.
115    pub fn stable_id(&self) -> *const () {
116        Rc::as_ptr(&self.range) as *const ()
117    }
118}
119
120impl Debug for TextSelection {
121    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct("TextSelection")
123            .field("range", &self.range())
124            .finish_non_exhaustive()
125    }
126}
127
128/// Snapshot of a text field's editing state including text, selection, and
129/// IME composition range. Corresponds to Compose's `TextFieldValue`.
130#[derive(Clone, Debug, PartialEq)]
131pub struct TextFieldValue {
132    /// The annotated text. Plain text is accessible via `text()` or `annotated_string.text`.
133    pub annotated_string: AnnotatedString,
134    /// Selection range in byte offsets. Collapsed range (start == end) = cursor.
135    pub selection: TextRange,
136    /// Active IME composition range in byte offsets, or None.
137    pub composition: Option<TextRange>,
138}
139
140impl TextFieldValue {
141    /// Create from plain text (no annotations).
142    pub fn new(text: impl Into<String>) -> Self {
143        let annotated = AnnotatedString::from(text.into());
144        let len = annotated.text.len();
145        Self {
146            selection: TextRange::collapsed(len),
147            annotated_string: annotated,
148            composition: None,
149        }
150    }
151
152    /// Create from an `AnnotatedString` preserving all annotations.
153    pub fn from_annotated(annotated: AnnotatedString) -> Self {
154        let len = annotated.text.len();
155        Self {
156            selection: TextRange::collapsed(len),
157            annotated_string: annotated,
158            composition: None,
159        }
160    }
161
162    /// Convenience: plain text content (delegates to `annotated_string.text`).
163    pub fn text(&self) -> &str {
164        &self.annotated_string.text
165    }
166
167    pub fn with_selection(mut self, start: usize, end: usize) -> Self {
168        let len = self.annotated_string.text.len();
169        self.selection = TextRange::new(start.min(len), end.min(len));
170        self
171    }
172
173    pub fn get_text_before_selection(&self, max_chars: usize) -> AnnotatedString {
174        let sel_min = self.selection.min();
175        let start = sel_min.saturating_sub(max_chars);
176        let text = self.annotated_string.text[start..sel_min].to_string();
177        // Preserve spans that intersect the sub-range
178        let spans: Vec<TextSpan> = self
179            .annotated_string
180            .spans
181            .iter()
182            .filter(|s| s.start >= start && s.end <= sel_min)
183            .map(|s| TextSpan {
184                start: s.start - start,
185                end: s.end - start,
186                style: s.style.clone(),
187                url: s.url.clone(),
188            })
189            .collect();
190        AnnotatedString::new(text, spans)
191    }
192
193    pub fn get_text_after_selection(&self, max_chars: usize) -> AnnotatedString {
194        let sel_max = self.selection.max();
195        let end = (sel_max + max_chars).min(self.annotated_string.text.len());
196        let text = self.annotated_string.text[sel_max..end].to_string();
197        let spans: Vec<TextSpan> = self
198            .annotated_string
199            .spans
200            .iter()
201            .filter(|s| s.start >= sel_max && s.end <= end)
202            .map(|s| TextSpan {
203                start: s.start - sel_max,
204                end: s.end - sel_max,
205                style: s.style.clone(),
206                url: s.url.clone(),
207            })
208            .collect();
209        AnnotatedString::new(text, spans)
210    }
211
212    pub fn get_selected_text(&self) -> AnnotatedString {
213        let r = self.selection.min()..self.selection.max();
214        let text = self.annotated_string.text[r.clone()].to_string();
215        let spans: Vec<TextSpan> = self
216            .annotated_string
217            .spans
218            .iter()
219            .filter(|s| s.start >= r.start && s.end <= r.end)
220            .map(|s| TextSpan {
221                start: s.start - r.start,
222                end: s.end - r.start,
223                style: s.style.clone(),
224                url: s.url.clone(),
225            })
226            .collect();
227        AnnotatedString::new(text, spans)
228    }
229
230    pub fn copy(&self, annotated_string: AnnotatedString) -> Self {
231        TextFieldValue {
232            annotated_string,
233            selection: self.selection,
234            composition: self.composition,
235        }
236    }
237
238    pub fn copy_text(&self, text: String) -> Self {
239        TextFieldValue {
240            annotated_string: AnnotatedString::from(text),
241            selection: self.selection,
242            composition: self.composition,
243        }
244    }
245}
246
247/// Result of text layout for `on_text_layout`.
248#[derive(Clone, Debug)]
249pub struct TextLayoutResult {
250    pub line_count: usize,
251    pub width_px: f32,
252    pub height_px: f32,
253    pub first_baseline: f32,
254    pub last_baseline: f32,
255    pub did_overflow_width: bool,
256    pub did_overflow_height: bool,
257    pub lines: Vec<TextLineInfo>,
258}
259
260/// How text is obfuscated in secure fields.
261#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
262pub enum TextObfuscationMode {
263    /// Text is visible, no obfuscation.
264    Visible,
265    /// Reveal the last typed character briefly, then hide.
266    RevealLastTyped,
267    /// All characters are obfuscated.
268    Hidden,
269    /// Uses the platform's default obfuscation behavior.
270    #[default]
271    System,
272}
273
274/// Layout information for a single line of text.
275#[derive(Clone, Debug)]
276pub struct TextLineInfo {
277    /// Byte offset of the line start in the text.
278    pub start: usize,
279    /// Byte offset of the line end (exclusive) in the text.
280    pub end: usize,
281    /// Top y position in px relative to the text field content area.
282    pub top: f32,
283    /// Baseline y position in px relative to the text field content area.
284    pub baseline: f32,
285    /// Bottom y position in px relative to the text field content area.
286    pub bottom: f32,
287    /// Left x position in px relative to the text field content area.
288    pub left: f32,
289    /// Right x position in px relative to the text field content area.
290    pub right: f32,
291    /// Width of this line in px.
292    pub width: f32,
293}
294
295impl TextLayoutResult {
296    pub fn get_line_start(&self, line_index: usize) -> Option<usize> {
297        self.lines.get(line_index).map(|l| l.start)
298    }
299
300    pub fn get_line_end(&self, line_index: usize) -> Option<usize> {
301        self.lines.get(line_index).map(|l| l.end)
302    }
303
304    pub fn get_line_end_visible(&self, line_index: usize) -> Option<usize> {
305        self.lines.get(line_index).map(|l| l.end)
306    }
307
308    pub fn is_line_ellipsized(&self, _line_index: usize) -> bool {
309        false
310    }
311
312    pub fn get_line_top(&self, line_index: usize) -> Option<f32> {
313        self.lines.get(line_index).map(|l| l.top)
314    }
315
316    pub fn get_line_baseline(&self, line_index: usize) -> Option<f32> {
317        self.lines.get(line_index).map(|l| l.baseline)
318    }
319
320    pub fn get_line_bottom(&self, line_index: usize) -> Option<f32> {
321        self.lines.get(line_index).map(|l| l.bottom)
322    }
323
324    pub fn get_line_left(&self, line_index: usize) -> Option<f32> {
325        self.lines.get(line_index).map(|l| l.left)
326    }
327
328    pub fn get_line_right(&self, line_index: usize) -> Option<f32> {
329        self.lines.get(line_index).map(|l| l.right)
330    }
331
332    pub fn get_line_for_offset(&self, offset: usize) -> usize {
333        for (i, line) in self.lines.iter().enumerate() {
334            if offset >= line.start && offset < line.end {
335                return i;
336            }
337        }
338        self.line_count.saturating_sub(1)
339    }
340
341    pub fn get_line_for_vertical_position(&self, vertical: f32) -> usize {
342        for (i, line) in self.lines.iter().enumerate() {
343            if vertical >= line.top && vertical < line.bottom {
344                return i;
345            }
346        }
347        self.line_count.saturating_sub(1)
348    }
349
350    pub fn get_horizontal_position(&self, offset: usize, _use_primary_direction: bool) -> f32 {
351        self.lines
352            .iter()
353            .find(|l| offset >= l.start && offset <= l.end)
354            .map(|l| l.left)
355            .unwrap_or(0.0)
356    }
357
358    pub fn has_visual_overflow(&self) -> bool {
359        self.did_overflow_width || self.did_overflow_height
360    }
361
362    pub fn get_bounding_box(&self, offset: usize) -> crate::Rect {
363        if self.lines.is_empty() || offset > self.lines.last().unwrap().end {
364            return crate::Rect::default();
365        }
366        let line = self
367            .lines
368            .iter()
369            .find(|l| offset >= l.start && offset < l.end)
370            .unwrap_or_else(|| {
371                if offset >= self.lines.last().unwrap().end {
372                    self.lines.last().unwrap()
373                } else {
374                    &self.lines[0]
375                }
376            });
377        let _line_idx = self.get_line_for_offset(offset);
378        let char_in_line = offset - line.start;
379        let pos_in_line = if char_in_line == 0 {
380            line.left
381        } else {
382            let chars = line.end - line.start;
383            if chars == 0 {
384                line.left
385            } else {
386                line.left + (line.width * (char_in_line as f32) / (chars as f32))
387            }
388        };
389        crate::Rect {
390            x: pos_in_line,
391            y: line.top,
392            w: if char_in_line < (line.end - line.start) {
393                line.width / (line.end - line.start).max(1) as f32
394            } else {
395                1.0
396            },
397            h: line.bottom - line.top,
398        }
399    }
400
401    pub fn get_cursor_rect(&self, offset: usize) -> crate::Rect {
402        let line = self
403            .lines
404            .iter()
405            .find(|l| offset >= l.start && offset <= l.end)
406            .unwrap_or_else(|| {
407                if offset >= self.lines.last().map(|l| l.end).unwrap_or(0) {
408                    self.lines.last().unwrap()
409                } else {
410                    &self.lines[0]
411                }
412            });
413        let char_in_line = offset.saturating_sub(line.start);
414        let chars = (line.end - line.start).max(1);
415        let x = line.left + (line.width * (char_in_line as f32) / (chars as f32));
416        crate::Rect {
417            x,
418            y: line.top,
419            w: 1.0,
420            h: line.bottom - line.top,
421        }
422    }
423
424    pub fn get_offset_for_position(&self, position: (f32, f32)) -> Option<usize> {
425        let line_idx = self.get_line_for_vertical_position(position.1);
426        let line = self.lines.get(line_idx)?;
427        if position.0 <= line.left {
428            return Some(line.start);
429        }
430        if position.0 >= line.right {
431            return Some(line.end);
432        }
433        let fraction = (position.0 - line.left) / line.width.max(1.0);
434        let offset_in_line = ((line.end - line.start) as f32 * fraction).round() as usize;
435        Some((line.start + offset_in_line).min(line.end))
436    }
437
438    pub fn get_word_boundary(&self, _offset: usize) -> super::TextRange {
439        // Stub: layout results don't retain the full text, so real word
440        // boundaries can't be computed yet.
441        super::TextRange::new(0, 0)
442    }
443
444    pub fn get_paragraph_direction(&self, _offset: usize) -> u8 {
445        0 // LTR
446    }
447
448    pub fn get_bidi_run_direction(&self, _offset: usize) -> u8 {
449        0 // LTR
450    }
451}
452
453pub trait OffsetMapping: Debug + Send + Sync + 'static {
454    fn original_to_transformed(&self, offset: usize) -> usize;
455    fn transformed_to_original(&self, offset: usize) -> usize;
456    fn clone_box(&self) -> Box<dyn OffsetMapping>;
457}
458
459/// Identity offset mapping: original and transformed offsets are the same.
460#[derive(Clone, Copy, Debug)]
461pub struct IdentityOffsetMapping;
462
463impl OffsetMapping for IdentityOffsetMapping {
464    fn original_to_transformed(&self, offset: usize) -> usize {
465        offset
466    }
467    fn transformed_to_original(&self, offset: usize) -> usize {
468        offset
469    }
470    fn clone_box(&self) -> Box<dyn OffsetMapping> {
471        Box::new(*self)
472    }
473}
474
475/// Transforms display text without changing the underlying value (e.g. password masking).
476pub trait VisualTransformation: Debug + Send + Sync + 'static {
477    /// Transform the text for display. Takes the original `AnnotatedString` and returns
478    /// the transformed `TransformedText` with an offset mapping.
479    fn filter(&self, text: &AnnotatedString) -> TransformedText;
480}
481
482/// Output of `VisualTransformation::filter`.
483pub struct TransformedText {
484    pub text: AnnotatedString,
485    pub offset_mapping: Box<dyn OffsetMapping>,
486}
487
488impl TransformedText {
489    pub fn new(text: AnnotatedString, offset_mapping: Box<dyn OffsetMapping>) -> Self {
490        TransformedText {
491            text,
492            offset_mapping,
493        }
494    }
495}
496
497impl Clone for TransformedText {
498    fn clone(&self) -> Self {
499        Self {
500            text: self.text.clone(),
501            offset_mapping: self.offset_mapping.clone_box(),
502        }
503    }
504}
505
506impl Debug for TransformedText {
507    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508        f.debug_struct("TransformedText")
509            .field("text", &self.text.text)
510            .finish()
511    }
512}
513
514#[derive(Clone, Copy, Debug)]
515pub struct IdentityVisualTransformation;
516
517impl VisualTransformation for IdentityVisualTransformation {
518    fn filter(&self, text: &AnnotatedString) -> TransformedText {
519        TransformedText {
520            text: text.clone(),
521            offset_mapping: Box::new(IdentityOffsetMapping),
522        }
523    }
524}
525
526/// A `VisualTransformation` that masks all characters with a given character.
527/// Matches Compose's `PasswordVisualTransformation`.
528#[derive(Clone, Copy, Debug)]
529pub struct PasswordVisualTransformation {
530    pub mask: char,
531}
532
533impl Default for PasswordVisualTransformation {
534    fn default() -> Self {
535        Self { mask: '\u{2022}' }
536    }
537}
538
539/// Char-index offset mapping for masked text: the Nth original char maps to
540/// the Nth mask char (byte offsets differ when widths differ, e.g. `a\U0001F44D`
541/// (5B) masked to `\u{2022}\u{2022}` (6B)). Identity mapping here silently
542/// mis-placed carets mid-mask-char for non-BMP input.
543#[derive(Clone, Debug)]
544pub struct PasswordOffsetMapping {
545    original: Vec<usize>,
546    transformed: Vec<usize>,
547}
548
549impl PasswordOffsetMapping {
550    pub fn new(original: &str, mask: char, masked: &str) -> Self {
551        let mut o = Vec::with_capacity(original.chars().count() + 1);
552        for (i, _) in original.char_indices() {
553            o.push(i);
554        }
555        o.push(original.len());
556        let mut t = vec![0usize];
557        let n = original.chars().count();
558        let mut byte = 0usize;
559        for _ in 0..n {
560            byte += mask.len_utf8();
561            t.push(byte);
562        }
563        if byte != masked.len() {
564            t.clear();
565            t.push(0);
566            let mut b = 0usize;
567            for ch in masked.chars() {
568                b += ch.len_utf8();
569                t.push(b);
570            }
571        }
572        Self {
573            original: o,
574            transformed: t,
575        }
576    }
577
578    fn snap_back(offsets: &[usize], text_len: usize, offset: usize) -> usize {
579        let o = offset.min(text_len);
580        match offsets.binary_search(&o) {
581            Ok(_) => o,
582            Err(i) => offsets.get(i.saturating_sub(1)).copied().unwrap_or(0),
583        }
584    }
585    fn index_of(offsets: &[usize], snapped: usize) -> usize {
586        match offsets.binary_search(&snapped) {
587            Ok(i) => i,
588            Err(i) => i.min(offsets.len().saturating_sub(1)),
589        }
590    }
591}
592
593impl OffsetMapping for PasswordOffsetMapping {
594    fn original_to_transformed(&self, offset: usize) -> usize {
595        let o_text_len = *self.original.last().unwrap_or(&0);
596        let snapped = Self::snap_back(&self.original, o_text_len, offset);
597        let idx = Self::index_of(&self.original, snapped);
598        self.transformed.get(idx).copied().unwrap_or(0)
599    }
600    fn transformed_to_original(&self, offset: usize) -> usize {
601        let t_text_len = *self.transformed.last().unwrap_or(&0);
602        let snapped = Self::snap_back(&self.transformed, t_text_len, offset);
603        let idx = Self::index_of(&self.transformed, snapped);
604        self.original.get(idx).copied().unwrap_or(0)
605    }
606    fn clone_box(&self) -> Box<dyn OffsetMapping> {
607        Box::new(self.clone())
608    }
609}
610
611impl VisualTransformation for PasswordVisualTransformation {
612    fn filter(&self, text: &AnnotatedString) -> TransformedText {
613        let masked_text: String = text.text.chars().map(|_| self.mask).collect();
614        let mapping = PasswordOffsetMapping::new(&text.text, self.mask, &masked_text);
615        TransformedText {
616            text: AnnotatedString::new(masked_text, vec![]),
617            offset_mapping: Box::new(mapping),
618        }
619    }
620}
621
622/// Convert a byte offset in the original text to the corresponding byte offset
623/// in the visually-transformed display text.
624pub fn original_offset_to_display(original: &str, display: &str, original_byte: usize) -> usize {
625    original_offset_to_display_with_mapping(original, display, original_byte, None)
626}
627
628/// Convert a byte offset in the original text to the corresponding byte offset
629/// in the visually-transformed display text, using the provided `OffsetMapping` if available.
630pub fn original_offset_to_display_with_mapping(
631    original: &str,
632    display: &str,
633    original_byte: usize,
634    offset_mapping: Option<&dyn OffsetMapping>,
635) -> usize {
636    if let Some(om) = offset_mapping {
637        om.original_to_transformed(original_byte)
638    } else {
639        let char_idx = original[..original_byte.min(original.len())]
640            .chars()
641            .count();
642        display
643            .char_indices()
644            .nth(char_idx)
645            .map(|(i, _)| i)
646            .unwrap_or(display.len())
647    }
648}
649
650/// Configures automatic capitalization behavior for the keyboard.
651/// Corresponds to Compose's `KeyboardCapitalization`.
652#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
653pub enum KeyboardCapitalization {
654    #[default]
655    Unspecified,
656    None,
657    Characters,
658    Words,
659    Sentences,
660}
661
662/// Text shadow. Offsets and blur are in [`Dp`](crate::units::Dp),
663/// converted to px at the paint boundary.
664#[derive(Clone, Copy, Debug, PartialEq)]
665pub struct Shadow {
666    pub color: Color,
667    /// Horizontal offset in [`Dp`](crate::units::Dp).
668    pub offset_x: crate::units::Dp,
669    /// Vertical offset in [`Dp`](crate::units::Dp).
670    pub offset_y: crate::units::Dp,
671    /// Blur radius in [`Dp`](crate::units::Dp).
672    pub blur_radius: crate::units::Dp,
673}
674
675/// Font synthesis controls whether the font renderer may synthesize
676/// bold, italic, or small-caps variants when the font lacks them.
677#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
678pub enum FontSynthesis {
679    #[default]
680    Unspecified,
681    None,
682    Weight,
683    Style,
684    SmallCaps,
685    All,
686}
687
688/// Baseline shift for subscript/superscript.
689/// Wraps a multiplier applied against font_size for glyph y-offset.
690#[derive(Clone, Copy, Debug, PartialEq)]
691pub struct BaselineShift(pub f32);
692
693#[allow(non_upper_case_globals)]
694impl BaselineShift {
695    /// No baseline shift (zero offset).
696    pub const Unspecified: BaselineShift = BaselineShift(0.0);
697    /// Default superscript offset: shift up by 33.3% of font_size (CSS standard).
698    pub const Superscript: BaselineShift = BaselineShift(-0.333);
699    /// Default subscript offset: shift down by 20% of font_size (CSS standard).
700    pub const Subscript: BaselineShift = BaselineShift(0.2);
701}
702
703impl Default for BaselineShift {
704    fn default() -> Self {
705        BaselineShift::Unspecified
706    }
707}
708
709/// Hyphenation behavior.
710#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
711pub enum Hyphens {
712    #[default]
713    Unspecified,
714    None,
715    Auto,
716}
717
718/// Line break behavior.
719#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
720pub enum LineBreak {
721    #[default]
722    Unspecified,
723    Simple,
724    Heading,
725    Paragraph,
726}
727
728/// First-line and rest-line indent in [`Dp`](crate::units::Dp).
729#[derive(Clone, Copy, Debug, PartialEq)]
730pub struct TextIndent {
731    pub first_line: crate::units::Dp,
732    pub rest_lines: crate::units::Dp,
733}
734
735impl Default for TextIndent {
736    fn default() -> Self {
737        Self {
738            first_line: crate::units::Dp::ZERO,
739            rest_lines: crate::units::Dp::ZERO,
740        }
741    }
742}
743
744/// Path effect applied to a stroked path.
745/// Mirrors Compose's `PathEffect`.
746#[derive(Clone, Debug, PartialEq)]
747pub enum PathEffect {
748    /// Replace sharp corners with rounded arcs of the given radius.
749    Corner {
750        /// Corner radius in em-units.
751        radius: f32,
752    },
753    /// Draw the path as a dashed line.
754    Dash {
755        /// Interleaved on/off lengths in em-units.
756        intervals: Vec<f32>,
757        /// Starting phase offset in em-units.
758        phase: f32,
759    },
760}
761
762/// Draw style for text (fill or stroke).
763#[derive(Clone, Debug, PartialEq, Default)]
764pub enum DrawStyle {
765    #[default]
766    Fill,
767    Stroke {
768        /// Stroke width in em-units (fraction of font size). 0.05 = 5% of em.
769        width: f32,
770        /// Line cap style for stroke endpoints.
771        cap: crate::StrokeCap,
772        /// Line join style for stroke segment joins.
773        join: crate::StrokeJoin,
774        /// Miter limit for miter joins.
775        miter: f32,
776        /// Optional path effect (dash, corner rounding, etc.).
777        path_effect: Option<PathEffect>,
778    },
779    /// Fill plus an outline in the same color. Renders the fill first,
780    /// then the stroke on top (same layout; stroke width in em-units).
781    /// Faux-bold for fonts without a bold face: single layout pass,
782    /// no extra view needed.
783    FillAndStroke {
784        /// Stroke width in em-units (fraction of font size). 0.05 = 5% of em.
785        width: f32,
786        /// Line cap style for stroke endpoints.
787        cap: crate::StrokeCap,
788        /// Line join style for stroke segment joins.
789        join: crate::StrokeJoin,
790        /// Miter limit for miter joins.
791        miter: f32,
792        /// Optional path effect (dash, corner rounding, etc.).
793        path_effect: Option<PathEffect>,
794        /// Stroke color; `None` reuses the text's fill color.
795        outline_color: Option<crate::Color>,
796    },
797}
798
799impl DrawStyle {
800    /// Create a `Stroke` variant with default cap, join, miter, and no path effect.
801    pub const fn stroke(width: f32) -> Self {
802        Self::Stroke {
803            width,
804            cap: crate::StrokeCap::Butt,
805            join: crate::StrokeJoin::Miter,
806            miter: 4.0,
807            path_effect: None,
808        }
809    }
810
811    /// Create a `FillAndStroke` variant with default cap, join, miter,
812    /// and no path effect, stroking in the text's own color.
813    pub const fn fill_and_stroke(width: f32) -> Self {
814        Self::FillAndStroke {
815            width,
816            cap: crate::StrokeCap::Butt,
817            join: crate::StrokeJoin::Miter,
818            miter: 4.0,
819            path_effect: None,
820            outline_color: None,
821        }
822    }
823
824    /// [`fill_and_stroke`](Self::fill_and_stroke) with a contrasting stroke,
825    /// drawn beneath the fill. `width` is em-units and the stroke is
826    /// centred on the glyph outline, so pass `2 * outline_px / font_px` to
827    /// grow `outline_px` outward like Godot's `font_outline_size`.
828    pub const fn fill_and_stroke_with_outline(width: f32, outline_color: crate::Color) -> Self {
829        Self::FillAndStroke {
830            width,
831            cap: crate::StrokeCap::Butt,
832            join: crate::StrokeJoin::Miter,
833            miter: 4.0,
834            path_effect: None,
835            outline_color: Some(outline_color),
836        }
837    }
838
839    /// Outline parameters when this style draws a stroke, else `None`.
840    pub const fn stroke_params(
841        &self,
842    ) -> Option<(
843        f32,
844        crate::StrokeCap,
845        crate::StrokeJoin,
846        f32,
847        &Option<PathEffect>,
848    )> {
849        match self {
850            Self::Stroke {
851                width,
852                cap,
853                join,
854                miter,
855                path_effect,
856            }
857            | Self::FillAndStroke {
858                width,
859                cap,
860                join,
861                miter,
862                path_effect,
863                ..
864            } => Some((*width, *cap, *join, *miter, path_effect)),
865            Self::Fill => None,
866        }
867    }
868
869    /// Whether this style draws the glyph fill.
870    pub const fn draws_fill(&self) -> bool {
871        !matches!(self, Self::Stroke { .. })
872    }
873}
874
875/// Style configuration for text displayed in a text field.
876/// Corresponds to Compose's `TextStyle` (font sizes are `TextUnit` Sp there).
877#[derive(Clone, Debug)]
878pub struct TextStyle {
879    /// Font size in [`Sp`](crate::units::Sp). `Sp::ZERO` = use default (16sp for TextField).
880    pub font_size: crate::units::Sp,
881    /// Text color. None = use theme default.
882    pub color: Option<Color>,
883    /// Font weight. None = NORMAL.
884    pub font_weight: Option<u16>,
885    /// Font family. None = use default (sans-serif).
886    pub font_family: Option<&'static str>,
887    /// Font style. None = Normal.
888    pub font_style: Option<u8>,
889    /// Text alignment. Unspecified = inherit.
890    pub text_align: crate::TextAlign,
891    /// Letter spacing in [`Sp`](crate::units::Sp). `Sp::ZERO` = no extra spacing.
892    pub letter_spacing: crate::units::Sp,
893    /// Line height in [`Sp`](crate::units::Sp). `Sp::ZERO` = default (font_size).
894    pub line_height: crate::units::Sp,
895    /// Text background color. None = transparent.
896    pub background: Option<Color>,
897    /// Text decoration (underline, strikethrough). None = no decoration.
898    pub text_decoration: Option<crate::TextDecoration>,
899    /// Text shadow. None = no shadow.
900    pub shadow: Option<Shadow>,
901    /// Text direction. None = inherit from thread-local default (usually LTR).
902    pub text_direction: Option<crate::TextDirection>,
903    /// Font synthesis policy (synthesize missing bold/italic/small-caps).
904    pub font_synthesis: FontSynthesis,
905    /// Baseline shift (superscript/subscript).
906    pub baseline_shift: BaselineShift,
907    /// Hyphenation behavior.
908    pub hyphens: Hyphens,
909    /// Line break behavior.
910    pub line_break: LineBreak,
911    /// First-line and rest-line indent in dp.
912    pub text_indent: Option<TextIndent>,
913    /// Draw style (fill or stroke).
914    pub draw_style: DrawStyle,
915    /// Text opacity (0.0-1.0). 0.0 = use default (fully opaque).
916    pub alpha: f32,
917    /// Locale hint for text shaping. Empty = use default.
918    pub locale_list: Option<String>,
919    /// OpenType font feature settings (e.g. "liga", "kern").
920    pub font_feature_settings: Option<String>,
921    /// OpenType font variation settings (e.g. "wght 700, opsz 24").
922    pub font_variation_settings: Option<String>,
923}
924
925impl Default for TextStyle {
926    fn default() -> Self {
927        Self {
928            font_size: crate::units::Sp::ZERO,
929            color: None,
930            font_weight: None,
931            font_family: Some("sans-serif"),
932            font_style: None,
933            text_align: crate::TextAlign::Unspecified,
934            letter_spacing: crate::units::Sp::ZERO,
935            line_height: crate::units::Sp::ZERO,
936            background: None,
937            text_decoration: None,
938            shadow: None,
939            text_direction: None,
940            font_synthesis: FontSynthesis::Unspecified,
941            baseline_shift: BaselineShift::Unspecified,
942            hyphens: Hyphens::Unspecified,
943            line_break: LineBreak::Unspecified,
944            text_indent: None,
945            draw_style: DrawStyle::Fill,
946            alpha: 0.0,
947            locale_list: None,
948            font_feature_settings: None,
949            font_variation_settings: None,
950        }
951    }
952}
953
954/// Hints the platform about the type of keyboard to show.
955#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
956pub enum KeyboardType {
957    #[default]
958    Unspecified,
959    Text,
960    Ascii,
961    Number,
962    Phone,
963    Uri,
964    Email,
965    Password,
966    NumberPassword,
967    Decimal,
968    PasswordVisible,
969    PostalAddress,
970    PersonName,
971    EmailSubject,
972    ShortMessage,
973    LongMessage,
974    Filter,
975    Phonetic,
976    DateTime,
977    Date,
978    Time,
979    NumberSigned,
980    DecimalSigned,
981    DecimalPassword,
982    NumberPasswordSigned,
983    DecimalPasswordSigned,
984}
985
986/// The action button on the IME (soft keyboard).
987#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
988pub enum ImeAction {
989    #[default]
990    Unspecified,
991    None,
992    Default,
993    Go,
994    Search,
995    Send,
996    Previous,
997    Next,
998    Done,
999}
1000
1001/// High-level IME purpose for the platform's soft keyboard.
1002///
1003/// Unlike [`KeyboardType`], which enumerates the many Compose-style keyboard
1004/// layouts, this is the small set of intents platforms can actually react (for NativeA) to
1005/// (password fields, e-mail addresses, URLs, phone numbers, plain text).
1006/// On the web it also selects the `inputmode` attribute for mobile browsers.
1007#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
1008pub enum ImePurposeHint {
1009    #[default]
1010    Normal,
1011    Password,
1012    Email,
1013    Url,
1014    Phone,
1015    Number,
1016}
1017
1018impl KeyboardType {
1019    /// Map this keyboard type to the coarser platform IME purpose.
1020    pub fn ime_purpose_hint(self) -> ImePurposeHint {
1021        use KeyboardType::*;
1022        match self {
1023            Password
1024            | NumberPassword
1025            | DecimalPassword
1026            | NumberPasswordSigned
1027            | DecimalPasswordSigned => ImePurposeHint::Password,
1028            Email | EmailSubject => ImePurposeHint::Email,
1029            Uri => ImePurposeHint::Url,
1030            Phone => ImePurposeHint::Phone,
1031            Number | NumberSigned | Decimal | DecimalSigned => ImePurposeHint::Number,
1032            _ => ImePurposeHint::Normal,
1033        }
1034    }
1035}
1036
1037/// Scope provided to `KeyboardActions` callbacks, allowing fallback to the
1038/// platform's default IME action behavior. Corresponds to Compose's `KeyboardActionScope`.
1039pub trait KeyboardActionScope {
1040    fn default_keyboard_action(&self, action: ImeAction);
1041}
1042
1043/// Callbacks for IME action button presses on the soft keyboard.
1044/// Corresponds to Compose's legacy `KeyboardActions`.
1045#[derive(Clone, Default)]
1046pub struct KeyboardActions {
1047    pub on_done: Option<Rc<dyn Fn(&dyn KeyboardActionScope)>>,
1048    pub on_go: Option<Rc<dyn Fn(&dyn KeyboardActionScope)>>,
1049    pub on_next: Option<Rc<dyn Fn(&dyn KeyboardActionScope)>>,
1050    pub on_previous: Option<Rc<dyn Fn(&dyn KeyboardActionScope)>>,
1051    pub on_search: Option<Rc<dyn Fn(&dyn KeyboardActionScope)>>,
1052    pub on_send: Option<Rc<dyn Fn(&dyn KeyboardActionScope)>>,
1053}
1054
1055impl KeyboardActions {
1056    pub fn on_any(f: impl Fn(ImeAction, &dyn KeyboardActionScope) + 'static) -> Self {
1057        let f = Rc::new(f);
1058        KeyboardActions {
1059            on_done: Some({
1060                let f = f.clone();
1061                Rc::new(move |scope| f(ImeAction::Done, scope))
1062            }),
1063            on_go: Some({
1064                let f = f.clone();
1065                Rc::new(move |scope| f(ImeAction::Go, scope))
1066            }),
1067            on_next: Some({
1068                let f = f.clone();
1069                Rc::new(move |scope| f(ImeAction::Next, scope))
1070            }),
1071            on_previous: Some({
1072                let f = f.clone();
1073                Rc::new(move |scope| f(ImeAction::Previous, scope))
1074            }),
1075            on_search: Some({
1076                let f = f.clone();
1077                Rc::new(move |scope| f(ImeAction::Search, scope))
1078            }),
1079            on_send: Some(Rc::new(move |scope| f(ImeAction::Send, scope))),
1080        }
1081    }
1082}
1083
1084/// Handles IME action button presses. Single-callback interface used by the
1085/// new `BasicTextField(state, ...)` API. Corresponds to Compose's `KeyboardActionHandler`.
1086pub trait KeyboardActionHandler: Debug + 'static {
1087    fn on_keyboard_action(&self, perform_default: &dyn Fn());
1088}
1089
1090/// A simple `KeyboardActionHandler` that only executes the default behavior.
1091#[derive(Clone, Copy, Debug)]
1092pub struct DefaultKeyboardActionHandler;
1093
1094impl KeyboardActionHandler for DefaultKeyboardActionHandler {
1095    fn on_keyboard_action(&self, perform_default: &dyn Fn()) {
1096        perform_default();
1097    }
1098}
1099
1100/// Mutable text buffer used as the scope for `InputTransformation` and
1101/// `OutputTransformation`. Corresponds to Compose's `TextFieldBuffer`.
1102pub trait TextFieldBuffer {
1103    fn text(&self) -> &str;
1104    fn set_text(&mut self, text: &str);
1105    fn selection(&self) -> TextRange;
1106    fn set_selection(&mut self, sel: TextRange);
1107    fn length(&self) -> usize;
1108    fn replace(&mut self, start: usize, end: usize, text: &str);
1109    fn insert(&mut self, index: usize, text: &str);
1110    fn delete(&mut self, start: usize, end: usize);
1111    fn place_cursor_before_char_at(&mut self, index: usize);
1112    fn place_cursor_at_end(&mut self);
1113    fn select_all(&mut self);
1114    fn revert_all_changes(&mut self);
1115    fn original_text(&self) -> &str;
1116    fn original_selection(&self) -> TextRange;
1117    fn has_selection(&self) -> bool;
1118}
1119
1120/// Limits on the number of visible lines in a text field.
1121/// Corresponds to Compose's `TextFieldLineLimits`.
1122#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1123pub enum TextFieldLineLimits {
1124    SingleLine,
1125    MultiLine {
1126        min_height_in_lines: usize,
1127        max_height_in_lines: usize,
1128    },
1129}
1130
1131impl TextFieldLineLimits {
1132    pub fn default() -> Self {
1133        TextFieldLineLimits::MultiLine {
1134            min_height_in_lines: 1,
1135            max_height_in_lines: usize::MAX,
1136        }
1137    }
1138}
1139
1140/// Wraps the inner text field with custom decorations.
1141/// Corresponds to Compose's `TextFieldDecorator`.
1142pub trait TextFieldDecorator: Debug + 'static {
1143    fn decorate(&self, inner: crate::View) -> crate::View;
1144}
1145
1146/// A `TextFieldDecorator` that passes through the inner text field unchanged.
1147#[derive(Clone, Copy, Debug)]
1148pub struct DefaultTextFieldDecorator;
1149
1150impl TextFieldDecorator for DefaultTextFieldDecorator {
1151    fn decorate(&self, inner: crate::View) -> crate::View {
1152        inner
1153    }
1154}
1155
1156/// Transforms user input before it is applied to the text field.
1157/// Corresponds to Compose's `InputTransformation`.
1158pub trait InputTransformation: Debug + 'static {
1159    fn keyboard_options(&self) -> Option<KeyboardOptions> {
1160        None
1161    }
1162    fn transform_input(&self, buffer: &mut dyn TextFieldBuffer);
1163}
1164
1165/// Transforms text output for display.
1166/// Corresponds to Compose's `OutputTransformation`.
1167pub trait OutputTransformation: Debug + 'static {
1168    fn transform_output(&self, buffer: &mut dyn TextFieldBuffer);
1169}
1170
1171/// Internal 1-to-1 codepoint transformation for password obfuscation.
1172/// Corresponds to Compose's `CodepointTransformation`.
1173pub struct CodepointTransformation {
1174    pub transform: Box<dyn Fn(usize, char) -> char>,
1175}
1176
1177impl Clone for CodepointTransformation {
1178    fn clone(&self) -> Self {
1179        // Cannot clone Box<dyn Fn>; this is for internal use only.
1180        // In practice, CodepointTransformation is passed as an Option and
1181        // constructed fresh each time. If clone is needed, wrap the Fn in Rc.
1182        panic!("CodepointTransformation::clone() is not supported -> use Rc instead");
1183    }
1184}
1185
1186impl CodepointTransformation {
1187    pub fn new(transform: impl Fn(usize, char) -> char + 'static) -> Self {
1188        CodepointTransformation {
1189            transform: Box::new(transform),
1190        }
1191    }
1192
1193    pub fn transform(&self, codepoint_index: usize, codepoint: char) -> char {
1194        (self.transform)(codepoint_index, codepoint)
1195    }
1196}
1197
1198/// Input transformation settings: keyboard type, capitalization, and IME action.
1199/// Corresponds to Compose's `KeyboardOptions`.
1200#[derive(Clone, Copy, Debug, PartialEq)]
1201pub struct KeyboardOptions {
1202    pub keyboard_type: KeyboardType,
1203    pub capitalization: KeyboardCapitalization,
1204    pub ime_action: ImeAction,
1205    pub auto_correct_enabled: Option<bool>,
1206    pub show_keyboard_on_focus: Option<bool>,
1207    pub platform_ime_options: Option<&'static str>,
1208    pub hint_locales: Option<&'static str>,
1209}
1210
1211impl KeyboardOptions {
1212    pub const DEFAULT: KeyboardOptions = KeyboardOptions {
1213        keyboard_type: KeyboardType::Text,
1214        capitalization: KeyboardCapitalization::Unspecified,
1215        ime_action: ImeAction::Unspecified,
1216        auto_correct_enabled: None,
1217        show_keyboard_on_focus: None,
1218        platform_ime_options: None,
1219        hint_locales: None,
1220    };
1221
1222    pub const SECURE_TEXT_FIELD: KeyboardOptions = KeyboardOptions {
1223        keyboard_type: KeyboardType::Password,
1224        capitalization: KeyboardCapitalization::Unspecified,
1225        ime_action: ImeAction::Unspecified,
1226        auto_correct_enabled: Some(false),
1227        show_keyboard_on_focus: None,
1228        platform_ime_options: None,
1229        hint_locales: None,
1230    };
1231
1232    pub fn fill_unspecified_values_with(&self, other: Option<&KeyboardOptions>) -> KeyboardOptions {
1233        let other = match other {
1234            Some(o) => o,
1235            None => return *self,
1236        };
1237        KeyboardOptions {
1238            keyboard_type: if self.keyboard_type == KeyboardType::Unspecified {
1239                other.keyboard_type
1240            } else {
1241                self.keyboard_type
1242            },
1243            capitalization: if self.capitalization == KeyboardCapitalization::Unspecified {
1244                other.capitalization
1245            } else {
1246                self.capitalization
1247            },
1248            ime_action: if self.ime_action == ImeAction::Unspecified {
1249                other.ime_action
1250            } else {
1251                self.ime_action
1252            },
1253            auto_correct_enabled: self.auto_correct_enabled.or(other.auto_correct_enabled),
1254            show_keyboard_on_focus: self.show_keyboard_on_focus.or(other.show_keyboard_on_focus),
1255            platform_ime_options: self.platform_ime_options.or(other.platform_ime_options),
1256            hint_locales: self.hint_locales.or(other.hint_locales),
1257        }
1258    }
1259
1260    /// Returns a new [KeyboardOptions] that merges this with [other].
1261    /// [other]'s null or Unspecified values are replaced with this object's values.
1262    /// Corresponds to Compose's `KeyboardOptions.merge()`.
1263    pub fn merge(&self, other: Option<&KeyboardOptions>) -> KeyboardOptions {
1264        other.map_or(*self, |o| o.fill_unspecified_values_with(Some(self)))
1265    }
1266}
1267
1268impl Default for KeyboardOptions {
1269    fn default() -> Self {
1270        Self::DEFAULT
1271    }
1272}
1273
1274#[derive(Debug, Clone, PartialEq)]
1275pub struct SpanStyle {
1276    pub color: Option<Color>,
1277    pub font_size: Option<crate::units::Sp>,
1278    pub font_weight: Option<u16>,
1279    pub font_family: Option<&'static str>,
1280    pub font_style: Option<u8>,
1281    pub text_align: Option<crate::TextAlign>,
1282    pub letter_spacing: Option<crate::units::Sp>,
1283    pub line_height: Option<crate::units::Sp>,
1284    pub background: Option<Color>,
1285    pub text_decoration: Option<crate::TextDecoration>,
1286    pub text_direction: Option<crate::TextDirection>,
1287    pub font_synthesis: Option<FontSynthesis>,
1288    pub baseline_shift: Option<BaselineShift>,
1289    pub hyphens: Option<Hyphens>,
1290    pub line_break: Option<LineBreak>,
1291    pub text_indent: Option<TextIndent>,
1292    pub draw_style: Option<DrawStyle>,
1293    pub alpha: f32,
1294    /// OpenType font variation settings (e.g. "wght 700, opsz 24").
1295    pub font_variation_settings: Option<String>,
1296}
1297
1298impl SpanStyle {
1299    pub const fn default() -> Self {
1300        Self {
1301            color: None,
1302            font_size: None,
1303            font_weight: None,
1304            font_family: None,
1305            font_style: None,
1306            text_align: None,
1307            letter_spacing: None,
1308            line_height: None,
1309            background: None,
1310            text_decoration: None,
1311            text_direction: None,
1312            font_synthesis: None,
1313            baseline_shift: None,
1314            hyphens: None,
1315            line_break: None,
1316            text_indent: None,
1317            draw_style: None,
1318            alpha: 0.0,
1319            font_variation_settings: None,
1320        }
1321    }
1322
1323    pub fn color(mut self, c: Color) -> Self {
1324        self.color = Some(c);
1325        self
1326    }
1327
1328    pub fn font_family(mut self, family: &'static str) -> Self {
1329        self.font_family = Some(family);
1330        self
1331    }
1332
1333    pub fn line_height(mut self, line_height: Sp) -> Self {
1334        self.line_height = Some(line_height);
1335        self
1336    }
1337
1338    pub fn font_size(mut self, size: crate::units::Sp) -> Self {
1339        self.font_size = Some(size);
1340        self
1341    }
1342
1343    pub fn text_decoration(mut self, d: TextDecoration) -> Self {
1344        self.text_decoration = Some(d);
1345        self
1346    }
1347
1348    pub fn font_weight(mut self, w: u16) -> Self {
1349        self.font_weight = Some(w);
1350        self
1351    }
1352
1353    pub fn font_style(mut self, s: u8) -> Self {
1354        self.font_style = Some(s);
1355        self
1356    }
1357
1358    pub fn draw_style(mut self, s: DrawStyle) -> Self {
1359        self.draw_style = Some(s);
1360        self
1361    }
1362
1363    pub fn background(mut self, c: Color) -> Self {
1364        self.background = Some(c);
1365        self
1366    }
1367
1368    pub fn baseline_shift(mut self, s: BaselineShift) -> Self {
1369        self.baseline_shift = Some(s);
1370        self
1371    }
1372}
1373
1374impl Default for SpanStyle {
1375    fn default() -> Self {
1376        Self::default()
1377    }
1378}
1379
1380/// A span of text with an associated style.
1381#[derive(Debug, Clone, PartialEq)]
1382pub struct TextSpan {
1383    /// Byte offset start in the original text.
1384    pub start: usize,
1385    /// Byte offset end (exclusive) in the original text.
1386    pub end: usize,
1387    pub style: SpanStyle,
1388    /// URL for clickable links.
1389    pub url: Option<Arc<str>>,
1390}
1391
1392/// Text with multiple styled spans.
1393///
1394/// Analogous to Compose's `AnnotatedString`.
1395#[derive(Debug, Clone, PartialEq)]
1396pub struct AnnotatedString {
1397    pub text: String,
1398    pub spans: Arc<[TextSpan]>,
1399}
1400
1401impl AnnotatedString {
1402    pub fn new(text: impl Into<String>, spans: Vec<TextSpan>) -> Self {
1403        let text = text.into();
1404        Self {
1405            text,
1406            spans: spans.into(),
1407        }
1408    }
1409
1410    pub fn as_str(&self) -> &str {
1411        &self.text
1412    }
1413}
1414
1415impl From<String> for AnnotatedString {
1416    fn from(text: String) -> Self {
1417        Self {
1418            text,
1419            spans: Arc::from([]),
1420        }
1421    }
1422}
1423
1424impl From<&str> for AnnotatedString {
1425    fn from(text: &str) -> Self {
1426        Self {
1427            text: text.to_string(),
1428            spans: Arc::from([]),
1429        }
1430    }
1431}
1432
1433/// Builder for constructing an `AnnotatedString`.
1434#[derive(Default)]
1435pub struct AnnotatedStringBuilder {
1436    text: String,
1437    spans: Vec<TextSpan>,
1438}
1439
1440impl AnnotatedStringBuilder {
1441    pub fn new() -> Self {
1442        Self::default()
1443    }
1444
1445    /// Append plain text (inherits parent style, or default if at top level).
1446    pub fn push(&mut self, text: &str) -> &mut Self {
1447        self.text.push_str(text);
1448        self
1449    }
1450
1451    /// Append text with a specific style.
1452    pub fn push_with_style(&mut self, text: &str, style: SpanStyle) -> &mut Self {
1453        let start = self.text.len();
1454        self.text.push_str(text);
1455        let end = self.text.len();
1456        if start < end {
1457            self.spans.push(TextSpan {
1458                start,
1459                end,
1460                style,
1461                url: None,
1462            });
1463        }
1464        self
1465    }
1466
1467    /// Append text in a specific color.
1468    pub fn push_color(&mut self, text: &str, color: Color) -> &mut Self {
1469        self.push_with_style(text, SpanStyle::default().color(color))
1470    }
1471
1472    /// Append text with a clickable link URL (auto-applies underline + blue color).
1473    pub fn push_link(&mut self, text: &str, url: impl Into<Arc<str>>) -> &mut Self {
1474        let start = self.text.len();
1475        self.text.push_str(text);
1476        let end = self.text.len();
1477        if start < end {
1478            self.spans.push(TextSpan {
1479                start,
1480                end,
1481                style: SpanStyle::default()
1482                    .color(Color::from_rgba(0x15, 0x76, 0xFF, 255))
1483                    .text_decoration(TextDecoration::UNDERLINE),
1484                url: Some(url.into()),
1485            });
1486        }
1487        self
1488    }
1489
1490    /// Apply a style to a range of already-appended text.
1491    /// Annotate a range of already-appended text as a clickable link.
1492    pub fn add_link(
1493        &mut self,
1494        start: usize,
1495        end: usize,
1496        url: impl Into<Arc<str>>,
1497        style: SpanStyle,
1498    ) -> &mut Self {
1499        if start < end && end <= self.text.len() {
1500            self.spans.push(TextSpan {
1501                start,
1502                end,
1503                style,
1504                url: Some(url.into()),
1505            });
1506        }
1507        self
1508    }
1509
1510    pub fn add_style(&mut self, start: usize, end: usize, style: SpanStyle) -> &mut Self {
1511        if start < end && end <= self.text.len() {
1512            self.spans.push(TextSpan {
1513                start,
1514                end,
1515                style,
1516                url: None,
1517            });
1518        }
1519        self
1520    }
1521
1522    pub fn build(&mut self) -> AnnotatedString {
1523        let text = std::mem::take(&mut self.text);
1524        self.spans.sort_by_key(|s| s.start);
1525        // Merge overlapping/adjacent spans with same style
1526        let mut merged: Vec<TextSpan> = Vec::new();
1527        for span in std::mem::take(&mut self.spans) {
1528            if let Some(last) = merged.last_mut()
1529                && last.end == span.start
1530                && last.style == span.style
1531            {
1532                last.end = span.end;
1533                continue;
1534            }
1535            merged.push(span);
1536        }
1537        AnnotatedString {
1538            text,
1539            spans: merged.into(),
1540        }
1541    }
1542}
1543
1544/// Horizontal text alignment.
1545#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Default)]
1546pub enum TextAlign {
1547    Left,
1548    Right,
1549    Center,
1550    Justify,
1551    Start,
1552    End,
1553    #[default]
1554    Unspecified,
1555}
1556
1557/// Font weight as a numeric value 100-900, matching CSS `font-weight`.
1558#[derive(Clone, Copy, Debug, PartialEq)]
1559pub struct FontWeight(pub u16);
1560
1561impl FontWeight {
1562    pub const THIN: FontWeight = FontWeight(100);
1563    pub const EXTRA_LIGHT: FontWeight = FontWeight(200);
1564    pub const LIGHT: FontWeight = FontWeight(300);
1565    pub const NORMAL: FontWeight = FontWeight(400);
1566    pub const MEDIUM: FontWeight = FontWeight(500);
1567    pub const SEMI_BOLD: FontWeight = FontWeight(600);
1568    pub const BOLD: FontWeight = FontWeight(700);
1569    pub const EXTRA_BOLD: FontWeight = FontWeight(800);
1570    pub const BLACK: FontWeight = FontWeight(900);
1571}
1572
1573impl Default for FontWeight {
1574    fn default() -> Self {
1575        FontWeight::NORMAL
1576    }
1577}
1578
1579/// Font style: normal or italic.
1580#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Default)]
1581pub enum FontStyle {
1582    #[default]
1583    Normal,
1584    Italic,
1585}
1586
1587/// Text decoration state.
1588#[derive(Clone, Copy, Debug, PartialEq, Default)]
1589pub struct TextDecoration {
1590    pub underline: bool,
1591    pub strikethrough: bool,
1592    pub color: Option<Color>,
1593}
1594
1595impl TextDecoration {
1596    pub const UNDERLINE: TextDecoration = TextDecoration {
1597        underline: true,
1598        strikethrough: false,
1599        color: None,
1600    };
1601    pub const STRIKETHROUGH: TextDecoration = TextDecoration {
1602        underline: false,
1603        strikethrough: true,
1604        color: None,
1605    };
1606}
1607
1608/// Convenience function to build an `AnnotatedString`.
1609pub fn build_annotated_string(b: impl FnOnce(&mut AnnotatedStringBuilder)) -> AnnotatedString {
1610    let mut builder = AnnotatedStringBuilder::new();
1611    b(&mut builder);
1612    builder.build()
1613}