waft-widgets 0.14.1

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

use waft_foundation::{App, DiagnosticPropertiesBuilder, FlagProperty};
use waft_painting::{EdgeInsets, EdgeInsetsGeometry};

use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
use crate::widgets::basic::{Padding, SliverPadding};
use crate::widgets::media_query::MediaQuery;

/// Dart's `SafeArea.debugFillProperties`, which a sliver safe area prints too.
fn safe_area_flags(
    left: bool,
    top: bool,
    right: bool,
    bottom: bool,
    properties: &mut DiagnosticPropertiesBuilder,
) {
    properties.add(FlagProperty::new("left", Some(left)).if_true("avoid left padding"));
    properties.add(FlagProperty::new("top", Some(top)).if_true("avoid top padding"));
    properties.add(FlagProperty::new("right", Some(right)).if_true("avoid right padding"));
    properties.add(FlagProperty::new("bottom", Some(bottom)).if_true("avoid bottom padding"));
}

/// A widget that insets its child by sufficient padding to avoid intrusions by the operating
/// system.
///
/// For example, this will indent the child by enough to avoid the status bar at the top of
/// the screen.
///
/// It will also indent the child by the amount necessary to avoid The Notch on the iPhone X,
/// or other similar creative physical features of the display.
///
/// When a [`minimum`](Self::minimum) padding is specified, the greater of the minimum padding
/// or the safe area padding will be applied.
///
/// See also:
///
///  * `SliverSafeArea`, for insetting slivers to avoid operating system intrusions.
///  * `Padding`, for insetting widgets in general.
///  * `MediaQuery`, from which the window padding is obtained.
///  * `dart:ui.FlutterView.padding`, which reports the padding from the operating system.
#[derive(Debug)]
pub struct SafeArea {
    pub key: Option<KeyRef>,
    /// Whether to avoid system intrusions on the left.
    pub left: bool,
    /// Whether to avoid system intrusions at the top of the screen, typically the system
    /// status bar.
    pub top: bool,
    /// Whether to avoid system intrusions on the right.
    pub right: bool,
    /// Whether to avoid system intrusions on the bottom side of the screen.
    pub bottom: bool,
    /// This minimum padding to apply.
    ///
    /// The greater of the minimum insets and the media padding will be applied.
    pub minimum: EdgeInsets,
    /// Specifies whether the `SafeArea` should maintain the bottom `MediaQueryData.viewPadding`
    /// instead of the bottom `MediaQueryData.padding`, defaults to false.
    ///
    /// For example, if there is an onscreen keyboard displayed above the SafeArea, the
    /// padding can be maintained below the obstruction rather than being consumed. This can
    /// be helpful in cases where your layout contains flexible widgets, which could visibly
    /// move when opening a software keyboard due to the change in the padding value. Setting
    /// this to true will avoid the UI shift.
    pub maintain_bottom_view_padding: bool,
    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl SafeArea {
    /// Creates a widget that avoids operating system interfaces.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(child: impl IntoWidget<K>) -> SafeArea {
        SafeArea {
            key: None,
            left: true,
            top: true,
            right: true,
            bottom: true,
            minimum: EdgeInsets::ZERO,
            maintain_bottom_view_padding: false,
            child: child.into_widget(),
        }
    }

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

    /// Dart `SafeArea(left:)`.
    pub fn left(mut self, left: bool) -> SafeArea {
        self.left = left;
        self
    }

    /// Dart `SafeArea(top:)`.
    pub fn top(mut self, top: bool) -> SafeArea {
        self.top = top;
        self
    }

    /// Dart `SafeArea(right:)`.
    pub fn right(mut self, right: bool) -> SafeArea {
        self.right = right;
        self
    }

    /// Dart `SafeArea(bottom:)`.
    pub fn bottom(mut self, bottom: bool) -> SafeArea {
        self.bottom = bottom;
        self
    }

    /// Dart `SafeArea(minimum:)`.
    pub fn minimum(mut self, minimum: EdgeInsets) -> SafeArea {
        self.minimum = minimum;
        self
    }

