waft-widgets 0.1.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
//! Flutter counterpart: `widgets/annotated_region.dart`.

use std::fmt::Debug;
use std::rc::Rc;

use waft_foundation::App;
use waft_rendering::{AnyRenderObject, RenderAnnotatedRegion, RenderBox, RenderHandle};

use crate::framework::{
    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, WidgetRef,
};

/// Annotates a region of the layer tree with a value.
///
/// See also:
///
///  * [`Layer::find`](waft_rendering::AnyLayer::find), for how this value is
///    retrieved.
///  * [`AnnotatedRegionLayer`](waft_rendering::AnnotatedRegionLayer), the layer pushed into
///    the recording.
#[derive(Debug)]
pub struct AnnotatedRegion<T> {
    pub key: Option<KeyRef>,
    /// A value which can be retrieved using
    /// [`AnyLayer::find`](waft_rendering::AnyLayer::find).
    ///
    /// Dart's `T value`; it is shared rather than copied so the recording can carry it.
    pub value: Rc<T>,
    /// If false, the layer pushed into the tree will not be provided with a size.
    ///
    /// An [`AnnotatedRegionLayer`](waft_rendering::AnnotatedRegionLayer) with a size checks
    /// that the offset provided in [`AnyLayer::find`](waft_rendering::AnyLayer::find)
    /// is within the bounds, returning `None` otherwise.
    pub sized: bool,
    pub child: WidgetRef,
}

impl<T: PartialEq + Debug + 'static> AnnotatedRegion<T> {
    /// Creates a new annotated region to insert `value` into the layer tree.
    ///
    /// [`sized`](Self::sized) defaults to true and controls whether the annotated region will
    /// clip its child.
    pub fn new<K>(child: impl IntoWidget<K>, value: T) -> AnnotatedRegion<T> {
        AnnotatedRegion {
            key: None,
            value: Rc::new(value),
            sized: true,
            child: child.into_widget(),
        }
    }

    /// Dart `AnnotatedRegion(key:)`.
    pub fn key(mut self, key: KeyRef) -> AnnotatedRegion<T> {
        self.key = Some(key);
        self
    }

    /// Dart `AnnotatedRegion(sized:)`.
    pub fn sized(mut self, sized: bool) -> AnnotatedRegion<T> {
        self.sized = sized;
        self
    }
}

impl<T: PartialEq + Debug + 'static> RenderObjectWidget for AnnotatedRegion<T> {
    type RenderObject = RenderAnnotatedRegion<T>;

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

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderAnnotatedRegion::new(app, Rc::clone(&self.value), self.sized, None).as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        _context: BuildContext,
        render_object: RenderHandle<RenderAnnotatedRegion<T>>,
    ) {
        render_object.set_value(app, Rc::clone(&self.value));
        render_object.set_sized(app, self.sized);
    }
}

