cranpose-ui 0.24.0

Composable widgets, text, layouts and input for Cranpose apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Text widget implementation
//!
//! This implementation follows Jetpack Compose's BasicText architecture where text content
//! is implemented as a modifier node rather than as a measure policy. This properly separates
//! concerns: MeasurePolicy handles child layout, while TextModifierNode handles text content
//! measurement, drawing, and semantics.

use std::{rc::Rc, sync::Arc};

use cranpose_core::{MutableState, NodeId, State};
use cranpose_foundation::modifier_element;

use crate::{
    density::Density,
    modifier::Modifier,
    text::{TextLayoutOptions, TextOptions, TextOverflow, TextStyle},
    text_modifier_node::{TextModifierElement, TextModifierNode, shared_text_style},
    widgets::{layout::NodeModifier, nodes::LayoutNode},
};

/// Text produced by a callback that runs each time the text composes, so state read in the callback
/// recomposes the text.
#[derive(Clone)]
pub struct DynamicTextSource(Rc<dyn Fn() -> crate::text::AnnotatedString>);

impl DynamicTextSource {
    /// Creates a source whose text `resolver` returns.
    pub fn new<F>(resolver: F) -> Self
    where
        F: Fn() -> crate::text::AnnotatedString + 'static,
    {
        Self(Rc::new(resolver))
    }

    fn resolve(&self) -> crate::text::AnnotatedString {
        (self.0)()
    }
}

impl PartialEq for DynamicTextSource {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

/// Where a text widget gets its text.
#[derive(Clone, PartialEq)]
pub enum TextSource {
    /// A fixed text.
    Static(crate::text::AnnotatedString),
    /// A text produced by a callback each time the widget composes.
    Dynamic(DynamicTextSource),
}

impl TextSource {
    fn resolve(&self) -> crate::text::AnnotatedString {
        match self {
            Self::Static(text) => text.clone(),
            Self::Dynamic(dynamic) => dynamic.resolve(),
        }
    }
}

/// A fixed text as a widget was given it, which the widget compares with the
/// text its node shows without making a copy.
#[doc(hidden)]
#[derive(Clone, Copy)]
pub enum StaticText<'a> {
    /// Characters with no styles, annotations or links.
    Plain(&'a str),
    /// An annotated string.
    Annotated(&'a crate::text::AnnotatedString),
}

impl StaticText<'_> {
    pub(crate) fn is(self, shown: &crate::text::AnnotatedString) -> bool {
        match self {
            Self::Plain(text) => shown.is_plain(text),
            Self::Annotated(text) => shown == text,
        }
    }
}

#[doc(hidden)]
pub trait IntoTextSource {
    fn into_text_source(self) -> TextSource;

    /// The text, when it is fixed: `None` for a text read from a state or
    /// a callback each time it composes.
    fn static_text(&self) -> Option<StaticText<'_>> {
        None
    }
}

impl IntoTextSource for String {
    fn into_text_source(self) -> TextSource {
        TextSource::Static(crate::text::AnnotatedString::from(self))
    }

    fn static_text(&self) -> Option<StaticText<'_>> {
        Some(StaticText::Plain(self))
    }
}

impl IntoTextSource for &str {
    fn into_text_source(self) -> TextSource {
        TextSource::Static(crate::text::AnnotatedString::from(self))
    }

    fn static_text(&self) -> Option<StaticText<'_>> {
        Some(StaticText::Plain(self))
    }
}

impl IntoTextSource for crate::text::AnnotatedString {
    fn into_text_source(self) -> TextSource {
        TextSource::Static(self)
    }

    fn static_text(&self) -> Option<StaticText<'_>> {
        Some(StaticText::Annotated(self))
    }
}

impl<T> IntoTextSource for State<T>
where
    T: ToString + Clone + 'static,
{
    fn into_text_source(self) -> TextSource {
        let state = self;
        TextSource::Dynamic(DynamicTextSource::new(move || {
            crate::text::AnnotatedString::from(state.value().to_string())
        }))
    }
}

impl<T> IntoTextSource for MutableState<T>
where
    T: ToString + Clone + 'static,
{
    fn into_text_source(self) -> TextSource {
        let state = self;
        TextSource::Dynamic(DynamicTextSource::new(move || {
            crate::text::AnnotatedString::from(state.value().to_string())
        }))
    }
}

impl<F> IntoTextSource for F
where
    F: Fn() -> String + 'static,
{
    fn into_text_source(self) -> TextSource {
        TextSource::Dynamic(DynamicTextSource::new(move || {
            crate::text::AnnotatedString::from(self())
        }))
    }
}

