compose-rust 0.0.0

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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! The tree the Host describes has to be a tree.
//!
//! Every Insert and Move names a parent, and a renderer that keeps that parent for each
//! node walks up from a node to find its root. A chain that loops has no root, so the walk
//! never ends.

use compose_rust::prelude::*;
use compose_rust::protocol::{HostEvent, Mutation, PropertyValue, decode_batch, encode_event};
use compose_rust::{EventPayload, Host, PropertyKind, WidgetKind};
use std::collections::HashMap;

/// A screen with two branches, both of which place the same held `Element`.
///
/// Holding an `Element` in a variable and using it in more than one branch is the shape
/// that produced a looping parent chain: the same node is mounted, unmounted and mounted
/// again as the branches swap.
fn branching_app() -> Element {
    let mut expanded = use_signal(|| false);
    let held = rsx! { Text { text: "held" } };
    rsx! {
        Column {
            Button {
                text: "toggle",
                on_click: move |_| {
                    let now = expanded();
                    expanded.set(!now);
                },
            }
            if expanded() {
                Column {
                    {held.clone()}
                    Text { text: "only while expanded" }
                }
            } else {
                Row {
                    Text { text: "only while collapsed" }
                    {held.clone()}
                }
            }
        }
    }
}

/// The same held `Element` placed in two branches that can both be on screen at once,
/// with a sibling that comes and goes between them.
fn doubled_app() -> Element {
    let mut step = use_signal(|| 0_usize);
    let held = rsx! {
        Column {
            Text { text: "held" }
            Text { text: "held tail" }
        }
    };
    let phase = step() % 3;
    rsx! {
        Column {
            Button {
                text: "step",
                on_click: move |_| {
                    let now = step();
                    step.set(now + 1);
                },
            }
            if phase == 0 {
                Row { {held.clone()} }
            }
            if phase != 1 {
                Text { text: "between" }
            }
            Column {
                {held.clone()}
                if phase == 2 {
                    Row {
                        Text { text: "tail" }
                        {held.clone()}
                    }
                }
            }
        }
    }
}

/// The parent of each node, as a renderer that trusts every Insert and Move would hold it.
fn follow(batch: &[u8], parents: &mut HashMap<u32, u32>) {
    for mutation in decode_batch(batch).unwrap() {
        match mutation {
            Mutation::Insert {
                parent_id, node_id, ..
            }
            | Mutation::Move {
                parent_id, node_id, ..
            } => {
                if node_id != 0 {
                    parents.insert(node_id, parent_id);
                }
            }
            Mutation::Remove { node_id } => {
                parents.remove(&node_id);
            }
            _ => {}
        }
    }
}

/// The chain from `node` up to its root, or the node the walk met twice.
fn loops_from(parents: &HashMap<u32, u32>, node: u32) -> Option<Vec<u32>> {
    let mut chain = vec![node];
    let mut current = node;
    for _ in 0..parents.len() + 1 {
        let Some(&parent) = parents.get(&current) else {
            return None;
        };
        if chain.contains(&parent) {
            chain.push(parent);
            return Some(chain);
        }
        chain.push(parent);
        current = parent;
    }
    Some(chain)
}

/// Clicks the one button `rounds` times, following every parent the Host names and
/// failing the moment a chain loops.
fn toggle_and_follow(app: fn() -> Element, rounds: usize) {
    let mut host = Host::new(app);
    let mut parents = HashMap::new();
    let batch = host.rebuild().unwrap().to_vec();
    follow(&batch, &mut parents);

    let records = decode_batch(&batch).unwrap();
    let button = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::Create {
                node_id,
                widget: WidgetKind::Button,
            } => Some(*node_id),
            _ => None,
        })
        .expect("the screen has a button");
    let handler = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::SetProp {
                node_id,
                property: PropertyKind::OnClick,
                value: PropertyValue::Integer(id),
            } if *node_id == button => Some(*id as u64),
            _ => None,
        })
        .expect("the button reports its clicks");

    for round in 0..rounds {
        let mut wire = Vec::new();
        encode_event(
            &HostEvent {
                node_id: button,
                handler_id: handler,
                payload: EventPayload::Clicked,
            },
            &mut wire,
        )
        .unwrap();
        let (batch, _) = host.dispatch_event(&wire).unwrap();
        follow(&batch.to_vec(), &mut parents);

        let nodes: Vec<u32> = parents.keys().copied().collect();
        for node in nodes {
            assert!(
                loops_from(&parents, node).is_none(),
                "round {round}: the parent chain from {node} loops: {:?}",
                loops_from(&parents, node),
            );
        }
    }
}

