waft-widgets 0.5.0

Widget framework and widgets for Waft
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
//! Framework tests on the shared test root.

use std::cell::Cell;
use std::rc::Rc;

use waft_embedder::Size;
use waft_foundation::{App, AppCell, Entity, Handle};
use waft_painting::EdgeInsetsGeometry;
use waft_rendering::{
    AnyRenderObject, BoxConstraints, RenderBox, RenderConstrainedBox, RenderHandle, RenderPadding,
};

use super::*;
use crate::test_harness::{Harness, padding_under_root};

// ---- widgets under test ----

/// `Padding` in miniature.
#[derive(Debug)]
struct Padding {
    key: Option<KeyRef>,
    padding: f64,
    child: Option<WidgetRef>,
}

impl RenderObjectWidget for Padding {
    type RenderObject = RenderPadding;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderPadding::new(app, EdgeInsetsGeometry::all(self.padding), None, None).as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        _context: BuildContext,
        render_object: RenderHandle<RenderPadding>,
    ) {
        render_object.set_padding(app, EdgeInsetsGeometry::all(self.padding));
    }
}

impl SingleChildRenderObjectWidget for Padding {
    fn child(&self) -> Option<&WidgetRef> {
        self.child.as_ref()
    }
}

/// `SizedBox` in miniature.
#[derive(Debug)]
struct Sized {
    size: Size,
}

impl RenderObjectWidget for Sized {
    type RenderObject = RenderConstrainedBox;

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderConstrainedBox::new(app, BoxConstraints::tight(self.size), None).as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        _context: BuildContext,
        render_object: RenderHandle<RenderConstrainedBox>,
    ) {
        render_object.set_additional_constraints(app, BoxConstraints::tight(self.size));
    }
}

impl LeafRenderObjectWidget for Sized {}

/// A stateless widget that counts its builds.
#[derive(Debug)]
struct Labelled {
    builds: Rc<Cell<u32>>,
    padding: f64,
}

impl StatelessWidget for Labelled {
    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        self.builds.set(self.builds.get() + 1);
        Padding {
            key: None,
            padding: self.padding,
            child: Some(
                Sized {
                    size: Size::new(10.0, 10.0),
                }
                .into_widget(),
            ),
        }
        .into_widget()
    }
}

/// A stateful counter whose state decides the padding.
#[derive(Debug)]
struct Counter {
    key: Option<KeyRef>,
    initial: f64,
}

impl StatefulWidget for Counter {
    type State = CounterState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> CounterState {
        CounterState {
            state: StateData::new(),
            padding: 0.0,
            builds: 0,
            updates: 0,
            disposed: false,
        }
    }
}

struct CounterState {
    state: StateData<Counter>,
    padding: f64,
    builds: u32,
    updates: u32,
    disposed: bool,
}

impl State for CounterState {
    type Widget = Counter;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let initial = self.widget(app).initial;
        app.get_mut(self).padding = initial;
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Counter) {
        app.get_mut(self).updates += 1;
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        app.get_mut(self).builds += 1;
        Padding {
            key: None,
            padding: app.get(self).padding,
            child: Some(
                Sized {
                    size: Size::new(10.0, 10.0),
                }
                .into_widget(),
            ),
        }
        .into_widget()
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).disposed = true;
    }
}

/// An inherited widget carrying a number.
#[derive(Debug)]
struct Theme {
    value: f64,
    child: WidgetRef,
}

impl InheritedWidget for Theme {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &Theme) -> bool {
        self.value != old_widget.value
    }
}

/// Reads the theme and pads by it.
#[derive(Debug)]
struct Themed {
    builds: Rc<Cell<u32>>,
}

impl StatelessWidget for Themed {
    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        self.builds.set(self.builds.get() + 1);
        let value = context
            .depend_on_inherited_widget_of_exact_type::<Theme>(app)
            .map_or(0.0, |theme| theme.value);
        Padding {
            key: None,
            padding: value,
            child: Some(
                Sized {
                    size: Size::new(10.0, 10.0),
                }
                .into_widget(),
            ),
        }
        .into_widget()
    }
}

#[test]
fn mounting_builds_the_render_tree_and_lays_it_out() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let builds = Rc::new(Cell::new(0));
    let harness = Harness::mount(
        &mut app,
        Labelled {
            builds: Rc::clone(&builds),
            padding: 4.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1);
    let padding = padding_under_root(&harness, &app);
    assert_eq!(padding.padding(&app), EdgeInsetsGeometry::all(4.0));
    assert_eq!(
        padding.size(&app),
        Size::new(18.0, 18.0),
        "the sized box plus 4 on each side"
    );
    assert_eq!(harness.owner.global_key_count(&app), 0);
}