impl IntoTextSource for DynamicTextSource {
    fn into_text_source(self) -> TextSource {
        TextSource::Dynamic(self)
    }
}

// The modifier of a text's node: the caller's `modifier`, then the text's
// `element`.
fn text_node_modifier(modifier: Modifier, element: TextModifierElement) -> Modifier {
    modifier.then(Modifier::from_dyn_element(modifier_element(element)))
}

// The style and options a text lays out with: the style in the locale in
// force, where the app localizes, and the options normalized.
fn text_layout_inputs(
    style: Arc<TextStyle>,
    options: TextLayoutOptions,
) -> (Arc<TextStyle>, TextLayoutOptions) {
    #[cfg(feature = "localization")]
    let style = crate::localization::apply_shared_text_locale(style);
    (style, options.normalized())
}

// Composes a text widget: a fixed text outside a selection container
// composes in its caller's group; any other in a group of its own.
#[track_caller]
fn compose_text<S>(
    text: S,
    modifier: Modifier,
    style: Arc<TextStyle>,
    options: TextLayoutOptions,
) -> NodeId
where
    S: IntoTextSource + Clone + PartialEq + 'static,
{
    if let Some(fixed) = text.static_text()
        && crate::widgets::selection_container::current_selection_registrar().is_none()
    {
        return static_text::Text(fixed, modifier, style, options);
    }
    text_group::Text(text, modifier, style, options)
}

// The modifier of a fixed text's node as a text widget sets it: the
// caller's modifier, then the text's element, made only when the node does
// not show them already.
struct StaticTextModifier<'a> {
    modifier: Modifier,
    text: StaticText<'a>,
    style: Arc<TextStyle>,
    options: TextLayoutOptions,
    density: Density,
}

impl StaticTextModifier<'_> {
    // The text, shared with equal texts the app shows.
    fn shared_text(&self) -> crate::text::AnnotatedString {
        match self.text {
            StaticText::Plain(text) => crate::render_state::current_app_context()
                .map_or_else(|| text.into(), |context| context.text.plain_text(text)),
            StaticText::Annotated(text) => text.clone(),
        }
    }

    fn element(&self) -> TextModifierElement {
        TextModifierElement::with_shared_style(
            self.shared_text(),
            Arc::clone(&self.style),
            self.options,
            self.density,
        )
    }

    // Shows the text in the text node after the caller's modifier in
    // `node`'s chain, comparing it once: whether the node took another text,
    // or `None` when the chain holds no such node. An inspection build keeps
    // the inspector metadata of the whole modifier, so another text goes
    // through the modifier.
    fn show_in(&self, node: &LayoutNode) -> Option<bool> {
        let last = node.node_after(&self.modifier)?;
        let mut last = last.borrow_mut();
        let text_node = last.as_any_mut().downcast_mut::<TextModifierNode>()?;
        if text_node.shows(self.text, &self.style, self.options, self.density) {
            return Some(false);
        }
        if cfg!(feature = "inspection") {
            return None;
        }
        text_node.show(&self.shared_text(), &self.style, self.options, self.density);
        Some(true)
    }
}

impl NodeModifier for StaticTextModifier<'_> {
    fn provided_locals(&self) -> Vec<cranpose_core::ProvidedValue> {
        self.modifier.provided_composition_locals()
    }

    fn to_modifier(&self) -> Modifier {
        text_node_modifier(self.modifier.clone(), self.element())
    }

    fn set_on(&mut self, node: &mut LayoutNode) {
        // A node that shows another text takes this one in its text node,
        // with no modifier made for it, as a ticker's does each frame.
        match self.show_in(node) {
            Some(true) => node.note_last_node_updated(),
            Some(false) => {}
            None => node.set_modifier(self.to_modifier()),
        }
    }
}

// The text widget of a fixed text, named `Text` for the source traces
// inspection shows.
mod static_text {
    use std::sync::Arc;

    use cranpose_core::NodeId;

    use super::{StaticText, StaticTextModifier, text_layout_inputs};
    use crate::{
        composable,
        modifier::Modifier,
        text::{TextLayoutOptions, TextStyle},
        widgets::layout::{LayoutEnvironment, compose_empty_layout},
    };

    // Composes in its caller's group, as an inline composable: a fixed text
    // reads no state, and its node holds what a later composition compares,
    // so it keeps no group, scope or parameters of its own.
    #[composable(no_skip)]
    pub(super) fn Text(
        text: StaticText<'_>,
        modifier: Modifier,
        style: Arc<TextStyle>,
        options: TextLayoutOptions,
    ) -> NodeId {
        let (style, options) = text_layout_inputs(style, options);
        let environment = LayoutEnvironment::current();
        compose_empty_layout(
            StaticTextModifier {
                modifier,
                text,
                style,
                options,
                density: environment.density,
            },
            environment,
        )
    }
}