#[test]
fn nfr7_swapping_branches_never_loops_the_parent_chain() {
    toggle_and_follow(branching_app, 6);
}

#[test]
fn nfr7_mounting_a_held_element_twice_never_loops_the_parent_chain() {
    toggle_and_follow(doubled_app, 9);
}

/// Two branches that are both empty at first, in two different parents.
///
/// An empty branch is a Dioxus placeholder, and a placeholder is not a node in the Compose
/// tree. Two of them on screen at once still stand in two different places, and when they
/// fill in, each one's content belongs to its own parent.
fn two_placeholders_app() -> Element {
    let mut show = use_signal(|| false);
    rsx! {
        Column {
            Button {
                text: "toggle",
                on_click: move |_| {
                    let now = show();
                    show.set(!now);
                },
            }
            Row {
                Text { text: "row head" }
                if show() {
                    Text { text: "inside the row" }
                }
            }
            Card {
                Text { text: "card head" }
                if show() {
                    Text { text: "inside the card" }
                }
            }
        }
    }
}

/// The node the given text was set on.
fn node_with_text(batch: &[Mutation<'_>], text: &str) -> Option<u32> {
    batch.iter().find_map(|mutation| match mutation {
        Mutation::SetProp {
            node_id,
            property: PropertyKind::Text,
            value: PropertyValue::String(value),
        } if *value == text => Some(*node_id),
        _ => None,
    })
}

/// The parent the given node was last attached to.
fn parent_of(batch: &[Mutation<'_>], node: u32) -> Option<u32> {
    batch.iter().rev().find_map(|mutation| match mutation {
        Mutation::Insert {
            parent_id, node_id, ..
        }
        | Mutation::Move {
            parent_id, node_id, ..
        } if *node_id == node => Some(*parent_id),
        _ => None,
    })
}

#[test]
fn fr1_an_empty_branch_fills_in_under_its_own_parent() {
    let mut host = Host::new(two_placeholders_app);
    let first = host.rebuild().unwrap().to_vec();
    let records = decode_batch(&first).unwrap();
    let row = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::Create {
                node_id,
                widget: WidgetKind::Row,
            } => Some(*node_id),
            _ => None,
        })
        .expect("the screen has a row");
    let card = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::Create {
                node_id,
                widget: WidgetKind::Card,
            } => Some(*node_id),
            _ => None,
        })
        .expect("the screen has a card");
    let button = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::Create {
                node_id,
                widget: WidgetKind::Button,
            } => Some(*node_id),
            _ => None,
        })
        .expect("the screen has a button");
    let handler = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::SetProp {
                node_id,
                property: PropertyKind::OnClick,
                value: PropertyValue::Integer(id),
            } if *node_id == button => Some(*id as u64),
            _ => None,
        })
        .expect("the button reports its clicks");

    let mut wire = Vec::new();
    encode_event(
        &HostEvent {
            node_id: button,
            handler_id: handler,
            payload: EventPayload::Clicked,
        },
        &mut wire,
    )
    .unwrap();
    let second = host.dispatch_event(&wire).unwrap().0.to_vec();
    let filled = decode_batch(&second).unwrap();

    let in_row = node_with_text(&filled, "inside the row").expect("the row's branch filled in");
    let in_card = node_with_text(&filled, "inside the card").expect("the card's branch filled in");
    assert_eq!(
        Some(row),
        parent_of(&filled, in_row),
        "the row's branch was attached somewhere else",
    );
    assert_eq!(
        Some(card),
        parent_of(&filled, in_card),
        "the card's branch was attached somewhere else",
    );
}

