smudge-core 0.1.0

Widget tree, reactive bindings, layout, paint and damage tracking for the Smudge GUI library
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
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::element::{Element, IntoElement, UpdateQueue, mount, show};
use crate::geometry::Color;
use crate::paint::PaintOp;
use crate::reactive::{self, Owner, WriteSignal, prelude::*};
use crate::style::Length;
use crate::theme::ColorValue;
use crate::tree::{Dirty, WidgetId, WidgetTree};
use crate::widget::{PaintCx, Widget, panel};

/// Mounts `element` as the root of a fresh tree.
fn mount_root(element: impl IntoElement) -> (WidgetTree, UpdateQueue, WidgetId) {
    reactive::init();
    let mut tree = WidgetTree::new();
    let queue = UpdateQueue::default();
    let root = mount(element.into_any(), &mut tree, &queue, None);
    (tree, queue, root)
}

/// Runs the reactive tasks and applies the updates they queue, as a frame does.
fn settle(tree: &mut WidgetTree, queue: &UpdateQueue) {
    for _ in 0..16 {
        reactive::flush();
        if !queue.apply(tree) {
            return;
        }
    }
    panic!("the queue did not settle within sixteen rounds");
}

#[test]
fn a_static_background_lands_in_the_paint_properties() {
    let (tree, _queue, root) =
        mount_root(panel().width(Length::px(120.0)).background(Color::WHITE));

    let style = tree.style(root).expect("the root is live");
    assert_eq!(style.layout.width, Length::px(120.0));
    assert_eq!(style.paint.background, Some(Color::WHITE.into()));
    assert_eq!(
        tree.dirty(root),
        Some(Dirty::Layout),
        "a new node has never been laid out"
    );
    assert!(tree.layout_is_dirty());
}

#[test]
fn a_binding_reads_its_value_when_the_node_mounts() {
    let (color, _set_color) = signal_local(Color::BLACK);
    let (mut tree, queue, root) = mount_root(panel().background(move || color.get().into()));

    queue.apply(&mut tree);

    assert_eq!(
        tree.style(root).expect("the root is live").paint.background,
        Some(Color::BLACK.into()),
        "the first run is queued at mount, before any flush"
    );
}

#[test]
fn a_background_binding_marks_the_node_for_paint_only() {
    let (on, set_on) = signal_local(false);
    let (mut tree, queue, root) = mount_root(panel().background(move || {
        if on.get() {
            Color::BLACK.into()
        } else {
            Color::WHITE.into()
        }
    }));
    settle(&mut tree, &queue);
    tree.clear_dirty();

    set_on.set(true);
    settle(&mut tree, &queue);

    assert_eq!(
        tree.style(root).expect("the root is live").paint.background,
        Some(Color::BLACK.into())
    );
    assert_eq!(tree.dirty(root), Some(Dirty::Paint));
    assert!(!tree.layout_is_dirty(), "a paint change never needs layout");
}

#[test]
fn a_width_binding_marks_the_node_for_layout() {
    let (width, set_width) = signal_local(Length::px(20.0));
    let (mut tree, queue, root) = mount_root(panel().width(move || width.get()));
    settle(&mut tree, &queue);
    tree.clear_dirty();

    set_width.set(Length::px(40.0));
    settle(&mut tree, &queue);

    assert_eq!(
        tree.style(root).expect("the root is live").layout.width,
        Length::px(40.0)
    );
    assert_eq!(tree.dirty(root), Some(Dirty::Layout));
    assert!(tree.layout_is_dirty());
}

#[test]
fn a_binding_change_waits_for_the_queue_to_drain() {
    let (on, set_on) = signal_local(false);
    let (mut tree, queue, root) = mount_root(panel().background(move || {
        if on.get() {
            Color::BLACK.into()
        } else {
            Color::WHITE.into()
        }
    }));
    settle(&mut tree, &queue);

    set_on.set(true);
    reactive::flush();

    assert_eq!(
        tree.style(root).expect("the root is live").paint.background,
        Some(Color::WHITE.into()),
        "the effect queued the change and left the tree alone"
    );

    queue.apply(&mut tree);

    assert_eq!(
        tree.style(root).expect("the root is live").paint.background,
        Some(Color::BLACK.into())
    );
}

