Skip to main content

sui_widgets/
layout_policy.rs

1use sui_animation::{AnimationSpec, Easing};
2use sui_core::{
3    InvalidationKind, Point, Rect, SafeAreaInsets, SemanticsNode, SemanticsRole, Size, Vector,
4};
5use sui_layout::{
6    Alignment, Axis, Constraints, GridItem, GridLayout, GridPlacement, GridStyle, GridTrack,
7    Padding, grid_layout,
8};
9use sui_runtime::{
10    ArrangeCtx, LayerOptions, MeasureCtx, Motion, PaintBoundaryMode, PaintCtx, SemanticsCtx,
11    SingleChild, Widget, WidgetChildren, WidgetPodMutVisitor, WidgetPodVisitor,
12};
13use sui_scene::{LayerCompositionMode, LayerProperties};
14
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct GridCell {
17    pub placement: GridPlacement,
18    pub horizontal_alignment: Alignment,
19    pub vertical_alignment: Alignment,
20}
21
22impl GridCell {
23    pub const fn new(row: usize, column: usize) -> Self {
24        Self {
25            placement: GridPlacement::new(row, column),
26            horizontal_alignment: Alignment::Stretch,
27            vertical_alignment: Alignment::Stretch,
28        }
29    }
30
31    pub const fn span(mut self, rows: usize, columns: usize) -> Self {
32        self.placement = self.placement.span(rows, columns);
33        self
34    }
35
36    pub const fn align(mut self, horizontal: Alignment, vertical: Alignment) -> Self {
37        self.horizontal_alignment = horizontal;
38        self.vertical_alignment = vertical;
39        self
40    }
41}
42
43/// Retained explicit grid container backed by the renderer-independent
44/// `sui-layout` track solver.
45pub struct Grid {
46    style: GridStyle,
47    cells: Vec<GridCell>,
48    children: WidgetChildren,
49    layout: GridLayout,
50    name: Option<String>,
51}
52
53impl Grid {
54    pub fn new(columns: impl IntoIterator<Item = GridTrack>) -> Self {
55        Self {
56            style: GridStyle::new(columns),
57            cells: Vec::new(),
58            children: WidgetChildren::new(),
59            layout: grid_layout(&GridStyle::default(), &[], Constraints::default()),
60            name: None,
61        }
62    }
63
64    pub fn name(mut self, name: impl Into<String>) -> Self {
65        self.name = Some(name.into());
66        self
67    }
68
69    pub fn rows(mut self, rows: impl IntoIterator<Item = GridTrack>) -> Self {
70        self.style = self.style.rows(rows);
71        self
72    }
73
74    pub fn gap(mut self, gap: f32) -> Self {
75        self.style = self.style.gap(gap);
76        self
77    }
78
79    pub fn column_gap(mut self, gap: f32) -> Self {
80        self.style = self.style.column_gap(gap);
81        self
82    }
83
84    pub fn row_gap(mut self, gap: f32) -> Self {
85        self.style = self.style.row_gap(gap);
86        self
87    }
88
89    pub fn with_child<W>(mut self, child: W) -> Self
90    where
91        W: Widget + 'static,
92    {
93        let columns = self.style.columns.len().max(1);
94        let index = self.children.len();
95        self.children.push(child);
96        self.cells
97            .push(GridCell::new(index / columns, index % columns));
98        self
99    }
100
101    pub fn with_cell<W>(mut self, cell: GridCell, child: W) -> Self
102    where
103        W: Widget + 'static,
104    {
105        self.children.push(child);
106        self.cells.push(cell);
107        self
108    }
109
110    pub fn push<W>(&mut self, child: W)
111    where
112        W: Widget + 'static,
113    {
114        let columns = self.style.columns.len().max(1);
115        let index = self.children.len();
116        self.children.push(child);
117        self.cells
118            .push(GridCell::new(index / columns, index % columns));
119    }
120
121    pub fn push_cell<W>(&mut self, cell: GridCell, child: W)
122    where
123        W: Widget + 'static,
124    {
125        self.children.push(child);
126        self.cells.push(cell);
127    }
128
129    pub fn layout(&self) -> &GridLayout {
130        &self.layout
131    }
132
133    fn layout_items(&self, natural_sizes: &[Size], minimum_widths: &[f32]) -> Vec<GridItem> {
134        self.cells
135            .iter()
136            .zip(natural_sizes)
137            .zip(minimum_widths)
138            .map(|((cell, natural_size), minimum_width)| {
139                GridItem::new(cell.placement, *natural_size)
140                    .minimum_size(Size::new(*minimum_width, natural_size.height))
141                    .align(cell.horizontal_alignment, cell.vertical_alignment)
142            })
143            .collect()
144    }
145}
146
147impl Grid {
148    fn measure_layout(
149        &mut self,
150        ctx: &mut MeasureCtx,
151        constraints: Constraints,
152        size_only: bool,
153    ) -> GridLayout {
154        let mut natural_sizes = Vec::with_capacity(self.children.len());
155        let mut minimum_widths = Vec::with_capacity(self.children.len());
156        for child in self.children.as_mut_slice() {
157            let natural = child.probe_measure(ctx, Constraints::UNBOUNDED);
158            let intrinsic = child.intrinsic_size(ctx, Axis::Horizontal, natural.height);
159            natural_sizes.push(natural);
160            minimum_widths.push(intrinsic.minimum);
161        }
162
163        let provisional = grid_layout(
164            &self.style,
165            &self.layout_items(&natural_sizes, &minimum_widths),
166            constraints,
167        );
168        for (index, child) in self.children.as_mut_slice().iter_mut().enumerate() {
169            let cell = provisional
170                .items
171                .get(index)
172                .map(|item| item.cell)
173                .unwrap_or(Rect::ZERO);
174            let resolved = Constraints::new(Size::ZERO, Size::new(cell.width(), f32::INFINITY));
175            natural_sizes[index] = if size_only {
176                child.probe_measure(ctx, resolved)
177            } else {
178                child.measure(ctx, resolved)
179            };
180        }
181        grid_layout(
182            &self.style,
183            &self.layout_items(&natural_sizes, &minimum_widths),
184            constraints,
185        )
186    }
187}
188
189impl Widget for Grid {
190    fn supports_output_reuse(&self) -> bool {
191        true
192    }
193    fn measure_size(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
194        self.measure_layout(ctx, constraints, true).size
195    }
196
197    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
198        self.layout = self.measure_layout(ctx, constraints, false);
199        self.layout.size
200    }
201
202    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
203        let translation = bounds.origin.to_vector();
204        for (index, item) in self.layout.items.iter().enumerate() {
205            self.children
206                .arrange_child(index, ctx, item.rect.translate(translation));
207        }
208    }
209
210    fn paint(&self, ctx: &mut PaintCtx) {
211        self.children.paint(ctx);
212    }
213
214    fn semantics(&self, ctx: &mut SemanticsCtx) {
215        if let Some(name) = &self.name {
216            let mut node = SemanticsNode::new(
217                ctx.widget_id(),
218                SemanticsRole::GenericContainer,
219                ctx.bounds(),
220            );
221            node.name = Some(name.clone());
222            ctx.push(node);
223        }
224        self.children.semantics(ctx);
225    }
226
227    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
228        self.children.visit_children(visitor);
229    }
230
231    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
232        self.children.visit_children_mut(visitor);
233    }
234}
235
236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
237pub enum AspectRatioFit {
238    #[default]
239    Contain,
240    Cover,
241}
242
243/// Constrains one retained child to an aspect ratio without specializing it as
244/// an image or media widget.
245pub struct AspectRatio {
246    ratio: f32,
247    fit: AspectRatioFit,
248    alignment: (Alignment, Alignment),
249    child: SingleChild,
250}
251
252impl AspectRatio {
253    pub fn new<W>(ratio: f32, child: W) -> Self
254    where
255        W: Widget + 'static,
256    {
257        Self {
258            ratio: normalize_ratio(ratio),
259            fit: AspectRatioFit::Contain,
260            alignment: (Alignment::Center, Alignment::Center),
261            child: SingleChild::new(child),
262        }
263    }
264
265    pub fn fit(mut self, fit: AspectRatioFit) -> Self {
266        self.fit = fit;
267        self
268    }
269
270    pub fn align(mut self, horizontal: Alignment, vertical: Alignment) -> Self {
271        self.alignment = (horizontal, vertical);
272        self
273    }
274
275    pub fn ratio(mut self, ratio: f32) -> Self {
276        self.ratio = normalize_ratio(ratio);
277        self
278    }
279
280    fn child_rect(&self, bounds: Rect) -> Rect {
281        let size = aspect_size(bounds.size, self.ratio, self.fit);
282        let x = aligned_start(self.alignment.0, bounds.x(), bounds.width(), size.width);
283        let y = aligned_start(self.alignment.1, bounds.y(), bounds.height(), size.height);
284        Rect::new(x, y, size.width, size.height)
285    }
286}
287
288impl Widget for AspectRatio {
289    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
290        let natural = self.child.measure(ctx, constraints.loosen());
291        let desired = if natural.width > 0.0 || natural.height > 0.0 {
292            aspect_size(natural, self.ratio, AspectRatioFit::Contain)
293        } else {
294            Size::ZERO
295        };
296        constraints.clamp(desired)
297    }
298
299    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
300        self.child.arrange(ctx, self.child_rect(bounds));
301    }
302
303    fn paint(&self, ctx: &mut PaintCtx) {
304        if self.fit == AspectRatioFit::Cover {
305            ctx.push_clip_rect(ctx.bounds());
306            self.child.paint(ctx);
307            ctx.pop_clip();
308        } else {
309            self.child.paint(ctx);
310        }
311    }
312
313    fn semantics(&self, ctx: &mut SemanticsCtx) {
314        self.child.semantics(ctx);
315    }
316
317    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
318        self.child.visit_children(visitor);
319    }
320
321    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
322        self.child.visit_children_mut(visitor);
323    }
324}
325
326fn normalize_ratio(ratio: f32) -> f32 {
327    if ratio.is_finite() {
328        ratio.max(0.01)
329    } else {
330        1.0
331    }
332}
333
334fn aspect_size(available: Size, ratio: f32, fit: AspectRatioFit) -> Size {
335    let width = available.width.max(0.0);
336    let height = available.height.max(0.0);
337    if width == 0.0 || height == 0.0 {
338        return if width > 0.0 {
339            Size::new(width, width / ratio)
340        } else if height > 0.0 {
341            Size::new(height * ratio, height)
342        } else {
343            Size::ZERO
344        };
345    }
346    let available_ratio = width / height;
347    let use_width = match fit {
348        AspectRatioFit::Contain => available_ratio <= ratio,
349        AspectRatioFit::Cover => available_ratio >= ratio,
350    };
351    if use_width {
352        Size::new(width, width / ratio)
353    } else {
354        Size::new(height * ratio, height)
355    }
356}
357
358/// Selects which edges of [`SafeArea`] consume the platform-provided insets.
359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub struct SafeAreaEdges(u8);
361
362impl SafeAreaEdges {
363    pub const NONE: Self = Self(0);
364    pub const LEFT: Self = Self(1 << 0);
365    pub const TOP: Self = Self(1 << 1);
366    pub const RIGHT: Self = Self(1 << 2);
367    pub const BOTTOM: Self = Self(1 << 3);
368    pub const HORIZONTAL: Self = Self(Self::LEFT.0 | Self::RIGHT.0);
369    pub const VERTICAL: Self = Self(Self::TOP.0 | Self::BOTTOM.0);
370    pub const ALL: Self = Self(Self::HORIZONTAL.0 | Self::VERTICAL.0);
371
372    pub const fn union(self, other: Self) -> Self {
373        Self(self.0 | other.0)
374    }
375
376    pub const fn contains(self, edge: Self) -> bool {
377        self.0 & edge.0 == edge.0
378    }
379}
380
381impl Default for SafeAreaEdges {
382    fn default() -> Self {
383        Self::ALL
384    }
385}
386
387/// Insets one retained child by the current window's safe area.
388///
389/// Insets enter through `DpiInfo`, so a platform adapter can update them with
390/// `WindowEvent::SafeAreaChanged` without rebuilding the widget tree.
391pub struct SafeArea {
392    edges: SafeAreaEdges,
393    minimum: SafeAreaInsets,
394    child: SingleChild,
395}
396
397impl SafeArea {
398    pub fn new<W>(child: W) -> Self
399    where
400        W: Widget + 'static,
401    {
402        Self {
403            edges: SafeAreaEdges::ALL,
404            minimum: SafeAreaInsets::ZERO,
405            child: SingleChild::new(child),
406        }
407    }
408
409    pub fn edges(mut self, edges: SafeAreaEdges) -> Self {
410        self.edges = edges;
411        self
412    }
413
414    /// Guarantee at least these logical insets, even when the platform reports
415    /// smaller values or no safe area.
416    pub fn minimum(mut self, minimum: SafeAreaInsets) -> Self {
417        self.minimum = minimum.normalized();
418        self
419    }
420
421    fn resolved_insets(&self, platform: SafeAreaInsets) -> Padding {
422        let platform = platform.normalized();
423        Padding {
424            left: if self.edges.contains(SafeAreaEdges::LEFT) {
425                platform.left.max(self.minimum.left)
426            } else {
427                0.0
428            },
429            top: if self.edges.contains(SafeAreaEdges::TOP) {
430                platform.top.max(self.minimum.top)
431            } else {
432                0.0
433            },
434            right: if self.edges.contains(SafeAreaEdges::RIGHT) {
435                platform.right.max(self.minimum.right)
436            } else {
437                0.0
438            },
439            bottom: if self.edges.contains(SafeAreaEdges::BOTTOM) {
440                platform.bottom.max(self.minimum.bottom)
441            } else {
442                0.0
443            },
444        }
445    }
446}
447
448impl Widget for SafeArea {
449    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
450        let insets = self.resolved_insets(ctx.dpi().safe_area);
451        let child_size = self.child.measure(
452            ctx,
453            Constraints::new(insets.inset(constraints.min), insets.inset(constraints.max)),
454        );
455        constraints.clamp(Size::new(
456            child_size.width + insets.left + insets.right,
457            child_size.height + insets.top + insets.bottom,
458        ))
459    }
460
461    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
462        let insets = self.resolved_insets(ctx.dpi().safe_area);
463        self.child.arrange(
464            ctx,
465            Rect::from_origin_size(
466                bounds.origin + insets.offset().to_vector(),
467                insets.inset(bounds.size),
468            ),
469        );
470    }
471
472    fn paint(&self, ctx: &mut PaintCtx) {
473        self.child.paint(ctx);
474    }
475
476    fn semantics(&self, ctx: &mut SemanticsCtx) {
477        self.child.semantics(ctx);
478    }
479
480    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
481        self.child.visit_children(visitor);
482    }
483
484    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
485        self.child.visit_children_mut(visitor);
486    }
487}
488
489/// Animates a retained subtree from its previous arranged origin to its new
490/// origin while layout itself immediately settles at the destination.
491///
492/// Because the child pod is retained, focus, scroll position, editor state,
493/// and keyed reconciliation identity survive the structural layout update.
494pub struct LayoutTransition {
495    child: SingleChild,
496    duration: f64,
497    easing: Easing,
498    destination: Option<Point>,
499    /// How far the child is presented from where it was last arranged; it
500    /// glides to zero after each move.
501    offset: Motion<Vector>,
502}
503
504impl LayoutTransition {
505    pub fn new<W>(child: W) -> Self
506    where
507        W: Widget + 'static,
508    {
509        Self {
510            child: SingleChild::new(child),
511            duration: 0.18,
512            easing: Easing::EaseOut,
513            destination: None,
514            offset: Motion::new(Vector::ZERO)
515                .invalidating(InvalidationKind::Transform)
516                .movement(),
517        }
518    }
519
520    pub fn duration(mut self, duration: f64) -> Self {
521        self.duration = duration.max(0.0);
522        self
523    }
524
525    pub fn easing(mut self, easing: Easing) -> Self {
526        self.easing = easing;
527        self
528    }
529}
530
531impl Widget for LayoutTransition {
532    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
533        self.child.measure(ctx, constraints)
534    }
535
536    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
537        if let Some(previous_destination) = self.destination
538            && previous_destination != bounds.origin
539        {
540            // Keep the child where it is on screen, then glide it into its
541            // new place. The runtime moves the layer; nothing repaints.
542            let visual_origin = previous_destination + self.offset.get(ctx);
543            self.offset.jump_to(visual_origin - bounds.origin);
544            ctx.animate(
545                &mut self.offset,
546                Vector::ZERO,
547                AnimationSpec::tween(self.duration, self.easing),
548            );
549            ctx.request_transform();
550        }
551        self.destination = Some(bounds.origin);
552        self.child.arrange(ctx, bounds);
553    }
554
555    fn paint(&self, ctx: &mut PaintCtx) {
556        self.child.paint(ctx);
557    }
558
559    fn layer_options(&self) -> LayerOptions {
560        LayerOptions {
561            paint_boundary: PaintBoundaryMode::Explicit,
562            composition_mode: LayerCompositionMode::Normal,
563        }
564    }
565
566    fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
567        LayerProperties::default().with_translation(self.offset.at(frame_time))
568    }
569
570    fn semantics(&self, ctx: &mut SemanticsCtx) {
571        self.child.semantics(ctx);
572    }
573
574    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
575        self.child.visit_children(visitor);
576    }
577
578    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
579        self.child.visit_children_mut(visitor);
580    }
581}
582
583fn aligned_start(alignment: Alignment, start: f32, available: f32, child: f32) -> f32 {
584    match alignment {
585        Alignment::Start | Alignment::Stretch => start,
586        Alignment::Center => start + (available - child) * 0.5,
587        Alignment::End => start + available - child,
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594    use sui_core::{Color, DpiInfo, Event, WindowEvent, WindowId};
595    use sui_reactive::Signal;
596    use sui_runtime::{Application, WidgetPod, WindowBuilder};
597
598    struct Fixed(Size);
599
600    impl Widget for Fixed {
601        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
602            constraints.clamp(self.0)
603        }
604
605        fn paint(&self, ctx: &mut PaintCtx) {
606            ctx.fill_bounds(Color::WHITE);
607        }
608
609        fn intrinsic_size(
610            &mut self,
611            _ctx: &mut MeasureCtx,
612            axis: Axis,
613            _available_cross: f32,
614        ) -> sui_layout::IntrinsicSize {
615            let natural = match axis {
616                Axis::Horizontal => self.0.width,
617                Axis::Vertical => self.0.height,
618            };
619            sui_layout::IntrinsicSize::new(0.0, natural)
620        }
621    }
622
623    #[test]
624    fn grid_wraps_children_against_resolved_fraction_tracks() {
625        let root = Grid::new([GridTrack::Fixed(80.0), GridTrack::Fraction(1.0)])
626            .gap(8.0)
627            .with_child(Fixed(Size::new(80.0, 20.0)))
628            .with_child(Fixed(Size::new(220.0, 30.0)));
629        let mut runtime = Application::new()
630            .window(WindowBuilder::new().root(root))
631            .build()
632            .unwrap();
633        let window = runtime.window_ids()[0];
634        runtime
635            .handle_event(
636                window,
637                sui_core::Event::Window(sui_core::WindowEvent::Resized(Size::new(240.0, 80.0))),
638            )
639            .unwrap();
640        let output = runtime.render(window).unwrap();
641        let graph = runtime.widget_graph(window).unwrap();
642        assert_eq!(output.frame.viewport, Size::new(240.0, 80.0));
643        assert_eq!(graph.nodes[1].bounds.width(), 80.0);
644        assert_eq!(graph.nodes[2].bounds.x(), 88.0);
645        assert_eq!(graph.nodes[2].bounds.width(), 152.0);
646    }
647
648    #[test]
649    fn aspect_ratio_contains_child_inside_tight_bounds() {
650        let mut pod = WidgetPod::new(AspectRatio::new(16.0 / 9.0, Fixed(Size::new(10.0, 10.0))));
651        let mut measure = sui_runtime::MeasureCtx::with_layout(
652            WindowId::new(1),
653            pod.id(),
654            Rect::ZERO,
655            sui_layout::LayoutContext::new(
656                DpiInfo::default(),
657                std::sync::Arc::new(sui_text::TextSystem::new()),
658                std::sync::Arc::new(sui_text::FontRegistry::new()),
659                std::sync::Arc::new(sui_scene::ImageRegistry::new()),
660            ),
661        );
662        assert_eq!(
663            pod.measure(&mut measure, Constraints::tight(Size::new(160.0, 120.0))),
664            Size::new(160.0, 120.0)
665        );
666    }
667
668    #[test]
669    fn safe_area_tracks_window_insets_and_selected_edges() {
670        let root = SafeArea::new(Fixed(Size::new(20.0, 20.0)))
671            .edges(SafeAreaEdges::LEFT.union(SafeAreaEdges::TOP));
672        let mut runtime = Application::new()
673            .window(WindowBuilder::new().root(root))
674            .build()
675            .unwrap();
676        let window = runtime.window_ids()[0];
677        runtime
678            .handle_event(
679                window,
680                Event::Window(WindowEvent::SafeAreaChanged(SafeAreaInsets::new(
681                    10.0, 12.0, 14.0, 16.0,
682                ))),
683            )
684            .unwrap();
685        runtime
686            .handle_event(
687                window,
688                Event::Window(WindowEvent::Resized(Size::new(100.0, 80.0))),
689            )
690            .unwrap();
691        runtime.render(window).unwrap();
692
693        let graph = runtime.widget_graph(window).unwrap();
694        assert_eq!(graph.nodes[1].bounds, Rect::new(10.0, 12.0, 90.0, 68.0));
695    }
696
697    struct MovingHost {
698        moved: Signal<bool>,
699        child: SingleChild,
700    }
701
702    impl Widget for MovingHost {
703        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
704            let _ = self
705                .child
706                .measure(ctx, Constraints::tight(Size::new(20.0, 20.0)));
707            constraints.clamp(Size::new(100.0, 20.0))
708        }
709
710        fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
711            let x = if ctx.observe(&self.moved) { 60.0 } else { 0.0 };
712            self.child
713                .arrange(ctx, Rect::new(bounds.x() + x, bounds.y(), 20.0, 20.0));
714        }
715
716        fn paint(&self, ctx: &mut PaintCtx) {
717            self.child.paint(ctx);
718        }
719
720        fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
721            self.child.visit_children(visitor);
722        }
723
724        fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
725            self.child.visit_children_mut(visitor);
726        }
727    }
728
729    #[test]
730    fn layout_transition_schedules_compositor_animation_after_rearrange() {
731        let moved = Signal::new(false);
732        let root = MovingHost {
733            moved: moved.clone(),
734            child: SingleChild::new(LayoutTransition::new(Fixed(Size::new(20.0, 20.0)))),
735        };
736        let mut runtime = Application::new()
737            .window(WindowBuilder::new().root(root))
738            .build()
739            .unwrap();
740        let window = runtime.window_ids()[0];
741        runtime
742            .handle_event(
743                window,
744                Event::Window(WindowEvent::Resized(Size::new(100.0, 20.0))),
745            )
746            .unwrap();
747        runtime.render(window).unwrap();
748
749        moved.set(true);
750        runtime.render(window).unwrap();
751        let graph = runtime.widget_graph(window).unwrap();
752        assert_eq!(graph.nodes[1].bounds.x(), 60.0);
753        assert_eq!(runtime.next_wakeup_time(window).unwrap(), Some(0.0));
754
755        // Midway, the child is presented between its old and new place by
756        // moving its layer.
757        runtime.tick(0.0);
758        let _ = runtime.drain_ready_events();
759        runtime.render(window).unwrap();
760        runtime.tick(0.09);
761        assert!(
762            runtime.drain_ready_events().is_empty(),
763            "no frame events needed"
764        );
765        let midway = runtime.render(window).unwrap();
766        let mut offsets = Vec::new();
767        midway.frame.scene.visit_layers(&mut |layer| {
768            offsets.push(layer.descriptor.properties.translation.x);
769        });
770        assert!(
771            offsets.iter().any(|x| *x < -1.0 && *x > -59.0),
772            "the layer glides toward its new place: {offsets:?}"
773        );
774
775        runtime.tick(0.2);
776        for (ready_window, event) in runtime.drain_ready_events() {
777            runtime.handle_event(ready_window, event).unwrap();
778        }
779        runtime.render(window).unwrap();
780        assert_eq!(runtime.next_wakeup_time(window).unwrap(), None);
781    }
782}