basic/
basic.rs

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
use compose_rt::{Composer, Root};
use compose_taffy::{LayoutNode, LayoutTree, TaffyConfig};
use taffy::{AvailableSpace, Dimension, JustifyContent, Size, Style};

type Scope<T> = compose_taffy::Scope<T, ()>;

struct Container;

#[track_caller]
fn container<P, C>(s: Scope<P>, style: Style, content: C)
where
    P: 'static,
    C: Fn(Scope<Container>) + Clone + 'static,
{
    let scope = s.child::<Container>();
    s.create_node(
        scope,
        content,
        move |_| style.clone(),
        |style, _| LayoutNode::new(style),
        |n, style, _| {
            if n.style != style {
                n.style = style;
            }
        },
    );
}

struct Leaf;
#[track_caller]
fn leaf<P>(s: Scope<P>, style: Style)
where
    P: 'static,
{
    let scope = s.child::<Leaf>();
    s.create_node(
        scope,
        |_| {},
        move |_| style.clone(),
        |style, _| LayoutNode::new(style),
        |n, style, _| {
            if n.style != style {
                n.style = style;
                n.mark_dirty();
            }
        },
    );
}

fn app(s: Scope<Root>) {
    container(
        s,
        Style {
            size: Size {
                width: Dimension::Length(100.0),
                height: Dimension::Length(100.0),
            },
            justify_content: Some(JustifyContent::Center),
            ..Default::default()
        },
        |s| {
            leaf(
                s,
                Style {
                    size: Size {
                        width: Dimension::Percent(0.5),
                        height: Dimension::Auto,
                    },
                    ..Default::default()
                },
            );
        },
    );
}

fn main() {
    let mut recomposer = Composer::compose(app, TaffyConfig::default());
    let _ = recomposer.compute_layout(Size {
        height: AvailableSpace::Definite(100.0),
        width: AvailableSpace::Definite(100.0),
    });
    let _ = recomposer.print_layout_tree();
}