    /// Dart `SafeArea(maintainBottomViewPadding:)`.
    pub fn maintain_bottom_view_padding(mut self, maintain_bottom_view_padding: bool) -> SafeArea {
        self.maintain_bottom_view_padding = maintain_bottom_view_padding;
        self
    }
}

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

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        safe_area_flags(self.left, self.top, self.right, self.bottom, properties);
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let mut padding = MediaQuery::padding_of(app, context);
        // Bottom padding has been consumed - i.e. by the keyboard
        if self.maintain_bottom_view_padding {
            let view_padding = MediaQuery::view_padding_of(app, context);
            padding = padding.copy_with(None, None, None, Some(view_padding.bottom));
        }
        let inset = |avoid: bool, padding: f64, minimum: f64| {
            f64::max(if avoid { padding } else { 0.0 }, minimum)
        };
        let child = MediaQuery::remove_padding(
            app,
            context,
            self.left,
            self.top,
            self.right,
            self.bottom,
            self.child.clone(),
        )
        .into_widget();
        Padding::new(EdgeInsetsGeometry::only(
            inset(self.left, padding.left, self.minimum.left),
            inset(self.top, padding.top, self.minimum.top),
            inset(self.right, padding.right, self.minimum.right),
            inset(self.bottom, padding.bottom, self.minimum.bottom),
        ))
        .child(child)
        .into_widget()
    }
}

/// A sliver that insets another sliver by sufficient padding to avoid intrusions by the
/// operating system.
///
/// For example, this will indent the sliver by enough to avoid the status bar at the top of the
/// screen.
///
/// It will also indent the sliver by the amount necessary to avoid The Notch on the iPhone X, or
/// other similar creative physical features of the display.
///
/// When a [`minimum`](Self::minimum) padding is specified, the greater of the minimum padding or
/// the safe area padding will be applied.
///
/// See also:
///
///  * [`SafeArea`], for insetting box widgets to avoid operating system intrusions.
///  * [`SliverPadding`], for insetting slivers in general.
///  * `MediaQuery`, from which the window padding is obtained.
#[derive(Debug)]
pub struct SliverSafeArea {
    pub key: Option<KeyRef>,
    /// Whether to avoid system intrusions on the left.
    pub left: bool,
    /// Whether to avoid system intrusions at the top of the screen, typically the system status
    /// bar.
    pub top: bool,
    /// Whether to avoid system intrusions on the right.
    pub right: bool,
    /// Whether to avoid system intrusions on the bottom side of the screen.
    pub bottom: bool,
    /// This minimum padding to apply.
    ///
    /// The greater of the minimum padding and the media padding is be applied.
    pub minimum: EdgeInsets,
    /// The sliver below this sliver in the tree.
    ///
    /// The padding on the `MediaQuery` for the sliver will be suitably adjusted to zero out any
    /// sides that were avoided by this sliver.
    pub sliver: WidgetRef,
}

