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
8#![allow(non_snake_case)]
9
10use std::rc::Rc;
11
12use cranpose_core::{MutableState, NodeId, State};
13use cranpose_foundation::modifier_element;
14
15use crate::{
16    composable,
17    layout::policies::EmptyMeasurePolicy,
18    modifier::Modifier,
19    text::{TextLayoutOptions, TextOptions, TextOverflow, TextStyle},
20    text_modifier_node::TextModifierElement,
21    widgets::Layout,
22};
23
24#[derive(Clone)]
25pub struct DynamicTextSource(Rc<dyn Fn() -> Rc<crate::text::AnnotatedString>>);
26
27impl DynamicTextSource {
28    pub fn new<F>(resolver: F) -> Self
29    where
30        F: Fn() -> Rc<crate::text::AnnotatedString> + 'static,
31    {
32        Self(Rc::new(resolver))
33    }
34
35    fn resolve(&self) -> Rc<crate::text::AnnotatedString> {
36        (self.0)()
37    }
38}
39
40impl PartialEq for DynamicTextSource {
41    fn eq(&self, other: &Self) -> bool {
42        Rc::ptr_eq(&self.0, &other.0)
43    }
44}
45
46#[derive(Clone, PartialEq)]
47pub enum TextSource {
48    Static(Rc<crate::text::AnnotatedString>),
49    Dynamic(DynamicTextSource),
50}
51
52impl TextSource {
53    fn resolve(&self) -> Rc<crate::text::AnnotatedString> {
54        match self {
55            TextSource::Static(text) => text.clone(),
56            TextSource::Dynamic(dynamic) => dynamic.resolve(),
57        }
58    }
59}
60
61#[doc(hidden)]
62pub trait IntoTextSource {
63    fn into_text_source(self) -> TextSource;
64}
65
66impl IntoTextSource for String {
67    fn into_text_source(self) -> TextSource {
68        TextSource::Static(Rc::new(crate::text::AnnotatedString::from(self)))
69    }
70}
71
72impl IntoTextSource for &str {
73    fn into_text_source(self) -> TextSource {
74        TextSource::Static(Rc::new(crate::text::AnnotatedString::from(self)))
75    }
76}
77
78impl IntoTextSource for crate::text::AnnotatedString {
79    fn into_text_source(self) -> TextSource {
80        TextSource::Static(Rc::new(self))
81    }
82}
83
84impl IntoTextSource for Rc<crate::text::AnnotatedString> {
85    fn into_text_source(self) -> TextSource {
86        TextSource::Static(self)
87    }
88}
89
90impl<T> IntoTextSource for State<T>
91where
92    T: ToString + Clone + 'static,
93{
94    fn into_text_source(self) -> TextSource {
95        let state = self;
96        TextSource::Dynamic(DynamicTextSource::new(move || {
97            Rc::new(crate::text::AnnotatedString::from(
98                state.value().to_string(),
99            ))
100        }))
101    }
102}
103
104impl<T> IntoTextSource for MutableState<T>
105where
106    T: ToString + Clone + 'static,
107{
108    fn into_text_source(self) -> TextSource {
109        let state = self;
110        TextSource::Dynamic(DynamicTextSource::new(move || {
111            Rc::new(crate::text::AnnotatedString::from(
112                state.value().to_string(),
113            ))
114        }))
115    }
116}
117
118impl<F> IntoTextSource for F
119where
120    F: Fn() -> String + 'static,
121{
122    fn into_text_source(self) -> TextSource {
123        TextSource::Dynamic(DynamicTextSource::new(move || {
124            Rc::new(crate::text::AnnotatedString::from(self()))
125        }))
126    }
127}
128
129impl IntoTextSource for DynamicTextSource {
130    fn into_text_source(self) -> TextSource {
131        TextSource::Dynamic(self)
132    }
133}
134
135/// High-level element that displays text.
136///
137/// # When to use
138/// Use this widget to display read-only text on the screen. For editable text,
139/// use [`BasicTextField`](crate::widgets::BasicTextField).
140///
141/// # Arguments
142///
143/// * `value` - The string to display. Can be a `&str`, `String`, or `State<String>`.
144/// * `modifier` - Modifiers to apply (e.g., padding, background, layout instructions).
145/// * `style` - Text styling (color, font size).
146///
147/// # Example
148///
149/// ```rust,ignore
150/// Text("Hello World", Modifier::padding(16.0), TextStyle::default());
151/// ```
152fn compose_basic_text_group(
153    text: TextSource,
154    modifier: Modifier,
155    style: TextStyle,
156    options: TextLayoutOptions,
157) -> NodeId {
158    let current = text.resolve();
159
160    let options = options.normalized();
161
162    let text_element = modifier_element(TextModifierElement::new(current, style, options));
163    let final_modifier = Modifier::from_parts(vec![text_element]);
164    let combined_modifier = modifier.then(final_modifier);
165
166    Layout(combined_modifier, EmptyMeasurePolicy, || {})
167}
168
169#[composable]
170pub fn BasicTextWithOptions<S>(
171    text: S,
172    modifier: Modifier,
173    style: TextStyle,
174    options: TextLayoutOptions,
175) -> NodeId
176where
177    S: IntoTextSource + Clone + PartialEq + 'static,
178{
179    compose_basic_text_group(text.into_text_source(), modifier, style, options)
180}
181
182#[composable]
183pub fn BasicText<S>(
184    text: S,
185    modifier: Modifier,
186    style: TextStyle,
187    overflow: TextOverflow,
188    soft_wrap: bool,
189    max_lines: usize,
190    min_lines: usize,
191) -> NodeId
192where
193    S: IntoTextSource + Clone + PartialEq + 'static,
194{
195    BasicTextWithOptions(
196        text,
197        modifier,
198        style,
199        TextLayoutOptions {
200            overflow,
201            soft_wrap,
202            max_lines,
203            min_lines,
204        },
205    )
206}
207
208#[composable]
209pub fn TextWithOptions<S>(
210    value: S,
211    modifier: Modifier,
212    style: TextStyle,
213    options: TextOptions,
214) -> NodeId
215where
216    S: IntoTextSource + Clone + PartialEq + 'static,
217{
218    BasicTextWithOptions(value, modifier, style, TextLayoutOptions::from(options))
219}
220
221#[composable]
222pub fn Text<S>(value: S, modifier: Modifier, style: TextStyle) -> NodeId
223where
224    S: IntoTextSource + Clone + PartialEq + 'static,
225{
226    TextWithOptions(value, modifier, style, TextOptions::default())
227}
228
229#[cfg(test)]
230mod tests {
231    use std::{cell::Cell, rc::Rc};
232
233    use cranpose_core::{Composition, MemoryApplier, location_key};
234
235    use super::*;
236    use crate::run_test_composition;
237
238    #[test]
239    fn basic_text_creates_node() {
240        let _app_context = crate::render_state::app_context_test_scope();
241        let composition = run_test_composition(|| {
242            BasicTextWithOptions(
243                "Hello",
244                Modifier::empty(),
245                TextStyle::default(),
246                TextLayoutOptions::default(),
247            );
248        });
249
250        assert!(composition.root().is_some());
251    }
252
253    #[test]
254    fn text_with_options_creates_node() {
255        let _app_context = crate::render_state::app_context_test_scope();
256        let composition = run_test_composition(|| {
257            TextWithOptions(
258                "Hello",
259                Modifier::empty(),
260                TextStyle::default(),
261                TextOptions {
262                    overflow: TextOverflow::Ellipsis,
263                    soft_wrap: false,
264                    max_lines: Some(1),
265                    ..TextOptions::default()
266                },
267            );
268        });
269
270        assert!(composition.root().is_some());
271    }
272
273    #[test]
274    fn basic_text_recomposes_when_dynamic_source_changes() {
275        let _app_context = crate::render_state::app_context_test_scope();
276        let mut composition = Composition::new(MemoryApplier::new());
277        let runtime = composition.runtime_handle();
278        let state = MutableState::with_runtime("Hello".to_string(), runtime);
279        let resolutions = Rc::new(Cell::new(0));
280
281        composition
282            .render(location_key(file!(), line!(), column!()), {
283                let text_state = state;
284                let resolutions = Rc::clone(&resolutions);
285                move || {
286                    let text_state = text_state;
287                    let resolutions = Rc::clone(&resolutions);
288                    BasicText(
289                        DynamicTextSource::new(move || {
290                            resolutions.set(resolutions.get() + 1);
291                            Rc::new(crate::text::AnnotatedString::from(text_state.value()))
292                        }),
293                        Modifier::empty(),
294                        TextStyle::default(),
295                        TextOverflow::Clip,
296                        true,
297                        usize::MAX,
298                        1,
299                    );
300                }
301            })
302            .expect("initial text render");
303
304        assert_eq!(resolutions.get(), 1);
305
306        state.set_value("World".to_string());
307        composition
308            .process_invalid_scopes()
309            .expect("dynamic text recomposition");
310
311        assert_eq!(resolutions.get(), 2);
312    }
313}