cranpose-ui 0.9.10

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
//! A layout pass keeps a node's measurement when only nodes below it changed
//! and every changed child measures the same for it. These tests change a
//! screen frame by frame and check each incremental layout against a fresh
//! composition of the same state.

use cranpose_core::{Composition, MemoryApplier, MutableState, NodeId, location_key};
use cranpose_foundation::lazy::LazyListScope;
use cranpose_macros::composable;
use cranpose_ui_layout::{
    Constraints, IntrinsicSize, Measurable, MeasurePolicy, MeasureResult, MeasureScope, Placement,
};

use crate::{
    Alignment, Box, BoxSpec, Column, ColumnSpec, Layout, LazyColumn, LazyColumnSpec,
    LinearArrangement, Modifier, Row, RowSpec, Size, Text, TextStyle,
    layout::{MeasureLayoutOptions, build_layout_tree_from_applier},
    measure_layout_with_options, rememberLazyListState,
    widgets::BoxWithConstraints,
};

#[composable]
fn KeptScreen(tick: MutableState<usize>) {
    BoxWithConstraints(Modifier::empty().fill_max_size(), move |_scope| {
        Column(
            Modifier::empty().fill_max_width(),
            ColumnSpec::default(),
            move || {
                WeightRow(tick);
                AlignedBox(tick);
                IntrinsicColumn(tick);
                for row in 0..5 {
                    KeptRow(tick, row);
                }
                let list = rememberLazyListState();
                LazyColumn(
                    Modifier::empty().fill_max_width().height(120.0),
                    list,
                    LazyColumnSpec::default(),
                    move |scope| {
                        scope.items(20, move |item| KeptRow(tick, item + 10));
                    },
                );
            },
        );
    });
}

/// A screen whose lazy list measures at the same constraints every frame,
/// so it keeps its measurement while its items change, and whose last
/// layout reads intrinsic sizes on some frames only.
#[composable]
fn KeptListScreen(tick: MutableState<usize>) {
    Column(
        Modifier::empty().fill_max_width(),
        ColumnSpec::default(),
        move || {
            let list = rememberLazyListState();
            LazyColumn(
                Modifier::empty().fill_max_width().height(160.0),
                list,
                LazyColumnSpec::default(),
                move |scope| {
                    scope.item(move || GrowingItem(tick));
                    scope.item(move || AlignedBox(tick));
                    scope.item(move || SplitItem(tick));
                    scope.items(20, move |item| SameSizeRow(tick, item));
                },
            );
            IntrinsicReaderLayout(tick);
        },
    );
}

/// A row whose texts keep their width on most frames and change it on
/// others, whose weighted box changes its weight, and whose last text
/// changes its padding.
#[composable]
fn KeptRow(tick: MutableState<usize>, row: usize) {
    let value = tick.get() + row;
    let label = if value.is_multiple_of(4) {
        format!("{:>4}!", value % 1000)
    } else {
        format!("{:>4}", value % 1000)
    };
    let weight = if value.is_multiple_of(7) { 2.0 } else { 1.0 };
    let height = 4.0 + (value % 3) as f32;
    let padding = (value % 2) as f32;
    Row(
        Modifier::empty().fill_max_width().padding(2.0),
        RowSpec::default(),
        move || {
            Text(label.clone(), Modifier::empty(), TextStyle::default());
            Box(
                Modifier::empty().weight(weight).height(height),
                BoxSpec::default(),
                || {},
            );
            Text(
                format!("{}", value % 10),
                Modifier::empty().padding(padding),
                TextStyle::default(),
            );
        },
    );
}

/// A row whose only change is the weight of its first box: the boxes keep
/// their sizes at the constraints they had, so only their parent data says
/// the row has to share its width again.
#[composable]
fn WeightRow(tick: MutableState<usize>) {
    let weight = if tick.get().is_multiple_of(2) {
        1.0
    } else {
        3.0
    };
    Row(
        Modifier::empty().fill_max_width(),
        RowSpec::default(),
        move || {
            Box(
                Modifier::empty().weight(weight).height(6.0),
                BoxSpec::default(),
                || {},
            );
            Box(
                Modifier::empty().weight(1.0).height(6.0),
                BoxSpec::default(),
                || {},
            );
        },
    );
}

/// A box whose only change is its child's alignment, on even frames: the
/// child keeps its size and moves.
#[composable]
fn AlignedBox(tick: MutableState<usize>) {
    let alignment = if (tick.get() / 2).is_multiple_of(2) {
        Alignment::TOP_START
    } else {
        Alignment::TOP_END
    };
    Box(
        Modifier::empty().fill_max_width().height(10.0),
        BoxSpec::default(),
        move || {
            Box(
                Modifier::empty().align(alignment).width(4.0).height(4.0),
                BoxSpec::default(),
                || {},
            );
        },
    );
}