/// A Menu whose children are a branch that is not taken, inside a list item.
///
/// The empty branch and the loop over nothing both leave a placeholder, and the list
/// materialises its window on demand, so the same positions are filled in and emptied
/// again as the window moves.
fn menu_in_a_list_app() -> Element {
    rsx! {
        LazyColumn {
            item_count: 20,
            item: move |index: usize| rsx! {
                Row {
                    Text { text: "row {index}" }
                    if index == usize::MAX {
                        Text { text: "never" }
                    }
                    Menu {
                        expanded: false,
                        anchor: rsx! { Button { text: "menu" } },
                        if index == usize::MAX {
                            Text { text: "never either" }
                        }
                        for entry in Vec::<usize>::new() {
                            Text { text: "{entry}" }
                        }
                    }
                }
            },
        }
    }
}

#[test]
fn nfr7_a_menu_of_empty_branches_in_a_list_item_never_loops_the_parent_chain() {
    let mut host = Host::new(menu_in_a_list_app);
    let mut parents = HashMap::new();
    let batch = host.rebuild().unwrap().to_vec();
    follow(&batch, &mut parents);

    let records = decode_batch(&batch).unwrap();
    let list = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::Create {
                node_id,
                widget: WidgetKind::LazyColumn,
            } => Some(*node_id),
            _ => None,
        })
        .expect("the screen has a list");
    let handler = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::SetProp {
                node_id,
                property: PropertyKind::OnRangeRequested,
                value: PropertyValue::Integer(id),
            } if *node_id == list => Some(*id as u64),
            _ => None,
        })
        .expect("the list asks for its range");

    // Three windows, each one replacing the last, which is what scrolling costs.
    for (round, start) in [0_u32, 6, 12].into_iter().enumerate() {
        let mut wire = Vec::new();
        encode_event(
            &HostEvent {
                node_id: list,
                handler_id: handler,
                payload: EventPayload::RangeRequested { start, count: 6 },
            },
            &mut wire,
        )
        .unwrap();
        let batch = host.dispatch_event(&wire).unwrap().0.to_vec();
        follow(&batch, &mut parents);

        let nodes: Vec<u32> = parents.keys().copied().collect();
        for node in nodes {
            assert!(
                loops_from(&parents, node).is_none(),
                "round {round}: the parent chain from {node} loops: {:?}",
                loops_from(&parents, node),
            );
        }
    }
}

/// A list whose items hold an empty Box.
///
/// A Box with no children still has a children slot, and an empty slot is a placeholder,
/// so a window of these items is a window of placeholders standing in different parents.
fn empty_box_in_a_list_app() -> Element {
    rsx! {
        LazyColumn {
            item_count: 20,
            item: move |index: usize| rsx! {
                Column {
                    compose_rust::Box {}
                    Text { text: "row {index}" }
                }
            },
        }
    }
}

