Skip to main content

waft_widgets/widgets/
placeholder.rs

1//! Flutter `widgets/placeholder.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug};
5
6use waft_embedder::valo::FillRule;
7use waft_embedder::{Canvas, Color, Offset, Paint, PaintStyle, PathBuilder, Size, Stroke};
8use waft_foundation::{App, DiagnosticPropertiesBuilder, DoubleProperty};
9use waft_painting::ColorProperty;
10use waft_rendering::CustomPainter;
11
12use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
13use crate::widgets::basic::{CustomPaint, LimitedBox};
14
15struct PlaceholderPainter {
16    color: Color,
17    stroke_width: f64,
18}
19
20impl CustomPainter for PlaceholderPainter {
21    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
22        let paint = Paint {
23            color: self.color.into(),
24            style: PaintStyle::Stroke(Stroke::new(self.stroke_width as f32)),
25            ..Paint::default()
26        };
27        let rect = Offset::ZERO & size;
28        let mut path = PathBuilder::new();
29        path.rect(rect.into());
30        path.move_to(rect.top_right());
31        path.line_to(rect.bottom_left());
32        path.move_to(rect.top_left());
33        path.line_to(rect.bottom_right());
34        canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
35    }
36
37    fn should_repaint(&self, _app: &App, old_painter: &dyn CustomPainter) -> bool {
38        let Some(old_painter) = old_painter.as_any().downcast_ref::<PlaceholderPainter>() else {
39            return true;
40        };
41        old_painter.color != self.color || old_painter.stroke_width != self.stroke_width
42    }
43
44    fn hit_test(&self, _app: &App, _position: Offset) -> Option<bool> {
45        Some(false)
46    }
47
48    fn as_any(&self) -> &dyn Any {
49        self
50    }
51}
52
53/// A widget that draws a box that represents where other widgets will one day be added.
54///
55/// This widget is useful during development to indicate that the interface is not yet
56/// complete.
57///
58/// By default, the placeholder is sized to fit its container. If the placeholder is in an
59/// unbounded space, it will size itself according to the given
60/// [`fallback_width`](Self::fallback_width) and [`fallback_height`](Self::fallback_height).
61pub struct Placeholder {
62    pub key: Option<KeyRef>,
63    /// The color to draw the placeholder box.
64    pub color: Color,
65    /// The width of the lines in the placeholder box.
66    pub stroke_width: f64,
67    /// The width to use when the placeholder is in a situation with an unbounded width.
68    ///
69    /// See also:
70    ///
71    ///  * [`fallback_height`](Self::fallback_height), the same but vertically.
72    pub fallback_width: f64,
73    /// The height to use when the placeholder is in a situation with an unbounded height.
74    ///
75    /// See also:
76    ///
77    ///  * [`fallback_width`](Self::fallback_width), the same but horizontally.
78    pub fallback_height: f64,
79    /// The widget below this widget in the tree.
80    ///
81    /// The placeholder is drawn below the child, so the child stays visible.
82    pub child: Option<WidgetRef>,
83}
84
85impl Placeholder {
86    /// Creates a widget which draws a box.
87    pub fn new() -> Placeholder {
88        Placeholder::default()
89    }
90
91    /// Dart `Placeholder(key:)`.
92    pub fn key(mut self, key: KeyRef) -> Placeholder {
93        self.key = Some(key);
94        self
95    }
96
97    /// Dart `Placeholder(color:)`.
98    pub fn color(mut self, color: Color) -> Placeholder {
99        self.color = color;
100        self
101    }
102
103    /// Dart `Placeholder(strokeWidth:)`.
104    pub fn stroke_width(mut self, stroke_width: f64) -> Placeholder {
105        self.stroke_width = stroke_width;
106        self
107    }
108
109    /// Dart `Placeholder(fallbackWidth:)`.
110    pub fn fallback_width(mut self, fallback_width: f64) -> Placeholder {
111        self.fallback_width = fallback_width;
112        self
113    }
114
115    /// Dart `Placeholder(fallbackHeight:)`.
116    pub fn fallback_height(mut self, fallback_height: f64) -> Placeholder {
117        self.fallback_height = fallback_height;
118        self
119    }
120
121    /// Dart `Placeholder(child:)`.
122    #[cfg_attr(debug_assertions, track_caller)]
123    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Placeholder {
124        self.child = Some(child.into_widget());
125        self
126    }
127}
128
129impl Default for Placeholder {
130    fn default() -> Placeholder {
131        Placeholder {
132            key: None,
133            color: Color::new(0xFF455A64), // Blue Grey 700
134            stroke_width: 2.0,
135            fallback_width: 400.0,
136            fallback_height: 400.0,
137            child: None,
138        }
139    }
140}
141
142impl StatelessWidget for Placeholder {
143    fn key(&self) -> Option<&KeyRef> {
144        self.key.as_ref()
145    }
146
147    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
148        properties.add(
149            ColorProperty::new("color", self.color)
150                .default_value(Some(waft_embedder::Color::new(0xFF455A64))),
151        );
152        properties
153            .add(DoubleProperty::new("strokeWidth", self.stroke_width).default_value(Some(2.0)));
154        properties.add(
155            DoubleProperty::new("fallbackWidth", self.fallback_width).default_value(Some(400.0)),
156        );
157        properties.add(
158            DoubleProperty::new("fallbackHeight", self.fallback_height).default_value(Some(400.0)),
159        );
160    }
161
162    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
163        let mut custom_paint =
164            CustomPaint::new()
165                .size(Size::INFINITE)
166                .painter(PlaceholderPainter {
167                    color: self.color,
168                    stroke_width: self.stroke_width,
169                });
170        if let Some(child) = &self.child {
171            custom_paint = custom_paint.child(child.clone());
172        }
173        LimitedBox::new()
174            .max_width(self.fallback_width)
175            .max_height(self.fallback_height)
176            .child(custom_paint)
177            .into_widget()
178    }
179}
180
181impl Debug for Placeholder {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        f.debug_struct("Placeholder")
184            .field("color", &self.color)
185            .field("stroke_width", &self.stroke_width)
186            .field("fallback_width", &self.fallback_width)
187            .field("fallback_height", &self.fallback_height)
188            .finish()
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use waft_embedder::TextDirection;
195    use waft_embedder::valo::Op;
196    use waft_rendering::{
197        RenderBox, RenderCustomPaint, RenderLimitedBox, RenderObjectWithChildMixin,
198    };
199
200    use super::*;
201    use crate::framework::GlobalKey;
202    use crate::testing::{WidgetTester, test_widgets};
203    use crate::widgets::basic::{Center, Directionality, Positioned, SizedBox, Stack};
204    use crate::widgets::text::Text;
205
206    /// The `drawPath` calls of the placeholder's painter at its size: Dart's `paints..path()`.
207    fn painted_paths(tester: &WidgetTester, key: &GlobalKey) -> Vec<Paint> {
208        let render = tester.render_object(key);
209        let mut app = tester.cell.borrow_mut();
210        let custom_paint = render
211            .downcast::<RenderLimitedBox>(&app)
212            .and_then(|limited_box| limited_box.child(&app))
213            .and_then(|child| child.as_object().downcast::<RenderCustomPaint>(&app))
214            .expect("the placeholder's custom paint");
215        let size = custom_paint.size(&app);
216        let painter = custom_paint.painter(&app).expect("the placeholder painter");
217        let mut canvas = Canvas::new();
218        painter.paint(&mut app, &mut canvas, size);
219        canvas
220            .build()
221            .ops()
222            .iter()
223            .filter_map(|op| match op {
224                Op::DrawPath { paint, .. } => Some(paint.clone()),
225                _ => None,
226            })
227            .collect()
228    }
229
230    fn keyed_placeholder(key: &GlobalKey) -> Placeholder {
231        Placeholder::new().key(key.clone().into())
232    }
233
234    #[test]
235    fn placeholder() {
236        test_widgets(|tester| {
237            let key = GlobalKey::new();
238            tester.pump_widget(keyed_placeholder(&key));
239            assert_eq!(tester.get_size(&key), Size::new(800.0, 600.0));
240            tester.pump_widget(Center::new().child(keyed_placeholder(&key)));
241            assert_eq!(tester.get_size(&key), Size::new(800.0, 600.0));
242            tester.pump_widget(
243                Stack::new()
244                    .text_direction(TextDirection::Ltr)
245                    .children([Positioned::new(keyed_placeholder(&key))
246                        .top(0.0)
247                        .bottom(0.0)
248                        .into_widget()]),
249            );
250            assert_eq!(tester.get_size(&key), Size::new(400.0, 600.0));
251            tester.pump_widget(
252                Stack::new()
253                    .text_direction(TextDirection::Ltr)
254                    .children([Positioned::new(keyed_placeholder(&key))
255                        .left(0.0)
256                        .right(0.0)
257                        .into_widget()]),
258            );
259            assert_eq!(tester.get_size(&key), Size::new(800.0, 400.0));
260            tester.pump_widget(
261                Stack::new()
262                    .text_direction(TextDirection::Ltr)
263                    .children([Positioned::new(
264                        keyed_placeholder(&key)
265                            .fallback_width(200.0)
266                            .fallback_height(300.0),
267                    )
268                    .top(0.0)
269                    .into_widget()]),
270            );
271            assert_eq!(tester.get_size(&key), Size::new(200.0, 300.0));
272        });
273    }
274
275    #[test]
276    fn placeholder_color() {
277        test_widgets(|tester| {
278            let key = GlobalKey::new();
279            tester.pump_widget(keyed_placeholder(&key));
280            let paths = painted_paths(tester, &key);
281            assert_eq!(paths.len(), 1);
282            assert_eq!(paths[0].color, Color::new(0xFF455A64).into());
283            tester.pump_widget(keyed_placeholder(&key).color(Color::new(0xFF00FF00)));
284            assert_eq!(
285                painted_paths(tester, &key)[0].color,
286                Color::new(0xFF00FF00).into()
287            );
288        });
289    }
290
291    #[test]
292    fn placeholder_stroke_width() {
293        let stroke_width = |paint: &Paint| match &paint.style {
294            PaintStyle::Stroke(stroke) => Some(stroke.width),
295            PaintStyle::Fill => None,
296        };
297        test_widgets(|tester| {
298            let key = GlobalKey::new();
299            tester.pump_widget(keyed_placeholder(&key));
300            assert_eq!(stroke_width(&painted_paths(tester, &key)[0]), Some(2.0));
301            tester.pump_widget(keyed_placeholder(&key).stroke_width(10.0));
302            assert_eq!(stroke_width(&painted_paths(tester, &key)[0]), Some(10.0));
303        });
304    }
305
306    #[test]
307    fn placeholder_child_widget() {
308        test_widgets(|tester| {
309            let key = GlobalKey::new();
310            let label = GlobalKey::new();
311            tester.pump_widget(keyed_placeholder(&key));
312            assert!(label.current_context(&tester.cell.borrow()).is_none());
313            tester.pump_widget(keyed_placeholder(&key).child(Directionality::new(
314                TextDirection::Ltr,
315                Text::new("Label").key(label.clone().into()),
316            )));
317            assert!(label.current_context(&tester.cell.borrow()).is_some());
318        });
319    }
320
321    #[test]
322    fn placeholder_does_not_crash_at_zero_area() {
323        test_widgets(|tester| {
324            let key = GlobalKey::new();
325            tester.pump_widget(Directionality::new(
326                TextDirection::Ltr,
327                Center::new().child(SizedBox::shrink().child(keyed_placeholder(&key))),
328            ));
329            assert_eq!(tester.get_size(&key), Size::ZERO);
330        });
331    }
332}