compose-rust 0.0.4

Declarative UI in Rust, rendered by an AOT-compiled Compose Multiplatform engine.
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
//! The widget vocabulary as composables: the same widgets, the same properties and the
//! same Modifier slots the `rsx!` layer writes, with Compose's names and Compose's shape.
//!
//! ```ignore
//! use compose_rust::runtime::*;
//! use compose_rust::ui::*;
//!
//! #[composable]
//! fn Greeting(name: String) {
//!     Column().modifier(Modifier.padding(16.0).fill_max_width()).content(|| {
//!         Text(format!("Hello, {name}")).type_role(TypeRole::Title);
//!         Button("Wave").on_click(|| show_message("Hello back"));
//!     });
//! }
//! ```
//!
//! **A widget is written as a statement.** `Text("Hello")` creates a description and the
//! statement's end hands it to the composition; the methods in between set what Compose
//! would take as named arguments. A container's children are the closure given to
//! `content`, which runs at once. Binding a widget to a variable delays it to the end of
//! the variable's scope, so a widget is not bound.
//!
//! **Nothing here defines a widget.** Each composable writes exactly the attributes its
//! `rsx!` counterpart writes, through the same translation into wire records, so a screen
//! written either way is the same tree of the same nodes for the Renderer. A Modifier the
//! `rsx!` counterpart does not accept is still written when it is set, because the wire
//! carries every Modifier slot on every node.

mod lazy;
mod widgets;

pub use crate::boundary::LaunchBuilder;
pub use crate::brush::{Brush, Stop, brush};
pub use crate::drawing::{DrawCommand, DrawList, DrawListBuilder};
pub use crate::message::{Message, show_message};
pub use crate::runtime::{application, launch};
pub use crate::schema::{
    Alignment, Arrangement, ButtonKind, ButtonVariant, Color, ColorRole, ColorScheme, DesignSystem,
    IconRole, Key, MaterialRole, MessageDuration, MotionRole, Paint, ShapeRole, SpaceRole,
    TextAlign, TextOverflow, Theme, TypeRole, WindowHeightClass, WindowSizeClass,
};
pub use crate::spans::TextSpans;
pub use crate::theme::{ThemeHandle, current_theme};

/// The application's theme, to read and to change while it runs. A change is one
/// `SetTheme` record in the batch the call that made it produces.
pub fn theme() -> ThemeHandle {
    ThemeHandle::default()
}
pub use crate::window::{NodeSize, WindowSize};
pub use crate::{
    Cursor, FileDrop, KeyEvent, PointerEvent, PointerKind, PointerKinds, RangeRequest, UserSelect,
    asset, pointer_button,
};
pub use lazy::{LazyColumn, LazyGrid, LazyList, LazyListScope, LazyRow};
pub use widgets::*;

use crate::runtime::composer::{EventCallback, OwnedAttr};
use crate::runtime::{group_guard, with_composer, with_composer_if_idle};
use crate::schema::WidgetKind;

/// What sits around a widget: its size, its surface, its outline, how far its content
/// is inset, and what the Renderer reports about it. Compose's `Modifier`.
///
/// Written the way Compose writes it, from the empty value `Modifier`:
///
/// ```ignore
/// Card().modifier(Modifier.fill_max_width().padding(16.0).background(Paint::Role(ColorRole::Surface)))
/// ```
///
/// The order of the calls does not matter. Each kind of Modifier has a fixed slot in the
/// node's chain, outside in: size, shape, fill, outline, lift, press, inset. That is what
/// the `rsx!` attributes do too, so the same Modifier draws the same either way.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Modifier {
    observe_size: Option<i64>,
    motion: Option<MotionRole>,
    material: Option<MaterialRole>,
    weight: Option<f32>,
    width: Option<f32>,
    height: Option<f32>,
    padding: Option<f32>,
    padding_role: Option<SpaceRole>,
    background: Option<Paint>,
    shape_role: Option<ShapeRole>,
    corner_radius: Option<f32>,
    border_width: Option<f32>,
    border_color: Option<Paint>,
    elevation: Option<f32>,
    alpha: Option<f32>,
    transform: Option<[f32; 8]>,
    animated_alpha: Option<crate::Animated<f32>>,
    animated_background: Option<crate::Animated<Paint>>,
    animated_offset: Option<crate::Animated<(f32, f32)>>,
    cursor: Option<crate::Cursor>,
    user_select: Option<crate::UserSelect>,
    fill_max_width: bool,
    fill_max_height: bool,
}