#[test]
fn fr8_an_empty_box_in_a_list_item_keeps_the_item_under_its_own_parent() {
    let mut host = Host::new(empty_box_in_a_list_app);
    let mut parents = HashMap::new();
    let batch = host.rebuild().unwrap().to_vec();
    follow(&batch, &mut parents);

    let records = decode_batch(&batch).unwrap();
    let list = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::Create {
                node_id,
                widget: WidgetKind::LazyColumn,
            } => Some(*node_id),
            _ => None,
        })
        .expect("the screen has a list");
    let handler = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::SetProp {
                node_id,
                property: PropertyKind::OnRangeRequested,
                value: PropertyValue::Integer(id),
            } if *node_id == list => Some(*id as u64),
            _ => None,
        })
        .expect("the list asks for its range");

    let mut wire = Vec::new();
    encode_event(
        &HostEvent {
            node_id: list,
            handler_id: handler,
            payload: EventPayload::RangeRequested { start: 0, count: 4 },
        },
        &mut wire,
    )
    .unwrap();
    let batch = host.dispatch_event(&wire).unwrap().0.to_vec();
    follow(&batch, &mut parents);
    let window = decode_batch(&batch).unwrap();

    for index in 0..4 {
        let text = node_with_text(&window, &format!("row {index}"))
            .unwrap_or_else(|| panic!("item {index} was not materialised"));
        let column = parent_of(&window, text).expect("the item's text was attached");
        let wrapper = parent_of(&window, column).expect("the item's column was attached");
        assert_eq!(
            Some(list),
            parent_of(&window, wrapper),
            "item {index} was attached outside the list",
        );
    }
    let nodes: Vec<u32> = parents.keys().copied().collect();
    for node in nodes {
        assert!(
            loops_from(&parents, node).is_none(),
            "the parent chain from {node} loops: {:?}",
            loops_from(&parents, node),
        );
    }
}

/// A list of rows whose actions are entries declared only while the row's menu is open.
///
/// This is the shape a row of overflow actions wants: nothing is built for an action until
/// someone asks for it. It puts three conditionals in one item, one inside another. The
/// row chooses between editing and reading, the menu's entries are a branch of their own,
/// and the entries themselves are a loop, so an item carries three placeholders that fill
/// in and empty again while the list's window moves over them.
fn menu_of_lazy_entries_app() -> Element {
    let mut open = use_signal(|| None::<usize>);
    let mut editing = use_signal(|| None::<usize>);
    rsx! {
        LazyColumn {
            item_count: 40,
            item: move |index: usize| rsx! {
                Row {
                    if editing() == Some(index) {
                        TextField { placeholder: "title" }
                        Button {
                            text: "Save",
                            on_click: move |_| editing.set(None),
                        }
                    } else {
                        Text { text: "row {index}" }
                        Menu {
                            expanded: open() == Some(index),
                            on_dismiss: move |_| open.set(None),
                            anchor: rsx! {
                                Button {
                                    text: "actions",
                                    on_click: move |_| open.set(Some(index)),
                                }
                            },
                            if open() == Some(index) {
                                for entry in MENU_ENTRIES {
                                    Button {
                                        text: "{entry}",
                                        on_click: move |_| {
                                            open.set(None);
                                            if entry == MENU_ENTRIES[0] {
                                                editing.set(Some(index));
                                            }
                                        },
                                    }
                                }
                            }
                        }
                    }
                }
            },
        }
    }
}

/// What one row's menu offers, in the order the entries are declared.
const MENU_ENTRIES: [&str; 4] = ["Edit", "Move up", "Move down", "Delete"];