// The text widget in a group of its own, named `Text` for the source traces
// inspection shows: a text read from a state or a callback, whose scope that
// read recomposes alone, or one in a selection container, which remembers
// its place in the container's selection.
mod text_group {
    use std::sync::Arc;

    use cranpose_core::NodeId;

    use super::{
        IntoTextSource, TextModifierElement, TextSource, text_layout_inputs, text_node_modifier,
    };
    use crate::{
        composable,
        modifier::Modifier,
        text::{TextLayoutOptions, TextStyle},
        widgets::layout::{LayoutEnvironment, compose_empty_layout},
    };

    // Its stored parameters hold the style `shared_text_style` shares with
    // equal ones, eight bytes where a style takes 320, and compare it by
    // pointer.
    #[composable]
    pub(super) fn Text<S>(
        text: S,
        modifier: Modifier,
        style: Arc<TextStyle>,
        options: TextLayoutOptions,
    ) -> NodeId
    where
        S: IntoTextSource + Clone + PartialEq + 'static,
    {
        text_node(&text.into_text_source(), modifier, style, options)
    }

    // What the group makes of any text type. Out of line, one copy: the group
    // of each text type would repeat it.
    #[inline(never)]
    fn text_node(
        source: &TextSource,
        modifier: Modifier,
        style: Arc<TextStyle>,
        options: TextLayoutOptions,
    ) -> NodeId {
        let (style, options) = text_layout_inputs(style, options);
        let environment = LayoutEnvironment::current();
        let text = source.resolve();
        let modifier = match crate::widgets::selection_container::current_selection_registrar() {
            Some(registrar) => modifier.then(crate::widgets::selection_container::selectable_text(
                registrar,
                text.clone(),
                Arc::clone(&style),
                options,
            )),
            None => modifier,
        };
        compose_empty_layout(
            text_node_modifier(
                modifier,
                TextModifierElement::with_shared_style(text, style, options, environment.density),
            ),
            environment,
        )
    }
}

/// Displays `text` in `style` with the given layout `options`. Compose's `BasicText`.
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
pub fn BasicTextWithOptions<S>(
    text: S,
    modifier: Modifier,
    style: TextStyle,
    options: TextLayoutOptions,
) -> NodeId
where
    S: IntoTextSource + Clone + PartialEq + 'static,
{
    compose_text(text, modifier, shared_text_style(style), options)
}

/// Displays `text` in `style` with the given overflow, wrapping and line limits. Compose's
/// `BasicText`.
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
pub fn BasicText<S>(
    text: S,
    modifier: Modifier,
    style: TextStyle,
    overflow: TextOverflow,
    soft_wrap: bool,
    max_lines: usize,
    min_lines: usize,
) -> NodeId
where
    S: IntoTextSource + Clone + PartialEq + 'static,
{
    compose_text(
        text,
        modifier,
        shared_text_style(style),
        TextLayoutOptions {
            overflow,
            soft_wrap,
            max_lines,
            min_lines,
        },
    )
}

/// Displays `value` in `style` with the given text `options`. Compose's `Text`.
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
pub fn TextWithOptions<S>(
    value: S,
    modifier: Modifier,
    style: TextStyle,
    options: TextOptions,
) -> NodeId
where
    S: IntoTextSource + Clone + PartialEq + 'static,
{
    compose_text(
        value,
        modifier,
        shared_text_style(style),
        TextLayoutOptions::from(options),
    )
}

/// Displays plain or annotated text with the supplied style. The modifier
/// controls layout, appearance and input around the text.
///
/// # Example
///
/// ```rust
/// use cranpose_ui::*;
///
/// #[composable]
/// fn Greeting() {
///     Text(
///         "Hello",
///         Modifier::empty().padding(16.0),
///         TextStyle::default(),
///     );
/// }
/// ```
#[track_caller]
#[expect(non_snake_case, reason = "names follow Compose's casing")]
pub fn Text<S>(value: S, modifier: Modifier, style: TextStyle) -> NodeId
where
    S: IntoTextSource + Clone + PartialEq + 'static,
{
    compose_text(
        value,
        modifier,
        shared_text_style(style),
        TextLayoutOptions::from(TextOptions::default()),
    )
}

#[cfg(test)]
#[path = "tests/text_tests.rs"]
mod tests;