#[test]
fn a_new_widget_of_the_same_type_updates_the_render_object_in_place() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let builds = Rc::new(Cell::new(0));
    let harness = Harness::mount(
        &mut app,
        Labelled {
            builds: Rc::clone(&builds),
            padding: 4.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let before = padding_under_root(&harness, &app);

    harness.set_child(
        &mut app,
        Labelled {
            builds: Rc::clone(&builds),
            padding: 6.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let after = padding_under_root(&harness, &app);
    assert_eq!(after, before, "the same RenderPadding is reconfigured");
    assert_eq!(after.padding(&app), EdgeInsetsGeometry::all(6.0));
    assert_eq!(builds.get(), 2);
}

#[test]
fn set_state_rebuilds_only_after_the_owner_flushes() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let harness = Harness::mount(
        &mut app,
        Counter {
            key: None,
            initial: 2.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let state = harness.root.as_element().children(&app)[0]
        .state_handle::<CounterState>(&app)
        .expect("the counter's state");
    assert_eq!(app.get(state).builds, 1);
    assert_eq!(
        padding_under_root(&harness, &app).padding(&app),
        EdgeInsetsGeometry::all(2.0)
    );

    state.set_state(&mut app, |state| state.padding = 5.0);
    assert!(state.context(&app).dirty(&app));
    assert_eq!(app.get(state).builds, 1, "not rebuilt until the frame");
    harness.pump(&mut app);
    assert_eq!(app.get(state).builds, 2);
    assert_eq!(
        padding_under_root(&harness, &app).padding(&app),
        EdgeInsetsGeometry::all(5.0)
    );
}

#[test]
fn a_new_stateful_widget_keeps_its_state_and_reports_the_update() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let harness = Harness::mount(
        &mut app,
        Counter {
            key: None,
            initial: 2.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let state = harness.root.as_element().children(&app)[0]
        .state_handle::<CounterState>(&app)
        .unwrap();
    harness.set_child(
        &mut app,
        Counter {
            key: None,
            initial: 9.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let same_state = harness.root.as_element().children(&app)[0]
        .state_handle::<CounterState>(&app)
        .unwrap();
    assert_eq!(same_state, state);
    assert_eq!(app.get(state).updates, 1);
    assert_eq!(app.get(state).padding, 2.0, "init_state does not run again");
    assert_eq!(app.get(state).builds, 2);
}

#[test]
fn a_different_widget_type_disposes_the_old_subtree_at_finalize() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let harness = Harness::mount(
        &mut app,
        Counter {
            key: None,
            initial: 2.0,
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let old_element = harness.root.as_element().children(&app)[0];
    let state = old_element.state_handle::<CounterState>(&app).unwrap();
    let old_padding = padding_under_root(&harness, &app);

    harness.set_child(
        &mut app,
        Sized {
            size: Size::new(5.0, 5.0),
        }
        .into_widget(),
    );
    assert!(harness.owner.debug_inactive_contains(&app, old_element));
    assert_eq!(old_element.lifecycle(&app), ElementLifecycle::Inactive);
    assert!(!app.get(state).disposed, "dispose waits for finalize_tree");
    harness.pump(&mut app);
    assert_eq!(old_element.lifecycle(&app), ElementLifecycle::Defunct);
    assert!(
        !app.contains(state),
        "the state slot is freed after dispose"
    );
    assert!(
        !app.contains(old_padding.as_object().id()),
        "the render object is disposed"
    );
    assert!(
        harness
            .render_root(&app)
            .child(&app)
            .unwrap()
            .as_object()
            .downcast::<RenderConstrainedBox>(&app)
            .is_some()
    );
}

#[test]
fn inherited_widgets_notify_their_dependents_only_when_they_should() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let builds = Rc::new(Cell::new(0));
    // One child instance, reused like a `const` widget, so only the theme decides rebuilds.
    let child: WidgetRef = Themed {
        builds: Rc::clone(&builds),
    }
    .into_widget();
    let themed = |value: f64| {
        Theme {
            value,
            child: child.clone(),
        }
        .into_widget()
    };
    let harness = Harness::mount(&mut app, themed(3.0));
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1);
    assert_eq!(
        padding_under_root(&harness, &app).padding(&app),
        EdgeInsetsGeometry::all(3.0)
    );

    harness.set_child(&mut app, themed(3.0));
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1, "an equal theme does not notify");

    harness.set_child(&mut app, themed(7.0));
    harness.pump(&mut app);
    assert_eq!(builds.get(), 2, "a changed theme rebuilds the dependent");
    assert_eq!(
        padding_under_root(&harness, &app).padding(&app),
        EdgeInsetsGeometry::all(7.0)
    );
}

#[test]
fn a_global_key_moves_an_element_with_its_state() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let key: KeyRef = Rc::new(GlobalKey::new());
    let global = downcast_key(&key);
    let counter = |key: &KeyRef| {
        Counter {
            key: Some(key.clone()),
            initial: 1.0,
        }
        .into_widget()
    };
    let harness = Harness::mount(
        &mut app,
        Padding {
            key: None,
            padding: 1.0,
            child: Some(counter(&key)),
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    assert_eq!(harness.owner.global_key_count(&app), 1);
    let registered = harness
        .owner
        .global_key_element(&app, global.identity())
        .unwrap();
    let state = registered.state_handle::<CounterState>(&app).unwrap();
    state.set_state(&mut app, |state| state.padding = 8.0);
    harness.pump(&mut app);

    // Move the keyed counter under a different parent.
    harness.set_child(
        &mut app,
        Padding {
            key: None,
            padding: 2.0,
            child: Some(
                Padding {
                    key: None,
                    padding: 3.0,
                    child: Some(counter(&key)),
                }
                .into_widget(),
            ),
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    let moved = harness
        .owner
        .global_key_element(&app, global.identity())
        .unwrap();
    assert_eq!(moved, registered, "the same element was reparented");
    assert_eq!(moved.depth(&app), registered.depth(&app));
    assert_eq!(app.get(state).padding, 8.0, "its state survived the move");
    assert!(!app.get(state).disposed);
    assert_eq!(harness.owner.global_key_count(&app), 1);
}

fn downcast_key(key: &KeyRef) -> &GlobalKey {
    ((&**key) as &dyn std::any::Any)
        .downcast_ref::<GlobalKey>()
        .expect("a global key")
}

struct Store {
    count: i32,
}

#[derive(Debug)]
struct StoreView {
    key: Option<KeyRef>,
    store: Entity<Store>,
    builds: Rc<Cell<u32>>,
    last: Rc<Cell<i32>>,
}

impl StatelessWidget for StoreView {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
        self.builds.set(self.builds.get() + 1);
        self.last.set(self.store.read(app).count);
        Sized {
            size: Size::new(10.0, 10.0),
        }
        .into_widget()
    }
}

#[test]
fn a_build_that_reads_an_entity_rebuilds_when_it_notifies() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let store = app.new_entity(|_cx| Store { count: 1 });
    let builds = Rc::new(Cell::new(0));
    let last = Rc::new(Cell::new(0));
    let harness = Harness::mount(
        &mut app,
        StoreView {
            key: None,
            store: store.clone(),
            builds: Rc::clone(&builds),
            last: Rc::clone(&last),
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1);
    assert_eq!(last.get(), 1);

    store.update(&mut app, |store, cx| {
        store.count = 4;
        cx.notify();
    });
    harness.pump(&mut app);
    assert_eq!(builds.get(), 2);
    assert_eq!(last.get(), 4);
}

#[derive(Debug)]
struct BlindView {
    builds: Rc<Cell<u32>>,
}

impl StatelessWidget for BlindView {
    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        self.builds.set(self.builds.get() + 1);
        Sized {
            size: Size::new(10.0, 10.0),
        }
        .into_widget()
    }
}

#[test]
fn a_read_outside_build_does_not_subscribe() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let store = app.new_entity(|_cx| Store { count: 1 });
    let builds = Rc::new(Cell::new(0));
    let harness = Harness::mount(
        &mut app,
        BlindView {
            builds: Rc::clone(&builds),
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1);

    let _ = store.read(&app).count;
    store.update(&mut app, |_store, cx| cx.notify());
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1);
}

#[test]
fn an_entity_notify_while_inactive_rebuilds_on_activate() {
    let cell = AppCell::new();
    let mut app = cell.borrow_mut();
    let store = app.new_entity(|_cx| Store { count: 1 });
    let builds = Rc::new(Cell::new(0));
    let last = Rc::new(Cell::new(0));
    let key: KeyRef = Rc::new(GlobalKey::new());
    let view = || {
        StoreView {
            key: Some(key.clone()),
            store: store.clone(),
            builds: Rc::clone(&builds),
            last: Rc::clone(&last),
        }
        .into_widget()
    };
    let harness = Harness::mount(
        &mut app,
        Padding {
            key: None,
            padding: 1.0,
            child: Some(view()),
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    assert_eq!(builds.get(), 1);

    // Park on the inactive list; do not pump, or finalize_tree unmounts it.
    harness.set_child(
        &mut app,
        Sized {
            size: Size::new(10.0, 10.0),
        }
        .into_widget(),
    );
    store.update(&mut app, |store, cx| {
        store.count = 4;
        cx.notify();
    });

    harness.set_child(
        &mut app,
        Padding {
            key: None,
            padding: 1.0,
            child: Some(view()),
        }
        .into_widget(),
    );
    harness.pump(&mut app);
    assert_eq!(builds.get(), 2);
    assert_eq!(last.get(), 4);
}