/// The empty Modifier, to start a chain from: `Modifier.padding(8.0)`.
#[allow(non_upper_case_globals)]
pub const Modifier: Modifier = Modifier::new();

impl Modifier {
    /// The empty Modifier. The same as the value `Modifier`.
    pub const fn new() -> Self {
        Self {
            observe_size: None,
            motion: None,
            material: None,
            weight: None,
            width: None,
            height: None,
            padding: None,
            padding_role: None,
            background: None,
            shape_role: None,
            corner_radius: None,
            border_width: None,
            border_color: None,
            elevation: None,
            alpha: None,
            transform: None,
            animated_alpha: None,
            animated_background: None,
            animated_offset: None,
            cursor: None,
            user_select: None,
            fill_max_width: false,
            fill_max_height: false,
        }
    }

    /// A share of the space left in a `Row` or `Column`.
    pub const fn weight(mut self, weight: f32) -> Self {
        self.weight = Some(weight);
        self
    }

    pub const fn width(mut self, dp: f32) -> Self {
        self.width = Some(dp);
        self
    }

    pub const fn height(mut self, dp: f32) -> Self {
        self.height = Some(dp);
        self
    }

    /// Both at once.
    pub const fn size(self, width: f32, height: f32) -> Self {
        self.width(width).height(height)
    }

    /// A width that may be unset, for a screen whose measure depends on the window.
    pub const fn width_if(mut self, dp: Option<f32>) -> Self {
        self.width = dp;
        self
    }

    pub const fn fill_max_width(mut self) -> Self {
        self.fill_max_width = true;
        self
    }

    pub const fn fill_max_height(mut self) -> Self {
        self.fill_max_height = true;
        self
    }

    pub const fn fill_max_size(self) -> Self {
        self.fill_max_width().fill_max_height()
    }

    /// Fills the width only when `fill` is true.
    pub const fn fill_max_width_if(mut self, fill: bool) -> Self {
        self.fill_max_width = fill;
        self
    }

    /// The same inset on every side, in dp.
    pub const fn padding(mut self, dp: f32) -> Self {
        self.padding = Some(dp);
        self
    }

    /// An inset from the design system's spacing ladder. Wins over `padding`.
    pub const fn padding_role(mut self, role: SpaceRole) -> Self {
        self.padding_role = Some(role);
        self
    }

    /// The same, when the inset may be unset.
    pub const fn padding_role_if(mut self, role: Option<SpaceRole>) -> Self {
        self.padding_role = role;
        self
    }

    pub const fn background(mut self, paint: Paint) -> Self {
        self.background = Some(paint);
        self
    }

    /// The same, when there may be no background.
    pub const fn background_if(mut self, paint: Option<Paint>) -> Self {
        self.background = paint;
        self
    }

    /// A shape from the design system's ladder.
    pub const fn shape_role(mut self, role: ShapeRole) -> Self {
        self.shape_role = Some(role);
        self
    }

    /// A literal corner, in dp. Wins over `shape_role`.
    pub const fn corner_radius(mut self, dp: f32) -> Self {
        self.corner_radius = Some(dp);
        self
    }

    pub const fn border(mut self, width: f32, paint: Paint) -> Self {
        self.border_width = Some(width);
        self.border_color = Some(paint);
        self
    }

    /// A resting height above the default, in dp. How it is drawn is the design system's.
    pub const fn elevation(mut self, dp: f32) -> Self {
        self.elevation = Some(dp);
        self
    }

    /// Asks the Renderer to report this node's size under the token from
    /// [`crate::runtime::remember_node_size`].
    pub const fn observe_size(mut self, token: i64) -> Self {
        self.observe_size = Some(token);
        self
    }

    /// How important this node's changes are. The curve is the design system's.
    pub const fn motion(mut self, role: MotionRole) -> Self {
        self.motion = Some(role);
        self
    }

    /// What this node's surface is made of. The effect is the design system's.
    pub const fn material(mut self, role: MaterialRole) -> Self {
        self.material = Some(role);
        self
    }

    /// An opacity for the node and everything in it, faded as one group.
    pub const fn alpha(mut self, alpha: f32) -> Self {
        self.alpha = Some(alpha);
        self
    }

    /// Compose's `graphicsLayer`: a rotation, a scale and a translation about an origin,
    /// drawn without moving the layout, and an opacity for the whole group. A pointer is
    /// tested against the shape that is drawn.
    pub fn graphics_layer(mut self, layer: crate::GraphicsLayer) -> Self {
        if let crate::schema::Modifier::Transform {
            a,
            b,
            c,
            d,
            e,
            f,
            origin_x,
            origin_y,
        } = layer.transform()
        {
            self.transform = Some([a, b, c, d, e, f, origin_x, origin_y]);
        }
        self.alpha = Some(layer.alpha);
        self
    }