impl<T: PartialEq + Debug + 'static> SingleChildRenderObjectWidget for AnnotatedRegion<T> {
    fn child(&self) -> Option<&WidgetRef> {
        Some(&self.child)
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::rc::Rc;

    use waft_embedder::{
        ApplicationSwitcherDescription, Brightness, Offset, SystemChrome, SystemUiOverlayStyle,
    };
    use waft_foundation::AppCell;
    use waft_rendering::{AnnotationResult, AnyContainerLayer, ErasedLayer};
    use waft_test::TestPlatform;

    use super::*;
    use crate::test_harness::Harness;
    use crate::widgets::basic::{Center, Column, SizedBox};

    /// A host that records how it was asked to draw the system's bars.
    #[derive(Default)]
    struct RecordingChrome {
        styles: RefCell<Vec<SystemUiOverlayStyle>>,
    }

    impl RecordingChrome {
        fn styles(&self) -> Vec<SystemUiOverlayStyle> {
            self.styles.borrow().clone()
        }
    }

    impl SystemChrome for RecordingChrome {
        fn set_overlay_style(&self, style: &SystemUiOverlayStyle) {
            self.styles.borrow_mut().push(*style);
        }

        fn set_application_switcher_description(
            &self,
            _description: &ApplicationSwitcherDescription,
        ) {
        }
    }

    /// Mounts `child`, lays it out and composites one frame, which is where the system's
    /// bars are styled from the tree. Answers what the host was told.
    fn styles_of_one_frame(child: WidgetRef) -> Vec<SystemUiOverlayStyle> {
        let chrome = Rc::new(RecordingChrome::default());
        let platform = TestPlatform::new().with_system_chrome(chrome.clone());
        let cell = AppCell::with_platform(Rc::new(platform));
        let harness = Harness::mount(&mut cell.borrow_mut(), child);
        harness.pump(&mut cell.borrow_mut());
        let root = harness.render_root(&cell.borrow());
        root.composite_frame(&mut cell.borrow_mut());
        // The style is sent from a microtask, as Dart's `SystemChrome` sends it.
        cell.checkpoint();
        chrome.styles()
    }

    /// The whole view annotated with one style, so both the status bar and the navigation
    /// bar are sampled from it.
    fn the_whole_view(style: SystemUiOverlayStyle) -> WidgetRef {
        AnnotatedRegion::new(SizedBox::expand(), style).into_widget()
    }

    #[test]
    fn one_region_over_the_whole_view_styles_both_of_the_system_bars() {
        let style = SystemUiOverlayStyle::new()
            .status_bar_icon_brightness(Brightness::Dark)
            .system_navigation_bar_icon_brightness(Brightness::Dark);
        assert_eq!(styles_of_one_frame(the_whole_view(style)), vec![style]);
    }

    #[test]
    fn a_view_that_annotates_nothing_leaves_the_system_bars_alone() {
        assert_eq!(
            styles_of_one_frame(SizedBox::expand().into_widget()),
            vec![]
        );
    }

    #[test]
    fn the_region_under_each_bar_styles_that_bar_and_not_the_other() {
        let half = |style: SystemUiOverlayStyle| {
            AnnotatedRegion::new(sized(300.0, 100.0), style).into_widget()
        };
        let upper = SystemUiOverlayStyle::new().status_bar_icon_brightness(Brightness::Dark);
        let lower =
            SystemUiOverlayStyle::new().system_navigation_bar_icon_brightness(Brightness::Light);
        let view = Column::new()
            .children(vec![half(upper), half(lower)])
            .into_widget();
        assert_eq!(
            styles_of_one_frame(view),
            vec![
                SystemUiOverlayStyle::new()
                    .status_bar_icon_brightness(Brightness::Dark)
                    .system_navigation_bar_icon_brightness(Brightness::Light)
            ],
            "the upper region speaks for the status bar and the lower for the navigation bar"
        );
    }

    /// The annotated value; two markers of the same type so one search finds both.
    #[derive(Debug, PartialEq)]
    struct Marker(u32);

    fn sized(width: f64, height: f64) -> WidgetRef {
        SizedBox {
            width: Some(width),
            height: Some(height),
            ..Default::default()
        }
        .into_widget()
    }

    /// The root layer of a mounted tree, which `find` searches.
    fn root_layer(harness: &Harness, app: &App) -> AnyContainerLayer {
        harness
            .render_root(app)
            .as_object()
            .debug_layer(app)
            .expect("the root has a layer")
    }

    /// A `sized` 100 x 50 region centred in the 300 x 200 view, so it spans (100, 75) to
    /// (200, 125).
    fn centred_region(sized_region: bool) -> WidgetRef {
        Center::new()
            .child(
                SizedBox {
                    width: Some(100.0),
                    height: Some(50.0),
                    child: Some(
                        AnnotatedRegion::new(SizedBox::expand(), Marker(1))
                            .sized(sized_region)
                            .into_widget(),
                    ),
                    ..Default::default()
                }
                .into_widget(),
            )
            .into_widget()
    }

    #[test]
    fn a_sized_region_answers_inside_its_bounds_and_nowhere_else() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(&mut app, centred_region(true));
        harness.pump(&mut app);
        let layer = root_layer(&harness, &app).as_layer();

        let inside = layer.find::<Marker>(&app, Offset::new(150.0, 100.0));
        assert_eq!(inside.as_deref(), Some(&Marker(1)));
        assert!(
            layer
                .find::<Marker>(&app, Offset::new(100.0, 75.0))
                .is_some(),
            "the top left corner is inside"
        );
        assert!(
            layer
                .find::<Marker>(&app, Offset::new(10.0, 10.0))
                .is_none(),
            "outside the region"
        );
        assert!(
            layer
                .find::<Marker>(&app, Offset::new(200.0, 100.0))
                .is_none(),
            "the right edge is excluded"
        );
    }

    #[test]
    fn an_unsized_region_answers_everywhere() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(&mut app, centred_region(false));
        harness.pump(&mut app);
        let layer = root_layer(&harness, &app).as_layer();

        assert_eq!(
            layer
                .find::<Marker>(&app, Offset::new(150.0, 100.0))
                .as_deref(),
            Some(&Marker(1))
        );
        assert_eq!(
            layer.find::<Marker>(&app, Offset::new(1.0, 1.0)).as_deref(),
            Some(&Marker(1)),
            "no size means no bounds check"
        );
    }

    #[test]
    fn a_find_of_another_type_finds_nothing() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(&mut app, centred_region(true));
        harness.pump(&mut app);
        assert!(
            root_layer(&harness, &app)
                .as_layer()
                .find::<u32>(&app, Offset::new(150.0, 100.0))
                .is_none(),
            "the target type must be identical to the annotated type"
        );
    }

    #[test]
    fn nested_regions_answer_innermost_first() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let inner = AnnotatedRegion::new(SizedBox::expand(), Marker(2));
        let tree = Center::new()
            .child(
                SizedBox {
                    width: Some(100.0),
                    height: Some(50.0),
                    child: Some(
                        AnnotatedRegion::new(
                            Center::new().child(
                                SizedBox {
                                    width: Some(40.0),
                                    height: Some(20.0),
                                    child: Some(inner.into_widget()),
                                    ..Default::default()
                                }
                                .into_widget(),
                            ),
                            Marker(1),
                        )
                        .into_widget(),
                    ),
                    ..Default::default()
                }
                .into_widget(),
            )
            .into_widget();
        let harness = Harness::mount(&mut app, tree);
        harness.pump(&mut app);
        let layer = root_layer(&harness, &app).as_layer();

        let result: AnnotationResult<Marker> =
            layer.find_all_annotations(&app, Offset::new(150.0, 100.0));
        assert_eq!(
            result
                .annotations()
                .map(|marker| marker.0)
                .collect::<Vec<_>>(),
            vec![2, 1],
            "the innermost region is the most specific"
        );
        assert_eq!(
            result
                .entries()
                .iter()
                .map(|entry| entry.local_position)
                .collect::<Vec<_>>(),
            vec![Offset::new(20.0, 10.0), Offset::new(50.0, 25.0)],
            "each entry is in the coordinate space of its own region"
        );

        assert_eq!(
            layer
                .find::<Marker>(&app, Offset::new(150.0, 100.0))
                .as_deref(),
            Some(&Marker(2)),
            "`find` stops at the first"
        );

        let outer_only: AnnotationResult<Marker> =
            layer.find_all_annotations(&app, Offset::new(110.0, 80.0));
        assert_eq!(
            outer_only
                .annotations()
                .map(|marker| marker.0)
                .collect::<Vec<_>>(),
            vec![1],
            "outside the inner region, only the outer one answers"
        );
    }

    #[test]
    fn a_region_reconfigures_its_render_object_in_place() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let region = |value: u32, sized_region: bool| {
            AnnotatedRegion::new(sized(10.0, 10.0), Marker(value))
                .sized(sized_region)
                .into_widget()
        };
        let harness = Harness::mount(&mut app, region(1, true));
        harness.pump(&mut app);
        let render_object = harness
            .render_root(&app)
            .child(&app)
            .expect("a child")
            .as_object()
            .downcast::<RenderAnnotatedRegion<Marker>>(&app)
            .expect("a RenderAnnotatedRegion");
        assert_eq!(*render_object.value(&app), Marker(1));
        assert!(render_object.sized(&app), "Dart's default");

        harness.set_child(&mut app, region(2, false));
        harness.pump(&mut app);
        assert_eq!(
            *render_object.value(&app),
            Marker(2),
            "the same render object is reconfigured"
        );
        assert!(!render_object.sized(&app));
    }
}