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::{cell::RefCell, rc::Rc, sync::Arc};
9
10use cranpose_core::{MutableState, NodeId, State};
11use cranpose_foundation::modifier_element;
12
13use crate::{
14    density::Density,
15    modifier::Modifier,
16    text::{TextLayoutOptions, TextOptions, TextOverflow, TextStyle},
17    text_modifier_node::{TextModifierElement, TextModifierNode, shared_text_style},
18    widgets::{layout::NodeModifier, nodes::LayoutNode},
19};
20
21/// Text produced by a callback that runs each time the text composes, so state read in the callback
22/// recomposes the text.
23#[derive(Clone)]
24pub struct DynamicTextSource(Rc<dyn Fn() -> crate::text::AnnotatedString>);
25
26impl DynamicTextSource {
27    /// Creates a source whose text `resolver` returns.
28    pub fn new<F>(resolver: F) -> Self
29    where
30        F: Fn() -> crate::text::AnnotatedString + 'static,
31    {
32        Self(Rc::new(resolver))
33    }
34
35    fn resolve(&self) -> 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/// Where a text widget gets its text.
47#[derive(Clone, PartialEq)]
48pub enum TextSource {
49    /// A fixed text.
50    Static(crate::text::AnnotatedString),
51    /// A text produced by a callback each time the widget composes.
52    Dynamic(DynamicTextSource),
53}
54
55impl TextSource {
56    fn resolve(self) -> crate::text::AnnotatedString {
57        match self {
58            Self::Static(text) => text,
59            Self::Dynamic(dynamic) => dynamic.resolve(),
60        }
61    }
62}
63
64// The most bytes past its text that an owned string keeps in its room once a
65// text shows it: what `format!` and `to_string` leave past a short number.
66const SPARE_ROOM_KEPT: usize = 8;
67
68/// A fixed text as a widget was given it, which the widget compares with the
69/// text its node shows without making a copy, and gives the node when the
70/// node shows another.
71#[doc(hidden)]
72pub enum StaticText {
73    /// Characters with no styles, annotations or links, whose room the
74    /// node takes.
75    Owned(String),
76    /// Characters with no styles, annotations or links, which the node
77    /// copies.
78    Borrowed(&'static str),
79    /// An annotated string.
80    Annotated(crate::text::AnnotatedString),
81}
82
83impl Default for StaticText {
84    fn default() -> Self {
85        Self::Borrowed("")
86    }
87}
88
89// Out of line, as the comparison below: a text group compares and keeps its
90// text, and inlined there each would be one more copy in every build.
91impl Clone for StaticText {
92    #[inline(never)]
93    fn clone(&self) -> Self {
94        match self {
95            Self::Owned(text) => Self::Owned(text.clone()),
96            Self::Borrowed(text) => Self::Borrowed(text),
97            Self::Annotated(text) => Self::Annotated(text.clone()),
98        }
99    }
100}
101
102impl PartialEq for StaticText {
103    #[inline(never)]
104    fn eq(&self, other: &Self) -> bool {
105        match (self, other) {
106            (Self::Owned(text), Self::Owned(other)) => text == other,
107            (Self::Borrowed(text), Self::Borrowed(other)) => text == other,
108            (Self::Annotated(text), Self::Annotated(other)) => text == other,
109            _ => false,
110        }
111    }
112}
113
114impl StaticText {
115    pub(crate) fn is(&self, shown: &crate::text::AnnotatedString) -> bool {
116        match self {
117            Self::Owned(text) => shown.is_plain(text),
118            Self::Borrowed(text) => shown.is_plain(text),
119            Self::Annotated(text) => shown == text,
120        }
121    }
122
123    // The text as an annotated string, in the room of a string a text gave
124    // up when the app context keeps one. An owned string keeps its room for
125    // as long as the text shows it, so a room with more than
126    // `SPARE_ROOM_KEPT` bytes past the text gives the rest back first.
127    fn into_annotated(self) -> crate::text::AnnotatedString {
128        let context = crate::render_state::current_app_context();
129        match self {
130            Self::Owned(mut text) => {
131                if text.capacity() - text.len() > SPARE_ROOM_KEPT {
132                    text.shrink_to_fit();
133                }
134                match context {
135                    Some(context) => context.text.plain_string(text),
136                    None => crate::text::AnnotatedString::new(text),
137                }
138            }
139            Self::Borrowed(text) => {
140                context.map_or_else(|| text.into(), |context| context.text.plain_text(text))
141            }
142            Self::Annotated(text) => text,
143        }
144    }
145}
146
147#[doc(hidden)]
148pub trait IntoTextSource {
149    fn into_text_source(self) -> TextSource;
150
151    /// The text, when it is fixed; the source itself, which a text reads
152    /// from a state or a callback each time it composes, when not.
153    fn into_static_text(self) -> Result<StaticText, Self>
154    where
155        Self: Sized,
156    {
157        Err(self)
158    }
159
160    /// The text as its widget composes it, in the widget's own group: a
161    /// state or a callback read now, so the read recomposes the widget alone.
162    fn into_composed_text(self) -> crate::text::AnnotatedString
163    where
164        Self: Sized,
165    {
166        self.into_text_source().resolve()
167    }
168}
169
170impl IntoTextSource for StaticText {
171    fn into_text_source(self) -> TextSource {
172        TextSource::Static(self.into_annotated())
173    }
174
175    fn into_static_text(self) -> Result<StaticText, Self> {
176        Ok(self)
177    }
178}
179
180impl IntoTextSource for String {
181    fn into_text_source(self) -> TextSource {
182        TextSource::Static(crate::text::AnnotatedString::from(self))
183    }
184
185    fn into_static_text(self) -> Result<StaticText, Self> {
186        Ok(StaticText::Owned(self))
187    }
188}
189
190impl IntoTextSource for &'static str {
191    fn into_text_source(self) -> TextSource {
192        TextSource::Static(crate::text::AnnotatedString::from(self))
193    }
194
195    fn into_static_text(self) -> Result<StaticText, Self> {
196        Ok(StaticText::Borrowed(self))
197    }
198}
199
200impl IntoTextSource for crate::text::AnnotatedString {
201    fn into_text_source(self) -> TextSource {
202        TextSource::Static(self)
203    }
204
205    fn into_static_text(self) -> Result<StaticText, Self> {
206        Ok(StaticText::Annotated(self))
207    }
208}
209
210// A source that reads `text` each time it resolves.
211fn reading(text: impl Fn() -> String + 'static) -> TextSource {
212    TextSource::Dynamic(DynamicTextSource::new(move || {
213        crate::text::AnnotatedString::from(text())
214    }))
215}
216
217// A state's and a callback's source reads them each time it resolves, so a
218// source made once follows them. Its widget reads them as it composes, in
219// its own group, with no source made. A value formats outside the state's
220// borrow: its `ToString` may write the state.
221macro_rules! state_text_source {
222    ($state:ident) => {
223        impl<T> IntoTextSource for $state<T>
224        where
225            T: ToString + Clone + 'static,
226        {
227            fn into_text_source(self) -> TextSource {
228                reading(move || self.with(T::to_string))
229            }
230
231            fn into_composed_text(self) -> crate::text::AnnotatedString {
232                StaticText::Owned(self.with(T::to_string)).into_annotated()
233            }
234        }
235    };
236}
237
238state_text_source!(State);
239state_text_source!(MutableState);
240
241impl<F> IntoTextSource for F
242where
243    F: Fn() -> String + 'static,
244{
245    fn into_text_source(self) -> TextSource {
246        reading(self)
247    }
248
249    fn into_composed_text(self) -> crate::text::AnnotatedString {
250        StaticText::Owned(self()).into_annotated()
251    }
252}
253
254impl IntoTextSource for DynamicTextSource {
255    fn into_text_source(self) -> TextSource {
256        TextSource::Dynamic(self)
257    }
258}
259
260// The modifier of a text's node: the caller's `modifier`, then the text's
261// `element`.
262fn text_node_modifier(modifier: Modifier, element: TextModifierElement) -> Modifier {
263    modifier.then(Modifier::from_dyn_element(modifier_element(element)))
264}
265
266// The style and options a text lays out with: the style in the locale in
267// force, where the app localizes, and the options normalized.
268fn text_layout_inputs(
269    style: Arc<TextStyle>,
270    options: TextLayoutOptions,
271) -> (Arc<TextStyle>, TextLayoutOptions) {
272    #[cfg(feature = "localization")]
273    let style = crate::localization::apply_shared_text_locale(style);
274    (style, options.normalized())
275}
276
277// Composes a text widget: a fixed text outside a selection container
278// composes in its caller's group; any other in a group of its own.
279#[track_caller]
280fn compose_text<S>(
281    text: S,
282    modifier: Modifier,
283    style: Arc<TextStyle>,
284    options: TextLayoutOptions,
285) -> NodeId
286where
287    S: IntoTextSource + Clone + PartialEq + 'static,
288{
289    match text.into_static_text() {
290        Ok(fixed)
291            if crate::widgets::selection_container::current_selection_registrar().is_none() =>
292        {
293            static_text::Text(fixed, modifier, style, options)
294        }
295        Ok(fixed) => text_group::Text(fixed, modifier, style, options),
296        Err(text) => text_group::Text(text, modifier, style, options),
297    }
298}
299
300// The modifier of a text's node as a text widget sets it: the caller's
301// modifier, then the text's element, made only when the node does not show
302// them already. A node that shows another text takes the text in place.
303struct TextNodeModifier {
304    modifier: Modifier,
305    // The text as the widget has it, until a node takes it: then the string
306    // the node shows.
307    text: RefCell<StaticText>,
308    style: Arc<TextStyle>,
309    options: TextLayoutOptions,
310    density: Density,
311}
312
313impl TextNodeModifier {
314    // The text as a node shows it, which the modifier compares from then
315    // on: a node made for the modifier may take it once more.
316    fn shared_text(&self) -> crate::text::AnnotatedString {
317        let mut text = self.text.borrow_mut();
318        if let StaticText::Annotated(shown) = &*text {
319            return shown.clone();
320        }
321        let shown = std::mem::take(&mut *text).into_annotated();
322        *text = StaticText::Annotated(shown.clone());
323        shown
324    }
325
326    fn element(&self) -> TextModifierElement {
327        TextModifierElement::with_shared_style(
328            self.shared_text(),
329            Arc::clone(&self.style),
330            self.options,
331            self.density,
332        )
333    }
334
335    // Shows the text in the text node after the caller's modifier in
336    // `node`'s chain, comparing it once: whether the node took another text,
337    // or `None` when the chain holds no such node. An inspection build keeps
338    // the inspector metadata of the whole modifier, so another text goes
339    // through the modifier. The node takes the text: the modifier compares
340    // it no more.
341    fn show_in(&mut self, node: &LayoutNode) -> Option<bool> {
342        let last = node.node_after(&self.modifier)?;
343        let mut last = last.borrow_mut();
344        let text_node = last.as_any_mut().downcast_mut::<TextModifierNode>()?;
345        let text = self.text.get_mut();
346        if text_node.shows(text, &self.style, self.options, self.density) {
347            return Some(false);
348        }
349        if cfg!(feature = "inspection") {
350            return None;
351        }
352        let shown = std::mem::take(text).into_annotated();
353        text_node.show(shown, &self.style, self.options, self.density);
354        Some(true)
355    }
356}
357
358impl NodeModifier for TextNodeModifier {
359    fn provided_locals(&self) -> Vec<cranpose_core::ProvidedValue> {
360        self.modifier.provided_composition_locals()
361    }
362
363    fn to_modifier(&self) -> Modifier {
364        text_node_modifier(self.modifier.clone(), self.element())
365    }
366
367    fn set_on(&mut self, node: &mut LayoutNode) {
368        // A node that shows another text takes this one in its text node,
369        // with no modifier made for it, as a ticker's does each frame.
370        match self.show_in(node) {
371            Some(true) => node.note_last_node_updated(),
372            Some(false) => {}
373            None => node.set_modifier(self.to_modifier()),
374        }
375    }
376}
377
378// The text widget of a fixed text, named `Text` for the source traces
379// inspection shows.
380mod static_text {
381    use std::{cell::RefCell, sync::Arc};
382
383    use cranpose_core::NodeId;
384
385    use super::{StaticText, TextNodeModifier, text_layout_inputs};
386    use crate::{
387        composable,
388        modifier::Modifier,
389        text::{TextLayoutOptions, TextStyle},
390        widgets::layout::{LayoutEnvironment, compose_empty_layout},
391    };
392
393    // Composes in its caller's group, as an inline composable: a fixed text
394    // reads no state, and its node holds what a later composition compares,
395    // so it keeps no group, scope or parameters of its own.
396    #[composable(no_skip)]
397    pub(super) fn Text(
398        text: StaticText,
399        modifier: Modifier,
400        style: Arc<TextStyle>,
401        options: TextLayoutOptions,
402    ) -> NodeId {
403        let (style, options) = text_layout_inputs(style, options);
404        let environment = LayoutEnvironment::current();
405        compose_empty_layout(
406            TextNodeModifier {
407                modifier,
408                text: RefCell::new(text),
409                style,
410                options,
411                density: environment.density,
412            },
413            environment,
414        )
415    }
416}
417
418// The text widget in a group of its own, named `Text` for the source traces
419// inspection shows: a text read from a state or a callback, whose scope that
420// read recomposes alone, or one in a selection container, which remembers
421// its place in the container's selection.
422mod text_group {
423    use std::{cell::RefCell, sync::Arc};
424
425    use cranpose_core::NodeId;
426
427    use super::{IntoTextSource, StaticText, TextNodeModifier, text_layout_inputs};
428    use crate::{
429        composable,
430        modifier::Modifier,
431        text::{TextLayoutOptions, TextStyle},
432        widgets::layout::{LayoutEnvironment, compose_empty_layout},
433    };
434
435    // Its stored parameters hold the style `shared_text_style` shares with
436    // equal ones, eight bytes where a style takes 320, and compare it by
437    // pointer.
438    #[composable]
439    pub(super) fn Text<S>(
440        text: S,
441        modifier: Modifier,
442        style: Arc<TextStyle>,
443        options: TextLayoutOptions,
444    ) -> NodeId
445    where
446        S: IntoTextSource + Clone + PartialEq + 'static,
447    {
448        text_node(text.into_composed_text(), modifier, style, options)
449    }
450
451    // What the group makes of any text type. Out of line, one copy: the group
452    // of each text type would repeat it.
453    #[inline(never)]
454    fn text_node(
455        text: crate::text::AnnotatedString,
456        modifier: Modifier,
457        style: Arc<TextStyle>,
458        options: TextLayoutOptions,
459    ) -> NodeId {
460        let (style, options) = text_layout_inputs(style, options);
461        let environment = LayoutEnvironment::current();
462        let modifier = match crate::widgets::selection_container::current_selection_registrar() {
463            Some(registrar) => modifier.then(crate::widgets::selection_container::selectable_text(
464                registrar,
465                text.clone(),
466                Arc::clone(&style),
467                options,
468            )),
469            None => modifier,
470        };
471        compose_empty_layout(
472            TextNodeModifier {
473                modifier,
474                text: RefCell::new(StaticText::Annotated(text)),
475                style,
476                options,
477                density: environment.density,
478            },
479            environment,
480        )
481    }
482}
483
484/// Displays `text` in `style` with the given layout `options`. Compose's `BasicText`.
485#[track_caller]
486#[expect(non_snake_case, reason = "names follow Compose's casing")]
487#[expect(
488    clippy::needless_pass_by_value,
489    reason = "Compose's Text takes its style by value; the function shares it without a copy"
490)]
491pub fn BasicTextWithOptions<S>(
492    text: S,
493    modifier: Modifier,
494    style: TextStyle,
495    options: TextLayoutOptions,
496) -> NodeId
497where
498    S: IntoTextSource + Clone + PartialEq + 'static,
499{
500    compose_text(text, modifier, shared_text_style(&style), options)
501}
502
503/// Displays `text` in `style` with the given overflow, wrapping and line limits. Compose's
504/// `BasicText`.
505#[track_caller]
506#[expect(non_snake_case, reason = "names follow Compose's casing")]
507#[expect(
508    clippy::needless_pass_by_value,
509    reason = "Compose's Text takes its style by value; the function shares it without a copy"
510)]
511pub fn BasicText<S>(
512    text: S,
513    modifier: Modifier,
514    style: TextStyle,
515    overflow: TextOverflow,
516    soft_wrap: bool,
517    max_lines: usize,
518    min_lines: usize,
519) -> NodeId
520where
521    S: IntoTextSource + Clone + PartialEq + 'static,
522{
523    compose_text(
524        text,
525        modifier,
526        shared_text_style(&style),
527        TextLayoutOptions {
528            overflow,
529            soft_wrap,
530            max_lines,
531            min_lines,
532        },
533    )
534}
535
536/// Displays `value` in `style` with the given text `options`. Compose's `Text`.
537#[track_caller]
538#[expect(non_snake_case, reason = "names follow Compose's casing")]
539#[expect(
540    clippy::needless_pass_by_value,
541    reason = "Compose's Text takes its style by value; the function shares it without a copy"
542)]
543pub fn TextWithOptions<S>(
544    value: S,
545    modifier: Modifier,
546    style: TextStyle,
547    options: TextOptions,
548) -> NodeId
549where
550    S: IntoTextSource + Clone + PartialEq + 'static,
551{
552    compose_text(
553        value,
554        modifier,
555        shared_text_style(&style),
556        TextLayoutOptions::from(options),
557    )
558}
559
560/// Displays plain or annotated text with the supplied style. The modifier
561/// controls layout, appearance and input around the text.
562///
563/// # Example
564///
565/// ```rust
566/// use cranpose_ui::*;
567///
568/// #[composable]
569/// fn Greeting() {
570///     Text(
571///         "Hello",
572///         Modifier::empty().padding(16.0),
573///         TextStyle::default(),
574///     );
575/// }
576/// ```
577#[track_caller]
578#[expect(non_snake_case, reason = "names follow Compose's casing")]
579#[expect(
580    clippy::needless_pass_by_value,
581    reason = "Compose's Text takes its style by value; the function shares it without a copy"
582)]
583pub fn Text<S>(value: S, modifier: Modifier, style: TextStyle) -> NodeId
584where
585    S: IntoTextSource + Clone + PartialEq + 'static,
586{
587    compose_text(
588        value,
589        modifier,
590        shared_text_style(&style),
591        TextLayoutOptions::from(TextOptions::default()),
592    )
593}
594
595#[cfg(test)]
596#[path = "tests/text_tests.rs"]
597mod tests;