    /// An opacity the Renderer animates to, from [`crate::animate_float_as_state`]. It
    /// takes the place of `alpha`.
    pub const fn animated_alpha(mut self, value: crate::Animated<f32>) -> Self {
        self.animated_alpha = Some(value);
        self
    }

    /// A background the Renderer animates to, from [`crate::animate_color_as_state`]. It
    /// takes the place of `background`.
    pub const fn animated_background(mut self, value: crate::Animated<Paint>) -> Self {
        self.animated_background = Some(value);
        self
    }

    /// A translation the Renderer animates to, from [`crate::animate_offset_as_state`].
    /// It takes the place of the transform a `graphics_layer` would draw.
    pub const fn animated_offset(mut self, value: crate::Animated<(f32, f32)>) -> Self {
        self.animated_offset = Some(value);
        self
    }

    /// The cursor the platform shows over the node. CSS `cursor`: the deepest node under
    /// the pointer that names one other than `Cursor::Auto` wins, and while a node holds a
    /// pointer capture its cursor stays.
    pub const fn cursor(mut self, cursor: crate::Cursor) -> Self {
        self.cursor = Some(cursor);
        self
    }

    /// Whether the text under the node can be selected. CSS `user-select`; `Auto` follows
    /// the parent.
    pub const fn user_select(mut self, user_select: crate::UserSelect) -> Self {
        self.user_select = Some(user_select);
        self
    }
}

/// Which Modifier attributes a widget's `rsx!` counterpart always writes. The others are
/// written only when they are set.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mods {
    /// The containers that take every Modifier: Column, Row, Box, Card, Surface.
    Container,
    /// The thirteen every other widget takes.
    Standard,
    /// A chip's six.
    Chip,
    /// A Scaffold's background and material.
    Scaffold,
    /// None.
    None,
}

