Skip to main content

waft_widgets/widgets/
preferred_size.rs

1//! Flutter `widgets/preferred_size.dart` (+ the `Size` subclass mechanism a preferred size
2//! travels in).
3
4use std::any::Any;
5use std::fmt::{self, Debug};
6use std::ops::Deref;
7use std::rc::Rc;
8
9use waft_embedder::Size;
10use waft_foundation::App;
11
12use crate::framework::{
13    BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef, downcast_widget,
14};
15
16/// What a subclass of `Size` adds to its value.
17///
18/// Flutter's `_PreferredAppBarSize extends Size` travels wherever a preferred size is
19/// stored, to be recognised later by an `is` check (`AppBar.preferredHeightFor`). Here the
20/// engine's [`Size`] is a plain value; a subclass is an extension that an [`AnySize`] carries
21/// beside the value the subclass constructor passed to `super`, as `AnyColor` carries a
22/// `Color` subclass.
23///
24/// Unlike `ColorExtension`, there is no `==` to override: dart:ui's `Size.==` compares the
25/// values only, without the runtime type, and no framework subclass overrides it.
26pub trait SizeExtension: Any {
27    /// The extension as `Any`, for Dart's `is` checks ([`AnySize::extension`]).
28    fn as_any(&self) -> &dyn Any;
29}
30
31/// A `Size` that may be an instance of a `Size` subclass.
32///
33/// The framework stores this where Flutter stores a `Size` that a later reader type-checks:
34/// [`PreferredSizeWidget::preferred_size`] and [`PreferredSize`]'s field. The plain value is
35/// the one the subclass passed to `super`, reached by [`size`](Self::size) or by deref; the
36/// subclass is recovered with [`extension`](Self::extension), Dart's `is` check.
37///
38/// Equality follows dart:ui's `Size.==`: the values alone, so a subclass instance equals a
39/// plain size of the same width and height.
40#[derive(Clone)]
41pub struct AnySize {
42    size: Size,
43    extension: Option<Rc<dyn SizeExtension>>,
44}
45
46impl AnySize {
47    /// A plain size.
48    pub const fn new(size: Size) -> AnySize {
49        AnySize {
50            size,
51            extension: None,
52        }
53    }
54
55    /// A subclass instance: `size` is what it passed to `super`.
56    pub fn with_shared(size: Size, extension: Rc<dyn SizeExtension>) -> AnySize {
57        AnySize {
58            size,
59            extension: Some(extension),
60        }
61    }
62
63    /// The size as the engine sees it: the subclass's `super` value.
64    pub fn size(&self) -> Size {
65        self.size
66    }
67
68    /// Dart's `size is T`: the subclass instance, if this size is one.
69    pub fn extension<T: SizeExtension>(&self) -> Option<&T> {
70        self.extension
71            .as_ref()
72            .and_then(|extension| extension.as_any().downcast_ref::<T>())
73    }
74
75    /// Whether this size is a subclass instance.
76    pub fn has_extension(&self) -> bool {
77        self.extension.is_some()
78    }
79}
80
81impl Deref for AnySize {
82    type Target = Size;
83
84    fn deref(&self) -> &Size {
85        &self.size
86    }
87}
88
89impl From<Size> for AnySize {
90    fn from(size: Size) -> AnySize {
91        AnySize::new(size)
92    }
93}
94
95impl PartialEq for AnySize {
96    fn eq(&self, other: &AnySize) -> bool {
97        self.size == other.size
98    }
99}
100
101impl PartialEq<Size> for AnySize {
102    fn eq(&self, other: &Size) -> bool {
103        self.size == *other
104    }
105}
106
107/// A subclass prints as its `Size`: no framework subclass overrides `toString`.
108impl Debug for AnySize {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        Debug::fmt(&self.size, f)
111    }
112}
113
114/// An interface for widgets that can return the size this widget would prefer
115/// if it were otherwise unconstrained.
116///
117/// There are a few cases, notably `AppBar` and `TabBar`, where it would be
118/// undesirable for the widget to constrain its own size but where the widget
119/// needs to expose a preferred or "default" size. For example a primary
120/// `Scaffold` sets its app bar height to the app bar's preferred height
121/// plus the height of the system status bar.
122///
123/// Widgets that need to know the preferred size of their child can require
124/// that their child implement this interface by using this class rather
125/// than `Widget` as the type of their `child` property: the field holds a
126/// [`PreferredSizeWidgetRef`].
127///
128/// Use [`PreferredSize`] to give a preferred size to an arbitrary widget.
129pub trait PreferredSizeWidget: 'static {
130    /// The size this widget would prefer if it were otherwise unconstrained.
131    ///
132    /// In many cases it's only necessary to define one preferred dimension.
133    /// For example the `Scaffold` only depends on its app bar's preferred
134    /// height. In that case implementations of this method can just return
135    /// `Size::from_height(my_app_bar_height).into()`.
136    fn preferred_size(&self) -> AnySize;
137}
138
139/// A [`PreferredSizeWidget`] held as a value: the erased widget, whose preferred size is
140/// still answered by the widget it holds. Dart types such a field `PreferredSizeWidget`.
141#[derive(Clone)]
142pub struct PreferredSizeWidgetRef {
143    widget: WidgetRef,
144    preferred_size: fn(&WidgetRef) -> AnySize,
145}
146
147impl PreferredSizeWidgetRef {
148    /// Erases `widget`.
149    #[cfg_attr(debug_assertions, track_caller)]
150    pub fn new<K, W: PreferredSizeWidget + IntoWidget<K>>(widget: W) -> PreferredSizeWidgetRef {
151        PreferredSizeWidgetRef {
152            widget: widget.into_widget(),
153            preferred_size: |widget| {
154                downcast_widget::<W>(&**widget)
155                    .expect("an erased widget keeps its type")
156                    .preferred_size()
157            },
158        }
159    }
160
161    /// See [`PreferredSizeWidget::preferred_size`].
162    pub fn preferred_size(&self) -> AnySize {
163        (self.preferred_size)(&self.widget)
164    }
165
166    /// The widget itself.
167    pub fn widget(&self) -> &WidgetRef {
168        &self.widget
169    }
170}
171
172impl Debug for PreferredSizeWidgetRef {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        Debug::fmt(&self.widget, f)
175    }
176}
177
178/// The kind tag of [`IntoWidget`] for a [`PreferredSizeWidgetRef`].
179pub struct PreferredSizeWidgetRefKind;
180
181impl IntoWidget<PreferredSizeWidgetRefKind> for PreferredSizeWidgetRef {
182    #[cfg_attr(debug_assertions, track_caller)]
183    fn into_widget(self) -> WidgetRef {
184        self.widget
185    }
186}
187
188/// A widget with a preferred size.
189///
190/// This widget does not impose any constraints on its child, and it doesn't
191/// affect the child's layout in any way. It just advertises a preferred size
192/// which can be used by the parent.
193///
194/// Parents like `Scaffold` use [`PreferredSizeWidget`] to require that their
195/// children implement that interface. To give a preferred size to an arbitrary
196/// widget so that it can be used in a `child` property of that type, this
197/// widget, [`PreferredSize`], can be used.
198///
199/// Widgets like `AppBar` implement a [`PreferredSizeWidget`], so that this
200/// [`PreferredSize`] widget is not necessary for them.
201///
202/// See also:
203///
204///  * `AppBar.bottom` and `Scaffold.appBar`, which require preferred size widgets.
205///  * [`PreferredSizeWidget`], the interface which this widget implements to expose
206///    its preferred size.
207///  * `AppBar` and `TabBar`, which implement PreferredSizeWidget.
208#[derive(Debug)]
209pub struct PreferredSize {
210    key: Option<KeyRef>,
211    /// The widget below this widget in the tree.
212    child: WidgetRef,
213    preferred_size: AnySize,
214}
215
216impl PreferredSize {
217    /// Creates a widget that has a preferred size that the parent can query.
218    #[cfg_attr(debug_assertions, track_caller)]
219    pub fn new<K>(preferred_size: impl Into<AnySize>, child: impl IntoWidget<K>) -> PreferredSize {
220        PreferredSize {
221            key: None,
222            child: child.into_widget(),
223            preferred_size: preferred_size.into(),
224        }
225    }
226
227    /// Dart `PreferredSize(key:)`.
228    pub fn key(mut self, key: KeyRef) -> PreferredSize {
229        self.key = Some(key);
230        self
231    }
232}
233
234impl PreferredSizeWidget for PreferredSize {
235    fn preferred_size(&self) -> AnySize {
236        self.preferred_size.clone()
237    }
238}
239
240impl StatelessWidget for PreferredSize {
241    fn key(&self) -> Option<&KeyRef> {
242        self.key.as_ref()
243    }
244
245    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
246        Some(self)
247    }
248
249    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
250        self.child.clone()
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use waft_foundation::AppCell;
257    use waft_rendering::RenderConstrainedBox;
258
259    use super::*;
260    use crate::test_harness::Harness;
261    use crate::widgets::basic::SizedBox;
262
263    #[derive(Debug, PartialEq)]
264    struct TaggedSize {
265        tag: u32,
266    }
267
268    impl SizeExtension for TaggedSize {
269        fn as_any(&self) -> &dyn Any {
270            self
271        }
272    }
273
274    #[test]
275    fn a_preferred_size_keeps_the_subclass_it_was_given() {
276        let tagged = AnySize::with_shared(Size::from_height(56.0), Rc::new(TaggedSize { tag: 7 }));
277        let bar = PreferredSizeWidgetRef::new(PreferredSize::new(tagged, SizedBox::shrink()));
278        assert_eq!(
279            bar.preferred_size().extension::<TaggedSize>(),
280            Some(&TaggedSize { tag: 7 })
281        );
282        assert!(
283            PreferredSize::new(Size::from_height(56.0), SizedBox::shrink())
284                .preferred_size()
285                .extension::<TaggedSize>()
286                .is_none()
287        );
288    }
289
290    #[test]
291    fn a_subclass_size_equals_a_plain_size_of_the_same_value_as_dart_ui_compares_sizes() {
292        let tagged = AnySize::with_shared(Size::from_height(56.0), Rc::new(TaggedSize { tag: 7 }));
293        assert_eq!(tagged, AnySize::new(Size::from_height(56.0)));
294        assert_eq!(tagged, Size::from_height(56.0));
295        assert_ne!(tagged, Size::from_height(64.0));
296    }
297
298    #[test]
299    fn an_erased_preferred_size_widget_still_answers_its_size_and_builds_its_child() {
300        let bar = PreferredSizeWidgetRef::new(PreferredSize::new(
301            Size::from_height(80.0),
302            SizedBox::shrink(),
303        ));
304        assert_eq!(bar.preferred_size(), Size::from_height(80.0));
305
306        let cell = AppCell::new();
307        let mut app = cell.borrow_mut();
308        let harness = Harness::mount(&mut app, bar.into_widget());
309        harness.pump(&mut app);
310        assert!(
311            harness
312                .render_root(&app)
313                .child(&app)
314                .expect("the child")
315                .as_object()
316                .downcast::<RenderConstrainedBox>(&app)
317                .is_some()
318        );
319    }
320}