cranpose-ui 0.28.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! 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::{cell::RefCell, 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,
            Self::Dynamic(dynamic) => dynamic.resolve(),
        }
    }
}

// The most bytes past its text that an owned string keeps in its room once a
// text shows it: what `format!` and `to_string` leave past a short number.
const SPARE_ROOM_KEPT: usize = 8;

/// A fixed text as a widget was given it, which the widget compares with the
/// text its node shows without making a copy, and gives the node when the
/// node shows another.
#[doc(hidden)]
pub enum StaticText {
    /// Characters with no styles, annotations or links, whose room the
    /// node takes.
    Owned(String),
    /// Characters with no styles, annotations or links, which the node
    /// copies.
    Borrowed(&'static str),
    /// An annotated string.
    Annotated(crate::text::AnnotatedString),
}

impl Default for StaticText {
    fn default() -> Self {
        Self::Borrowed("")
    }
}

// Out of line, as the comparison below: a text group compares and keeps its
// text, and inlined there each would be one more copy in every build.
impl Clone for StaticText {
    #[inline(never)]
    fn clone(&self) -> Self {
        match self {
            Self::Owned(text) => Self::Owned(text.clone()),
            Self::Borrowed(text) => Self::Borrowed(text),
            Self::Annotated(text) => Self::Annotated(text.clone()),
        }
    }
}

impl PartialEq for StaticText {
    #[inline(never)]
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Owned(text), Self::Owned(other)) => text == other,
            (Self::Borrowed(text), Self::Borrowed(other)) => text == other,
            (Self::Annotated(text), Self::Annotated(other)) => text == other,
            _ => false,
        }
    }
}

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

    // The text as an annotated string, in the room of a string a text gave
    // up when the app context keeps one. An owned string keeps its room for
    // as long as the text shows it, so a room with more than
    // `SPARE_ROOM_KEPT` bytes past the text gives the rest back first.
    fn into_annotated(self) -> crate::text::AnnotatedString {
        let context = crate::render_state::current_app_context();
        match self {
            Self::Owned(mut text) => {
                if text.capacity() - text.len() > SPARE_ROOM_KEPT {
                    text.shrink_to_fit();
                }
                match context {
                    Some(context) => context.text.plain_string(text),
                    None => crate::text::AnnotatedString::new(text),
                }
            }
            Self::Borrowed(text) => {
                context.map_or_else(|| text.into(), |context| context.text.plain_text(text))
            }
            Self::Annotated(text) => text,
        }
    }
}

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

    /// The text, when it is fixed; the source itself, which a text reads
    /// from a state or a callback each time it composes, when not.
    fn into_static_text(self) -> Result<StaticText, Self>
    where
        Self: Sized,
    {
        Err(self)
    }

    /// The text as its widget composes it, in the widget's own group: a
    /// state or a callback read now, so the read recomposes the widget alone.
    fn into_composed_text(self) -> crate::text::AnnotatedString
    where
        Self: Sized,
    {
        self.into_text_source().resolve()
    }
}

impl IntoTextSource for StaticText {
    fn into_text_source(self) -> TextSource {
        TextSource::Static(self.into_annotated())
    }

    fn into_static_text(self) -> Result<StaticText, Self> {
        Ok(self)
    }
}

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

    fn into_static_text(self) -> Result<StaticText, Self> {
        Ok(StaticText::Owned(self))
    }
}

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

    fn into_static_text(self) -> Result<StaticText, Self> {
        Ok(StaticText::Borrowed(self))
    }
}

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

    fn into_static_text(self) -> Result<StaticText, Self> {
        Ok(StaticText::Annotated(self))
    }
}

// A source that reads `text` each time it resolves.
fn reading(text: impl Fn() -> String + 'static) -> TextSource {
    TextSource::Dynamic(DynamicTextSource::new(move || {
        crate::text::AnnotatedString::from(text())
    }))
}

// A state's and a callback's source reads them each time it resolves, so a
// source made once follows them. Its widget reads them as it composes, in
// its own group, with no source made. A value formats outside the state's
// borrow: its `ToString` may write the state.
macro_rules! state_text_source {
    ($state:ident) => {
        impl<T> IntoTextSource for $state<T>
        where
            T: ToString + Clone + 'static,
        {
            fn into_text_source(self) -> TextSource {
                reading(move || self.with(T::to_string))
            }

            fn into_composed_text(self) -> crate::text::AnnotatedString {
                StaticText::Owned(self.with(T::to_string)).into_annotated()
            }
        }
    };
}

state_text_source!(State);
state_text_source!(MutableState);

impl<F> IntoTextSource for F
where
    F: Fn() -> String + 'static,
{
    fn into_text_source(self) -> TextSource {
        reading(self)
    }

    fn into_composed_text(self) -> crate::text::AnnotatedString {
        StaticText::Owned(self()).into_annotated()
    }
}

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,
{
    match text.into_static_text() {
        Ok(fixed)
            if crate::widgets::selection_container::current_selection_registrar().is_none() =>
        {
            static_text::Text(fixed, modifier, style, options)
        }
        Ok(fixed) => text_group::Text(fixed, modifier, style, options),
        Err(text) => text_group::Text(text, modifier, style, options),
    }
}

// The modifier of a 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. A node that shows another text takes the text in place.
struct TextNodeModifier {
    modifier: Modifier,
    // The text as the widget has it, until a node takes it: then the string
    // the node shows.
    text: RefCell<StaticText>,
    style: Arc<TextStyle>,
    options: TextLayoutOptions,
    density: Density,
}

impl TextNodeModifier {
    // The text as a node shows it, which the modifier compares from then
    // on: a node made for the modifier may take it once more.
    fn shared_text(&self) -> crate::text::AnnotatedString {
        let mut text = self.text.borrow_mut();
        if let StaticText::Annotated(shown) = &*text {
            return shown.clone();
        }
        let shown = std::mem::take(&mut *text).into_annotated();
        *text = StaticText::Annotated(shown.clone());
        shown
    }

    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. The node takes the text: the modifier compares
    // it no more.
    fn show_in(&mut 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>()?;
        let text = self.text.get_mut();
        if text_node.shows(text, &self.style, self.options, self.density) {
            return Some(false);
        }
        if cfg!(feature = "inspection") {
            return None;
        }
        let shown = std::mem::take(text).into_annotated();
        text_node.show(shown, &self.style, self.options, self.density);
        Some(true)
    }
}

impl NodeModifier for TextNodeModifier {
    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::{cell::RefCell, sync::Arc};

    use cranpose_core::NodeId;

    use super::{StaticText, TextNodeModifier, 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(
            TextNodeModifier {
                modifier,
                text: RefCell::new(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::{cell::RefCell, sync::Arc};

    use cranpose_core::NodeId;

    use super::{IntoTextSource, StaticText, TextNodeModifier, text_layout_inputs};
    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_composed_text(), 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(
        text: crate::text::AnnotatedString,
        modifier: Modifier,
        style: Arc<TextStyle>,
        options: TextLayoutOptions,
    ) -> NodeId {
        let (style, options) = text_layout_inputs(style, options);
        let environment = LayoutEnvironment::current();
        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(
            TextNodeModifier {
                modifier,
                text: RefCell::new(StaticText::Annotated(text)),
                style,
                options,
                density: 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")]
#[expect(
    clippy::needless_pass_by_value,
    reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
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")]
#[expect(
    clippy::needless_pass_by_value,
    reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
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")]
#[expect(
    clippy::needless_pass_by_value,
    reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
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")]
#[expect(
    clippy::needless_pass_by_value,
    reason = "Compose's Text takes its style by value; the function shares it without a copy"
)]
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;