#[test]
fn children_are_mounted_in_the_order_they_were_added() {
    let (tree, _queue, root) =
        mount_root(panel().child(panel().background(Color::WHITE)).children([
            panel().background(Color::BLACK),
            panel().background(Color::TRANSPARENT),
        ]));

    let children = tree.children(root).expect("the root is live");
    assert_eq!(children.len(), 3);
    let backgrounds: Vec<Option<ColorValue>> = children
        .iter()
        .map(|child| {
            tree.style(*child)
                .expect("every mounted child is live")
                .paint
                .background
        })
        .collect();
    assert_eq!(
        backgrounds,
        vec![
            Some(Color::WHITE.into()),
            Some(Color::BLACK.into()),
            Some(Color::TRANSPARENT.into())
        ]
    );
    tree.debug_assert_consistent();
}

#[test]
fn a_widget_binding_updates_the_widget_and_marks_it() {
    /// A widget with one property of its own.
    struct Dot(u8);

    impl Widget for Dot {
        fn paint(&self, _cx: &PaintCx<'_>, _out: &mut Vec<PaintOp>) {}
    }

    let (value, set_value) = signal_local(1u8);
    let (mut tree, queue, root) = mount_root(Element::new(Dot(0)).bind(
        move || value.get(),
        |dot, value| {
            dot.0 = value;
            Dirty::Paint
        },
    ));
    settle(&mut tree, &queue);

    assert_eq!(
        tree.widget_mut::<Dot>(root).map(|dot| dot.0),
        Some(1),
        "the first run applies the bound value"
    );

    tree.clear_dirty();
    set_value.set(2);
    settle(&mut tree, &queue);

    assert_eq!(tree.widget_mut::<Dot>(root).map(|dot| dot.0), Some(2));
    assert_eq!(tree.dirty(root), Some(Dirty::Paint));
    assert!(!tree.layout_is_dirty());
}

#[test]
fn show_mounts_its_child_while_the_signal_is_true() {
    let (on, set_on) = signal_local(false);
    let (color, set_color) = signal_local(Color::WHITE);
    let runs = Rc::new(Cell::new(0u32));
    let counter = Rc::clone(&runs);

    let (mut tree, queue, slot) = mount_root(show(
        move || on.get(),
        move || {
            let counter = Rc::clone(&counter);
            let color = color.clone();
            panel().background(move || {
                counter.set(counter.get() + 1);
                color.get().into()
            })
        },
    ));
    settle(&mut tree, &queue);

    assert_eq!(tree.node_count(), 1, "nothing is mounted yet");
    assert_eq!(runs.get(), 0);

    set_on.set(true);
    settle(&mut tree, &queue);

    assert_eq!(tree.node_count(), 2, "the child is mounted");
    assert_eq!(
        tree.children(slot).expect("the slot is live").len(),
        1,
        "the child is mounted under the slot"
    );
    assert_eq!(runs.get(), 1, "the child's binding ran once");
    tree.debug_assert_consistent();

    set_color.set(Color::BLACK);
    settle(&mut tree, &queue);
    assert_eq!(runs.get(), 2, "the child's binding follows its signal");

    set_on.set(false);
    settle(&mut tree, &queue);

    assert_eq!(tree.node_count(), 1, "the child is removed");
    assert_eq!(
        tree.children(slot).expect("the slot is live").len(),
        0,
        "the slot no longer lists the child"
    );
    tree.debug_assert_consistent();

    set_color.set(Color::WHITE);
    settle(&mut tree, &queue);
    assert_eq!(runs.get(), 2, "the removed child's binding stopped");
}

#[test]
fn show_keeps_the_signals_its_child_created_while_the_child_stays_mounted() {
    let (visible, _set_visible) = signal_local(true);
    let (unrelated, set_unrelated) = signal_local(0u32);
    let builds = Rc::new(Cell::new(0u32));
    let first_writer: Rc<RefCell<Option<WriteSignal<Color>>>> = Rc::new(RefCell::new(None));
    let counter = Rc::clone(&builds);
    let stash = Rc::clone(&first_writer);

    let (mut tree, queue, slot) = mount_root(show(
        move || {
            unrelated.get();
            visible.get()
        },
        move || {
            counter.set(counter.get() + 1);
            let (color, set_color) = signal_local(Color::BLACK);
            stash.borrow_mut().get_or_insert(set_color);
            panel().background(move || color.get().into())
        },
    ));
    settle(&mut tree, &queue);
    let child = tree.children(slot).expect("the slot is live")[0];

    set_unrelated.set(1);
    settle(&mut tree, &queue);
    assert_eq!(
        tree.children(slot).expect("the slot is live"),
        &[child],
        "a check that leaves the child mounted keeps the same child"
    );
    assert_eq!(
        builds.get(),
        1,
        "the child is built once while it stays mounted"
    );

    let set_color = first_writer
        .borrow()
        .as_ref()
        .expect("the child was built")
        .clone();
    set_color.set(Color::WHITE);
    settle(&mut tree, &queue);
    assert_eq!(
        tree.style(child)
            .expect("the child is live")
            .paint
            .background,
        Some(Color::WHITE.into()),
        "the signal the child created still drives its binding"
    );
}

#[test]
fn show_disposes_the_scope_its_child_was_built_in() {
    let (visible, set_visible) = signal_local(true);
    let disposed = Arc::new(AtomicBool::new(false));
    let flag = Arc::clone(&disposed);

    let (mut tree, queue, slot) = mount_root(show(
        move || visible.get(),
        move || {
            let flag = Arc::clone(&flag);
            Owner::on_cleanup(move || flag.store(true, Ordering::Relaxed));
            panel()
        },
    ));
    settle(&mut tree, &queue);

    assert_eq!(
        tree.children(slot).expect("the slot is live").len(),
        1,
        "the child is mounted"
    );
    assert!(
        !disposed.load(Ordering::Relaxed),
        "the scope the child was built in stays alive while it is mounted"
    );

    set_visible.set(false);
    settle(&mut tree, &queue);

    assert!(
        disposed.load(Ordering::Relaxed),
        "removing the child disposes the scope it was built in"
    );
}

#[test]
fn style_children_restyles_the_children_added_before_it() {
    let element = panel()
        .child(panel().background(Color::WHITE))
        .child(panel().background(Color::BLACK))
        .style_children(|style| style.paint.background = Some(Color::rgb(128, 128, 128).into()));

    assert_eq!(
        element.children.len(),
        2,
        "both children are still on the element"
    );
    for child in &element.children {
        assert_eq!(
            child.style.paint.background,
            Some(Color::rgb(128, 128, 128).into()),
            "the style reaches a child the element already had"
        );
    }
}

#[test]
fn style_children_styles_the_children_added_after_it() {
    let element = panel()
        .style_children(|style| style.paint.background = Some(Color::rgb(128, 128, 128).into()))
        .child(panel().child(panel().background(Color::WHITE)));

    let [child, ..] = element.children.as_slice() else {
        panic!("the element holds the child that was added");
    };
    assert_eq!(
        child.style.paint.background,
        Some(Color::rgb(128, 128, 128).into()),
        "the style reaches a child added after it was set"
    );
    let [grandchild, ..] = child.children.as_slice() else {
        panic!("the child holds its own child");
    };
    assert_eq!(
        grandchild.style.paint.background,
        Some(Color::WHITE.into()),
        "the style stops at the direct children"
    );
}

#[test]
fn style_children_styles_the_children_added_through_children() {
    let gray = Color::rgb(128, 128, 128);
    let element = panel()
        .style_children(move |style| style.paint.background = Some(gray.into()))
        .children([panel(), panel()]);

    assert_eq!(element.children.len(), 2);
    for child in &element.children {
        assert_eq!(
            child.style.paint.background,
            Some(gray.into()),
            "the style reaches every child of the batch"
        );
    }
}

#[test]
fn a_role_reaches_the_node_it_is_set_on() {
    let (tree, _queue, root) = mount_root(panel().role(crate::semantics::Role::Group));

    assert_eq!(tree.semantics_nodes().len(), 1);
    let node = tree.semantics_node(root).expect("the root projects");
    assert_eq!(node.role, crate::semantics::Role::Group);
}

#[test]
fn a_static_accessible_label_is_written_when_the_node_mounts() {
    let (tree, _queue, root) = mount_root(
        panel()
            .role(crate::semantics::Role::Group)
            .accessible_label("Files"),
    );

    let node = tree.semantics_node(root).expect("the root projects");
    assert_eq!(node.label.as_deref(), Some("Files"));
}

#[test]
fn a_dynamic_accessible_label_follows_its_signal() {
    let (name, set_name) = signal_local(String::from("before"));
    let (mut tree, queue, root) = mount_root(
        panel()
            .role(crate::semantics::Role::Group)
            .accessible_label(move || name.get()),
    );
    settle(&mut tree, &queue);
    assert_eq!(
        tree.semantics_node(root).and_then(|node| node.label),
        Some(String::from("before")),
    );

    set_name.set(String::from("after"));
    settle(&mut tree, &queue);
    assert_eq!(
        tree.semantics_node(root).and_then(|node| node.label),
        Some(String::from("after")),
    );
}