impl SliverSafeArea {
    /// Creates a sliver that avoids operating system interfaces.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(sliver: impl IntoWidget<K>) -> SliverSafeArea {
        SliverSafeArea {
            key: None,
            left: true,
            top: true,
            right: true,
            bottom: true,
            minimum: EdgeInsets::ZERO,
            sliver: sliver.into_widget(),
        }
    }

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

    /// Dart `SliverSafeArea(left:)`.
    pub fn left(mut self, left: bool) -> SliverSafeArea {
        self.left = left;
        self
    }

    /// Dart `SliverSafeArea(top:)`.
    pub fn top(mut self, top: bool) -> SliverSafeArea {
        self.top = top;
        self
    }

    /// Dart `SliverSafeArea(right:)`.
    pub fn right(mut self, right: bool) -> SliverSafeArea {
        self.right = right;
        self
    }

    /// Dart `SliverSafeArea(bottom:)`.
    pub fn bottom(mut self, bottom: bool) -> SliverSafeArea {
        self.bottom = bottom;
        self
    }

    /// Dart `SliverSafeArea(minimum:)`.
    pub fn minimum(mut self, minimum: EdgeInsets) -> SliverSafeArea {
        self.minimum = minimum;
        self
    }
}

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

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        safe_area_flags(self.left, self.top, self.right, self.bottom, properties);
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let padding = MediaQuery::padding_of(app, context);
        let inset = |avoid: bool, padding: f64, minimum: f64| {
            f64::max(if avoid { padding } else { 0.0 }, minimum)
        };
        let sliver = MediaQuery::remove_padding(
            app,
            context,
            self.left,
            self.top,
            self.right,
            self.bottom,
            self.sliver.clone(),
        )
        .into_widget();
        SliverPadding::new(EdgeInsetsGeometry::only(
            inset(self.left, padding.left, self.minimum.left),
            inset(self.top, padding.top, self.minimum.top),
            inset(self.right, padding.right, self.minimum.right),
            inset(self.bottom, padding.bottom, self.minimum.bottom),
        ))
        .sliver(sliver)
        .into_widget()
    }
}

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

    use waft_rendering::RenderPadding;

    use super::*;
    use crate::test_harness::Harness;
    use crate::widgets::basic::{Builder, SizedBox};
    use crate::widgets::media_query::MediaQueryData;

    fn padded(padding: EdgeInsets, view_padding: EdgeInsets, area: SafeArea) -> WidgetRef {
        MediaQuery::new(
            MediaQueryData::new()
                .padding(padding)
                .view_padding(view_padding),
            area,
        )
        .into_widget()
    }

    fn render_padding(harness: &Harness, app: &App) -> EdgeInsetsGeometry {
        harness
            .render_root(app)
            .child(app)
            .expect("a child")
            .as_object()
            .downcast::<RenderPadding>(app)
            .expect("a RenderPadding")
            .padding(app)
    }

    #[test]
    fn a_safe_area_pads_by_the_media_padding_it_avoids_and_removes_it_below() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let seen = Rc::new(RefCell::new(None));
        let probe = Builder::new({
            let seen = Rc::clone(&seen);
            move |app, context| {
                *seen.borrow_mut() = Some(MediaQuery::padding_of(app, context));
                SizedBox::shrink().into_widget()
            }
        });
        let harness = Harness::mount(
            &mut app,
            padded(
                EdgeInsets::only(10.0, 20.0, 30.0, 40.0),
                EdgeInsets::ZERO,
                SafeArea::new(probe)
                    .left(false)
                    .minimum(EdgeInsets::only(0.0, 0.0, 5.0, 45.0)),
            ),
        );
        harness.pump(&mut app);
        assert_eq!(
            render_padding(&harness, &app),
            EdgeInsetsGeometry::only(0.0, 20.0, 30.0, 45.0)
        );
        assert_eq!(
            seen.borrow().clone(),
            Some(EdgeInsets::only(10.0, 0.0, 0.0, 0.0))
        );
    }

    #[test]
    fn maintaining_the_bottom_view_padding_uses_it_instead_of_the_consumed_padding() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(
            &mut app,
            padded(
                EdgeInsets::only(0.0, 0.0, 0.0, 0.0),
                EdgeInsets::only(0.0, 0.0, 0.0, 34.0),
                SafeArea::new(SizedBox::shrink()).maintain_bottom_view_padding(true),
            ),
        );
        harness.pump(&mut app);
        assert_eq!(
            render_padding(&harness, &app),
            EdgeInsetsGeometry::only(0.0, 0.0, 0.0, 34.0)
        );
    }
    /// A `SliverSafeArea` pads its sliver by the media padding it avoids, and removes that
    /// padding for its subtree.
    #[test]
    fn a_sliver_safe_area_pads_by_the_media_padding_it_avoids() {
        use waft_embedder::TextDirection;
        use waft_rendering::{
            ContainerRenderObjectMixin, FixedViewportOffset, RenderSliverPadding, RenderViewport,
        };

        use crate::widgets::basic::{Directionality, SliverToBoxAdapter};
        use crate::widgets::viewport::Viewport;

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let offset = FixedViewportOffset::zero(&mut app);
        let area =
            SliverSafeArea::new(SliverToBoxAdapter::new().child(SizedBox::new().height(50.0)))
                .left(false)
                .minimum(EdgeInsets::only(0.0, 0.0, 5.0, 45.0));
        let tree = Directionality::new(
            TextDirection::Ltr,
            MediaQuery::new(
                MediaQueryData::new().padding(EdgeInsets::only(10.0, 20.0, 30.0, 40.0)),
                Viewport::new(offset.erase()).slivers(vec![area.into_widget()]),
            )
            .into_widget(),
        )
        .into_widget();
        let harness = Harness::mount(&mut app, tree);
        harness.pump(&mut app);

        let padding = harness
            .render_root(&app)
            .child(&app)
            .expect("a child")
            .as_object()
            .downcast::<RenderViewport>(&app)
            .expect("a RenderViewport")
            .first_child(&app)
            .expect("the padding")
            .as_object()
            .downcast::<RenderSliverPadding>(&app)
            .expect("a RenderSliverPadding");
        assert_eq!(
            padding.padding(&app),
            EdgeInsetsGeometry::only(0.0, 20.0, 30.0, 45.0)
        );
    }
}