Skip to main content

waft_widgets/widgets/
container.rs

1//! Flutter counterpart: `widgets/container.dart`.
2//!
3//! [`Container`]'s `clipBehavior` step and its `_DecorationClipper` wait on `ClipPath`.
4
5use std::any::Any;
6use std::rc::Rc;
7use waft_embedder::{Clip, Matrix4, Offset, Path, Size, TextDirection};
8use waft_foundation::{
9    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsProperty, EnumProperty,
10    ObjectFlagProperty,
11};
12use waft_painting::{AlignmentGeometry, AnyColor, DecorationRef, EdgeInsetsGeometry};
13use waft_rendering::{
14    AnyRenderObject, BoxConstraints, Constraints, CustomClipper, DecorationPosition, RenderBox,
15    RenderDecoratedBox, RenderHandle,
16};
17
18use crate::framework::{
19    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget,
20    StatelessWidget, WidgetRef,
21};
22use crate::widgets::basic::{
23    Align, ClipPath, ColoredBox, ConstrainedBox, Directionality, LimitedBox, Padding, Transform,
24};
25use crate::widgets::image::create_local_image_configuration;
26
27/// A widget that paints a [`Decoration`] either before or after its child paints.
28///
29/// `Container` insets its child by the widths of the borders; this widget does
30/// not.
31///
32/// Commonly used with `BoxDecoration`.
33///
34/// The [`child`](Self::child) is not clipped. To clip a child to the shape of a particular
35/// `ShapeDecoration`, consider using a `ClipPath` widget.
36///
37/// This sample shows a radial gradient that draws a moon on a night sky:
38///
39/// ```text
40/// DecoratedBox {
41///   decoration: Box::new(BoxDecoration::new().gradient(RadialGradient { .. })),
42///   ..
43/// }
44/// ```
45///
46/// See also:
47///
48///  * `Ink`, which paints a [`Decoration`] on a `Material`, allowing
49///    `InkResponse` and `InkWell` splashes to paint over them.
50///  * `DecoratedSliver`, which applies a [`Decoration`] to a sliver.
51///  * `DecoratedBoxTransition`, the version of this class that animates on the
52///    [`decoration`](Self::decoration).
53///  * [`Decoration`], which you can extend to provide other effects with
54///    [`DecoratedBox`].
55///  * `CustomPaint`, another way to draw custom effects from the widget layer.
56///
57/// Flutter home: `widgets/container.dart`.
58#[derive(Debug)]
59pub struct DecoratedBox {
60    pub key: Option<KeyRef>,
61    /// What decoration to paint.
62    ///
63    /// Commonly a `BoxDecoration`.
64    pub decoration: DecorationRef,
65    /// Whether to paint the box decoration behind or in front of the child.
66    ///
67    /// By default the decoration paints behind the child.
68    pub position: DecorationPosition,
69    pub child: Option<WidgetRef>,
70}
71
72impl DecoratedBox {
73    /// Creates a `DecoratedBox`; Dart's optional named arguments are the setters.
74    pub fn new(decoration: impl Into<DecorationRef>) -> DecoratedBox {
75        DecoratedBox {
76            key: None,
77            decoration: decoration.into(),
78            position: DecorationPosition::Background,
79            child: None,
80        }
81    }
82
83    /// Dart `DecoratedBox(key:)`.
84    pub fn key(mut self, key: KeyRef) -> DecoratedBox {
85        self.key = Some(key);
86        self
87    }
88
89    /// Dart `DecoratedBox(position:)`.
90    pub fn position(mut self, position: DecorationPosition) -> DecoratedBox {
91        self.position = position;
92        self
93    }
94
95    /// Dart `DecoratedBox(child:)`.
96    #[cfg_attr(debug_assertions, track_caller)]
97    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> DecoratedBox {
98        self.child = Some(child.into_widget());
99        self
100    }
101}
102
103impl RenderObjectWidget for DecoratedBox {
104    type RenderObject = RenderDecoratedBox;
105
106    fn key(&self) -> Option<&KeyRef> {
107        self.key.as_ref()
108    }
109
110    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
111        let label = match self.position {
112            DecorationPosition::Background => "bg",
113            DecorationPosition::Foreground => "fg",
114        };
115        properties
116            .add(EnumProperty::new("position", self.position).with_level(DiagnosticLevel::Hidden));
117        properties.add(DiagnosticsProperty::<String>::new(
118            label,
119            Some(format!("{:?}", self.decoration)),
120        ));
121    }
122
123    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
124        let configuration = create_local_image_configuration(app, context, None);
125        RenderDecoratedBox::new(
126            app,
127            self.decoration.clone(),
128            self.position,
129            configuration,
130            None,
131        )
132        .as_object()
133    }
134
135    fn update_render_object(
136        &self,
137        app: &mut App,
138        context: BuildContext,
139        render_object: RenderHandle<RenderDecoratedBox>,
140    ) {
141        render_object.set_decoration(app, self.decoration.clone());
142        let configuration = create_local_image_configuration(app, context, None);
143        render_object.set_configuration(app, configuration);
144        render_object.set_position(app, self.position);
145    }
146}
147
148impl SingleChildRenderObjectWidget for DecoratedBox {
149    fn child(&self) -> Option<&WidgetRef> {
150        self.child.as_ref()
151    }
152}
153
154/// A convenience widget that combines common painting, positioning, and sizing
155/// widgets.
156///
157/// A container first surrounds the child with [`padding`](Self::padding) (inflated by any
158/// borders present in the [`decoration`](Self::decoration)) and then applies additional
159/// [`constraints`](Self::constraints) to the padded extent (incorporating the
160/// [`width`](Self::width) and [`height`](Self::height) as constraints, if either is set). The
161/// container is then surrounded by additional empty space described from the
162/// [`margin`](Self::margin).
163///
164/// During painting, the container first applies the given [`transform`](Self::transform), then
165/// paints the [`decoration`](Self::decoration) to fill the padded extent, then it paints the
166/// child, and finally paints the [`foreground_decoration`](Self::foreground_decoration), also
167/// filling the padded extent.
168///
169/// Containers with no children try to be as big as possible unless the incoming
170/// constraints are unbounded, in which case they try to be as small as
171/// possible. Containers with children size themselves to their children. The
172/// [`width`](Self::width), [`height`](Self::height), and [`constraints`](Self::constraints)
173/// arguments to the constructor override this.
174///
175/// By default, containers return false for all hit tests. If the [`color`](Self::color)
176/// property is specified, the hit testing is handled by [`ColoredBox`], which
177/// always returns true. If the [`decoration`](Self::decoration) or
178/// [`foreground_decoration`](Self::foreground_decoration) properties are specified, hit
179/// testing is handled by `Decoration::hit_test`.
180///
181/// ## Layout behavior
182///
183/// _See [`BoxConstraints`] for an introduction to box layout models._
184///
185/// Since [`Container`] combines a number of other widgets each with their own
186/// layout behavior, [`Container`]'s layout behavior is somewhat complicated.
187///
188/// Summary: [`Container`] tries, in order: to honor [`alignment`](Self::alignment), to size
189/// itself to the [`child`](Self::child), to honor the [`width`](Self::width),
190/// [`height`](Self::height), and [`constraints`](Self::constraints), to expand to fit the
191/// parent, to be as small as possible.
192///
193/// More specifically:
194///
195/// If the widget has no child, no height, no width, no [`constraints`](Self::constraints),
196/// and the parent provides unbounded constraints, then [`Container`] tries to
197/// size as small as possible.
198///
199/// If the widget has no child and no [`alignment`](Self::alignment), but a height, width, or
200/// [`constraints`](Self::constraints) are provided, then the [`Container`] tries to be as
201/// small as possible given the combination of those constraints and the parent's constraints.
202///
203/// If the widget has no child, no height, no width, no [`constraints`](Self::constraints), and
204/// no [`alignment`](Self::alignment), but the parent provides bounded constraints, then
205/// [`Container`] expands to fit the constraints provided by the parent.
206///
207/// If the widget has an [`alignment`](Self::alignment), and the parent provides unbounded
208/// constraints, then the [`Container`] tries to size itself around the child.
209///
210/// If the widget has an [`alignment`](Self::alignment), and the parent provides bounded
211/// constraints, then the [`Container`] tries to expand to fit the parent, and
212/// then positions the child within itself as per the [`alignment`](Self::alignment).
213///
214/// Otherwise, the widget has a [`child`](Self::child) but no height, no width, no
215/// [`constraints`](Self::constraints), and no [`alignment`](Self::alignment), and the
216/// [`Container`] passes the constraints from the parent to the child and sizes itself to match
217/// the child.
218///
219/// The [`margin`](Self::margin) and [`padding`](Self::padding) properties also affect the
220/// layout, as described in the documentation for those properties. (Their effects merely
221/// augment the rules described above.) The [`decoration`](Self::decoration) can implicitly
222/// increase the [`padding`](Self::padding) (e.g. borders in a `BoxDecoration` contribute to
223/// the [`padding`](Self::padding)); see `Decoration::padding`.
224///
225/// ## Example
226///
227/// This example shows a 48x48 amber square (placed inside a [`Center`](crate::Center) widget
228/// in case the parent widget has its own opinions regarding the size that the [`Container`]
229/// should take), with a margin so that it stays away from neighboring widgets:
230///
231/// ```text
232/// Center::new().child(
233///     Container::new()
234///         .margin(EdgeInsetsGeometry::all(10.0))
235///         .color(AMBER_600)
236///         .width(48.0)
237///         .height(48.0),
238/// )
239/// ```
240///
241/// See also:
242///
243///  * `AnimatedContainer`, a variant that smoothly animates the properties when
244///    they change.
245///  * `Border`, which has a sample which uses [`Container`] heavily.
246///  * `Ink`, which paints a [`Decoration`] on a `Material`, allowing
247///    `InkResponse` and `InkWell` splashes to paint over them.
248///  * The [catalog of layout widgets](https://docs.flutter.dev/ui/widgets/layout).
249///
250/// Flutter's `clipBehavior` waits on `ClipPath`.
251#[derive(Debug)]
252pub struct Container {
253    pub key: Option<KeyRef>,
254    /// Align the [`child`](Self::child) within the container.
255    ///
256    /// If non-`None`, the container will expand to fill its parent and position its
257    /// child within itself according to the given value. If the incoming
258    /// constraints are unbounded, then the child will be shrink-wrapped instead.
259    ///
260    /// Ignored if [`child`](Self::child) is `None`.
261    ///
262    /// See also:
263    ///
264    ///  * `Alignment`, a class with convenient constants typically used to
265    ///    specify an [`AlignmentGeometry`].
266    ///  * `AlignmentDirectional`, like `Alignment` for specifying alignments
267    ///    relative to text direction.
268    pub alignment: Option<AlignmentGeometry>,
269    /// Empty space to inscribe inside the [`decoration`](Self::decoration). The
270    /// [`child`](Self::child), if any, is placed inside this padding.
271    ///
272    /// This padding is in addition to any padding inherent in the
273    /// [`decoration`](Self::decoration); see `Decoration::padding`.
274    pub padding: Option<EdgeInsetsGeometry>,
275    /// The color to paint behind the [`child`](Self::child).
276    ///
277    /// This property should be preferred when the background is a simple color.
278    /// For other cases, such as gradients or images, use the
279    /// [`decoration`](Self::decoration) property.
280    ///
281    /// If the [`decoration`](Self::decoration) is used, this property must be `None`. A
282    /// background color may still be painted by the [`decoration`](Self::decoration) even if
283    /// this property is `None`.
284    pub color: Option<AnyColor>,
285    /// See [`ColoredBox::is_anti_alias`].
286    pub is_anti_alias: bool,
287    /// The decoration to paint behind the [`child`](Self::child).
288    ///
289    /// Use the [`color`](Self::color) property to specify a simple solid color.
290    ///
291    /// The [`child`](Self::child) is not clipped to the decoration. To clip a child to the
292    /// shape of a particular `ShapeDecoration`, consider using a `ClipPath` widget.
293    pub decoration: Option<DecorationRef>,
294    /// The decoration to paint in front of the [`child`](Self::child).
295    pub foreground_decoration: Option<DecorationRef>,
296    /// Additional constraints to apply to the child.
297    ///
298    /// The [`width`](Self::width) and [`height`](Self::height) setters are combined with the
299    /// given constraints: this is Dart's folded field.
300    ///
301    /// The [`padding`](Self::padding) goes inside the constraints.
302    pub constraints: Option<BoxConstraints>,
303    given_constraints: Option<BoxConstraints>,
304    width: Option<f64>,
305    height: Option<f64>,
306    /// Empty space to surround the [`decoration`](Self::decoration) and [`child`](Self::child).
307    pub margin: Option<EdgeInsetsGeometry>,
308    /// The clip behavior when [`decoration`](Self::decoration) is not `None`.
309    ///
310    /// Defaults to [`Clip::None`]. Must be [`Clip::None`] if
311    /// [`decoration`](Self::decoration) is `None`.
312    ///
313    /// If a clip is to be applied, the `Decoration::get_clip_path` method
314    /// for the provided decoration must return a clip path. (This is not
315    /// supported by all decorations; the default implementation of that
316    /// method throws an `UnsupportedError`.)
317    pub clip_behavior: Clip,
318    /// The transformation matrix to apply before painting the container.
319    pub transform: Option<Matrix4>,
320    /// The alignment of the origin, relative to the size of the container, if
321    /// [`transform`](Self::transform) is specified.
322    ///
323    /// When [`transform`](Self::transform) is `None`, the value of this property is ignored.
324    ///
325    /// See also:
326    ///
327    ///  * [`Transform::alignment`], which is set by this property.
328    pub transform_alignment: Option<AlignmentGeometry>,
329    /// The [`child`](Self::child) contained by the container.
330    ///
331    /// If `None`, and if the [`constraints`](Self::constraints) are unbounded or also `None`,
332    /// the container will expand to fill all available space in its parent, unless
333    /// the parent provides unbounded constraints, in which case the container
334    /// will attempt to be as small as possible.
335    pub child: Option<WidgetRef>,
336}
337
338impl Container {
339    /// Creates a widget that combines common painting, positioning, and sizing widgets;
340    /// Dart's named arguments are the setters.
341    ///
342    /// The [`height`](Self::height) and [`width`](Self::width) values include the padding.
343    ///
344    /// The [`color`](Self::color) and [`decoration`](Self::decoration) arguments cannot both
345    /// be supplied, since it would potentially result in the decoration drawing over the
346    /// background color. To supply a decoration with a color, use
347    /// `.decoration(BoxDecoration::new().color(color))`.
348    pub fn new() -> Container {
349        Container::default()
350    }
351
352    /// Dart `Container(key:)`.
353    pub fn key(mut self, key: KeyRef) -> Container {
354        self.key = Some(key);
355        self
356    }
357
358    /// Dart `Container(alignment:)`.
359    pub fn alignment(mut self, alignment: AlignmentGeometry) -> Container {
360        self.alignment = Some(alignment);
361        self
362    }
363
364    /// Dart `Container(padding:)`; must be non-negative.
365    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Container {
366        let padding = padding.into();
367        debug_assert!(padding.is_non_negative());
368        self.padding = Some(padding);
369        self
370    }
371
372    /// Dart `Container(color:)`; cannot be combined with
373    /// [`decoration`](Self::decoration).
374    pub fn color(mut self, color: impl Into<AnyColor>) -> Container {
375        debug_assert!(self.decoration.is_none(), "{CANNOT_PROVIDE_BOTH}");
376        self.color = Some(color.into());
377        self
378    }
379
380    /// Dart `Container(isAntiAlias:)`.
381    pub fn is_anti_alias(mut self, is_anti_alias: bool) -> Container {
382        self.is_anti_alias = is_anti_alias;
383        self
384    }
385
386    /// Dart `Container(decoration:)`; cannot be combined with [`color`](Self::color).
387    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> Container {
388        debug_assert!(self.color.is_none(), "{CANNOT_PROVIDE_BOTH}");
389        let decoration = decoration.into();
390        debug_assert!(decoration.debug_assert_is_valid());
391        self.decoration = Some(decoration);
392        self
393    }
394
395    /// Dart `Container(foregroundDecoration:)`.
396    pub fn foreground_decoration(
397        mut self,
398        foreground_decoration: impl Into<DecorationRef>,
399    ) -> Container {
400        self.foreground_decoration = Some(foreground_decoration.into());
401        self
402    }
403
404    /// Dart `Container(width:)`: tightens [`constraints`](Self::constraints).
405    pub fn width(mut self, width: f64) -> Container {
406        self.width = Some(width);
407        self.fold_constraints();
408        self
409    }
410
411    /// Dart `Container(height:)`: tightens [`constraints`](Self::constraints).
412    pub fn height(mut self, height: f64) -> Container {
413        self.height = Some(height);
414        self.fold_constraints();
415        self
416    }
417
418    /// Dart `Container(constraints:)`; must be valid.
419    pub fn constraints(mut self, constraints: BoxConstraints) -> Container {
420        debug_assert!(constraints.debug_assert_is_valid(false));
421        self.given_constraints = Some(constraints);
422        self.fold_constraints();
423        self
424    }
425
426    /// Dart `Container(margin:)`; must be non-negative.
427    pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> Container {
428        let margin = margin.into();
429        debug_assert!(margin.is_non_negative());
430        self.margin = Some(margin);
431        self
432    }
433
434    /// Dart `Container(clipBehavior:)`; must be `Clip::None` without a decoration.
435    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Container {
436        self.clip_behavior = clip_behavior;
437        self
438    }
439
440    /// Dart `Container(transform:)`.
441    pub fn transform(mut self, transform: Matrix4) -> Container {
442        self.transform = Some(transform);
443        self
444    }
445
446    /// Dart `Container(transformAlignment:)`.
447    pub fn transform_alignment(mut self, transform_alignment: AlignmentGeometry) -> Container {
448        self.transform_alignment = Some(transform_alignment);
449        self
450    }
451
452    /// Dart `Container(child:)`.
453    #[cfg_attr(debug_assertions, track_caller)]
454    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Container {
455        self.child = Some(child.into_widget());
456        self
457    }
458
459    /// Dart's constructor line folding `width` and `height` into `constraints`.
460    fn fold_constraints(&mut self) {
461        self.constraints = if self.width.is_some() || self.height.is_some() {
462            Some(match self.given_constraints {
463                Some(constraints) => constraints.tighten(self.width, self.height),
464                None => BoxConstraints::tight_for(self.width, self.height),
465            })
466        } else {
467            self.given_constraints
468        };
469    }
470
471    fn padding_including_decoration(&self) -> Option<EdgeInsetsGeometry> {
472        let decoration_padding = self
473            .decoration
474            .as_ref()
475            .map(|decoration| decoration.padding());
476        match (self.padding, decoration_padding) {
477            (None, padding) => padding,
478            (padding, None) => padding,
479            (Some(padding), Some(decoration_padding)) => Some(padding.add(decoration_padding)),
480        }
481    }
482}
483
484/// Dart's assert message when both a color and a decoration are supplied.
485const CANNOT_PROVIDE_BOTH: &str = "Cannot provide both a color and a decoration.\n\
486     The color argument is just a shorthand for \"decoration: BoxDecoration(color: color)\".\n\
487     To use both a color and other decoration properties, set the color in the BoxDecoration \
488     instead.";
489
490impl Default for Container {
491    fn default() -> Container {
492        Container {
493            key: None,
494            alignment: None,
495            padding: None,
496            color: None,
497            is_anti_alias: true,
498            decoration: None,
499            foreground_decoration: None,
500            constraints: None,
501            given_constraints: None,
502            width: None,
503            height: None,
504            margin: None,
505            clip_behavior: Clip::None,
506            transform: None,
507            transform_alignment: None,
508            child: None,
509        }
510    }
511}
512
513/// Dart's `_DecorationClipper`: a clipper that uses `Decoration::get_clip_path` to clip.
514struct DecorationClipper {
515    text_direction: TextDirection,
516    decoration: DecorationRef,
517}
518
519impl DecorationClipper {
520    fn new(text_direction: Option<TextDirection>, decoration: DecorationRef) -> Self {
521        DecorationClipper {
522            text_direction: text_direction.unwrap_or(TextDirection::Ltr),
523            decoration,
524        }
525    }
526}
527
528impl CustomClipper<Path> for DecorationClipper {
529    fn get_clip(&self, _app: &App, size: Size) -> Path {
530        self.decoration
531            .get_clip_path(Offset::ZERO & size, self.text_direction)
532    }
533
534    fn should_reclip(&self, _app: &App, old_clipper: &dyn CustomClipper<Path>) -> bool {
535        let Some(old_clipper) = old_clipper.as_any().downcast_ref::<DecorationClipper>() else {
536            return true;
537        };
538        old_clipper.decoration != self.decoration
539            || old_clipper.text_direction != self.text_direction
540    }
541
542    fn as_any(&self) -> &dyn Any {
543        self
544    }
545}
546
547impl StatelessWidget for Container {
548    fn key(&self) -> Option<&KeyRef> {
549        self.key.as_ref()
550    }
551
552    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
553        properties.add(
554            DiagnosticsProperty::<AlignmentGeometry>::new("alignment", self.alignment)
555                .with_show_name(false)
556                .default_value(None),
557        );
558        properties.add(
559            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
560                .default_value(None),
561        );
562        properties.add(
563            DiagnosticsProperty::new("clipBehavior", self.clip_behavior)
564                .default_value(Some(Clip::None)),
565        );
566        if self.color.is_some() {
567            properties.add(DiagnosticsProperty::<waft_embedder::Color>::new(
568                "bg",
569                self.color.as_ref().map(|color| color.color()),
570            ));
571        } else {
572            properties.add(
573                DiagnosticsProperty::<String>::new(
574                    "bg",
575                    self.decoration
576                        .as_ref()
577                        .map(|decoration| format!("{decoration:?}")),
578                )
579                .default_value(None),
580            );
581        }
582        properties.add(
583            DiagnosticsProperty::<String>::new(
584                "fg",
585                self.foreground_decoration
586                    .as_ref()
587                    .map(|decoration| format!("{decoration:?}")),
588            )
589            .default_value(None),
590        );
591        properties.add(
592            DiagnosticsProperty::<BoxConstraints>::new("constraints", self.constraints)
593                .default_value(None),
594        );
595        properties.add(
596            DiagnosticsProperty::<EdgeInsetsGeometry>::new("margin", self.margin)
597                .default_value(None),
598        );
599        properties.add(ObjectFlagProperty::<String>::has(
600            "transform",
601            self.transform.as_ref().map(|_| String::new()),
602        ));
603    }
604
605    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
606        debug_assert!(self.decoration.is_some() || self.clip_behavior == Clip::None);
607        let mut current = self.child.clone();
608
609        if self.child.is_none()
610            && self
611                .constraints
612                .is_none_or(|constraints| !constraints.is_tight())
613        {
614            current = Some(
615                LimitedBox::new()
616                    .max_width(0.0)
617                    .max_height(0.0)
618                    .child(ConstrainedBox::new(BoxConstraints::expand(None, None)))
619                    .into_widget(),
620            );
621        } else if let Some(alignment) = self.alignment {
622            current = Some(
623                Align {
624                    alignment,
625                    child: current,
626                    ..Align::new()
627                }
628                .into_widget(),
629            );
630        }
631
632        if let Some(effective_padding) = self.padding_including_decoration() {
633            current = Some(
634                Padding {
635                    key: None,
636                    padding: effective_padding,
637                    child: current,
638                }
639                .into_widget(),
640            );
641        }
642
643        if let Some(color) = &self.color {
644            current = Some(
645                ColoredBox {
646                    child: current,
647                    ..ColoredBox::new(color.clone()).is_anti_alias(self.is_anti_alias)
648                }
649                .into_widget(),
650            );
651        }
652
653        if self.clip_behavior != Clip::None {
654            let decoration = self
655                .decoration
656                .as_ref()
657                .expect("clip_behavior needs a decoration");
658            let text_direction = Directionality::maybe_of(app, context);
659            current = Some(
660                ClipPath {
661                    key: None,
662                    clipper: Some(Rc::new(DecorationClipper::new(
663                        text_direction,
664                        decoration.clone(),
665                    ))),
666                    clip_behavior: self.clip_behavior,
667                    child: current,
668                }
669                .into_widget(),
670            );
671        }
672
673        if let Some(decoration) = &self.decoration {
674            current = Some(
675                DecoratedBox {
676                    key: None,
677                    decoration: decoration.clone(),
678                    position: DecorationPosition::Background,
679                    child: current,
680                }
681                .into_widget(),
682            );
683        }
684
685        if let Some(foreground_decoration) = &self.foreground_decoration {
686            current = Some(
687                DecoratedBox {
688                    key: None,
689                    decoration: foreground_decoration.clone(),
690                    position: DecorationPosition::Foreground,
691                    child: current,
692                }
693                .into_widget(),
694            );
695        }
696
697        if let Some(constraints) = self.constraints {
698            current = Some(
699                ConstrainedBox {
700                    key: None,
701                    constraints,
702                    child: current,
703                }
704                .into_widget(),
705            );
706        }
707
708        if let Some(margin) = self.margin {
709            current = Some(
710                Padding {
711                    key: None,
712                    padding: margin,
713                    child: current,
714                }
715                .into_widget(),
716            );
717        }
718
719        if let Some(transform) = self.transform {
720            current = Some(
721                Transform {
722                    alignment: self.transform_alignment,
723                    child: current,
724                    ..Transform::new(transform)
725                }
726                .into_widget(),
727            );
728        }
729
730        current.expect("a Container builds at least one widget")
731    }
732}
733
734#[cfg(test)]
735mod tests {
736    use waft_embedder::{Clip, Color, Offset, SceneBuilder, Size, TextDirection};
737    use waft_foundation::AppCell;
738    use waft_painting::Decoration;
739    use waft_painting::{Border, BorderSide, BorderStyle, BoxDecoration};
740    use waft_rendering::{
741        AnyRenderBox, BoxParentData, RenderAligningShiftedBox, RenderBox, RenderColoredBox,
742        RenderConstrainedBox, RenderConstrainedBoxBase, RenderDecoratedBox, RenderHandle,
743        RenderLimitedBox, RenderObject, RenderObjectWithChildMixin, RenderPadding,
744        RenderPositionedBox, RenderTransform,
745    };
746
747    use super::*;
748    use crate::test_harness::Harness;
749    use crate::widgets::basic::SizedBox;
750
751    /// The typed render object under a single-child parent.
752    fn typed_child<P, C: RenderObject>(parent: RenderHandle<P>, app: &App) -> RenderHandle<C>
753    where
754        P: RenderObject + RenderObjectWithChildMixin<ChildType = AnyRenderBox>,
755    {
756        parent
757            .child(app)
758            .expect("a child")
759            .as_object()
760            .downcast::<C>(app)
761            .expect("the expected render object")
762    }
763
764    fn root_child<T: RenderObject>(harness: &Harness, app: &App) -> RenderHandle<T> {
765        harness
766            .render_root(app)
767            .child(app)
768            .expect("a child")
769            .as_object()
770            .downcast::<T>(app)
771            .expect("the expected render object")
772    }
773
774    #[test]
775    fn decorated_box_paints_its_decoration_and_updates_in_place() {
776        let cell = AppCell::new();
777        let mut app = cell.borrow_mut();
778        let red = Color::from_argb(255, 255, 0, 0);
779        let blue = Color::from_argb(255, 0, 0, 255);
780        let decorated = |color: Color| {
781            DecoratedBox {
782                key: None,
783                decoration: DecorationRef::new(BoxDecoration::new().color(color)),
784                position: DecorationPosition::Background,
785                child: Some(SizedBox::new().width(10.0).height(10.0).into_widget()),
786            }
787            .into_widget()
788        };
789        let harness = Harness::mount(&mut app, decorated(red));
790        harness.pump(&mut app);
791        let render_object = root_child::<RenderDecoratedBox>(&harness, &app);
792        assert!(!render_object.as_object().debug_needs_paint(&app));
793        let scene = harness
794            .render_root(&app)
795            .as_object()
796            .debug_layer(&app)
797            .expect("painted")
798            .build_scene(&mut app, SceneBuilder::new());
799        let ops = waft_embedder::flattened_ops(
800            &waft_embedder::slices(&scene, |_| None).picture_with_room(),
801        );
802        assert!(
803            ops.iter()
804                .any(|op| matches!(op, waft_embedder::valo::Op::DrawRect { .. })),
805            "the decoration's fill: {ops:?}"
806        );
807
808        harness.set_child(&mut app, decorated(blue));
809        harness.pump(&mut app);
810        let same = root_child::<RenderDecoratedBox>(&harness, &app);
811        assert_eq!(
812            same, render_object,
813            "the same RenderDecoratedBox is reconfigured"
814        );
815        let decoration = render_object
816            .decoration(&app)
817            .as_any()
818            .downcast_ref::<BoxDecoration>()
819            .expect("a BoxDecoration");
820        assert_eq!(decoration.color, Some(blue.into()));
821    }
822
823    #[test]
824    fn a_container_builds_dart_s_chain_outside_in() {
825        let cell = AppCell::new();
826        let mut app = cell.borrow_mut();
827        let harness = Harness::mount(
828            &mut app,
829            Container::new()
830                .alignment(AlignmentGeometry::TOP_LEFT)
831                .padding(EdgeInsetsGeometry::all(4.0))
832                .color(Color::from_argb(255, 255, 0, 0))
833                .width(80.0)
834                .height(60.0)
835                .margin(EdgeInsetsGeometry::all(2.0))
836                .transform(Matrix4::scale(2.0, 2.0))
837                .transform_alignment(AlignmentGeometry::CENTER)
838                .child(SizedBox::new().width(10.0).height(10.0))
839                .into_widget(),
840        );
841        harness.pump(&mut app);
842
843        let transform = root_child::<RenderTransform>(&harness, &app);
844        assert_eq!(transform.alignment(&app), Some(AlignmentGeometry::CENTER));
845        let margin = typed_child::<_, RenderPadding>(transform, &app);
846        assert_eq!(margin.padding(&app), EdgeInsetsGeometry::all(2.0));
847        let constrained = typed_child::<_, RenderConstrainedBox>(margin, &app);
848        assert_eq!(
849            constrained.additional_constraints(&app),
850            BoxConstraints::tight_for(Some(80.0), Some(60.0)),
851            "width and height fold into the constraints"
852        );
853        let colored = typed_child::<_, RenderColoredBox>(constrained, &app);
854        assert!(colored.is_anti_alias(&app));
855        let padding = typed_child::<_, RenderPadding>(colored, &app);
856        assert_eq!(padding.padding(&app), EdgeInsetsGeometry::all(4.0));
857        let align = typed_child::<_, RenderPositionedBox>(padding, &app);
858        assert_eq!(align.alignment(&app), AlignmentGeometry::TOP_LEFT);
859        let child = typed_child::<_, RenderConstrainedBox>(align, &app);
860        assert_eq!(child.size(&app), Size::new(10.0, 10.0));
861
862        assert_eq!(
863            transform.size(&app),
864            Size::new(84.0, 64.0),
865            "the margin is outside the constrained extent"
866        );
867    }
868
869    #[test]
870    fn a_childless_container_expands_inside_a_limited_box() {
871        let cell = AppCell::new();
872        let mut app = cell.borrow_mut();
873        let harness = Harness::mount(&mut app, Container::new().into_widget());
874        harness.pump(&mut app);
875        let limited = root_child::<RenderLimitedBox>(&harness, &app);
876        assert_eq!(limited.max_width(&app), 0.0);
877        assert_eq!(limited.max_height(&app), 0.0);
878        let expanded = typed_child::<_, RenderConstrainedBox>(limited, &app);
879        assert_eq!(
880            expanded.additional_constraints(&app),
881            BoxConstraints::expand(None, None)
882        );
883        assert_eq!(
884            limited.size(&app),
885            Size::new(300.0, 200.0),
886            "bounded constraints win over the zero limits"
887        );
888    }
889
890    #[test]
891    fn a_decoration_adds_its_padding_and_paints_behind_the_child() {
892        let cell = AppCell::new();
893        let mut app = cell.borrow_mut();
894        let decoration = BoxDecoration::new()
895            .color(Color::from_argb(255, 0, 0, 255))
896            .border(Border::all(
897                Color::from_argb(255, 0, 0, 0),
898                3.0,
899                BorderStyle::Solid,
900                BorderSide::STROKE_ALIGN_INSIDE,
901            ));
902        let decoration_padding = decoration.padding();
903        let harness = Harness::mount(
904            &mut app,
905            Container::new()
906                .padding(EdgeInsetsGeometry::all(4.0))
907                .decoration(decoration)
908                .child(SizedBox::new().width(10.0).height(10.0))
909                .into_widget(),
910        );
911        harness.pump(&mut app);
912
913        let decorated = root_child::<RenderDecoratedBox>(&harness, &app);
914        let padding = typed_child::<_, RenderPadding>(decorated, &app);
915        assert_eq!(
916            padding.padding(&app),
917            EdgeInsetsGeometry::all(4.0).add(decoration_padding),
918            "Dart's _paddingIncludingDecoration"
919        );
920        assert_eq!(
921            decorated.size(&app),
922            Size::new(24.0, 24.0),
923            "the child, the padding, and the border's own inset"
924        );
925    }
926
927    #[test]
928    fn an_aligned_container_positions_its_child() {
929        let cell = AppCell::new();
930        let mut app = cell.borrow_mut();
931        let harness = Harness::mount(
932            &mut app,
933            Container::new()
934                .alignment(AlignmentGeometry::BOTTOM_RIGHT)
935                .child(SizedBox::new().width(10.0).height(10.0))
936                .into_widget(),
937        );
938        harness.pump(&mut app);
939        let align = root_child::<RenderPositionedBox>(&harness, &app);
940        assert_eq!(
941            align.size(&app),
942            Size::new(300.0, 200.0),
943            "an alignment expands to fill the parent"
944        );
945        let child = typed_child::<_, RenderConstrainedBox>(align, &app);
946        assert_eq!(
947            child
948                .as_object()
949                .parent_data_of::<BoxParentData>(&app)
950                .offset,
951            Offset::new(290.0, 190.0)
952        );
953    }
954
955    #[test]
956    fn width_and_height_tighten_the_constraints_in_any_setter_order() {
957        let container = Container::new()
958            .constraints(BoxConstraints::new().min_width(20.0).max_width(200.0))
959            .width(80.0);
960        assert_eq!(
961            container.constraints,
962            Some(BoxConstraints::new().min_width(80.0).max_width(80.0)),
963            "Dart's constraints.tighten(width: ..)"
964        );
965        let reordered = Container::new()
966            .width(80.0)
967            .constraints(BoxConstraints::new().min_width(20.0).max_width(200.0));
968        assert_eq!(reordered.constraints, container.constraints);
969
970        let unconstrained = Container::new().height(60.0);
971        assert_eq!(
972            unconstrained.constraints,
973            Some(BoxConstraints::tight_for(None, Some(60.0))),
974            "Dart's BoxConstraints.tightFor(height: ..)"
975        );
976    }
977
978    #[test]
979    fn a_clip_behavior_clips_the_decoration_through_its_clip_path() {
980        let cell = AppCell::new();
981        let mut app = cell.borrow_mut();
982        let harness = Harness::mount(
983            &mut app,
984            Directionality::new(
985                TextDirection::Ltr,
986                Container::new()
987                    .decoration(
988                        BoxDecoration::new()
989                            .color(Color::new(0xFF00FF00))
990                            .border_radius(waft_painting::BorderRadiusGeometry::circular(6.0)),
991                    )
992                    .clip_behavior(Clip::AntiAlias)
993                    .child(SizedBox::shrink()),
994            )
995            .into_widget(),
996        );
997        harness.pump(&mut app);
998        let decorated = harness
999            .render_root(&app)
1000            .child(&app)
1001            .expect("the container's tree")
1002            .as_object()
1003            .downcast::<waft_rendering::RenderDecoratedBox>(&app)
1004            .expect("the background DecoratedBox");
1005        let clip = decorated
1006            .child(&app)
1007            .expect("the clip under the decoration")
1008            .as_object()
1009            .downcast::<waft_rendering::RenderClipPath>(&app)
1010            .expect("a RenderClipPath");
1011        assert_eq!(
1012            waft_rendering::RenderCustomClip::clip_behavior(clip, &app),
1013            Clip::AntiAlias
1014        );
1015    }
1016}