/// A column as wide as its widest child's intrinsic width, whose filling
/// child keeps its size while the text inside it changes that width.
#[composable]
fn IntrinsicColumn(tick: MutableState<usize>) {
    let label = if tick.get().is_multiple_of(2) {
        "ab"
    } else {
        "abcdef"
    };
    Column(
        Modifier::empty().width_intrinsic(IntrinsicSize::Max),
        ColumnSpec::default(),
        move || {
            Box(
                Modifier::empty().fill_max_width(),
                BoxSpec::default(),
                move || {
                    Text(label, Modifier::empty(), TextStyle::default());
                },
            );
            Box(
                Modifier::empty().fill_max_width().height(2.0),
                BoxSpec::default(),
                || {},
            );
        },
    );
}

/// Measures its one child at a width of 30, and takes the child's intrinsic
/// width as its own when `read` is set.
#[derive(Clone, PartialEq)]
struct IntrinsicReader {
    read: bool,
}

impl MeasurePolicy for IntrinsicReader {
    fn measure(
        &self,
        _scope: &dyn MeasureScope,
        measurables: &[std::boxed::Box<dyn Measurable>],
        _constraints: Constraints,
    ) -> MeasureResult {
        let Some(child) = measurables.first() else {
            return MeasureResult::new(Size::new(0.0, 0.0), Vec::new());
        };
        let width = if self.read {
            child.max_intrinsic_width(f32::INFINITY)
        } else {
            30.0
        };
        let placeable = child.measure(Constraints {
            min_width: 30.0,
            max_width: 30.0,
            min_height: 0.0,
            max_height: f32::INFINITY,
        });
        MeasureResult::new(
            Size::new(width, placeable.height()),
            vec![Placement::new(placeable.node_id(), 0.0, 0.0, 0)],
        )
    }

    fn min_intrinsic_width(&self, _: &[std::boxed::Box<dyn Measurable>], _: f32) -> f32 {
        30.0
    }

    fn max_intrinsic_width(&self, _: &[std::boxed::Box<dyn Measurable>], _: f32) -> f32 {
        30.0
    }

    fn min_intrinsic_height(&self, _: &[std::boxed::Box<dyn Measurable>], _: f32) -> f32 {
        0.0
    }

    fn max_intrinsic_height(&self, _: &[std::boxed::Box<dyn Measurable>], _: f32) -> f32 {
        0.0
    }
}

/// A layout that reads its child's intrinsic width on even frames only,
/// while the box inside that child changes its width on odd frames. The
/// child measures the same at the width it is given, so it keeps its
/// measurement while its intrinsic width changes.
#[composable]
fn IntrinsicReaderLayout(tick: MutableState<usize>) {
    let frame = tick.get();
    let width = if frame.div_ceil(2).is_multiple_of(2) {
        50.0
    } else {
        80.0
    };
    Layout(
        Modifier::empty(),
        IntrinsicReader {
            read: frame.is_multiple_of(2),
        },
        move || WidthBox(width),
    );
}

/// A filling box around a box of `width`, which skips its body while the
/// width stays.
#[composable]
fn WidthBox(width: f32) {
    Box(
        Modifier::empty().fill_max_width().height(10.0),
        BoxSpec::default(),
        move || {
            Box(Modifier::empty().width(width), BoxSpec::default(), || {});
        },
    );
}

/// A lazy item whose height changes on odd frames.
#[composable]
fn GrowingItem(tick: MutableState<usize>) {
    let height = if tick.get().div_ceil(2).is_multiple_of(2) {
        4.0
    } else {
        10.0
    };
    Column(
        Modifier::empty().fill_max_width(),
        ColumnSpec::default(),
        move || {
            Box(
                Modifier::empty().fill_max_width().height(height),
                BoxSpec::default(),
                || {},
            );
        },
    );
}

/// A lazy item that emits a second root node on some frames.
#[composable]
fn SplitItem(tick: MutableState<usize>) {
    Text("split", Modifier::empty(), TextStyle::default());
    if tick.get().is_multiple_of(6) {
        Text("extra", Modifier::empty(), TextStyle::default());
    }
}

/// A row whose text changes every frame and keeps its width.
#[composable]
fn SameSizeRow(tick: MutableState<usize>, row: usize) {
    let label = format!("{:>4}", (tick.get() + row) % 1000);
    Row(
        Modifier::empty().fill_max_width().padding(2.0),
        RowSpec::default(),
        move || {
            Text(label.clone(), Modifier::empty(), TextStyle::default());
        },
    );
}