/// The handler the given node reports its clicks through.
fn click_handler(batch: &[Mutation<'_>], node: u32) -> Option<u64> {
    batch.iter().find_map(|mutation| match mutation {
        Mutation::SetProp {
            node_id,
            property: PropertyKind::OnClick,
            value: PropertyValue::Integer(id),
        } if *node_id == node => Some(*id as u64),
        _ => None,
    })
}

/// The one node a property with the given name was created for.
fn only_node_of(batch: &[Mutation<'_>], widget: WidgetKind) -> Option<u32> {
    batch.iter().find_map(|mutation| match mutation {
        Mutation::Create {
            node_id,
            widget: got,
        } if *got == widget => Some(*node_id),
        _ => None,
    })
}

/// The nodes the given text was set on, in the order they appear.
fn nodes_with_text(batch: &[Mutation<'_>], text: &str) -> Vec<u32> {
    batch
        .iter()
        .filter_map(|mutation| match mutation {
            Mutation::SetProp {
                node_id,
                property: PropertyKind::Text,
                value: PropertyValue::String(value),
            } if *value == text => Some(*node_id),
            _ => None,
        })
        .collect()
}

/// Sends one event and hands back what came out of it.
fn send(host: &mut Host, event: HostEvent<'_>) -> Vec<u8> {
    let mut wire = Vec::new();
    encode_event(&event, &mut wire).unwrap();
    host.dispatch_event(&wire).unwrap().0.to_vec()
}

/// Fails with the chain it found if any node's parents lead back to the node itself.
fn assert_no_loop(parents: &HashMap<u32, u32>, what: &str) {
    let nodes: Vec<u32> = parents.keys().copied().collect();
    for node in nodes {
        assert!(
            loops_from(parents, node).is_none(),
            "{what}: the parent chain from {node} loops: {:?}",
            loops_from(parents, node),
        );
    }
}

#[test]
fn nfr7_a_menu_whose_entries_arrive_only_when_open_never_loops_the_parent_chain() {
    let mut host = Host::new(menu_of_lazy_entries_app);
    let mut parents = HashMap::new();
    let first = host.rebuild().unwrap().to_vec();
    follow(&first, &mut parents);
    let records = decode_batch(&first).unwrap();
    let list = only_node_of(&records, WidgetKind::LazyColumn).expect("the screen has a list");
    let range = records
        .iter()
        .find_map(|mutation| match mutation {
            Mutation::SetProp {
                node_id,
                property: PropertyKind::OnRangeRequested,
                value: PropertyValue::Integer(id),
            } if *node_id == list => Some(*id as u64),
            _ => None,
        })
        .expect("the list asks for its range");

    // The window moves forward and back over the same items, so every item is built,
    // dropped and built again with its menu opened in between.
    for start in [0_u32, 4, 8, 4, 0] {
        let window = send(
            &mut host,
            HostEvent {
                node_id: list,
                handler_id: range,
                payload: EventPayload::RangeRequested { start, count: 6 },
            },
        );
        follow(&window, &mut parents);
        assert_no_loop(&parents, &format!("window at {start}"));
        let window = decode_batch(&window).unwrap();

        let anchors = nodes_with_text(&window, "actions");
        assert!(
            !anchors.is_empty(),
            "the window at {start} materialised no rows",
        );
        for anchor in anchors {
            let menu = parent_of(&window, anchor).expect("the anchor sits in its menu");
            let handler = click_handler(&window, anchor).expect("the anchor reports its clicks");
            let opened = send(
                &mut host,
                HostEvent {
                    node_id: anchor,
                    handler_id: handler,
                    payload: EventPayload::Clicked,
                },
            );
            follow(&opened, &mut parents);
            assert_no_loop(&parents, &format!("window at {start}, menu {menu} open"));
            let opened = decode_batch(&opened).unwrap();

            for (offset, entry) in MENU_ENTRIES.iter().enumerate() {
                let nodes = nodes_with_text(&opened, entry);
                assert_eq!(
                    1,
                    nodes.len(),
                    "opening menu {menu} built {entry} {} times",
                    nodes.len(),
                );
                assert_eq!(
                    Some(menu),
                    parent_of(&opened, nodes[0]),
                    "{entry} was attached outside the menu it belongs to",
                );
                assert_eq!(
                    Some(offset as u32 + 1),
                    index_of(&opened, nodes[0]),
                    "the window at {start}: {entry} went in at the wrong place under menu \
                     {menu}, where the anchor holds the first position",
                );
            }
        }
    }
}

/// The slot the given node was last attached at.
fn index_of(batch: &[Mutation<'_>], node: u32) -> Option<u32> {
    batch.iter().rev().find_map(|mutation| match mutation {
        Mutation::Insert { node_id, index, .. } | Mutation::Move { node_id, index, .. }
            if *node_id == node =>
        {
            Some(*index)
        }
        _ => None,
    })
}