Skip to main content

waft_widgets/widgets/
safe_area.rs

1//! Flutter counterpart: `widgets/safe_area.dart`.
2
3use waft_foundation::{App, DiagnosticPropertiesBuilder, FlagProperty};
4use waft_painting::{EdgeInsets, EdgeInsetsGeometry};
5
6use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
7use crate::widgets::basic::{Padding, SliverPadding};
8use crate::widgets::media_query::MediaQuery;
9
10/// Dart's `SafeArea.debugFillProperties`, which a sliver safe area prints too.
11fn safe_area_flags(
12    left: bool,
13    top: bool,
14    right: bool,
15    bottom: bool,
16    properties: &mut DiagnosticPropertiesBuilder,
17) {
18    properties.add(FlagProperty::new("left", Some(left)).if_true("avoid left padding"));
19    properties.add(FlagProperty::new("top", Some(top)).if_true("avoid top padding"));
20    properties.add(FlagProperty::new("right", Some(right)).if_true("avoid right padding"));
21    properties.add(FlagProperty::new("bottom", Some(bottom)).if_true("avoid bottom padding"));
22}
23
24/// A widget that insets its child by sufficient padding to avoid intrusions by the operating
25/// system.
26///
27/// For example, this will indent the child by enough to avoid the status bar at the top of
28/// the screen.
29///
30/// It will also indent the child by the amount necessary to avoid The Notch on the iPhone X,
31/// or other similar creative physical features of the display.
32///
33/// When a [`minimum`](Self::minimum) padding is specified, the greater of the minimum padding
34/// or the safe area padding will be applied.
35///
36/// See also:
37///
38///  * `SliverSafeArea`, for insetting slivers to avoid operating system intrusions.
39///  * `Padding`, for insetting widgets in general.
40///  * `MediaQuery`, from which the window padding is obtained.
41///  * `dart:ui.FlutterView.padding`, which reports the padding from the operating system.
42#[derive(Debug)]
43pub struct SafeArea {
44    pub key: Option<KeyRef>,
45    /// Whether to avoid system intrusions on the left.
46    pub left: bool,
47    /// Whether to avoid system intrusions at the top of the screen, typically the system
48    /// status bar.
49    pub top: bool,
50    /// Whether to avoid system intrusions on the right.
51    pub right: bool,
52    /// Whether to avoid system intrusions on the bottom side of the screen.
53    pub bottom: bool,
54    /// This minimum padding to apply.
55    ///
56    /// The greater of the minimum insets and the media padding will be applied.
57    pub minimum: EdgeInsets,
58    /// Specifies whether the `SafeArea` should maintain the bottom `MediaQueryData.viewPadding`
59    /// instead of the bottom `MediaQueryData.padding`, defaults to false.
60    ///
61    /// For example, if there is an onscreen keyboard displayed above the SafeArea, the
62    /// padding can be maintained below the obstruction rather than being consumed. This can
63    /// be helpful in cases where your layout contains flexible widgets, which could visibly
64    /// move when opening a software keyboard due to the change in the padding value. Setting
65    /// this to true will avoid the UI shift.
66    pub maintain_bottom_view_padding: bool,
67    /// The widget below this widget in the tree.
68    pub child: WidgetRef,
69}
70
71impl SafeArea {
72    /// Creates a widget that avoids operating system interfaces.
73    #[cfg_attr(debug_assertions, track_caller)]
74    pub fn new<K>(child: impl IntoWidget<K>) -> SafeArea {
75        SafeArea {
76            key: None,
77            left: true,
78            top: true,
79            right: true,
80            bottom: true,
81            minimum: EdgeInsets::ZERO,
82            maintain_bottom_view_padding: false,
83            child: child.into_widget(),
84        }
85    }
86
87    /// Dart `SafeArea(key:)`.
88    pub fn key(mut self, key: KeyRef) -> SafeArea {
89        self.key = Some(key);
90        self
91    }
92
93    /// Dart `SafeArea(left:)`.
94    pub fn left(mut self, left: bool) -> SafeArea {
95        self.left = left;
96        self
97    }
98
99    /// Dart `SafeArea(top:)`.
100    pub fn top(mut self, top: bool) -> SafeArea {
101        self.top = top;
102        self
103    }
104
105    /// Dart `SafeArea(right:)`.
106    pub fn right(mut self, right: bool) -> SafeArea {
107        self.right = right;
108        self
109    }
110
111    /// Dart `SafeArea(bottom:)`.
112    pub fn bottom(mut self, bottom: bool) -> SafeArea {
113        self.bottom = bottom;
114        self
115    }
116
117    /// Dart `SafeArea(minimum:)`.
118    pub fn minimum(mut self, minimum: EdgeInsets) -> SafeArea {
119        self.minimum = minimum;
120        self
121    }
122
123    /// Dart `SafeArea(maintainBottomViewPadding:)`.
124    pub fn maintain_bottom_view_padding(mut self, maintain_bottom_view_padding: bool) -> SafeArea {
125        self.maintain_bottom_view_padding = maintain_bottom_view_padding;
126        self
127    }
128}
129
130impl StatelessWidget for SafeArea {
131    fn key(&self) -> Option<&KeyRef> {
132        self.key.as_ref()
133    }
134
135    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
136        safe_area_flags(self.left, self.top, self.right, self.bottom, properties);
137    }
138
139    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
140        let mut padding = MediaQuery::padding_of(app, context);
141        // Bottom padding has been consumed - i.e. by the keyboard
142        if self.maintain_bottom_view_padding {
143            let view_padding = MediaQuery::view_padding_of(app, context);
144            padding = padding.copy_with(None, None, None, Some(view_padding.bottom));
145        }
146        let inset = |avoid: bool, padding: f64, minimum: f64| {
147            f64::max(if avoid { padding } else { 0.0 }, minimum)
148        };
149        let child = MediaQuery::remove_padding(
150            app,
151            context,
152            self.left,
153            self.top,
154            self.right,
155            self.bottom,
156            self.child.clone(),
157        )
158        .into_widget();
159        Padding::new(EdgeInsetsGeometry::only(
160            inset(self.left, padding.left, self.minimum.left),
161            inset(self.top, padding.top, self.minimum.top),
162            inset(self.right, padding.right, self.minimum.right),
163            inset(self.bottom, padding.bottom, self.minimum.bottom),
164        ))
165        .child(child)
166        .into_widget()
167    }
168}
169
170/// A sliver that insets another sliver by sufficient padding to avoid intrusions by the
171/// operating system.
172///
173/// For example, this will indent the sliver by enough to avoid the status bar at the top of the
174/// screen.
175///
176/// It will also indent the sliver by the amount necessary to avoid The Notch on the iPhone X, or
177/// other similar creative physical features of the display.
178///
179/// When a [`minimum`](Self::minimum) padding is specified, the greater of the minimum padding or
180/// the safe area padding will be applied.
181///
182/// See also:
183///
184///  * [`SafeArea`], for insetting box widgets to avoid operating system intrusions.
185///  * [`SliverPadding`], for insetting slivers in general.
186///  * `MediaQuery`, from which the window padding is obtained.
187#[derive(Debug)]
188pub struct SliverSafeArea {
189    pub key: Option<KeyRef>,
190    /// Whether to avoid system intrusions on the left.
191    pub left: bool,
192    /// Whether to avoid system intrusions at the top of the screen, typically the system status
193    /// bar.
194    pub top: bool,
195    /// Whether to avoid system intrusions on the right.
196    pub right: bool,
197    /// Whether to avoid system intrusions on the bottom side of the screen.
198    pub bottom: bool,
199    /// This minimum padding to apply.
200    ///
201    /// The greater of the minimum padding and the media padding is be applied.
202    pub minimum: EdgeInsets,
203    /// The sliver below this sliver in the tree.
204    ///
205    /// The padding on the `MediaQuery` for the sliver will be suitably adjusted to zero out any
206    /// sides that were avoided by this sliver.
207    pub sliver: WidgetRef,
208}
209
210impl SliverSafeArea {
211    /// Creates a sliver that avoids operating system interfaces.
212    #[cfg_attr(debug_assertions, track_caller)]
213    pub fn new<K>(sliver: impl IntoWidget<K>) -> SliverSafeArea {
214        SliverSafeArea {
215            key: None,
216            left: true,
217            top: true,
218            right: true,
219            bottom: true,
220            minimum: EdgeInsets::ZERO,
221            sliver: sliver.into_widget(),
222        }
223    }
224
225    /// Dart `SliverSafeArea(key:)`.
226    pub fn key(mut self, key: KeyRef) -> SliverSafeArea {
227        self.key = Some(key);
228        self
229    }
230
231    /// Dart `SliverSafeArea(left:)`.
232    pub fn left(mut self, left: bool) -> SliverSafeArea {
233        self.left = left;
234        self
235    }
236
237    /// Dart `SliverSafeArea(top:)`.
238    pub fn top(mut self, top: bool) -> SliverSafeArea {
239        self.top = top;
240        self
241    }
242
243    /// Dart `SliverSafeArea(right:)`.
244    pub fn right(mut self, right: bool) -> SliverSafeArea {
245        self.right = right;
246        self
247    }
248
249    /// Dart `SliverSafeArea(bottom:)`.
250    pub fn bottom(mut self, bottom: bool) -> SliverSafeArea {
251        self.bottom = bottom;
252        self
253    }
254
255    /// Dart `SliverSafeArea(minimum:)`.
256    pub fn minimum(mut self, minimum: EdgeInsets) -> SliverSafeArea {
257        self.minimum = minimum;
258        self
259    }
260}
261
262impl StatelessWidget for SliverSafeArea {
263    fn key(&self) -> Option<&KeyRef> {
264        self.key.as_ref()
265    }
266
267    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
268        safe_area_flags(self.left, self.top, self.right, self.bottom, properties);
269    }
270
271    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
272        let padding = MediaQuery::padding_of(app, context);
273        let inset = |avoid: bool, padding: f64, minimum: f64| {
274            f64::max(if avoid { padding } else { 0.0 }, minimum)
275        };
276        let sliver = MediaQuery::remove_padding(
277            app,
278            context,
279            self.left,
280            self.top,
281            self.right,
282            self.bottom,
283            self.sliver.clone(),
284        )
285        .into_widget();
286        SliverPadding::new(EdgeInsetsGeometry::only(
287            inset(self.left, padding.left, self.minimum.left),
288            inset(self.top, padding.top, self.minimum.top),
289            inset(self.right, padding.right, self.minimum.right),
290            inset(self.bottom, padding.bottom, self.minimum.bottom),
291        ))
292        .sliver(sliver)
293        .into_widget()
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use std::cell::RefCell;
300    use std::rc::Rc;
301    use waft_foundation::AppCell;
302
303    use waft_rendering::RenderPadding;
304
305    use super::*;
306    use crate::test_harness::Harness;
307    use crate::widgets::basic::{Builder, SizedBox};
308    use crate::widgets::media_query::MediaQueryData;
309
310    fn padded(padding: EdgeInsets, view_padding: EdgeInsets, area: SafeArea) -> WidgetRef {
311        MediaQuery::new(
312            MediaQueryData::new()
313                .padding(padding)
314                .view_padding(view_padding),
315            area,
316        )
317        .into_widget()
318    }
319
320    fn render_padding(harness: &Harness, app: &App) -> EdgeInsetsGeometry {
321        harness
322            .render_root(app)
323            .child(app)
324            .expect("a child")
325            .as_object()
326            .downcast::<RenderPadding>(app)
327            .expect("a RenderPadding")
328            .padding(app)
329    }
330
331    #[test]
332    fn a_safe_area_pads_by_the_media_padding_it_avoids_and_removes_it_below() {
333        let cell = AppCell::new();
334        let mut app = cell.borrow_mut();
335        let seen = Rc::new(RefCell::new(None));
336        let probe = Builder::new({
337            let seen = Rc::clone(&seen);
338            move |app, context| {
339                *seen.borrow_mut() = Some(MediaQuery::padding_of(app, context));
340                SizedBox::shrink().into_widget()
341            }
342        });
343        let harness = Harness::mount(
344            &mut app,
345            padded(
346                EdgeInsets::only(10.0, 20.0, 30.0, 40.0),
347                EdgeInsets::ZERO,
348                SafeArea::new(probe)
349                    .left(false)
350                    .minimum(EdgeInsets::only(0.0, 0.0, 5.0, 45.0)),
351            ),
352        );
353        harness.pump(&mut app);
354        assert_eq!(
355            render_padding(&harness, &app),
356            EdgeInsetsGeometry::only(0.0, 20.0, 30.0, 45.0)
357        );
358        assert_eq!(
359            seen.borrow().clone(),
360            Some(EdgeInsets::only(10.0, 0.0, 0.0, 0.0))
361        );
362    }
363
364    #[test]
365    fn maintaining_the_bottom_view_padding_uses_it_instead_of_the_consumed_padding() {
366        let cell = AppCell::new();
367        let mut app = cell.borrow_mut();
368        let harness = Harness::mount(
369            &mut app,
370            padded(
371                EdgeInsets::only(0.0, 0.0, 0.0, 0.0),
372                EdgeInsets::only(0.0, 0.0, 0.0, 34.0),
373                SafeArea::new(SizedBox::shrink()).maintain_bottom_view_padding(true),
374            ),
375        );
376        harness.pump(&mut app);
377        assert_eq!(
378            render_padding(&harness, &app),
379            EdgeInsetsGeometry::only(0.0, 0.0, 0.0, 34.0)
380        );
381    }
382    /// A `SliverSafeArea` pads its sliver by the media padding it avoids, and removes that
383    /// padding for its subtree.
384    #[test]
385    fn a_sliver_safe_area_pads_by_the_media_padding_it_avoids() {
386        use waft_embedder::TextDirection;
387        use waft_rendering::{
388            ContainerRenderObjectMixin, FixedViewportOffset, RenderSliverPadding, RenderViewport,
389        };
390
391        use crate::widgets::basic::{Directionality, SliverToBoxAdapter};
392        use crate::widgets::viewport::Viewport;
393
394        let cell = AppCell::new();
395        let mut app = cell.borrow_mut();
396        let offset = FixedViewportOffset::zero(&mut app);
397        let area =
398            SliverSafeArea::new(SliverToBoxAdapter::new().child(SizedBox::new().height(50.0)))
399                .left(false)
400                .minimum(EdgeInsets::only(0.0, 0.0, 5.0, 45.0));
401        let tree = Directionality::new(
402            TextDirection::Ltr,
403            MediaQuery::new(
404                MediaQueryData::new().padding(EdgeInsets::only(10.0, 20.0, 30.0, 40.0)),
405                Viewport::new(offset.erase()).slivers(vec![area.into_widget()]),
406            )
407            .into_widget(),
408        )
409        .into_widget();
410        let harness = Harness::mount(&mut app, tree);
411        harness.pump(&mut app);
412
413        let padding = harness
414            .render_root(&app)
415            .child(&app)
416            .expect("a child")
417            .as_object()
418            .downcast::<RenderViewport>(&app)
419            .expect("a RenderViewport")
420            .first_child(&app)
421            .expect("the padding")
422            .as_object()
423            .downcast::<RenderSliverPadding>(&app)
424            .expect("a RenderSliverPadding");
425        assert_eq!(
426            padding.padding(&app),
427            EdgeInsetsGeometry::only(0.0, 20.0, 30.0, 45.0)
428        );
429    }
430}