/// Leaves inside a parent whose width moves every frame: a text that wraps
/// at some widths, a fixed box, a padded text and an offset box. Each keeps
/// its measurement while the width it gets leaves it unchanged, and
/// measures again where the text wraps differently.
#[composable]
fn ResizedLeavesScreen(tick: MutableState<usize>) {
    let width = 40.0 + (tick.get() % 13) as f32 * 23.0;
    Column(
        Modifier::empty().width(width),
        ColumnSpec::default(),
        move || {
            Text(
                "a few words that wrap at narrow widths",
                Modifier::empty(),
                TextStyle::default(),
            );
            Box(
                Modifier::empty().size_points(30.0, 12.0),
                BoxSpec::default(),
                || {},
            );
            Text(
                "padded",
                Modifier::empty().padding(3.0),
                TextStyle::default(),
            );
            Row(
                Modifier::empty().fill_max_width(),
                RowSpec::default(),
                || {
                    Box(
                        Modifier::empty().offset(4.0, 2.0).size_points(8.0, 8.0),
                        BoxSpec::default(),
                        || {},
                    );
                    Text("tail", Modifier::empty(), TextStyle::default());
                },
            );
            // Containers that size to their children: a spaced row that
            // runs out of room at the narrowest widths, a box around two
            // children, and a bar filling the height of a fixed row.
            Row(
                Modifier::empty(),
                RowSpec::new().horizontal_arrangement(LinearArrangement::spaced_by(6.0)),
                || {
                    for label in ["one", "two", "three"] {
                        Text(label, Modifier::empty().padding(2.0), TextStyle::default());
                    }
                    Box(
                        Modifier::empty().size_points(20.0, 6.0),
                        BoxSpec::default(),
                        || {},
                    );
                },
            );
            Box(Modifier::empty(), BoxSpec::default(), || {
                Text("boxed", Modifier::empty(), TextStyle::default());
                Box(
                    Modifier::empty().size_points(14.0, 30.0),
                    BoxSpec::default(),
                    || {},
                );
            });
            Row(Modifier::empty().height(18.0), RowSpec::default(), || {
                Box(
                    Modifier::empty().width(3.0).fill_max_height(),
                    BoxSpec::default(),
                    || {},
                );
                Text("beside", Modifier::empty(), TextStyle::default());
            });
        },
    );
}

/// Every node's rect and content offset bits, in tree order.
fn layout(composition: &mut Composition<MemoryApplier>, root: NodeId) -> Vec<[u32; 6]> {
    fn flatten(node: &crate::LayoutBox, out: &mut Vec<[u32; 6]>) {
        out.push([
            node.rect.x.to_bits(),
            node.rect.y.to_bits(),
            node.rect.width.to_bits(),
            node.rect.height.to_bits(),
            node.content_offset.x.to_bits(),
            node.content_offset.y.to_bits(),
        ]);
        for child in &node.children {
            flatten(child, out);
        }
    }

    let handle = composition.runtime_handle();
    let mut applier = composition.applier_mut();
    applier.set_runtime_handle(handle);
    measure_layout_with_options(
        &mut applier,
        root,
        Size::new(400.0, 800.0),
        MeasureLayoutOptions {
            collect_semantics: false,
            build_layout_tree: false,
        },
    )
    .expect("layout pass");
    let tree = build_layout_tree_from_applier(&mut applier, root)
        .expect("live layout tree")
        .expect("composition has a root");
    applier.clear_runtime_handle();
    let mut nodes = Vec::new();
    flatten(tree.root(), &mut nodes);
    nodes
}

/// Composes `screen` at `frame` and returns the composition and its root.
fn compose(
    screen: fn(MutableState<usize>),
    frame: usize,
) -> (Composition<MemoryApplier>, MutableState<usize>, NodeId) {
    let mut composition = Composition::new(MemoryApplier::new());
    let tick = MutableState::with_runtime(frame, composition.runtime_handle());
    composition
        .render(location_key(file!(), line!(), column!()), move || {
            screen(tick);
        })
        .expect("composition");
    let root = composition.root().expect("composition root");
    (composition, tick, root)
}

/// Changes `screen` frame by frame and checks each incremental layout
/// against a fresh composition of the same frame.
fn assert_incremental_layout_matches_fresh_compositions(screen: fn(MutableState<usize>)) {
    let _app_context = crate::render_state::app_context_test_scope();
    let (mut composition, tick, root) = compose(screen, 0);
    layout(&mut composition, root);

    for frame in 1..=48 {
        tick.set(frame);
        while composition.process_invalid_scopes().expect("recomposition") {}
        let incremental = layout(&mut composition, root);
        let (mut fresh, _, fresh_root) = compose(screen, frame);
        assert_eq!(
            incremental,
            layout(&mut fresh, fresh_root),
            "frame {frame}: the incremental layout differs from a fresh composition"
        );
    }
}

#[test]
fn incremental_layout_matches_a_fresh_composition() {
    assert_incremental_layout_matches_fresh_compositions(KeptScreen);
}

#[test]
fn incremental_lazy_list_layout_matches_a_fresh_composition() {
    assert_incremental_layout_matches_fresh_compositions(KeptListScreen);
}

#[test]
fn leaves_in_a_resized_parent_match_a_fresh_composition() {
    assert_incremental_layout_matches_fresh_compositions(ResizedLeavesScreen);
}