pub(crate) type Attrs = Vec<(&'static str, OwnedAttr)>;

fn float(value: Option<f32>) -> OwnedAttr {
    value.map_or(OwnedAttr::None, |value| OwnedAttr::Float(f64::from(value)))
}

fn role(value: Option<impl Into<u16>>) -> OwnedAttr {
    value.map_or(OwnedAttr::None, |value| {
        OwnedAttr::Int(i64::from(value.into()))
    })
}

fn paint(value: Option<Paint>) -> OwnedAttr {
    value.map_or(OwnedAttr::None, |paint| {
        OwnedAttr::Int(paint.to_bits() as i64)
    })
}

/// A role that was not set is tag 0, which means "not sent".
pub(crate) fn role_or_zero(value: Option<impl Into<u16>>) -> OwnedAttr {
    OwnedAttr::Int(value.map_or(0, |value| i64::from(value.into())))
}

/// A dp value that was not set is 0.
pub(crate) fn dp_or_zero(value: Option<f32>) -> OwnedAttr {
    OwnedAttr::Float(f64::from(value.unwrap_or(0.0)))
}

/// A paint that was not set is 0.
pub(crate) fn paint_or_zero(value: Option<Paint>) -> OwnedAttr {
    OwnedAttr::Int(value.map_or(0, |paint| paint.to_bits() as i64))
}

pub(crate) fn optional_text(value: Option<String>) -> OwnedAttr {
    value.map_or(OwnedAttr::None, OwnedAttr::Text)
}

/// Writes the Modifier attributes, in the order the `rsx!` widgets write them.
pub(crate) fn push_modifiers(modifier: &Modifier, mods: Mods, out: &mut Attrs) {
    let container = mods == Mods::Container;
    let standard = container || mods == Mods::Standard;
    let chip = standard || mods == Mods::Chip;
    let scaffold = mods == Mods::Scaffold;
    let mut push = |always: bool, name: &'static str, value: OwnedAttr| {
        let set = !matches!(value, OwnedAttr::None | OwnedAttr::Bool(false));
        if always || set {
            out.push((name, value));
        }
    };
    push(
        container,
        "observe_size",
        modifier
            .observe_size
            .map_or(OwnedAttr::None, OwnedAttr::Int),
    );
    push(container, "motion", role(modifier.motion));
    push(container || scaffold, "material", role(modifier.material));
    push(chip, "weight", float(modifier.weight));
    push(chip, "width", float(modifier.width));
    push(chip, "height", float(modifier.height));
    push(chip, "padding", float(modifier.padding));
    push(chip, "padding_role", role(modifier.padding_role));
    // An animated background owns the background's slot while it is set.
    push(
        standard || scaffold,
        "background",
        paint(if modifier.animated_background.is_some() {
            None
        } else {
            modifier.background
        }),
    );
    push(standard, "shape_role", role(modifier.shape_role));
    push(standard, "corner_radius", float(modifier.corner_radius));
    push(standard, "border_width", float(modifier.border_width));
    push(standard, "border_color", paint(modifier.border_color));
    push(standard, "elevation", float(modifier.elevation));
    push(
        chip,
        "fill_max_width",
        OwnedAttr::Bool(modifier.fill_max_width),
    );
    push(
        standard,
        "fill_max_height",
        OwnedAttr::Bool(modifier.fill_max_height),
    );
    // The layer and the values the Renderer animates, written only when they are set. An
    // animated value owns its slot while it is set, as an animated background does above.
    push(
        false,
        "alpha",
        float(if modifier.animated_alpha.is_some() {
            None
        } else {
            modifier.alpha
        }),
    );
    push(
        false,
        "transform",
        match (modifier.animated_offset, modifier.transform) {
            (None, Some(values)) => OwnedAttr::Bytes(
                values
                    .iter()
                    .flat_map(|value| value.to_le_bytes())
                    .collect(),
            ),
            _ => OwnedAttr::None,
        },
    );
    // Written only when set, and `Auto` is the same as not set.
    push(
        false,
        "cursor",
        match modifier.cursor {
            Some(crate::Cursor::Auto) | None => OwnedAttr::None,
            Some(cursor) => OwnedAttr::Int(i64::from(u16::from(cursor))),
        },
    );
    push(
        false,
        "user_select",
        match modifier.user_select {
            Some(crate::UserSelect::Auto) | None => OwnedAttr::None,
            Some(select) => OwnedAttr::Int(i64::from(u16::from(select))),
        },
    );
    push(
        false,
        "animated_alpha",
        modifier.animated_alpha.map_or(OwnedAttr::None, |value| {
            OwnedAttr::Bytes(crate::animation::animated_bytes(
                &[value.target.to_bits()],
                &value.spec,
            ))
        }),
    );
    push(
        false,
        "animated_background",
        modifier
            .animated_background
            .map_or(OwnedAttr::None, |value| {
                let bits = value.target.to_bits();
                OwnedAttr::Bytes(crate::animation::animated_bytes(
                    &[bits as u32, (bits >> 32) as u32],
                    &value.spec,
                ))
            }),
    );
    push(
        false,
        "animated_offset",
        modifier.animated_offset.map_or(OwnedAttr::None, |value| {
            OwnedAttr::Bytes(crate::animation::animated_bytes(
                &[value.target.0.to_bits(), value.target.1.to_bits()],
                &value.spec,
            ))
        }),
    );
}

/// Composes one widget node: its group, its attributes and listeners, and its children.
///
/// `fill` writes the attributes and runs while the composer is held, so it only moves
/// values out of the builder. `content` runs afterwards, with the node as the parent of
/// whatever it composes.
pub(crate) fn emit(
    key: u64,
    widget: WidgetKind,
    fill: impl FnOnce(&mut Attrs),
    listeners: Vec<(&'static str, EventCallback)>,
    content: impl FnOnce(),
) {
    let _group = group_guard(key);
    emit_node(widget, fill, listeners, content);
}

/// The same, inside a group the caller has already opened, for a widget that remembers
/// something of its own before its node.
pub(crate) fn emit_node(
    widget: WidgetKind,
    fill: impl FnOnce(&mut Attrs),
    listeners: Vec<(&'static str, EventCallback)>,
    content: impl FnOnce(),
) {
    let node = with_composer_if_idle(|composer| {
        if !composer.composing() {
            return None;
        }
        let mut attrs = composer.take_attrs();
        fill(&mut attrs);
        Some(composer.update_node(widget, attrs, listeners))
    })
    .flatten();
    let Some(node) = node else {
        return;
    };
    with_composer(|composer| composer.push_node_context(node));
    let _context = NodeContextGuard;
    content();
}

/// Closes a widget's node context on every way out of its content, an unwind included.
struct NodeContextGuard;

impl Drop for NodeContextGuard {
    fn drop(&mut self) {
        with_composer_if_idle(|composer| composer.pop_node_context());
    }
}

/// A call site key for a widget, from its name.
pub(crate) const fn widget_key(name: &str) -> u64 {
    crate::runtime::composer::call_site(name, 0)
}