Skip to main content

waft_material/
mergeable_material.rs

1//! Flutter counterpart: material_ui's `mergeable_material.dart`.
2
3use std::collections::{HashMap, HashSet};
4use std::fmt;
5use std::hash::Hash;
6use std::rc::Rc;
7
8use waft_animation::{
9    Animation, AnimationBehavior, AnimationController, AnimationStatus, CurvedAnimation, Curves,
10};
11use waft_embedder::{
12    Canvas, Color, Offset, Path, PathBuilder, Radius, Size, TextBaseline, rrect_radii_elliptical,
13    valo,
14};
15use waft_foundation::{
16    App, DiagnosticPropertiesBuilder, DiagnosticsNode, DoubleProperty, EnumProperty, Handle,
17    Listener, Ref, UniqueKey,
18};
19use waft_painting::{
20    Axis, AxisDirection, Border, BorderRadius, BorderRadiusGeometry, BorderSide, BoxDecoration,
21    ClipContext,
22};
23use waft_rendering::{
24    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ContainerBoxParentData,
25    ContainerParentDataMixin, ContainerRenderObjectData, ContainerRenderObjectMixin, RenderBox,
26    RenderBoxContainerDefaultsMixin, RenderBoxData, RenderHandle, RenderListBodyData,
27    RenderListBodyMixin, RenderObject, RenderObjectData,
28};
29use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
30use waft_widgets::{
31    AnimatedContainer, BuildContext, Container, IntoWidget, KeyRef, ListBody,
32    MultiChildRenderObjectWidget, RenderObjectWidget, SizedBox, State, StateData, StatefulWidget,
33    TickerProviderStateMixin, TickerProviderStateMixinData, WidgetRef,
34    get_axis_direction_from_axis_reverse_and_directionality,
35};
36
37use crate::colors::Colors;
38use crate::divider::Divider;
39use crate::material::{Material, MaterialType, k_material_edges};
40use crate::slider_parts::draw_shadow;
41use crate::theme::{K_THEME_ANIMATION_DURATION, Theme};
42
43/// The base type for [`MaterialSlice`] and [`MaterialGap`].
44///
45/// All [`MergeableMaterialItem`] objects need a key.
46#[derive(Clone, Debug)]
47pub enum MergeableMaterialItem {
48    /// A slice of `Material`.
49    Slice(MaterialSlice),
50    /// A gap between slices.
51    Gap(MaterialGap),
52}
53
54impl MergeableMaterialItem {
55    /// The key that matches this item from frame to frame.
56    pub fn key(&self) -> &KeyRef {
57        match self {
58            MergeableMaterialItem::Slice(slice) => &slice.key,
59            MergeableMaterialItem::Gap(gap) => &gap.key,
60        }
61    }
62
63    fn is_gap(&self) -> bool {
64        matches!(self, MergeableMaterialItem::Gap(_))
65    }
66}
67
68impl From<MaterialSlice> for MergeableMaterialItem {
69    fn from(slice: MaterialSlice) -> MergeableMaterialItem {
70        MergeableMaterialItem::Slice(slice)
71    }
72}
73
74impl From<MaterialGap> for MergeableMaterialItem {
75    fn from(gap: MaterialGap) -> MergeableMaterialItem {
76        MergeableMaterialItem::Gap(gap)
77    }
78}
79
80/// A class that can be used as a child to [`MergeableMaterial`]. It is a slice of `Material`
81/// that animates merging with other slices.
82///
83/// All [`MaterialSlice`] objects need a key.
84#[derive(Clone)]
85pub struct MaterialSlice {
86    /// The key for this item of the list.
87    pub key: KeyRef,
88    /// The contents of this slice.
89    pub child: WidgetRef,
90    /// Defines the color for the slice.
91    ///
92    /// By default, the value of `color` is `ThemeData::card_color`.
93    pub color: Option<Color>,
94}
95
96impl MaterialSlice {
97    /// Creates a slice of `Material` that's mergeable within a [`MergeableMaterial`]; Dart's
98    /// optional named arguments are the setters.
99    #[cfg_attr(debug_assertions, track_caller)]
100    pub fn new<K>(key: impl Into<KeyRef>, child: impl IntoWidget<K>) -> MaterialSlice {
101        MaterialSlice {
102            key: key.into(),
103            child: child.into_widget(),
104            color: None,
105        }
106    }
107
108    /// Dart `MaterialSlice(color:)`.
109    pub fn color(mut self, color: Color) -> MaterialSlice {
110        self.color = Some(color);
111        self
112    }
113}
114
115impl fmt::Debug for MaterialSlice {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        f.debug_struct("MaterialSlice")
118            .field("key", &self.key)
119            .field("color", &self.color)
120            .finish_non_exhaustive()
121    }
122}
123
124/// A class that represents a gap within [`MergeableMaterial`].
125///
126/// All [`MaterialGap`] objects need a key.
127#[derive(Clone, Debug)]
128pub struct MaterialGap {
129    /// The key for this item of the list.
130    pub key: KeyRef,
131    /// The main axis extent of this gap.
132    pub size: f64,
133}
134
135impl MaterialGap {
136    /// Creates a Material gap with a given size; Dart's optional named arguments are the
137    /// setters.
138    pub fn new(key: impl Into<KeyRef>) -> MaterialGap {
139        MaterialGap {
140            key: key.into(),
141            size: 16.0,
142        }
143    }
144
145    /// Dart `MaterialGap(size:)`.
146    pub fn size(mut self, size: f64) -> MaterialGap {
147        self.size = size;
148        self
149    }
150}
151
152/// Displays a list of [`MergeableMaterialItem`] children. The list contains [`MaterialSlice`]
153/// items whose boundaries are either "merged" with adjacent items or separated by a
154/// [`MaterialGap`]. The children are distributed along the given `main_axis` in the same way as
155/// the children of a `ListBody`. When the list of children changes, gaps are automatically
156/// animated open or closed as needed.
157///
158/// To enable this widget to correlate its list of children with the previous one, each child
159/// must specify a key.
160///
161/// When a new gap is added to the list of children the adjacent items are animated apart.
162/// Similarly when a gap is removed the adjacent items are brought back together.
163///
164/// When a new slice is added or removed, the app is responsible for animating the transition of
165/// the slices, while the gaps will be animated automatically.
166pub struct MergeableMaterial {
167    pub key: Option<KeyRef>,
168    /// The children of the mergeable material.
169    pub children: Vec<MergeableMaterialItem>,
170    /// The main layout axis.
171    pub main_axis: Axis,
172    /// The z-coordinate at which to place all the `Material` slices.
173    pub elevation: f64,
174    /// Whether connected pieces of `MaterialSlice` have dividers between them.
175    pub has_dividers: bool,
176    /// Defines the color used for dividers if `has_dividers` is true.
177    pub divider_color: Option<Color>,
178}
179
180impl MergeableMaterial {
181    /// Creates a mergeable Material list of items; Dart's optional named arguments are the
182    /// setters.
183    pub fn new() -> MergeableMaterial {
184        MergeableMaterial {
185            key: None,
186            children: Vec::new(),
187            main_axis: Axis::Vertical,
188            elevation: 2.0,
189            has_dividers: false,
190            divider_color: None,
191        }
192    }
193
194    /// Dart `MergeableMaterial(key:)`.
195    pub fn key(mut self, key: KeyRef) -> MergeableMaterial {
196        self.key = Some(key);
197        self
198    }
199
200    /// Dart `MergeableMaterial(children:)`.
201    pub fn children(
202        mut self,
203        children: impl IntoIterator<Item = MergeableMaterialItem>,
204    ) -> MergeableMaterial {
205        self.children = children.into_iter().collect();
206        self
207    }
208
209    /// Dart `MergeableMaterial(mainAxis:)`.
210    pub fn main_axis(mut self, main_axis: Axis) -> MergeableMaterial {
211        self.main_axis = main_axis;
212        self
213    }
214
215    /// Dart `MergeableMaterial(elevation:)`.
216    pub fn elevation(mut self, elevation: f64) -> MergeableMaterial {
217        self.elevation = elevation;
218        self
219    }
220
221    /// Dart `MergeableMaterial(hasDividers:)`.
222    pub fn has_dividers(mut self, has_dividers: bool) -> MergeableMaterial {
223        self.has_dividers = has_dividers;
224        self
225    }
226
227    /// Dart `MergeableMaterial(dividerColor:)`.
228    pub fn divider_color(mut self, divider_color: Color) -> MergeableMaterial {
229        self.divider_color = Some(divider_color);
230        self
231    }
232}
233
234impl Default for MergeableMaterial {
235    fn default() -> MergeableMaterial {
236        MergeableMaterial::new()
237    }
238}
239
240impl fmt::Debug for MergeableMaterial {
241    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242        f.debug_struct("MergeableMaterial")
243            .field("main_axis", &self.main_axis)
244            .field("elevation", &self.elevation)
245            .finish_non_exhaustive()
246    }
247}
248
249/// Dart's `_AnimationTuple`.
250struct AnimationTuple {
251    controller: Ref<AnimationController>,
252    start_animation: Ref<CurvedAnimation>,
253    end_animation: Ref<CurvedAnimation>,
254    gap_animation: Ref<CurvedAnimation>,
255    gap_start: f64,
256}
257
258impl AnimationTuple {
259    fn dispose(self, app: &mut App) {
260        self.controller.dispose(app);
261        self.start_animation.dispose(app);
262        self.end_animation.dispose(app);
263        self.gap_animation.dispose(app);
264    }
265}
266
267impl StatefulWidget for MergeableMaterial {
268    type State = MergeableMaterialState;
269
270    fn key(&self) -> Option<&KeyRef> {
271        self.key.as_ref()
272    }
273
274    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
275        properties.add(EnumProperty::new("mainAxis", self.main_axis));
276        properties.add(DoubleProperty::new("elevation", self.elevation));
277    }
278
279    fn create_state(&self) -> MergeableMaterialState {
280        MergeableMaterialState {
281            state: StateData::new(),
282            ticker_provider: TickerProviderStateMixinData::new(),
283            children: Vec::new(),
284            animation_tuples: HashMap::new(),
285        }
286    }
287}
288
289/// Dart's `_MergeableMaterialState`.
290pub struct MergeableMaterialState {
291    state: StateData<MergeableMaterial>,
292    ticker_provider: TickerProviderStateMixinData,
293    children: Vec<MergeableMaterialItem>,
294    animation_tuples: HashMap<KeyRef, AnimationTuple>,
295}
296
297impl MergeableMaterialState {
298    fn handle_tick(self: Handle<Self>, app: &mut App) {
299        self.set_state(app, |_state| {});
300    }
301
302    fn gap_tuple<'a>(self: Handle<Self>, app: &'a App, key: &KeyRef) -> &'a AnimationTuple {
303        app.get(self)
304            .animation_tuples
305            .get(key)
306            .expect("a gap has its animation tuple")
307    }
308
309    fn controller(self: Handle<Self>, app: &App, key: &KeyRef) -> Ref<AnimationController> {
310        self.gap_tuple(app, key).controller.clone()
311    }
312
313    fn init_gap(self: Handle<Self>, app: &mut App, gap: &MaterialGap) {
314        let controller = AnimationController::new(
315            app,
316            None,
317            Some(K_THEME_ANIMATION_DURATION),
318            None,
319            0.0,
320            1.0,
321            AnimationBehavior::Normal,
322            self,
323        );
324        let curve = || Curves::fast_out_slow_in();
325        let start_animation = CurvedAnimation::new(app, controller.erase(), curve(), None);
326        let end_animation = CurvedAnimation::new(app, controller.erase(), curve(), None);
327        let gap_animation = CurvedAnimation::new(app, controller.erase(), curve(), None);
328        controller.add_listener(app, Listener::handle_method(self, Self::handle_tick));
329        app.get_mut(self).animation_tuples.insert(
330            gap.key.clone(),
331            AnimationTuple {
332                controller,
333                start_animation,
334                end_animation,
335                gap_animation,
336                gap_start: 0.0,
337            },
338        );
339    }
340
341    fn dispose_tuple(self: Handle<Self>, app: &mut App, key: &KeyRef) {
342        if let Some(tuple) = app.get_mut(self).animation_tuples.remove(key) {
343            tuple.dispose(app);
344        }
345    }
346
347    /// Dart's `_debugHasConsecutiveGaps`, which reads the widget's children whatever it is given.
348    fn debug_has_consecutive_gaps(self: Handle<Self>, app: &App) -> bool {
349        self.widget(app)
350            .children
351            .windows(2)
352            .any(|pair| pair[0].is_gap() && pair[1].is_gap())
353    }
354
355    /// Dart's `_debugGapsAreValid`: no two gaps in a row, and neither end is a gap.
356    fn debug_gaps_are_valid(
357        self: Handle<Self>,
358        app: &App,
359        children: &[MergeableMaterialItem],
360    ) -> bool {
361        if self.debug_has_consecutive_gaps(app) {
362            return false;
363        }
364        if let (Some(first), Some(last)) = (children.first(), children.last())
365            && (first.is_gap() || last.is_gap())
366        {
367            return false;
368        }
369        true
370    }
371
372    fn insert_child(self: Handle<Self>, app: &mut App, index: usize, child: MergeableMaterialItem) {
373        if let MergeableMaterialItem::Gap(gap) = &child {
374            self.init_gap(app, gap);
375        }
376        app.get_mut(self).children.insert(index, child);
377    }
378
379    fn remove_child(self: Handle<Self>, app: &mut App, index: usize) -> MergeableMaterialItem {
380        let child = app.get_mut(self).children.remove(index);
381        if let MergeableMaterialItem::Gap(gap) = &child {
382            self.dispose_tuple(app, &gap.key);
383        }
384        child
385    }
386
387    fn is_closing_gap(self: Handle<Self>, app: &App, index: usize) -> bool {
388        let children = &app.get(self).children;
389        if index < children.len().saturating_sub(1)
390            && let MergeableMaterialItem::Gap(gap) = &children[index]
391        {
392            return self.controller(app, &gap.key).status(app) == AnimationStatus::Reverse;
393        }
394        false
395    }
396
397    fn remove_empty_gaps(self: Handle<Self>, app: &mut App) {
398        for j in (0..app.get(self).children.len()).rev() {
399            let dismissed = match &app.get(self).children[j] {
400                MergeableMaterialItem::Gap(gap) => {
401                    self.controller(app, &gap.key).status(app).is_dismissed()
402                }
403                MergeableMaterialItem::Slice(_) => false,
404            };
405            if dismissed {
406                self.remove_child(app, j);
407            }
408        }
409    }
410
411    fn border_radius(
412        self: Handle<Self>,
413        app: &App,
414        index: usize,
415        start: bool,
416        end: bool,
417    ) -> BorderRadiusGeometry {
418        let children = &app.get(self).children;
419        let card_radius = k_material_edges(MaterialType::Card)
420            .expect("the card material has a radius")
421            .top_left;
422        let mut start_radius = Radius::ZERO;
423        let mut end_radius = Radius::ZERO;
424        if index > 0
425            && let MergeableMaterialItem::Gap(gap) = &children[index - 1]
426        {
427            let value = self.gap_tuple(app, &gap.key).start_animation.value(app);
428            start_radius =
429                Radius::lerp(Some(Radius::ZERO), Some(card_radius), value).expect("a radius lerps");
430        }
431        if index + 1 < children.len().saturating_sub(1)
432            && let MergeableMaterialItem::Gap(gap) = &children[index + 1]
433        {
434            let value = self.gap_tuple(app, &gap.key).end_animation.value(app);
435            end_radius =
436                Radius::lerp(Some(Radius::ZERO), Some(card_radius), value).expect("a radius lerps");
437        }
438
439        let start_radius = if start { card_radius } else { start_radius };
440        let end_radius = if end { card_radius } else { end_radius };
441        match self.widget(app).main_axis {
442            Axis::Vertical => BorderRadiusGeometry::vertical(start_radius, end_radius),
443            Axis::Horizontal => BorderRadiusGeometry::BorderRadius(BorderRadius::horizontal(
444                start_radius,
445                end_radius,
446            )),
447        }
448    }
449
450    fn gap_size(self: Handle<Self>, app: &App, index: usize) -> f64 {
451        let MergeableMaterialItem::Gap(gap) = &app.get(self).children[index] else {
452            panic!("a gap is a gap");
453        };
454        let tuple = self.gap_tuple(app, &gap.key);
455        waft_embedder::lerp_double(
456            Some(tuple.gap_start),
457            Some(gap.size),
458            tuple.gap_animation.value(app),
459        )
460        .expect("a gap size lerps")
461    }
462
463    fn will_need_divider(self: Handle<Self>, app: &App, index: i64) -> bool {
464        if index < 0 || index as usize >= app.get(self).children.len() {
465            return false;
466        }
467        matches!(
468            app.get(self).children[index as usize],
469            MergeableMaterialItem::Slice(_)
470        ) || self.is_closing_gap(app, index as usize)
471    }
472}
473
474impl fmt::Debug for MergeableMaterialState {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476        f.debug_struct("MergeableMaterialState")
477            .field("children", &self.children.len())
478            .finish_non_exhaustive()
479    }
480}
481
482impl TickerProviderStateMixin for MergeableMaterialState {
483    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
484        &app.get(self).ticker_provider
485    }
486
487    fn ticker_provider_data_mut(
488        self: Handle<Self>,
489        app: &mut App,
490    ) -> &mut TickerProviderStateMixinData {
491        &mut app.get_mut(self).ticker_provider
492    }
493}
494
495/// Dart's `vsync: this`.
496impl TickerProviderObject for MergeableMaterialState {
497    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
498        TickerProviderStateMixin::create_ticker(self, app, on_tick)
499    }
500}
501
502impl State for MergeableMaterialState {
503    type Widget = MergeableMaterial;
504    waft_widgets::state_accessors!();
505
506    fn init_state(self: Handle<Self>, app: &mut App) {
507        let children = self.widget(app).children.clone();
508        app.get_mut(self).children = children.clone();
509        for child in &children {
510            if let MergeableMaterialItem::Gap(gap) = child {
511                self.init_gap(app, gap);
512                // Gaps are initially full-sized.
513                self.controller(app, &gap.key).set_value(app, 1.0);
514            }
515        }
516        debug_assert!(self.debug_gaps_are_valid(app, &children));
517    }
518
519    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MergeableMaterial) {
520        let old_keys: HashSet<KeyRef> = old_widget
521            .children
522            .iter()
523            .map(|child| child.key().clone())
524            .collect();
525        let new_children = self.widget(app).children.clone();
526        let new_keys: HashSet<KeyRef> = new_children
527            .iter()
528            .map(|child| child.key().clone())
529            .collect();
530        let new_only: HashSet<KeyRef> = new_keys.difference(&old_keys).cloned().collect();
531        let old_only: HashSet<KeyRef> = old_keys.difference(&new_keys).cloned().collect();
532
533        debug_assert!(self.debug_gaps_are_valid(app, &new_children));
534
535        self.remove_empty_gaps(app);
536
537        let mut i = 0usize;
538        let mut j = 0usize;
539        while i < new_children.len() && j < app.get(self).children.len() {
540            if new_only.contains(new_children[i].key())
541                || old_only.contains(app.get(self).children[j].key())
542            {
543                let start_new = i;
544                let start_old = j;
545
546                while i < new_children.len() && new_only.contains(new_children[i].key()) {
547                    i += 1;
548                }
549                while j < app.get(self).children.len()
550                    && (old_only.contains(app.get(self).children[j].key())
551                        || self.is_closing_gap(app, j))
552                {
553                    j += 1;
554                }
555                let new_length = i - start_new;
556                let old_length = j - start_old;
557
558                if new_length > 0 {
559                    if old_length > 1
560                        || (old_length == 1
561                            && matches!(
562                                app.get(self).children[start_old],
563                                MergeableMaterialItem::Slice(_)
564                            ))
565                    {
566                        if new_length == 1
567                            && matches!(new_children[start_new], MergeableMaterialItem::Gap(_))
568                        {
569                            let mut gap_size_sum = 0.0;
570                            while start_old < j {
571                                if let MergeableMaterialItem::Gap(gap) =
572                                    &app.get(self).children[start_old]
573                                {
574                                    gap_size_sum += gap.size;
575                                }
576                                self.remove_child(app, start_old);
577                                j -= 1;
578                            }
579                            self.insert_child(app, start_old, new_children[start_new].clone());
580                            let gap_key = new_children[start_new].key().clone();
581                            if let Some(tuple) =
582                                app.get_mut(self).animation_tuples.get_mut(&gap_key)
583                            {
584                                tuple.gap_start = gap_size_sum;
585                            }
586                            self.controller(app, &gap_key).forward(app, None);
587                            j += 1;
588                        } else {
589                            for _ in 0..old_length {
590                                self.remove_child(app, start_old);
591                            }
592                            for k in 0..new_length {
593                                self.insert_child(
594                                    app,
595                                    start_old + k,
596                                    new_children[start_new + k].clone(),
597                                );
598                            }
599                            j = j + new_length - old_length;
600                        }
601                    } else if old_length == 1 {
602                        let same_gap = new_length == 1
603                            && matches!(new_children[start_new], MergeableMaterialItem::Gap(_))
604                            && app.get(self).children[start_old].key()
605                                == new_children[start_new].key();
606                        if same_gap {
607                            let key = new_children[start_new].key().clone();
608                            self.controller(app, &key).forward(app, None);
609                        } else {
610                            let gap_size = self.gap_size(app, start_old);
611                            self.remove_child(app, start_old);
612                            for k in 0..new_length {
613                                self.insert_child(
614                                    app,
615                                    start_old + k,
616                                    new_children[start_new + k].clone(),
617                                );
618                            }
619                            j = j + new_length - 1;
620                            let mut gap_size_sum = 0.0;
621                            for child in &new_children[start_new..i] {
622                                if let MergeableMaterialItem::Gap(gap) = child {
623                                    gap_size_sum += gap.size;
624                                }
625                            }
626                            for child in &new_children[start_new..i] {
627                                if let MergeableMaterialItem::Gap(gap) = child {
628                                    let key = gap.key.clone();
629                                    if let Some(tuple) =
630                                        app.get_mut(self).animation_tuples.get_mut(&key)
631                                    {
632                                        tuple.gap_start = gap_size * gap.size / gap_size_sum;
633                                    }
634                                    let controller = self.controller(app, &key);
635                                    controller.set_value(app, 0.0);
636                                    controller.forward(app, None);
637                                }
638                            }
639                        }
640                    } else {
641                        for k in 0..new_length {
642                            let new_child = new_children[start_new + k].clone();
643                            self.insert_child(app, start_old + k, new_child.clone());
644                            if let MergeableMaterialItem::Gap(gap) = &new_child {
645                                self.controller(app, &gap.key).forward(app, None);
646                            }
647                        }
648                        j += new_length;
649                    }
650                } else if old_length > 1
651                    || (old_length == 1
652                        && matches!(
653                            app.get(self).children[start_old],
654                            MergeableMaterialItem::Slice(_)
655                        ))
656                {
657                    let mut gap_size_sum = 0.0;
658                    while start_old < j {
659                        if let MergeableMaterialItem::Gap(gap) = &app.get(self).children[start_old]
660                        {
661                            gap_size_sum += gap.size;
662                        }
663                        self.remove_child(app, start_old);
664                        j -= 1;
665                    }
666                    if gap_size_sum != 0.0 {
667                        let gap =
668                            MaterialGap::new(KeyRef::from(UniqueKey::new())).size(gap_size_sum);
669                        self.insert_child(app, start_old, MergeableMaterialItem::Gap(gap));
670                        let key = app.get(self).children[start_old].key().clone();
671                        if let Some(tuple) = app.get_mut(self).animation_tuples.get_mut(&key) {
672                            tuple.gap_start = 0.0;
673                        }
674                        let controller = self.controller(app, &key);
675                        controller.set_value(app, 1.0);
676                        controller.reverse(app, None);
677                        j += 1;
678                    }
679                } else if old_length == 1 {
680                    let MergeableMaterialItem::Gap(gap) = &app.get(self).children[start_old] else {
681                        panic!("the old child is a gap");
682                    };
683                    let key = gap.key.clone();
684                    if let Some(tuple) = app.get_mut(self).animation_tuples.get_mut(&key) {
685                        tuple.gap_start = 0.0;
686                    }
687                    self.controller(app, &key).reverse(app, None);
688                }
689            } else if app.get(self).children[j].is_gap() == new_children[i].is_gap() {
690                // Same kind: their places have been swapped.
691                app.get_mut(self).children[j] = new_children[i].clone();
692                i += 1;
693                j += 1;
694            } else {
695                // A closing gap, which is skipped.
696                debug_assert!(app.get(self).children[j].is_gap());
697                j += 1;
698            }
699        }
700
701        while j < app.get(self).children.len() {
702            self.remove_child(app, j);
703        }
704        while i < new_children.len() {
705            let new_child = new_children[i].clone();
706            self.insert_child(app, j, new_child.clone());
707            if let MergeableMaterialItem::Gap(gap) = &new_child {
708                self.controller(app, &gap.key).forward(app, None);
709            }
710            i += 1;
711            j += 1;
712        }
713    }
714
715    fn dispose(self: Handle<Self>, app: &mut App) {
716        let keys: Vec<KeyRef> = app.get(self).animation_tuples.keys().cloned().collect();
717        for key in keys {
718            self.dispose_tuple(app, &key);
719        }
720        TickerProviderStateMixin::dispose(self, app);
721    }
722
723    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
724        self.remove_empty_gaps(app);
725
726        let theme = Theme::of(app, context);
727        let main_axis = self.widget(app).main_axis;
728        let elevation = self.widget(app).elevation;
729        let has_dividers = self.widget(app).has_dividers;
730        let divider_color = self.widget(app).divider_color;
731        let mut widgets: Vec<WidgetRef> = Vec::new();
732        let mut slices: Vec<WidgetRef> = Vec::new();
733
734        for i in 0..app.get(self).children.len() {
735            if app.get(self).children[i].is_gap() {
736                debug_assert!(!slices.is_empty());
737                widgets.push(
738                    ListBody::new()
739                        .main_axis(main_axis)
740                        .children(std::mem::take(&mut slices))
741                        .into_widget(),
742                );
743                let gap_size = self.gap_size(app, i);
744                widgets.push(match main_axis {
745                    Axis::Horizontal => SizedBox::new().width(gap_size).into_widget(),
746                    Axis::Vertical => SizedBox::new().height(gap_size).into_widget(),
747                });
748            } else {
749                let (slice_child, slice_color, slice_key) = match &app.get(self).children[i] {
750                    MergeableMaterialItem::Slice(slice) => {
751                        (slice.child.clone(), slice.color, slice.key.clone())
752                    }
753                    MergeableMaterialItem::Gap(_) => unreachable!(),
754                };
755                let mut child = slice_child;
756
757                if has_dividers {
758                    let has_top_divider = self.will_need_divider(app, i as i64 - 1);
759                    let has_bottom_divider = self.will_need_divider(app, i as i64 + 1);
760                    let divider =
761                        Divider::create_border_side(app, Some(context), divider_color, Some(0.5));
762                    let side = |shown: bool| if shown { divider } else { BorderSide::NONE };
763                    let border = if i == 0 {
764                        Border {
765                            bottom: side(has_bottom_divider),
766                            ..Border::from_border_side(BorderSide::NONE)
767                        }
768                    } else if i == app.get(self).children.len() - 1 {
769                        Border {
770                            top: side(has_top_divider),
771                            ..Border::from_border_side(BorderSide::NONE)
772                        }
773                    } else {
774                        Border {
775                            top: side(has_top_divider),
776                            bottom: side(has_bottom_divider),
777                            ..Border::from_border_side(BorderSide::NONE)
778                        }
779                    };
780
781                    child = AnimatedContainer::new(K_THEME_ANIMATION_DURATION)
782                        .key(KeyRef::Global(waft_widgets::GlobalKey::wrapping(Rc::new(
783                            MergeableMaterialSliceKey(slice_key),
784                        ))))
785                        .decoration(BoxDecoration::new().border(border))
786                        .curve(Curves::fast_out_slow_in())
787                        .child(child)
788                        .into_widget();
789                }
790
791                let color = slice_color.unwrap_or(theme.card_color);
792                slices.push(
793                    Container::new()
794                        .decoration(BoxDecoration::new().color(color).border_radius(
795                            self.border_radius(
796                                app,
797                                i,
798                                i == 0,
799                                i == app.get(self).children.len() - 1,
800                            ),
801                        ))
802                        .child(
803                            Material::new()
804                                .r#type(MaterialType::Transparency)
805                                .child(child),
806                        )
807                        .into_widget(),
808                );
809            }
810        }
811        if !slices.is_empty() {
812            widgets.push(
813                ListBody::new()
814                    .main_axis(main_axis)
815                    .children(slices)
816                    .into_widget(),
817            );
818        }
819
820        MergeableMaterialListBody {
821            key: None,
822            main_axis,
823            elevation,
824            children: widgets,
825        }
826        .into_widget()
827    }
828}
829
830/// Dart's `_MergeableMaterialSliceKey`: a global key that compares by the slice's local key.
831#[derive(Debug)]
832struct MergeableMaterialSliceKey(KeyRef);
833
834impl waft_foundation::Key for MergeableMaterialSliceKey {
835    fn eq_key(&self, other: &dyn waft_foundation::Key) -> bool {
836        (other as &dyn std::any::Any)
837            .downcast_ref::<MergeableMaterialSliceKey>()
838            .is_some_and(|other| other.0 == self.0)
839    }
840
841    fn hash_key(&self, mut state: &mut dyn std::hash::Hasher) {
842        std::any::TypeId::of::<Self>().hash(&mut state);
843        self.0.hash(&mut state);
844    }
845}
846
847/// Dart's `_MergeableMaterialListBody`.
848struct MergeableMaterialListBody {
849    key: Option<KeyRef>,
850    main_axis: Axis,
851    elevation: f64,
852    children: Vec<WidgetRef>,
853}
854
855impl RenderObjectWidget for MergeableMaterialListBody {
856    type RenderObject = RenderMergeableMaterialListBody;
857
858    fn key(&self) -> Option<&KeyRef> {
859        self.key.as_ref()
860    }
861
862    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
863        let axis_direction = get_axis_direction_from_axis_reverse_and_directionality(
864            app,
865            context,
866            self.main_axis,
867            false,
868        );
869        let render_object = RenderMergeableMaterialListBody::new(app, axis_direction);
870        render_object.set_elevation(app, self.elevation);
871        render_object.as_object()
872    }
873
874    fn update_render_object(
875        &self,
876        app: &mut App,
877        context: BuildContext,
878        render_object: RenderHandle<RenderMergeableMaterialListBody>,
879    ) {
880        let axis_direction = get_axis_direction_from_axis_reverse_and_directionality(
881            app,
882            context,
883            self.main_axis,
884            false,
885        );
886        render_object.set_axis_direction(app, axis_direction);
887        render_object.set_elevation(app, self.elevation);
888    }
889}
890
891impl MultiChildRenderObjectWidget for MergeableMaterialListBody {
892    fn children(&self) -> &[WidgetRef] {
893        &self.children
894    }
895}
896
897impl fmt::Debug for MergeableMaterialListBody {
898    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899        f.debug_struct("MergeableMaterialListBody")
900            .field("main_axis", &self.main_axis)
901            .field("elevation", &self.elevation)
902            .finish_non_exhaustive()
903    }
904}
905
906/// Dart's `_RenderMergeableMaterialListBody`.
907struct RenderMergeableMaterialListBody {
908    render_object: RenderObjectData,
909    render_box: RenderBoxData,
910    container: ContainerRenderObjectData<AnyRenderBox>,
911    list_body: RenderListBodyData,
912    elevation: f64,
913}
914
915impl RenderMergeableMaterialListBody {
916    fn new(
917        app: &mut App,
918        axis_direction: AxisDirection,
919    ) -> RenderHandle<RenderMergeableMaterialListBody> {
920        RenderHandle::new_box(
921            app,
922            RenderMergeableMaterialListBody {
923                render_object: RenderObjectData::new(),
924                render_box: RenderBoxData::new(),
925                container: ContainerRenderObjectData::new(),
926                list_body: RenderListBodyData::new().axis_direction(axis_direction),
927                elevation: 0.0,
928            },
929        )
930    }
931
932    fn elevation(self: RenderHandle<Self>, app: &App) -> f64 {
933        self.get(app).elevation
934    }
935
936    fn set_elevation(self: RenderHandle<Self>, app: &mut App, value: f64) {
937        if self.get(app).elevation == value {
938            return;
939        }
940        self.get_mut(app).elevation = value;
941        self.mark_needs_paint(app);
942    }
943
944    fn paint_shadows(
945        self: RenderHandle<Self>,
946        app: &App,
947        canvas: &mut Canvas,
948        rect: waft_embedder::Rect,
949    ) {
950        let elevation = self.elevation(app);
951        if elevation != 0.0 {
952            let rrect = k_material_edges(MaterialType::Card)
953                .expect("the card material has a radius")
954                .to_rrect(rect);
955            let mut path = PathBuilder::new();
956            path.rrect_radii_elliptical(valo::Rect::from(rect), rrect_radii_elliptical(rrect));
957            draw_shadow(
958                app,
959                canvas,
960                self.as_object().as_box().expect("a list body is a box"),
961                &Path::new(path.build()),
962                Colors::BLACK,
963                elevation,
964                // The occluding object is not (necessarily) opaque.
965                true,
966            );
967        }
968    }
969}
970
971impl ContainerRenderObjectMixin for RenderMergeableMaterialListBody {
972    type ChildType = AnyRenderBox;
973    type ParentDataType = waft_rendering::ListBodyParentData;
974
975    fn container_data(
976        self: RenderHandle<Self>,
977        app: &App,
978    ) -> &ContainerRenderObjectData<AnyRenderBox> {
979        &self.get(app).container
980    }
981
982    fn container_data_mut(
983        self: RenderHandle<Self>,
984        app: &mut App,
985    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
986        &mut self.get_mut(app).container
987    }
988}
989
990impl RenderBoxContainerDefaultsMixin for RenderMergeableMaterialListBody {}
991
992impl RenderListBodyMixin for RenderMergeableMaterialListBody {
993    fn list_body_data(self: RenderHandle<Self>, app: &App) -> &RenderListBodyData {
994        &self.get(app).list_body
995    }
996
997    fn list_body_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderListBodyData {
998        &mut self.get_mut(app).list_body
999    }
1000}
1001
1002impl RenderObject for RenderMergeableMaterialListBody {
1003    waft_rendering::render_object_accessors!();
1004
1005    fn debug_fill_properties(
1006        self: RenderHandle<Self>,
1007        app: &App,
1008        properties: &mut DiagnosticPropertiesBuilder,
1009    ) {
1010        // Dart's `_RenderMergeableMaterialListBody` inherits `RenderListBody.debugFillProperties`.
1011        RenderListBodyMixin::debug_fill_properties(self, app, properties);
1012    }
1013
1014    fn debug_describe_children(
1015        self: RenderHandle<Self>,
1016        app: &App,
1017    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1018        ContainerRenderObjectMixin::debug_describe_children(self, app)
1019    }
1020
1021    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1022        RenderListBodyMixin::perform_layout(self, app)
1023    }
1024
1025    fn visit_children(
1026        self: RenderHandle<Self>,
1027        app: &App,
1028        visitor: &mut dyn FnMut(AnyRenderObject),
1029    ) {
1030        ContainerRenderObjectMixin::visit_children(self, app, visitor)
1031    }
1032
1033    fn did_attach(
1034        self: RenderHandle<Self>,
1035        app: &mut App,
1036        owner: Handle<waft_rendering::PipelineOwner>,
1037    ) {
1038        ContainerRenderObjectMixin::did_attach(self, app, owner)
1039    }
1040
1041    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1042        ContainerRenderObjectMixin::did_detach(self, app)
1043    }
1044
1045    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1046        ContainerRenderObjectMixin::redepth_children(self, app)
1047    }
1048
1049    fn paint(
1050        self: RenderHandle<Self>,
1051        app: &mut App,
1052        context: &mut waft_rendering::PaintingContext,
1053        offset: Offset,
1054    ) {
1055        let mut child = self.first_child(app);
1056        let mut index = 0;
1057        while let Some(current) = child {
1058            let parent_data = current
1059                .as_object()
1060                .parent_data_of::<waft_rendering::ListBodyParentData>(app);
1061            let child_offset = parent_data.box_parent_data().offset;
1062            let size = current.size(app);
1063            let rect = waft_embedder::Rect::from_ltwh(
1064                child_offset.dx() + offset.dx(),
1065                child_offset.dy() + offset.dy(),
1066                size.width(),
1067                size.height(),
1068            );
1069            if index % 2 == 0 {
1070                self.paint_shadows(app, context.canvas(), rect);
1071            }
1072            child = parent_data.next_sibling();
1073            index += 1;
1074        }
1075        RenderListBodyMixin::paint(self, app, context, offset)
1076    }
1077}
1078
1079impl RenderBox for RenderMergeableMaterialListBody {
1080    waft_rendering::render_box_accessors!();
1081
1082    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1083        RenderListBodyMixin::setup_parent_data(self, app, child)
1084    }
1085
1086    fn compute_dry_baseline(
1087        self: RenderHandle<Self>,
1088        app: &mut App,
1089        constraints: BoxConstraints,
1090        baseline: TextBaseline,
1091    ) -> Option<f64> {
1092        RenderListBodyMixin::compute_dry_baseline(self, app, constraints, baseline)
1093    }
1094
1095    fn compute_dry_layout(
1096        self: RenderHandle<Self>,
1097        app: &mut App,
1098        constraints: BoxConstraints,
1099    ) -> Size {
1100        RenderListBodyMixin::compute_dry_layout(self, app, constraints)
1101    }
1102
1103    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1104        RenderListBodyMixin::compute_min_intrinsic_width(self, app, height)
1105    }
1106
1107    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1108        RenderListBodyMixin::compute_max_intrinsic_width(self, app, height)
1109    }
1110
1111    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1112        RenderListBodyMixin::compute_min_intrinsic_height(self, app, width)
1113    }
1114
1115    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1116        RenderListBodyMixin::compute_max_intrinsic_height(self, app, width)
1117    }
1118
1119    fn compute_distance_to_actual_baseline(
1120        self: RenderHandle<Self>,
1121        app: &mut App,
1122        baseline: TextBaseline,
1123    ) -> Option<f64> {
1124        RenderListBodyMixin::compute_distance_to_actual_baseline(self, app, baseline)
1125    }
1126
1127    fn hit_test_children(
1128        self: RenderHandle<Self>,
1129        app: &mut App,
1130        result: &mut BoxHitTestResult<'_>,
1131        position: Offset,
1132    ) -> bool {
1133        RenderListBodyMixin::hit_test_children(self, app, result, position)
1134    }
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use std::time::Duration;
1140
1141    use waft_embedder::{Rect, Size};
1142    use waft_foundation::ValueKey;
1143    use waft_painting::{Border, BorderRadius, BorderRadiusGeometry, BorderSide, BoxDecoration};
1144    use waft_rendering::AnyRenderBox;
1145    use waft_rendering::testing::{PaintCall, assert_paints, paints};
1146    use waft_widgets::testing::{WidgetTester, find, test_widgets};
1147    use waft_widgets::{
1148        AnimatedContainer, Container, DecoratedBox, IntoWidget, SingleChildScrollView, SizedBox,
1149        Text, WidgetRef,
1150    };
1151
1152    use super::{MaterialGap, MaterialSlice, MergeableMaterial, MergeableMaterialItem};
1153    use crate::app::MaterialApp;
1154    use crate::colors::Colors;
1155    use crate::material::{MaterialType, k_material_edges};
1156    use crate::scaffold::Scaffold;
1157    use crate::test_support::PaintInspection;
1158    use crate::theme_data::ThemeData;
1159
1160    #[derive(Clone, Copy)]
1161    enum RadiusType {
1162        Sharp,
1163        Shifting,
1164        Round,
1165    }
1166
1167    fn card_radius() -> waft_embedder::Radius {
1168        k_material_edges(MaterialType::Card)
1169            .expect("the card material has a radius")
1170            .top_left
1171    }
1172
1173    /// Dart's `matches`: the corners at the top and at the bottom of `border_radius` are each
1174    /// sharp, on their way between sharp and the card's radius, or the card's radius.
1175    fn matches(border_radius: Option<BorderRadius>, top: RadiusType, bottom: RadiusType) {
1176        let border_radius = border_radius.expect("the slice has a border radius");
1177        matches_corners(border_radius.top_left, border_radius.top_right, top);
1178        matches_corners(
1179            border_radius.bottom_left,
1180            border_radius.bottom_right,
1181            bottom,
1182        );
1183    }
1184
1185    /// One of the two `switch`es of Dart's `matches`, on the two corners of one end.
1186    fn matches_corners(
1187        left: waft_embedder::Radius,
1188        right: waft_embedder::Radius,
1189        radius_type: RadiusType,
1190    ) {
1191        let card_radius = card_radius();
1192        match radius_type {
1193            RadiusType::Sharp => {
1194                assert_eq!(left, waft_embedder::Radius::ZERO);
1195                assert_eq!(right, waft_embedder::Radius::ZERO);
1196            }
1197            RadiusType::Shifting => {
1198                for corner in [left, right] {
1199                    assert!(corner.x > 0.0, "{corner:?} is shifting");
1200                    assert!(corner.x < card_radius.x, "{corner:?} is shifting");
1201                    assert!(corner.y > 0.0, "{corner:?} is shifting");
1202                    assert!(corner.y < card_radius.y, "{corner:?} is shifting");
1203                }
1204            }
1205            RadiusType::Round => {
1206                assert_eq!(left, card_radius);
1207                assert_eq!(right, card_radius);
1208            }
1209        }
1210    }
1211
1212    /// Dart's `getBorderRadius`: the border radius of the decoration of the `index`th
1213    /// `Container`, which depends on the exact structure Material and MergeableMaterial build.
1214    fn get_border_radius(tester: &WidgetTester, index: usize) -> Option<BorderRadius> {
1215        let containers = find::by_type::<Container>().evaluate(tester);
1216        tester.widget(containers[index], |container: &Container| {
1217            box_decoration(container.decoration.as_ref())
1218                .border_radius
1219                .map(|border_radius| match border_radius {
1220                    BorderRadiusGeometry::BorderRadius(border_radius) => border_radius,
1221                    _ => panic!("the radius is a BorderRadius"),
1222                })
1223        })
1224    }
1225
1226    /// Dart's `isDivider`.
1227    fn is_divider(decoration: &BoxDecoration, top: bool, bottom: bool) -> bool {
1228        let side = BorderSide::new(
1229            waft_embedder::Color::new(0x1F000000),
1230            0.5,
1231            waft_painting::BorderStyle::Solid,
1232            BorderSide::STROKE_ALIGN_INSIDE,
1233        );
1234        let side_if = |shown: bool| if shown { side } else { BorderSide::NONE };
1235        *decoration
1236            == BoxDecoration::new().border(Border {
1237                top: side_if(top),
1238                bottom: side_if(bottom),
1239                ..Border::from_border_side(BorderSide::NONE)
1240            })
1241    }
1242
1243    /// Dart's `decoration! as BoxDecoration`.
1244    fn box_decoration(decoration: Option<&waft_painting::DecorationRef>) -> BoxDecoration {
1245        decoration
1246            .expect("the widget has a decoration")
1247            .as_any()
1248            .downcast_ref::<BoxDecoration>()
1249            .expect("the decoration is a BoxDecoration")
1250            .clone()
1251    }
1252
1253    /// The decorations of every `AnimatedContainer`, in tree order.
1254    fn animated_container_decorations(tester: &WidgetTester) -> Vec<BoxDecoration> {
1255        find::by_type::<AnimatedContainer>()
1256            .evaluate(tester)
1257            .into_iter()
1258            .map(|container| {
1259                tester.widget(container, |container: &AnimatedContainer| {
1260                    box_decoration(container.decoration.as_ref())
1261                })
1262            })
1263            .collect()
1264    }
1265
1266    /// Dart's `MaterialSlice(key: ValueKey<String>(key), child: SizedBox(width: 100.0, height: 100.0))`.
1267    fn slice(key: &'static str) -> MergeableMaterialItem {
1268        MaterialSlice::new(
1269            ValueKey::new(key),
1270            SizedBox::new().width(100.0).height(100.0),
1271        )
1272        .into()
1273    }
1274
1275    /// Dart's `MaterialGap(key: ValueKey<String>(key))`.
1276    fn gap(key: &'static str) -> MergeableMaterialItem {
1277        MaterialGap::new(ValueKey::new(key)).into()
1278    }
1279
1280    /// Dart's `Scaffold(body: SingleChildScrollView(child: material))`.
1281    fn scaffold(material: MergeableMaterial) -> Scaffold {
1282        Scaffold::new().body(SingleChildScrollView::new().child(material))
1283    }
1284
1285    /// Dart's `MaterialApp(home: Scaffold(body: SingleChildScrollView(child: material)))`.
1286    fn app(material: MergeableMaterial) -> WidgetRef {
1287        MaterialApp::new().home(scaffold(material)).into_widget()
1288    }
1289
1290    /// Dart's `MaterialApp(theme: theme, home: Scaffold(body: SingleChildScrollView(child:
1291    /// material)))`.
1292    fn themed_app(theme: ThemeData, material: MergeableMaterial) -> WidgetRef {
1293        MaterialApp::new()
1294            .theme(theme)
1295            .home(scaffold(material))
1296            .into_widget()
1297    }
1298
1299    /// Dart's `ThemeData(useMaterial3: false)`.
1300    fn material2_theme(tester: &WidgetTester) -> ThemeData {
1301        ThemeData::builder()
1302            .use_material3(false)
1303            .build(&tester.cell.borrow())
1304    }
1305
1306    /// Dart's `tester.renderObject(find.byType(MergeableMaterial))` as a `RenderBox`.
1307    fn mergeable_material_box(tester: &WidgetTester) -> AnyRenderBox {
1308        tester
1309            .render_object(find::by_type::<MergeableMaterial>())
1310            .as_box()
1311            .expect("MergeableMaterial renders a box")
1312    }
1313
1314    /// Dart's `box.size.height`.
1315    fn height(tester: &WidgetTester, render_box: AnyRenderBox) -> f64 {
1316        tester.get_size(render_box).height()
1317    }
1318
1319    #[test]
1320    fn mergeable_material_empty() {
1321        test_widgets(|tester| {
1322            tester.pump_widget(app(MergeableMaterial::new()));
1323
1324            let render_box = mergeable_material_box(tester);
1325            assert_eq!(height(tester, render_box), 0.0);
1326        });
1327    }
1328
1329    #[test]
1330    fn mergeable_material_update_slice() {
1331        test_widgets(|tester| {
1332            let sized_slice = |height: f64| -> MergeableMaterialItem {
1333                MaterialSlice::new(
1334                    ValueKey::new("A"),
1335                    SizedBox::new().width(100.0).height(height),
1336                )
1337                .into()
1338            };
1339            tester.pump_widget(app(MergeableMaterial::new().children([sized_slice(100.0)])));
1340
1341            let mut render_box = mergeable_material_box(tester);
1342            assert_eq!(height(tester, render_box), 100.0);
1343
1344            tester.pump_widget(app(MergeableMaterial::new().children([sized_slice(200.0)])));
1345
1346            render_box = mergeable_material_box(tester);
1347            assert_eq!(height(tester, render_box), 200.0);
1348        });
1349    }
1350
1351    #[test]
1352    fn replacing_the_last_slice_with_a_new_key_updates_the_list() {
1353        test_widgets(|tester| {
1354            let labeled_slice = |key: &'static str, label: &'static str| -> MergeableMaterialItem {
1355                MaterialSlice::new(
1356                    ValueKey::new(key),
1357                    SizedBox::new()
1358                        .width(100.0)
1359                        .height(100.0)
1360                        .child(Text::new(label)),
1361                )
1362                .into()
1363            };
1364            tester.pump_widget(app(
1365                MergeableMaterial::new().children([labeled_slice("A", "First")])
1366            ));
1367            assert_eq!(find::text("First").evaluate(tester).len(), 1);
1368
1369            tester.pump_widget(app(
1370                MergeableMaterial::new().children([labeled_slice("B", "Second")])
1371            ));
1372            tester.pump_and_settle();
1373            assert!(find::text("First").evaluate(tester).is_empty());
1374            assert_eq!(find::text("Second").evaluate(tester).len(), 1);
1375            assert_eq!(height(tester, mergeable_material_box(tester)), 100.0);
1376        });
1377    }
1378
1379    #[test]
1380    fn mergeable_material_swap_slices() {
1381        test_widgets(|tester| {
1382            tester.pump_widget(app(
1383                MergeableMaterial::new().children([slice("A"), slice("B")])
1384            ));
1385
1386            let mut render_box = mergeable_material_box(tester);
1387            assert_eq!(height(tester, render_box), 200.0);
1388
1389            matches(
1390                get_border_radius(tester, 0),
1391                RadiusType::Round,
1392                RadiusType::Sharp,
1393            );
1394            matches(
1395                get_border_radius(tester, 1),
1396                RadiusType::Sharp,
1397                RadiusType::Round,
1398            );
1399
1400            tester.pump_widget(app(
1401                MergeableMaterial::new().children([slice("B"), slice("A")])
1402            ));
1403
1404            render_box = mergeable_material_box(tester);
1405            assert_eq!(height(tester, render_box), 200.0);
1406
1407            tester.pump_by(Duration::from_millis(100));
1408            assert_eq!(height(tester, render_box), 200.0);
1409
1410            matches(
1411                get_border_radius(tester, 0),
1412                RadiusType::Round,
1413                RadiusType::Sharp,
1414            );
1415            matches(
1416                get_border_radius(tester, 1),
1417                RadiusType::Sharp,
1418                RadiusType::Round,
1419            );
1420        });
1421    }
1422
1423    #[test]
1424    fn mergeable_material_paints_shadows() {
1425        test_widgets(|tester| {
1426            let theme = material2_theme(tester);
1427            tester.pump_widget(themed_app(
1428                theme,
1429                MergeableMaterial::new().children([slice("A")]),
1430            ));
1431
1432            let rrect = k_material_edges(MaterialType::Card)
1433                .expect("the card material has a radius")
1434                .to_rrect(Rect::from_ltrb(0.0, 0.0, 800.0, 100.0));
1435            let ops =
1436                tester.painted_ops(tester.render_object(find::by_type::<MergeableMaterial>()));
1437            assert_paints(
1438                &ops,
1439                &[
1440                    PaintCall::shadow_with_elevation(2.0, None),
1441                    PaintCall::RRect {
1442                        rrect: Some(rrect),
1443                        color: Some(Colors::WHITE),
1444                        style: None,
1445                        has_mask_filter: Some(false),
1446                    },
1447                ],
1448            );
1449        });
1450    }
1451
1452    #[test]
1453    fn mergeable_material_skips_shadow_for_zero_elevation() {
1454        test_widgets(|tester| {
1455            tester.pump_widget(app(MergeableMaterial::new()
1456                .elevation(0.0)
1457                .children([slice("A")])));
1458
1459            let ops =
1460                tester.painted_ops(tester.render_object(find::by_type::<MergeableMaterial>()));
1461            assert!(
1462                paints(&ops, &[PaintCall::shadow_with_elevation(0.0, None)]).is_err(),
1463                "MergeableMaterial paints no shadow at zero elevation"
1464            );
1465        });
1466    }
1467
1468    #[test]
1469    fn mergeable_material_merge_gap() {
1470        test_widgets(|tester| {
1471            tester.pump_widget(app(MergeableMaterial::new().children([
1472                slice("A"),
1473                gap("x"),
1474                slice("B"),
1475            ])));
1476
1477            let render_box = mergeable_material_box(tester);
1478            assert_eq!(height(tester, render_box), 216.0);
1479
1480            matches(
1481                get_border_radius(tester, 0),
1482                RadiusType::Round,
1483                RadiusType::Round,
1484            );
1485            matches(
1486                get_border_radius(tester, 1),
1487                RadiusType::Round,
1488                RadiusType::Round,
1489            );
1490
1491            tester.pump_widget(app(
1492                MergeableMaterial::new().children([slice("A"), slice("B")])
1493            ));
1494
1495            tester.pump_by(Duration::from_millis(100));
1496            assert!(height(tester, render_box) < 216.0);
1497
1498            matches(
1499                get_border_radius(tester, 0),
1500                RadiusType::Round,
1501                RadiusType::Shifting,
1502            );
1503            matches(
1504                get_border_radius(tester, 1),
1505                RadiusType::Shifting,
1506                RadiusType::Round,
1507            );
1508
1509            tester.pump_by(Duration::from_millis(100));
1510            assert_eq!(height(tester, render_box), 200.0);
1511
1512            matches(
1513                get_border_radius(tester, 0),
1514                RadiusType::Round,
1515                RadiusType::Sharp,
1516            );
1517            matches(
1518                get_border_radius(tester, 1),
1519                RadiusType::Sharp,
1520                RadiusType::Round,
1521            );
1522        });
1523    }
1524
1525    #[test]
1526    fn mergeable_material_separate_slices() {
1527        test_widgets(|tester| {
1528            tester.pump_widget(app(
1529                MergeableMaterial::new().children([slice("A"), slice("B")])
1530            ));
1531
1532            let render_box = mergeable_material_box(tester);
1533            assert_eq!(height(tester, render_box), 200.0);
1534
1535            matches(
1536                get_border_radius(tester, 0),
1537                RadiusType::Round,
1538                RadiusType::Sharp,
1539            );
1540            matches(
1541                get_border_radius(tester, 1),
1542                RadiusType::Sharp,
1543                RadiusType::Round,
1544            );
1545
1546            tester.pump_widget(app(MergeableMaterial::new().children([
1547                slice("A"),
1548                gap("x"),
1549                slice("B"),
1550            ])));
1551
1552            tester.pump_by(Duration::from_millis(100));
1553            assert!(height(tester, render_box) < 216.0);
1554
1555            matches(
1556                get_border_radius(tester, 0),
1557                RadiusType::Round,
1558                RadiusType::Shifting,
1559            );
1560            matches(
1561                get_border_radius(tester, 1),
1562                RadiusType::Shifting,
1563                RadiusType::Round,
1564            );
1565
1566            tester.pump_by(Duration::from_millis(100));
1567            assert_eq!(height(tester, render_box), 216.0);
1568
1569            matches(
1570                get_border_radius(tester, 0),
1571                RadiusType::Round,
1572                RadiusType::Round,
1573            );
1574            matches(
1575                get_border_radius(tester, 1),
1576                RadiusType::Round,
1577                RadiusType::Round,
1578            );
1579        });
1580    }
1581
1582    #[test]
1583    fn mergeable_material_separate_merge_separate() {
1584        test_widgets(|tester| {
1585            tester.pump_widget(app(
1586                MergeableMaterial::new().children([slice("A"), slice("B")])
1587            ));
1588
1589            let render_box = mergeable_material_box(tester);
1590            assert_eq!(height(tester, render_box), 200.0);
1591
1592            matches(
1593                get_border_radius(tester, 0),
1594                RadiusType::Round,
1595                RadiusType::Sharp,
1596            );
1597            matches(
1598                get_border_radius(tester, 1),
1599                RadiusType::Sharp,
1600                RadiusType::Round,
1601            );
1602
1603            tester.pump_widget(app(MergeableMaterial::new().children([
1604                slice("A"),
1605                gap("x"),
1606                slice("B"),
1607            ])));
1608
1609            tester.pump_by(Duration::from_millis(100));
1610            assert!(height(tester, render_box) < 216.0);
1611
1612            matches(
1613                get_border_radius(tester, 0),
1614                RadiusType::Round,
1615                RadiusType::Shifting,
1616            );
1617            matches(
1618                get_border_radius(tester, 1),
1619                RadiusType::Shifting,
1620                RadiusType::Round,
1621            );
1622
1623            tester.pump_by(Duration::from_millis(100));
1624            assert_eq!(height(tester, render_box), 216.0);
1625
1626            matches(
1627                get_border_radius(tester, 0),
1628                RadiusType::Round,
1629                RadiusType::Round,
1630            );
1631            matches(
1632                get_border_radius(tester, 1),
1633                RadiusType::Round,
1634                RadiusType::Round,
1635            );
1636
1637            tester.pump_widget(app(
1638                MergeableMaterial::new().children([slice("A"), slice("B")])
1639            ));
1640
1641            tester.pump_by(Duration::from_millis(100));
1642            assert!(height(tester, render_box) < 216.0);
1643
1644            matches(
1645                get_border_radius(tester, 0),
1646                RadiusType::Round,
1647                RadiusType::Shifting,
1648            );
1649            matches(
1650                get_border_radius(tester, 1),
1651                RadiusType::Shifting,
1652                RadiusType::Round,
1653            );
1654
1655            tester.pump_by(Duration::from_millis(100));
1656            assert_eq!(height(tester, render_box), 200.0);
1657
1658            matches(
1659                get_border_radius(tester, 0),
1660                RadiusType::Round,
1661                RadiusType::Sharp,
1662            );
1663            matches(
1664                get_border_radius(tester, 1),
1665                RadiusType::Sharp,
1666                RadiusType::Round,
1667            );
1668
1669            tester.pump_widget(app(MergeableMaterial::new().children([
1670                slice("A"),
1671                gap("x"),
1672                slice("B"),
1673            ])));
1674
1675            tester.pump_by(Duration::from_millis(100));
1676            assert!(height(tester, render_box) < 216.0);
1677
1678            matches(
1679                get_border_radius(tester, 0),
1680                RadiusType::Round,
1681                RadiusType::Shifting,
1682            );
1683            matches(
1684                get_border_radius(tester, 1),
1685                RadiusType::Shifting,
1686                RadiusType::Round,
1687            );
1688
1689            tester.pump_by(Duration::from_millis(100));
1690            assert_eq!(height(tester, render_box), 216.0);
1691
1692            matches(
1693                get_border_radius(tester, 0),
1694                RadiusType::Round,
1695                RadiusType::Round,
1696            );
1697            matches(
1698                get_border_radius(tester, 1),
1699                RadiusType::Round,
1700                RadiusType::Round,
1701            );
1702        });
1703    }
1704
1705    #[test]
1706    fn mergeable_material_insert_slice() {
1707        test_widgets(|tester| {
1708            tester.pump_widget(app(
1709                MergeableMaterial::new().children([slice("A"), slice("C")])
1710            ));
1711
1712            let render_box = mergeable_material_box(tester);
1713            assert_eq!(height(tester, render_box), 200.0);
1714
1715            matches(
1716                get_border_radius(tester, 0),
1717                RadiusType::Round,
1718                RadiusType::Sharp,
1719            );
1720            matches(
1721                get_border_radius(tester, 1),
1722                RadiusType::Sharp,
1723                RadiusType::Round,
1724            );
1725
1726            tester.pump_widget(app(MergeableMaterial::new().children([
1727                slice("A"),
1728                slice("B"),
1729                slice("C"),
1730            ])));
1731
1732            assert_eq!(height(tester, render_box), 300.0);
1733
1734            matches(
1735                get_border_radius(tester, 0),
1736                RadiusType::Round,
1737                RadiusType::Sharp,
1738            );
1739            matches(
1740                get_border_radius(tester, 1),
1741                RadiusType::Sharp,
1742                RadiusType::Sharp,
1743            );
1744            matches(
1745                get_border_radius(tester, 2),
1746                RadiusType::Sharp,
1747                RadiusType::Round,
1748            );
1749        });
1750    }
1751
1752    #[test]
1753    fn mergeable_material_remove_slice() {
1754        test_widgets(|tester| {
1755            tester.pump_widget(app(MergeableMaterial::new().children([
1756                slice("A"),
1757                slice("B"),
1758                slice("C"),
1759            ])));
1760
1761            let render_box = mergeable_material_box(tester);
1762            assert_eq!(height(tester, render_box), 300.0);
1763
1764            matches(
1765                get_border_radius(tester, 0),
1766                RadiusType::Round,
1767                RadiusType::Sharp,
1768            );
1769            matches(
1770                get_border_radius(tester, 1),
1771                RadiusType::Sharp,
1772                RadiusType::Sharp,
1773            );
1774            matches(
1775                get_border_radius(tester, 2),
1776                RadiusType::Sharp,
1777                RadiusType::Round,
1778            );
1779
1780            tester.pump_widget(app(
1781                MergeableMaterial::new().children([slice("A"), slice("C")])
1782            ));
1783
1784            tester.pump();
1785            assert_eq!(height(tester, render_box), 200.0);
1786
1787            matches(
1788                get_border_radius(tester, 0),
1789                RadiusType::Round,
1790                RadiusType::Sharp,
1791            );
1792            matches(
1793                get_border_radius(tester, 1),
1794                RadiusType::Sharp,
1795                RadiusType::Round,
1796            );
1797        });
1798    }
1799
1800    #[test]
1801    fn mergeable_material_insert_chunk() {
1802        test_widgets(|tester| {
1803            tester.pump_widget(app(
1804                MergeableMaterial::new().children([slice("A"), slice("C")])
1805            ));
1806
1807            let render_box = mergeable_material_box(tester);
1808            assert_eq!(height(tester, render_box), 200.0);
1809
1810            matches(
1811                get_border_radius(tester, 0),
1812                RadiusType::Round,
1813                RadiusType::Sharp,
1814            );
1815            matches(
1816                get_border_radius(tester, 1),
1817                RadiusType::Sharp,
1818                RadiusType::Round,
1819            );
1820
1821            tester.pump_widget(app(MergeableMaterial::new().children([
1822                slice("A"),
1823                gap("x"),
1824                slice("B"),
1825                gap("y"),
1826                slice("C"),
1827            ])));
1828
1829            tester.pump_by(Duration::from_millis(100));
1830            assert!(height(tester, render_box) < 332.0);
1831
1832            matches(
1833                get_border_radius(tester, 0),
1834                RadiusType::Round,
1835                RadiusType::Shifting,
1836            );
1837            matches(
1838                get_border_radius(tester, 1),
1839                RadiusType::Shifting,
1840                RadiusType::Shifting,
1841            );
1842            matches(
1843                get_border_radius(tester, 2),
1844                RadiusType::Shifting,
1845                RadiusType::Round,
1846            );
1847
1848            tester.pump_by(Duration::from_millis(100));
1849            assert_eq!(height(tester, render_box), 332.0);
1850
1851            matches(
1852                get_border_radius(tester, 0),
1853                RadiusType::Round,
1854                RadiusType::Round,
1855            );
1856            matches(
1857                get_border_radius(tester, 1),
1858                RadiusType::Round,
1859                RadiusType::Round,
1860            );
1861            matches(
1862                get_border_radius(tester, 2),
1863                RadiusType::Round,
1864                RadiusType::Round,
1865            );
1866        });
1867    }
1868
1869    #[test]
1870    fn mergeable_material_remove_chunk() {
1871        test_widgets(|tester| {
1872            tester.pump_widget(app(MergeableMaterial::new().children([
1873                slice("A"),
1874                gap("x"),
1875                slice("B"),
1876                gap("y"),
1877                slice("C"),
1878            ])));
1879
1880            let render_box = mergeable_material_box(tester);
1881            assert_eq!(height(tester, render_box), 332.0);
1882
1883            matches(
1884                get_border_radius(tester, 0),
1885                RadiusType::Round,
1886                RadiusType::Round,
1887            );
1888            matches(
1889                get_border_radius(tester, 1),
1890                RadiusType::Round,
1891                RadiusType::Round,
1892            );
1893            matches(
1894                get_border_radius(tester, 2),
1895                RadiusType::Round,
1896                RadiusType::Round,
1897            );
1898
1899            tester.pump_widget(app(
1900                MergeableMaterial::new().children([slice("A"), slice("C")])
1901            ));
1902
1903            tester.pump_by(Duration::from_millis(100));
1904            assert!(height(tester, render_box) < 332.0);
1905
1906            matches(
1907                get_border_radius(tester, 0),
1908                RadiusType::Round,
1909                RadiusType::Shifting,
1910            );
1911            matches(
1912                get_border_radius(tester, 1),
1913                RadiusType::Shifting,
1914                RadiusType::Round,
1915            );
1916
1917            tester.pump_by(Duration::from_millis(100));
1918            assert_eq!(height(tester, render_box), 200.0);
1919
1920            matches(
1921                get_border_radius(tester, 0),
1922                RadiusType::Round,
1923                RadiusType::Sharp,
1924            );
1925            matches(
1926                get_border_radius(tester, 1),
1927                RadiusType::Sharp,
1928                RadiusType::Round,
1929            );
1930        });
1931    }
1932
1933    #[test]
1934    fn mergeable_material_replace_gap_with_chunk() {
1935        test_widgets(|tester| {
1936            tester.pump_widget(app(MergeableMaterial::new().children([
1937                slice("A"),
1938                gap("x"),
1939                slice("C"),
1940            ])));
1941
1942            let render_box = mergeable_material_box(tester);
1943            assert_eq!(height(tester, render_box), 216.0);
1944
1945            matches(
1946                get_border_radius(tester, 0),
1947                RadiusType::Round,
1948                RadiusType::Round,
1949            );
1950            matches(
1951                get_border_radius(tester, 1),
1952                RadiusType::Round,
1953                RadiusType::Round,
1954            );
1955
1956            tester.pump_widget(app(MergeableMaterial::new().children([
1957                slice("A"),
1958                gap("y"),
1959                slice("B"),
1960                gap("z"),
1961                slice("C"),
1962            ])));
1963
1964            tester.pump_by(Duration::from_millis(100));
1965            assert!(height(tester, render_box) < 332.0);
1966
1967            matches(
1968                get_border_radius(tester, 0),
1969                RadiusType::Round,
1970                RadiusType::Shifting,
1971            );
1972            matches(
1973                get_border_radius(tester, 1),
1974                RadiusType::Shifting,
1975                RadiusType::Shifting,
1976            );
1977            matches(
1978                get_border_radius(tester, 2),
1979                RadiusType::Shifting,
1980                RadiusType::Round,
1981            );
1982
1983            tester.pump_by(Duration::from_millis(100));
1984            assert_eq!(height(tester, render_box), 332.0);
1985
1986            matches(
1987                get_border_radius(tester, 0),
1988                RadiusType::Round,
1989                RadiusType::Round,
1990            );
1991            matches(
1992                get_border_radius(tester, 1),
1993                RadiusType::Round,
1994                RadiusType::Round,
1995            );
1996            matches(
1997                get_border_radius(tester, 2),
1998                RadiusType::Round,
1999                RadiusType::Round,
2000            );
2001        });
2002    }
2003
2004    #[test]
2005    fn mergeable_material_replace_chunk_with_gap() {
2006        test_widgets(|tester| {
2007            tester.pump_widget(app(MergeableMaterial::new().children([
2008                slice("A"),
2009                gap("x"),
2010                slice("B"),
2011                gap("y"),
2012                slice("C"),
2013            ])));
2014
2015            let render_box = mergeable_material_box(tester);
2016            assert_eq!(height(tester, render_box), 332.0);
2017
2018            matches(
2019                get_border_radius(tester, 0),
2020                RadiusType::Round,
2021                RadiusType::Round,
2022            );
2023            matches(
2024                get_border_radius(tester, 1),
2025                RadiusType::Round,
2026                RadiusType::Round,
2027            );
2028            matches(
2029                get_border_radius(tester, 2),
2030                RadiusType::Round,
2031                RadiusType::Round,
2032            );
2033
2034            tester.pump_widget(app(MergeableMaterial::new().children([
2035                slice("A"),
2036                gap("z"),
2037                slice("C"),
2038            ])));
2039
2040            tester.pump_by(Duration::from_millis(100));
2041            assert!(height(tester, render_box) < 332.0);
2042
2043            matches(
2044                get_border_radius(tester, 0),
2045                RadiusType::Round,
2046                RadiusType::Shifting,
2047            );
2048            matches(
2049                get_border_radius(tester, 1),
2050                RadiusType::Shifting,
2051                RadiusType::Round,
2052            );
2053
2054            tester.pump_by(Duration::from_millis(100));
2055            assert_eq!(height(tester, render_box), 216.0);
2056
2057            matches(
2058                get_border_radius(tester, 0),
2059                RadiusType::Round,
2060                RadiusType::Round,
2061            );
2062            matches(
2063                get_border_radius(tester, 1),
2064                RadiusType::Round,
2065                RadiusType::Round,
2066            );
2067        });
2068    }
2069
2070    #[test]
2071    fn mergeable_material_insert_and_separate_slice() {
2072        test_widgets(|tester| {
2073            tester.pump_widget(app(MergeableMaterial::new().children([slice("A")])));
2074
2075            let render_box = mergeable_material_box(tester);
2076            assert_eq!(height(tester, render_box), 100.0);
2077
2078            matches(
2079                get_border_radius(tester, 0),
2080                RadiusType::Round,
2081                RadiusType::Round,
2082            );
2083
2084            tester.pump_widget(app(MergeableMaterial::new().children([
2085                slice("A"),
2086                gap("x"),
2087                slice("B"),
2088            ])));
2089
2090            tester.pump_by(Duration::from_millis(100));
2091            assert!(height(tester, render_box) < 216.0);
2092
2093            matches(
2094                get_border_radius(tester, 0),
2095                RadiusType::Round,
2096                RadiusType::Shifting,
2097            );
2098            matches(
2099                get_border_radius(tester, 1),
2100                RadiusType::Shifting,
2101                RadiusType::Round,
2102            );
2103
2104            tester.pump_by(Duration::from_millis(100));
2105            assert_eq!(height(tester, render_box), 216.0);
2106
2107            matches(
2108                get_border_radius(tester, 0),
2109                RadiusType::Round,
2110                RadiusType::Round,
2111            );
2112            matches(
2113                get_border_radius(tester, 1),
2114                RadiusType::Round,
2115                RadiusType::Round,
2116            );
2117        });
2118    }
2119
2120    #[test]
2121    fn mergeable_material_dividers() {
2122        test_widgets(|tester| {
2123            let theme = material2_theme(tester);
2124            tester.pump_widget(themed_app(
2125                theme.clone(),
2126                MergeableMaterial::new().has_dividers(true).children([
2127                    slice("A"),
2128                    slice("B"),
2129                    slice("C"),
2130                    slice("D"),
2131                ]),
2132            ));
2133
2134            let mut boxes = animated_container_decorations(tester);
2135
2136            let mut offset = 0;
2137
2138            assert!(is_divider(&boxes[offset], false, true));
2139            assert!(is_divider(&boxes[offset + 1], true, true));
2140            assert!(is_divider(&boxes[offset + 2], true, true));
2141            assert!(is_divider(&boxes[offset + 3], true, false));
2142
2143            tester.pump_widget(themed_app(
2144                theme,
2145                MergeableMaterial::new().has_dividers(true).children([
2146                    slice("A"),
2147                    slice("B"),
2148                    gap("x"),
2149                    slice("C"),
2150                    slice("D"),
2151                ]),
2152            ));
2153
2154            // Wait for dividers to shrink.
2155            tester.pump_by(Duration::from_millis(200));
2156
2157            boxes = animated_container_decorations(tester);
2158
2159            offset = 0;
2160
2161            assert!(is_divider(&boxes[offset], false, true));
2162            assert!(is_divider(&boxes[offset + 1], true, false));
2163            assert!(is_divider(&boxes[offset + 2], false, true));
2164            assert!(is_divider(&boxes[offset + 3], true, false));
2165        });
2166    }
2167
2168    #[test]
2169    fn mergeable_material_respects_divider_color() {
2170        test_widgets(|tester| {
2171            let divider_color = Colors::RED.primary();
2172            tester.pump_widget(app(MergeableMaterial::new()
2173                .has_dividers(true)
2174                .divider_color(divider_color)
2175                .children([slice("A"), slice("B")])));
2176
2177            let decoration = tester.widget(
2178                find::by_type::<DecoratedBox>().last(),
2179                |decorated_box: &DecoratedBox| box_decoration(Some(&decorated_box.decoration)),
2180            );
2181            // Since we are getting the last DecoratedBox, it will have a Border.top.
2182            assert_eq!(
2183                decoration
2184                    .border
2185                    .expect("the decoration has a border")
2186                    .top()
2187                    .color,
2188                divider_color
2189            );
2190        });
2191    }
2192
2193    #[test]
2194    fn mergeable_material_respects_material_slice_color() {
2195        test_widgets(|tester| {
2196            let theme_card_color = Colors::RED.primary();
2197            let material_slice_color = Colors::GREEN.primary();
2198
2199            let theme = ThemeData::builder()
2200                .card_color(theme_card_color)
2201                .build(&tester.cell.borrow());
2202            tester.pump_widget(themed_app(
2203                theme,
2204                MergeableMaterial::new().children([
2205                    MaterialSlice::new(
2206                        ValueKey::new("A"),
2207                        SizedBox::new().height(100.0).width(100.0),
2208                    )
2209                    .color(material_slice_color)
2210                    .into(),
2211                    gap("B"),
2212                    MaterialSlice::new(
2213                        ValueKey::new("C"),
2214                        SizedBox::new().height(100.0).width(100.0),
2215                    )
2216                    .into(),
2217                ]),
2218            ));
2219
2220            let container_color = |finder: waft_widgets::testing::Finder| {
2221                tester.widget(finder, |container: &Container| {
2222                    box_decoration(container.decoration.as_ref())
2223                        .color
2224                        .map(|color| color.color())
2225                })
2226            };
2227            assert_eq!(
2228                container_color(find::by_type::<Container>().first()),
2229                Some(material_slice_color)
2230            );
2231            assert_eq!(
2232                container_color(find::by_type::<Container>().last()),
2233                Some(theme_card_color)
2234            );
2235        });
2236    }
2237
2238    #[test]
2239    fn mergeable_material_does_not_crash_at_zero_area() {
2240        test_widgets(|tester| {
2241            tester.view().set_physical_size(Size::ZERO);
2242            tester.pump_widget(app(MergeableMaterial::new()));
2243            assert_eq!(
2244                tester.get_size(find::by_type::<MergeableMaterial>()),
2245                Size::ZERO
2246            );
2247        });
2248    }
2249
2250    /// Dart's `_RenderMergeableMaterialListBody` fills no properties of its own; it inherits
2251    /// `RenderListBody.debugFillProperties` and names its children `child 1`, `child 2`, ….
2252    #[test]
2253    fn a_mergeable_material_list_body_fills_the_properties_it_inherits() {
2254        use super::RenderMergeableMaterialListBody;
2255        use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
2256        use waft_painting::AxisDirection;
2257        use waft_rendering::{
2258            BoxConstraints, ContainerRenderObjectMixin, RenderBox, RenderConstrainedBox,
2259            RenderObject,
2260        };
2261
2262        let cell = AppCell::new();
2263        let mut app = cell.borrow_mut();
2264        let body = RenderMergeableMaterialListBody::new(&mut app, AxisDirection::Down);
2265        let first =
2266            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
2267                .as_box();
2268        let second =
2269            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None)
2270                .as_box();
2271        body.insert(&mut app, first, None);
2272        body.insert(&mut app, second, None);
2273
2274        let mut properties = DiagnosticPropertiesBuilder::new();
2275        RenderObject::debug_fill_properties(body, &app, &mut properties);
2276        let names: Vec<&str> = properties
2277            .properties
2278            .iter()
2279            .filter_map(|property| property.name())
2280            .collect();
2281        assert_eq!(names, ["axisDirection"]);
2282
2283        let node = body.as_object().to_diagnostics_node(&app, None);
2284        let children: Vec<&str> = node
2285            .children()
2286            .iter()
2287            .filter_map(|child| child.name())
2288            .collect();
2289        assert_eq!(children, ["child 1", "child 2"]);
2290    }
2291}