Skip to main content

cranpose_ui/widgets/
text.rs

1//! Text widget implementation
2//!
3//! This implementation follows Jetpack Compose's BasicText architecture where text content
4//! is implemented as a modifier node rather than as a measure policy. This properly separates
5//! concerns: MeasurePolicy handles child layout, while TextModifierNode handles text content
6//! measurement, drawing, and semantics.
7
8use std::rc::Rc;
9
10use cranpose_core::{MutableState, NodeId, State};
11use cranpose_foundation::modifier_element;
12
13use crate::{
14    composable,
15    layout::policies::EmptyMeasurePolicy,
16    modifier::Modifier,
17    text::{TextLayoutOptions, TextOptions, TextOverflow, TextStyle},
18    text_modifier_node::TextModifierElement,
19    widgets::layout::compose_layout,
20};
21
22#[derive(Clone)]
23pub struct DynamicTextSource(Rc<dyn Fn() -> Rc<crate::text::AnnotatedString>>);
24
25impl DynamicTextSource {
26    pub fn new<F>(resolver: F) -> Self
27    where
28        F: Fn() -> Rc<crate::text::AnnotatedString> + 'static,
29    {
30        Self(Rc::new(resolver))
31    }
32
33    fn resolve(&self) -> Rc<crate::text::AnnotatedString> {
34        (self.0)()
35    }
36}
37
38impl PartialEq for DynamicTextSource {
39    fn eq(&self, other: &Self) -> bool {
40        Rc::ptr_eq(&self.0, &other.0)
41    }
42}
43
44#[derive(Clone, PartialEq)]
45pub enum TextSource {
46    Static(Rc<crate::text::AnnotatedString>),
47    Dynamic(DynamicTextSource),
48}
49
50impl TextSource {
51    fn resolve(&self) -> Rc<crate::text::AnnotatedString> {
52        match self {
53            TextSource::Static(text) => text.clone(),
54            TextSource::Dynamic(dynamic) => dynamic.resolve(),
55        }
56    }
57}
58
59#[doc(hidden)]
60pub trait IntoTextSource {
61    fn into_text_source(self) -> TextSource;
62}
63
64impl IntoTextSource for String {
65    fn into_text_source(self) -> TextSource {
66        TextSource::Static(Rc::new(crate::text::AnnotatedString::from(self)))
67    }
68}
69
70impl IntoTextSource for &str {
71    fn into_text_source(self) -> TextSource {
72        TextSource::Static(Rc::new(crate::text::AnnotatedString::from(self)))
73    }
74}
75
76impl IntoTextSource for crate::text::AnnotatedString {
77    fn into_text_source(self) -> TextSource {
78        TextSource::Static(Rc::new(self))
79    }
80}
81
82impl IntoTextSource for Rc<crate::text::AnnotatedString> {
83    fn into_text_source(self) -> TextSource {
84        TextSource::Static(self)
85    }
86}
87
88impl<T> IntoTextSource for State<T>
89where
90    T: ToString + Clone + 'static,
91{
92    fn into_text_source(self) -> TextSource {
93        let state = self;
94        TextSource::Dynamic(DynamicTextSource::new(move || {
95            Rc::new(crate::text::AnnotatedString::from(
96                state.value().to_string(),
97            ))
98        }))
99    }
100}
101
102impl<T> IntoTextSource for MutableState<T>
103where
104    T: ToString + Clone + 'static,
105{
106    fn into_text_source(self) -> TextSource {
107        let state = self;
108        TextSource::Dynamic(DynamicTextSource::new(move || {
109            Rc::new(crate::text::AnnotatedString::from(
110                state.value().to_string(),
111            ))
112        }))
113    }
114}
115
116impl<F> IntoTextSource for F
117where
118    F: Fn() -> String + 'static,
119{
120    fn into_text_source(self) -> TextSource {
121        TextSource::Dynamic(DynamicTextSource::new(move || {
122            Rc::new(crate::text::AnnotatedString::from(self()))
123        }))
124    }
125}
126
127impl IntoTextSource for DynamicTextSource {
128    fn into_text_source(self) -> TextSource {
129        TextSource::Dynamic(self)
130    }
131}
132
133fn compose_basic_text_group(
134    text: TextSource,
135    modifier: Modifier,
136    style: TextStyle,
137    options: TextLayoutOptions,
138) -> NodeId {
139    let current = text.resolve();
140
141    let options = options.normalized();
142
143    let modifier = match crate::widgets::local_selection_registrar().current() {
144        Some(registrar) => modifier.then(crate::widgets::selection_container::selectable_text(
145            registrar,
146            Rc::clone(&current),
147            style.clone(),
148            options,
149        )),
150        None => modifier,
151    };
152    let density = crate::density::density();
153    let text_element = modifier_element(TextModifierElement::new(current, style, options, density));
154    let final_modifier = Modifier::from_parts(&[text_element]);
155    let combined_modifier = modifier.then(final_modifier);
156
157    compose_layout(combined_modifier, EmptyMeasurePolicy, density, || {})
158}
159
160#[composable]
161pub fn BasicTextWithOptions<S>(
162    text: S,
163    modifier: Modifier,
164    style: TextStyle,
165    options: TextLayoutOptions,
166) -> NodeId
167where
168    S: IntoTextSource + Clone + PartialEq + 'static,
169{
170    compose_basic_text_group(text.into_text_source(), modifier, style, options)
171}
172
173#[composable]
174pub fn BasicText<S>(
175    text: S,
176    modifier: Modifier,
177    style: TextStyle,
178    overflow: TextOverflow,
179    soft_wrap: bool,
180    max_lines: usize,
181    min_lines: usize,
182) -> NodeId
183where
184    S: IntoTextSource + Clone + PartialEq + 'static,
185{
186    compose_basic_text_group(
187        text.into_text_source(),
188        modifier,
189        style,
190        TextLayoutOptions {
191            overflow,
192            soft_wrap,
193            max_lines,
194            min_lines,
195        },
196    )
197}
198
199#[composable]
200pub fn TextWithOptions<S>(
201    value: S,
202    modifier: Modifier,
203    style: TextStyle,
204    options: TextOptions,
205) -> NodeId
206where
207    S: IntoTextSource + Clone + PartialEq + 'static,
208{
209    compose_basic_text_group(
210        value.into_text_source(),
211        modifier,
212        style,
213        TextLayoutOptions::from(options),
214    )
215}
216
217/// Displays plain or annotated text with the supplied style. The modifier
218/// controls layout, appearance and input around the text.
219///
220/// # Example
221///
222/// ```rust
223/// use cranpose_ui::*;
224///
225/// #[composable]
226/// fn Greeting() {
227///     Text(
228///         "Hello",
229///         Modifier::empty().padding(16.0),
230///         TextStyle::default(),
231///     );
232/// }
233/// ```
234#[composable]
235pub fn Text<S>(value: S, modifier: Modifier, style: TextStyle) -> NodeId
236where
237    S: IntoTextSource + Clone + PartialEq + 'static,
238{
239    compose_basic_text_group(
240        value.into_text_source(),
241        modifier,
242        style,
243        TextLayoutOptions::from(TextOptions::default()),
244    )
245}
246
247#[cfg(test)]
248#[path = "tests/text_tests.rs"]
249mod tests;