Skip to main content

waft_material/compose/
three_pane_scaffold.rs

1//! The pane scaffold: up to three panes laid out from a directive and a value, moving on
2//! Compose's pane spring when the value changes.
3
4use std::rc::Rc;
5
6use waft_animation::{AnimationBehavior, AnimationController, AnyAnimation};
7use waft_embedder::{Clip, Offset, Rect, Size, TextDirection};
8use waft_foundation::{App, Handle, Listenable, MergingListenable, Ref, ValueKey};
9use waft_painting::AlignmentGeometry;
10use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
11use waft_widgets::{
12    BuildContext, ClipPath, ClipRect, Directionality, IgnorePointer, IntoWidget, KeyRef,
13    LayoutBuilder, ListenableBuilder, Offstage, OverflowBox, Positioned, Stack, State, StateData,
14    StatefulWidget, TickerProviderStateMixin, TickerProviderStateMixinData, Transform, WidgetRef,
15};
16
17use crate::compose::pane_motion::{
18    PaneFrame, PaneMotion, PaneMotionData, PaneMotionDefaults, PaneMotionType,
19    ThreePaneScaffoldMotionData, calculate_pane_motion,
20};
21use crate::compose::{
22    Pane, PaneAdaptedValue, PaneScaffoldDirective, ThreePaneScaffoldHorizontalOrder,
23    ThreePaneScaffoldRole, ThreePaneScaffoldValue,
24};
25
26/// Up to three panes laid out from a directive and a value.
27///
28/// `list_detail` and `supporting` differ only in pane order and slot names. When the value
29/// changes, the panes move as Compose's do: shown panes move to their new bounds, and panes
30/// that appear or disappear slide in or out from the free side. A hidden pane stays mounted
31/// offstage, so a list keeps its scroll position while the detail covers it.
32#[derive(Debug)]
33pub struct ThreePaneScaffold {
34    /// The scaffold's key.
35    pub key: Option<KeyRef>,
36    /// The pane sizes and partitions.
37    pub directive: PaneScaffoldDirective,
38    /// The panes shown.
39    pub value: ThreePaneScaffoldValue,
40    /// The panes' order from start to end.
41    pub pane_order: ThreePaneScaffoldHorizontalOrder,
42    /// The primary pane's content.
43    pub primary_pane: Pane,
44    /// The secondary pane's content.
45    pub secondary_pane: Pane,
46    /// The tertiary pane's content, when the scaffold has one.
47    pub tertiary_pane: Option<Pane>,
48}
49
50impl ThreePaneScaffold {
51    /// Creates a pane scaffold with the panes in `pane_order`.
52    pub fn new(
53        directive: PaneScaffoldDirective,
54        value: ThreePaneScaffoldValue,
55        pane_order: ThreePaneScaffoldHorizontalOrder,
56        primary_pane: impl Into<Pane>,
57        secondary_pane: impl Into<Pane>,
58    ) -> ThreePaneScaffold {
59        ThreePaneScaffold {
60            key: None,
61            directive,
62            value,
63            pane_order,
64            primary_pane: primary_pane.into(),
65            secondary_pane: secondary_pane.into(),
66            tertiary_pane: None,
67        }
68    }
69
70    /// A list-detail scaffold: list, detail, extra.
71    pub fn list_detail(
72        directive: PaneScaffoldDirective,
73        value: ThreePaneScaffoldValue,
74        list_pane: impl Into<Pane>,
75        detail_pane: impl Into<Pane>,
76    ) -> ThreePaneScaffold {
77        ThreePaneScaffold::new(
78            directive,
79            value,
80            ThreePaneScaffoldHorizontalOrder::LIST_DETAIL,
81            detail_pane,
82            list_pane,
83        )
84    }
85
86    /// A supporting-pane scaffold: main, supporting, extra.
87    pub fn supporting(
88        directive: PaneScaffoldDirective,
89        value: ThreePaneScaffoldValue,
90        main_pane: impl Into<Pane>,
91        supporting_pane: impl Into<Pane>,
92    ) -> ThreePaneScaffold {
93        ThreePaneScaffold::new(
94            directive,
95            value,
96            ThreePaneScaffoldHorizontalOrder::SUPPORTING,
97            main_pane,
98            supporting_pane,
99        )
100    }
101
102    /// Adds the tertiary pane.
103    pub fn tertiary_pane(mut self, tertiary_pane: impl Into<Pane>) -> ThreePaneScaffold {
104        self.tertiary_pane = Some(tertiary_pane.into());
105        self
106    }
107
108    /// Sets the scaffold's key.
109    pub fn key(mut self, key: KeyRef) -> ThreePaneScaffold {
110        self.key = Some(key);
111        self
112    }
113
114    fn pane(&self, role: ThreePaneScaffoldRole) -> Option<&Pane> {
115        match role {
116            ThreePaneScaffoldRole::Primary => Some(&self.primary_pane),
117            ThreePaneScaffoldRole::Secondary => Some(&self.secondary_pane),
118            ThreePaneScaffoldRole::Tertiary => self.tertiary_pane.as_ref(),
119        }
120    }
121}
122
123impl StatefulWidget for ThreePaneScaffold {
124    type State = ThreePaneScaffoldState;
125
126    fn key(&self) -> Option<&KeyRef> {
127        self.key.as_ref()
128    }
129
130    fn create_state(&self) -> ThreePaneScaffoldState {
131        ThreePaneScaffoldState {
132            state: StateData::new(),
133            ticker_provider: TickerProviderStateMixinData::new(),
134            motion: None,
135            delayed_motion: None,
136            motions: [PaneMotion::NoMotion; 3],
137            origins: [None; 3],
138            bounds: [None; 3],
139            scaffold_width: 0.0,
140        }
141    }
142}
143
144/// The springs a [`ThreePaneScaffold`] moves its panes on, and each pane's motion.
145///
146/// The arrays are indexed by role. `bounds` and `scaffold_width` are written on every layout:
147/// the bounds each pane was last laid out at, which a hidden pane keeps. A change of value reads
148/// them to start the next motion from where the panes are drawn.
149pub struct ThreePaneScaffoldState {
150    state: StateData<ThreePaneScaffold>,
151    ticker_provider: TickerProviderStateMixinData,
152    motion: Option<Ref<AnimationController>>,
153    delayed_motion: Option<Ref<AnimationController>>,
154    motions: [PaneMotion; 3],
155    origins: [Option<Rect>; 3],
156    bounds: [Option<Rect>; 3],
157    scaffold_width: f64,
158}
159
160impl ThreePaneScaffoldState {
161    fn motion(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
162        app.get(self)
163            .motion
164            .as_ref()
165            .expect("created in init_state")
166            .handle()
167    }
168
169    fn delayed_motion(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
170        app.get(self)
171            .delayed_motion
172            .as_ref()
173            .expect("created in init_state")
174            .handle()
175    }
176
177    /// Starts each pane's motion from where it is drawn now towards `current`.
178    fn start_motion(
179        self: Handle<Self>,
180        app: &mut App,
181        previous: &ThreePaneScaffoldValue,
182        current: &ThreePaneScaffoldValue,
183        ltr_order: ThreePaneScaffoldHorizontalOrder,
184    ) {
185        let origins = self.drawn_content_rects(app, ltr_order);
186        let motions = calculate_pane_motion(previous, current, ltr_order);
187        let state = app.get_mut(self);
188        for (index, role) in ltr_order.roles().into_iter().enumerate() {
189            state.motions[role.index()] = motions[index];
190            state.origins[role.index()] = origins[index];
191        }
192        let motion = self.motion(app);
193        let delayed_motion = self.delayed_motion(app);
194        motion.animate_with(app, Box::new(PaneMotionDefaults::simulation()));
195        delayed_motion.animate_with(app, Box::new(PaneMotionDefaults::delayed_simulation()));
196    }
197
198    /// Where each pane's content is drawn now, left to right; `None` before its first layout.
199    fn drawn_content_rects(
200        self: Handle<Self>,
201        app: &App,
202        ltr_order: ThreePaneScaffoldHorizontalOrder,
203    ) -> [Option<Rect>; 3] {
204        let scaffold_width = app.get(self).scaffold_width;
205        let motion_data = self.motion_data(app, ltr_order, scaffold_width, Rect::ZERO);
206        let (progress, delayed_progress) = self.progress(app);
207        std::array::from_fn(|index| {
208            app.get(self).bounds[ltr_order.get(index).index()].map(|_| {
209                motion_data
210                    .frame(index, progress, delayed_progress)
211                    .content_rect()
212            })
213        })
214    }
215
216    fn progress(self: Handle<Self>, app: &App) -> (f64, f64) {
217        (
218            self.motion(app).value(app),
219            self.delayed_motion(app).value(app),
220        )
221    }
222
223    /// Each pane's motion data, left to right; a pane never laid out uses `unplaced`.
224    fn motion_data(
225        self: Handle<Self>,
226        app: &App,
227        ltr_order: ThreePaneScaffoldHorizontalOrder,
228        scaffold_width: f64,
229        unplaced: Rect,
230    ) -> ThreePaneScaffoldMotionData {
231        let state = app.get(self);
232        ThreePaneScaffoldMotionData {
233            scaffold_width,
234            panes: ltr_order.roles().map(|role| {
235                let target = state.bounds[role.index()].unwrap_or(unplaced);
236                PaneMotionData {
237                    motion: state.motions[role.index()],
238                    origin: state.origins[role.index()].unwrap_or(target),
239                    target,
240                }
241            }),
242        }
243    }
244
245    /// Lays the panes out in `size` and draws each where its motion has got to.
246    fn build_panes(
247        self: Handle<Self>,
248        app: &mut App,
249        context: BuildContext,
250        size: Size,
251    ) -> WidgetRef {
252        let text_direction = Directionality::of(app, context);
253        let ltr_order = self.widget(app).pane_order.to_ltr(text_direction);
254        self.lay_out(app, size, ltr_order, text_direction);
255        let unplaced = Rect::from_ltwh(0.0, 0.0, size.width(), size.height());
256        let motion_data = self.motion_data(app, ltr_order, size.width(), unplaced);
257        let (progress, delayed_progress) = self.progress(app);
258        let settled =
259            !self.motion(app).is_animating(app) && !self.delayed_motion(app).is_animating(app);
260
261        let widget = self.widget(app);
262        let mut hidden = Vec::new();
263        let mut shown = Vec::new();
264        for (index, role) in ltr_order.roles().into_iter().enumerate() {
265            let Some(pane) = widget.pane(role) else {
266                continue;
267            };
268            let is_shown = widget.value.get(role) != PaneAdaptedValue::Hidden;
269            let is_exiting =
270                motion_data.panes[index].motion.motion_type() == PaneMotionType::Exiting;
271            let drawn = drawn_pane(
272                role,
273                pane,
274                motion_data.frame(index, progress, delayed_progress),
275                is_shown,
276                !is_shown && (settled || !is_exiting),
277            );
278            if is_shown {
279                shown.push(drawn);
280            } else {
281                hidden.push(drawn);
282            }
283        }
284        // Panes on their way out are drawn under the shown ones, as Compose's hidden z-index.
285        hidden.extend(shown);
286        Stack::new().children(hidden).into_widget()
287    }
288
289    /// Records the bounds of the panes shown in `size`; a hidden pane keeps its last ones.
290    fn lay_out(
291        self: Handle<Self>,
292        app: &mut App,
293        size: Size,
294        ltr_order: ThreePaneScaffoldHorizontalOrder,
295        text_direction: TextDirection,
296    ) {
297        let targets = pane_bounds(self.widget(app), size, ltr_order, text_direction);
298        let state = app.get_mut(self);
299        state.scaffold_width = size.width();
300        for (index, role) in ltr_order.roles().into_iter().enumerate() {
301            if let Some(target) = targets[index] {
302                state.bounds[role.index()] = Some(target);
303            }
304        }
305    }
306}
307
308/// One pane drawn at `frame`. Every pane keeps this shape in every frame, so its content keeps
309/// its element, and its state, through each motion.
310fn drawn_pane(
311    role: ThreePaneScaffoldRole,
312    pane: &Pane,
313    frame: PaneFrame,
314    is_shown: bool,
315    offstage: bool,
316) -> WidgetRef {
317    let clip_behavior = if frame.clips {
318        Clip::HardEdge
319    } else {
320        Clip::None
321    };
322    let content = OverflowBox::new()
323        .alignment(AlignmentGeometry::CENTER)
324        .min_width(frame.content_width)
325        .max_width(frame.content_width)
326        .child(
327            Transform::translate(Offset::new(frame.content_offset, 0.0)).child(pane.child.clone()),
328        );
329    let clipped = ClipRect::new().clip_behavior(clip_behavior).child(content);
330    // The shape clips the pane's bounds as they move, as Compose's `clip(shape)` comes after its
331    // bounds animation.
332    let shaped = match &pane.shape {
333        Some(shape) => ClipPath::shape(shape.clone()).child(clipped).into_widget(),
334        None => clipped.into_widget(),
335    };
336    Positioned::from_rect(
337        frame.bounds,
338        Offstage::new()
339            .offstage(offstage)
340            .child(IgnorePointer::new().ignoring(!is_shown).child(shaped)),
341    )
342    .key(ValueKey::new(role).into())
343    .into_widget()
344}
345
346impl TickerProviderStateMixin for ThreePaneScaffoldState {
347    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
348        &app.get(self).ticker_provider
349    }
350
351    fn ticker_provider_data_mut(
352        self: Handle<Self>,
353        app: &mut App,
354    ) -> &mut TickerProviderStateMixinData {
355        &mut app.get_mut(self).ticker_provider
356    }
357}
358
359impl TickerProviderObject for ThreePaneScaffoldState {
360    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
361        TickerProviderStateMixin::create_ticker(self, app, on_tick)
362    }
363}
364
365impl State for ThreePaneScaffoldState {
366    type Widget = ThreePaneScaffold;
367    waft_widgets::state_accessors!();
368
369    fn init_state(self: Handle<Self>, app: &mut App) {
370        let motion = settled_controller(app, self);
371        let delayed_motion = settled_controller(app, self);
372        let state = app.get_mut(self);
373        state.motion = Some(motion);
374        state.delayed_motion = Some(delayed_motion);
375    }
376
377    fn activate(self: Handle<Self>, app: &mut App) {
378        TickerProviderStateMixin::activate(self, app);
379    }
380
381    fn dispose(self: Handle<Self>, app: &mut App) {
382        self.motion(app).dispose(app);
383        self.delayed_motion(app).dispose(app);
384        TickerProviderStateMixin::dispose(self, app);
385    }
386
387    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ThreePaneScaffold) {
388        let widget = self.widget(app);
389        if widget.value == old_widget.value {
390            return;
391        }
392        let current = widget.value;
393        let pane_order = widget.pane_order;
394        let context = self.context(app);
395        let ltr_order = pane_order.to_ltr(Directionality::of(app, context));
396        self.start_motion(app, &old_widget.value, &current, ltr_order);
397    }
398
399    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
400        let state = app.get(self);
401        let springs: Vec<Option<Rc<dyn Listenable>>> = [&state.motion, &state.delayed_motion]
402            .into_iter()
403            .map(|controller| {
404                let controller = controller.as_ref().expect("created in init_state");
405                let animation: Rc<dyn Listenable> =
406                    Rc::new(controller.erase::<AnyAnimation<f64>>());
407                Some(animation)
408            })
409            .collect();
410        ListenableBuilder::new(
411            Rc::new(MergingListenable::new(springs)),
412            move |_app, _context, _child| {
413                LayoutBuilder::new(move |app, context, constraints| {
414                    self.build_panes(app, context, constraints.constraints().biggest())
415                })
416                .into_widget()
417            },
418        )
419        .into_widget()
420    }
421}
422
423/// A controller for the pane spring, at rest on its end; unbounded, since the spring overshoots.
424fn settled_controller(
425    app: &mut App,
426    vsync: Handle<ThreePaneScaffoldState>,
427) -> Ref<AnimationController> {
428    AnimationController::unbounded(app, 1.0, None, None, AnimationBehavior::Normal, vsync)
429}
430
431/// Compose's `ThreePaneContentMeasurePolicy` without hinges, levitated panes or pane expansion:
432/// the bounds of each shown pane, left to right.
433///
434/// Expanded panes take their preferred widths; the leftover goes to the one with the highest
435/// priority, and they all shrink in proportion when they do not fit. A reflowed pane takes the
436/// bottom of its anchor's partition, at most half. Each pane's margins then move the edges it
437/// shares with the scaffold, as Compose's `doMeasureAndPlace` does after measuring.
438fn pane_bounds(
439    scaffold: &ThreePaneScaffold,
440    size: Size,
441    ltr_order: ThreePaneScaffoldHorizontalOrder,
442    text_direction: TextDirection,
443) -> [Option<Rect>; 3] {
444    let mut bounds = partition_bounds(scaffold, size, ltr_order);
445    for (index, role) in ltr_order.roles().into_iter().enumerate() {
446        if let (Some(rect), Some(pane)) = (bounds[index], scaffold.pane(role)) {
447            bounds[index] = Some(pane.within_margins(rect, size, text_direction));
448        }
449    }
450    bounds
451}
452
453/// The bounds of each shown pane, left to right, before margins.
454fn partition_bounds(
455    scaffold: &ThreePaneScaffold,
456    size: Size,
457    ltr_order: ThreePaneScaffoldHorizontalOrder,
458) -> [Option<Rect>; 3] {
459    let mut bounds = [None; 3];
460    let directive = &scaffold.directive;
461    let panes: Vec<(usize, ThreePaneScaffoldRole, &Pane)> = ltr_order
462        .roles()
463        .into_iter()
464        .enumerate()
465        .filter_map(|(index, role)| scaffold.pane(role).map(|pane| (index, role, pane)))
466        .collect();
467    let mut expanded: Vec<(usize, ThreePaneScaffoldRole, f64)> = panes
468        .iter()
469        .filter(|(_, role, _)| scaffold.value.get(*role) == PaneAdaptedValue::Expanded)
470        .map(|(index, role, pane)| {
471            let width = pane.width_for(size, directive.default_pane_preferred_width);
472            (*index, *role, width)
473        })
474        .collect();
475    let reflowed = panes
476        .iter()
477        .find_map(|(index, role, pane)| match scaffold.value.get(*role) {
478            PaneAdaptedValue::Reflowed { reflow_under } => Some((*index, reflow_under, *pane)),
479            _ => None,
480        });
481    if expanded.is_empty() {
482        return bounds;
483    }
484
485    let spacer = directive.horizontal_partition_spacer_size;
486    let allocatable_width = size.width() - (expanded.len() - 1) as f64 * spacer;
487    let total_preferred_width: f64 = expanded.iter().map(|(_, _, width)| width).sum();
488    if allocatable_width > total_preferred_width {
489        let (_, _, width) = expanded
490            .iter_mut()
491            .max_by_key(|(_, role, _)| priority(*role))
492            .expect("an expanded pane");
493        *width += allocatable_width - total_preferred_width;
494    } else if allocatable_width < total_preferred_width {
495        let scale = allocatable_width / total_preferred_width;
496        for (_, _, width) in &mut expanded {
497            *width *= scale;
498        }
499    }
500
501    let vertical_spacer = directive.vertical_partition_spacer_size;
502    let mut left = 0.0;
503    for (index, role, width) in expanded {
504        let mut height = size.height();
505        if let Some((reflowed_index, reflow_under, reflowed_pane)) = reflowed
506            && reflow_under == role
507        {
508            let available_height = size.height() - vertical_spacer;
509            let preferred_height =
510                reflowed_pane.height_for(size, directive.default_pane_preferred_height);
511            height = (available_height - preferred_height).max(available_height / 2.0);
512            bounds[reflowed_index] = Some(Rect::from_ltwh(
513                left,
514                height + vertical_spacer,
515                width,
516                available_height - height,
517            ));
518        }
519        bounds[index] = Some(Rect::from_ltwh(left, 0.0, width, height));
520        left += width + spacer;
521    }
522    bounds
523}
524
525/// Compose's `ThreePaneScaffoldDefaults` pane priorities.
526fn priority(role: ThreePaneScaffoldRole) -> u8 {
527    match role {
528        ThreePaneScaffoldRole::Primary => 10,
529        ThreePaneScaffoldRole::Secondary => 5,
530        ThreePaneScaffoldRole::Tertiary => 1,
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use std::time::Duration;
537
538    use waft_embedder::{Size, TextDirection};
539    use waft_foundation::ValueKey;
540    use waft_painting::EdgeInsetsGeometry;
541    use waft_painting::{BorderRadius, BorderSide, RoundedRectangleBorder};
542    use waft_widgets::testing::{
543        WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
544    };
545    use waft_widgets::{Directionality, Padding, SizedBox};
546
547    use super::*;
548    use crate::compose::{
549        PaneAdaptedValue, PanePreferredSize, SupportingPaneScaffoldRole, ThreePaneScaffoldValue,
550        WindowHeightSizeClass, WindowSizeClass, WindowWidthSizeClass,
551    };
552
553    fn directive(
554        width: WindowWidthSizeClass,
555        height: WindowHeightSizeClass,
556    ) -> PaneScaffoldDirective {
557        PaneScaffoldDirective::from_window_size_class(WindowSizeClass { width, height })
558    }
559
560    fn expanded_directive() -> PaneScaffoldDirective {
561        directive(
562            WindowWidthSizeClass::Expanded,
563            WindowHeightSizeClass::Expanded,
564        )
565    }
566
567    fn pane(key: i32) -> Pane {
568        Pane::new(SizedBox::new().key(ValueKey::new(key).into()))
569    }
570
571    fn pump_in(
572        tester: &mut WidgetTester,
573        text_direction: TextDirection,
574        width: f64,
575        height: f64,
576        scaffold: ThreePaneScaffold,
577    ) {
578        tester.set_surface_size(Some(Size::new(width, height)));
579        tester.pump_widget(Directionality::new(text_direction, scaffold).into_widget());
580    }
581
582    fn pump(tester: &mut WidgetTester, width: f64, height: f64, scaffold: ThreePaneScaffold) {
583        pump_in(tester, TextDirection::Ltr, width, height, scaffold);
584    }
585
586    fn rect_of(tester: &WidgetTester, key: i32) -> Rect {
587        tester.get_rect(find::by_key(ValueKey::new(key)).skip_offstage(false))
588    }
589
590    fn value(
591        primary: PaneAdaptedValue,
592        secondary: PaneAdaptedValue,
593        tertiary: PaneAdaptedValue,
594    ) -> ThreePaneScaffoldValue {
595        ThreePaneScaffoldValue {
596            primary,
597            secondary,
598            tertiary,
599        }
600    }
601
602    fn list_and_detail() -> ThreePaneScaffoldValue {
603        value(
604            PaneAdaptedValue::Expanded,
605            PaneAdaptedValue::Expanded,
606            PaneAdaptedValue::Hidden,
607        )
608    }
609
610    fn list_and_extra() -> ThreePaneScaffoldValue {
611        value(
612            PaneAdaptedValue::Hidden,
613            PaneAdaptedValue::Expanded,
614            PaneAdaptedValue::Expanded,
615        )
616    }
617
618    fn list_detail_extra(value: ThreePaneScaffoldValue) -> ThreePaneScaffold {
619        ThreePaneScaffold::list_detail(expanded_directive(), value, pane(1), pane(2))
620            .tertiary_pane(pane(3))
621    }
622
623    #[test]
624    fn a_wide_list_detail_places_the_list_beside_the_detail() {
625        test_widgets(|tester| {
626            pump(
627                tester,
628                1000.0,
629                600.0,
630                ThreePaneScaffold::list_detail(
631                    expanded_directive(),
632                    list_and_detail(),
633                    pane(1),
634                    pane(2),
635                ),
636            );
637            assert_eq!(rect_of(tester, 1), Rect::from_ltwh(0.0, 0.0, 360.0, 600.0));
638            assert_eq!(
639                rect_of(tester, 2),
640                Rect::from_ltwh(384.0, 0.0, 616.0, 600.0)
641            );
642        });
643    }
644
645    #[test]
646    fn the_panes_share_the_scaffold_s_own_width_not_the_window_s() {
647        test_widgets(|tester| {
648            let scaffold = ThreePaneScaffold::list_detail(
649                expanded_directive(),
650                list_and_detail(),
651                pane(1),
652                pane(2),
653            );
654            tester.set_surface_size(Some(Size::new(1000.0, 600.0)));
655            tester.pump_widget(
656                Directionality::new(
657                    TextDirection::Ltr,
658                    Padding::new(EdgeInsetsGeometry::only(80.0, 0.0, 0.0, 0.0)).child(scaffold),
659                )
660                .into_widget(),
661            );
662            assert_eq!(
663                rect_of(tester, 2),
664                Rect::from_ltwh(464.0, 0.0, 536.0, 600.0)
665            );
666        });
667    }
668
669    #[test]
670    fn a_reflowed_pane_sits_under_its_anchor() {
671        test_widgets(|tester| {
672            let value = value(
673                PaneAdaptedValue::Expanded,
674                PaneAdaptedValue::Reflowed {
675                    reflow_under: SupportingPaneScaffoldRole::MAIN,
676                },
677                PaneAdaptedValue::Hidden,
678            );
679            pump(
680                tester,
681                400.0,
682                800.0,
683                ThreePaneScaffold::supporting(
684                    directive(
685                        WindowWidthSizeClass::Compact,
686                        WindowHeightSizeClass::Expanded,
687                    ),
688                    value,
689                    pane(1),
690                    pane(2),
691                ),
692            );
693            assert_eq!(rect_of(tester, 1), Rect::from_ltwh(0.0, 0.0, 400.0, 388.0));
694            assert_eq!(
695                rect_of(tester, 2),
696                Rect::from_ltwh(0.0, 412.0, 400.0, 388.0)
697            );
698        });
699    }
700
701    #[test]
702    fn margins_move_only_the_edges_a_pane_shares_with_the_scaffold() {
703        test_widgets(|tester| {
704            let margins = EdgeInsetsGeometry::all(24.0);
705            pump(
706                tester,
707                1000.0,
708                600.0,
709                ThreePaneScaffold::list_detail(
710                    expanded_directive(),
711                    list_and_detail(),
712                    pane(1).margins(margins),
713                    pane(2).margins(margins),
714                ),
715            );
716            assert_eq!(
717                rect_of(tester, 1),
718                Rect::from_ltrb(24.0, 24.0, 360.0, 576.0)
719            );
720            assert_eq!(
721                rect_of(tester, 2),
722                Rect::from_ltrb(384.0, 24.0, 976.0, 576.0)
723            );
724        });
725    }
726
727    #[test]
728    fn directional_margins_follow_the_text_direction() {
729        test_widgets(|tester| {
730            pump_in(
731                tester,
732                TextDirection::Rtl,
733                1000.0,
734                600.0,
735                ThreePaneScaffold::list_detail(
736                    expanded_directive(),
737                    list_and_detail(),
738                    pane(1).margins(EdgeInsetsGeometry::directional(24.0, 0.0, 0.0, 0.0)),
739                    pane(2),
740                ),
741            );
742            assert_eq!(
743                rect_of(tester, 1),
744                Rect::from_ltrb(640.0, 0.0, 976.0, 600.0)
745            );
746        });
747    }
748
749    #[test]
750    fn a_shaped_pane_is_clipped_to_its_shape() {
751        test_widgets(|tester| {
752            let shape =
753                RoundedRectangleBorder::new(BorderSide::NONE, BorderRadius::circular(16.0).into());
754            pump(
755                tester,
756                1000.0,
757                600.0,
758                ThreePaneScaffold::list_detail(
759                    expanded_directive(),
760                    list_and_detail(),
761                    pane(1).shape(shape),
762                    pane(2),
763                ),
764            );
765            expect(
766                tester,
767                &find::ancestor(find::by_key(ValueKey::new(1)), find::by_type::<ClipPath>()),
768                finds_one_widget(),
769            );
770            expect(
771                tester,
772                &find::ancestor(find::by_key(ValueKey::new(2)), find::by_type::<ClipPath>()),
773                finds_nothing(),
774            );
775        });
776    }
777
778    #[test]
779    fn right_to_left_mirrors_the_panes() {
780        test_widgets(|tester| {
781            pump_in(
782                tester,
783                TextDirection::Rtl,
784                1000.0,
785                600.0,
786                ThreePaneScaffold::list_detail(
787                    expanded_directive(),
788                    list_and_detail(),
789                    pane(1),
790                    pane(2),
791                ),
792            );
793            assert_eq!(
794                rect_of(tester, 1),
795                Rect::from_ltwh(640.0, 0.0, 360.0, 600.0)
796            );
797            assert_eq!(rect_of(tester, 2), Rect::from_ltwh(0.0, 0.0, 616.0, 600.0));
798        });
799    }
800
801    #[test]
802    fn a_proportional_pane_takes_its_fraction_of_the_scaffold() {
803        test_widgets(|tester| {
804            let list = pane(1).preferred_width(PanePreferredSize::Proportion(0.25));
805            pump(
806                tester,
807                1000.0,
808                600.0,
809                ThreePaneScaffold::list_detail(
810                    expanded_directive(),
811                    list_and_detail(),
812                    list,
813                    pane(2),
814                ),
815            );
816            assert_eq!(rect_of(tester, 1), Rect::from_ltwh(0.0, 0.0, 250.0, 600.0));
817        });
818    }
819
820    #[test]
821    fn a_tertiary_pane_takes_the_third_partition() {
822        test_widgets(|tester| {
823            let all = value(
824                PaneAdaptedValue::Expanded,
825                PaneAdaptedValue::Expanded,
826                PaneAdaptedValue::Expanded,
827            );
828            pump(
829                tester,
830                1400.0,
831                600.0,
832                ThreePaneScaffold::list_detail(
833                    directive(WindowWidthSizeClass::Large, WindowHeightSizeClass::Expanded),
834                    all,
835                    pane(1),
836                    pane(2),
837                )
838                .tertiary_pane(pane(3)),
839            );
840            assert_eq!(
841                rect_of(tester, 3),
842                Rect::from_ltwh(988.0, 0.0, 412.0, 600.0)
843            );
844        });
845    }
846
847    #[test]
848    fn a_hidden_pane_stays_mounted_offstage() {
849        test_widgets(|tester| {
850            pump(tester, 1000.0, 600.0, list_detail_extra(list_and_detail()));
851            assert!(find::by_key(ValueKey::new(3)).evaluate(tester).is_empty());
852            assert_eq!(
853                find::by_key(ValueKey::new(3))
854                    .skip_offstage(false)
855                    .evaluate(tester)
856                    .len(),
857                1
858            );
859        });
860    }
861
862    #[test]
863    fn a_pane_that_appears_slides_in_on_the_spring_and_the_one_it_replaces_slides_out() {
864        test_widgets(|tester| {
865            pump(tester, 1000.0, 600.0, list_detail_extra(list_and_detail()));
866            pump(tester, 1000.0, 600.0, list_detail_extra(list_and_extra()));
867
868            // The list, of higher priority, takes the leftover width; the detail and the extra
869            // pane are both drawn while they move.
870            let extra_bounds = Rect::from_ltwh(640.0, 0.0, 360.0, 600.0);
871            tester.pump_by(Duration::from_millis(50));
872            let extra_content = rect_of(tester, 3);
873            let detail_content = rect_of(tester, 2);
874            assert!(
875                extra_content.left > extra_bounds.left,
876                "the extra pane is still sliding in from the right, at {}",
877                extra_content.left
878            );
879            assert!(
880                detail_content.left > 384.0,
881                "the detail is sliding out to the right, at {}",
882                detail_content.left
883            );
884            assert!(!find::by_key(ValueKey::new(2)).evaluate(tester).is_empty());
885
886            tester.pump_and_settle();
887            assert_eq!(rect_of(tester, 1), Rect::from_ltwh(0.0, 0.0, 616.0, 600.0));
888            assert_eq!(rect_of(tester, 3), extra_bounds);
889            assert!(find::by_key(ValueKey::new(2)).evaluate(tester).is_empty());
890        });
891    }
892
893    #[test]
894    fn a_shown_pane_moves_to_its_new_bounds_and_overshoots_on_the_way() {
895        test_widgets(|tester| {
896            let wide = list_and_detail();
897            let one = value(
898                PaneAdaptedValue::Expanded,
899                PaneAdaptedValue::Hidden,
900                PaneAdaptedValue::Hidden,
901            );
902            pump(
903                tester,
904                1000.0,
905                600.0,
906                ThreePaneScaffold::list_detail(expanded_directive(), wide, pane(1), pane(2)),
907            );
908            pump(
909                tester,
910                1000.0,
911                600.0,
912                ThreePaneScaffold::list_detail(expanded_directive(), one, pane(1), pane(2)),
913            );
914
915            let mut leftmost = f64::INFINITY;
916            for _ in 0..60 {
917                tester.pump_by(Duration::from_millis(16));
918                leftmost = leftmost.min(rect_of(tester, 2).left);
919            }
920            assert!(
921                leftmost < 0.0,
922                "a damping ratio of 0.8 overshoots, leftmost {leftmost}"
923            );
924            tester.pump_and_settle();
925            assert_eq!(rect_of(tester, 2), Rect::from_ltwh(0.0, 0.0, 1000.0, 600.0));
926        });
927    }
928}