Skip to main content

sui_widgets/
presence.rs

1//! Content that animates in and out.
2//!
3//! [`Presence`] shows or hides one child. [`KeyedStack`] keeps a row or
4//! column of children in step with a list of keyed items: new items animate
5//! in, removed ones animate out while the gap closes, and items that change
6//! places glide to their new positions.
7//!
8//! Leaving content stays on screen until its exit finishes, but it is inert
9//! from the moment it starts to leave: it takes no pointer input or focus and
10//! drops out of the accessibility tree. The runtime drives every transition;
11//! enter and exit fades and scales move retained layers without repainting.
12
13use std::{cell::Cell, collections::HashMap, hash::Hash, rc::Rc, sync::Arc};
14
15use sui_animation::{AnimationSpec, Stagger};
16use sui_core::{
17    Event, InvalidationKind, InvalidationRequest, InvalidationTarget, Point, Rect, Size, Vector,
18    WidgetId,
19};
20use sui_layout::{Alignment, Axis, Constraints};
21use sui_reactive::{Observable, Signal};
22use sui_runtime::{
23    ArrangeCtx, EventCtx, FrameClock, LayerOptions, MeasureCtx, Motion, PaintBoundaryMode,
24    PaintCtx, SemanticsCtx, SingleChild, Widget, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor,
25    motion_policy,
26};
27use sui_scene::{LayerCompositionMode, LayerProperties};
28
29use crate::DefaultTheme;
30use crate::animation::ENTRANCE_SCALE;
31
32/// Presence below this counts as gone.
33const ABSENT: f32 = 1.0e-4;
34
35/// How content looks at the absent end of an enter or exit, and how long each
36/// takes.
37///
38/// Content fades in from `opacity`, grows from `scale`, and slides in from
39/// `offset` as it appears, and does the reverse as it leaves. With `collapse`,
40/// the space it takes grows and shrinks too, so neighbors move smoothly;
41/// otherwise it takes its full space for as long as any of it shows.
42///
43/// Scaling, sliding, and collapsing are movement: under reduced motion content
44/// only fades, and space opens at once on entry and closes after an exit.
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct PresenceTransition {
47    pub opacity: f32,
48    pub scale: f32,
49    pub offset: Vector,
50    pub collapse: bool,
51    pub enter: AnimationSpec,
52    pub exit: AnimationSpec,
53}
54
55impl PresenceTransition {
56    /// Fade and grow from 96% with the theme's entrance and exit motion.
57    pub fn new() -> Self {
58        let motion = DefaultTheme::default().motion;
59        Self {
60            opacity: 0.0,
61            scale: ENTRANCE_SCALE,
62            offset: Vector::ZERO,
63            collapse: false,
64            enter: motion.entrance_spec(),
65            exit: motion.exit_spec(),
66        }
67    }
68
69    /// Only fade.
70    pub fn fade() -> Self {
71        Self::new().scale(1.0)
72    }
73
74    /// Appear and disappear at once.
75    pub fn none() -> Self {
76        Self {
77            enter: AnimationSpec::INSTANT,
78            exit: AnimationSpec::INSTANT,
79            ..Self::fade()
80        }
81    }
82
83    pub const fn opacity(mut self, opacity: f32) -> Self {
84        self.opacity = opacity;
85        self
86    }
87
88    pub const fn scale(mut self, scale: f32) -> Self {
89        self.scale = scale;
90        self
91    }
92
93    /// Slide in from, and out to, `offset` from the resting position.
94    pub const fn offset(mut self, offset: Vector) -> Self {
95        self.offset = offset;
96        self
97    }
98
99    pub const fn collapse(mut self, collapse: bool) -> Self {
100        self.collapse = collapse;
101        self
102    }
103
104    pub const fn enter(mut self, spec: AnimationSpec) -> Self {
105        self.enter = spec;
106        self
107    }
108
109    pub const fn exit(mut self, spec: AnimationSpec) -> Self {
110        self.exit = spec;
111        self
112    }
113
114    /// The layer presentation at `presence` (0 absent, 1 present). Without
115    /// `movement`, only the opacity changes.
116    pub fn layer_properties(&self, presence: f32, movement: bool) -> LayerProperties {
117        let opacity = lerp(self.opacity, 1.0, presence).clamp(0.0, 1.0);
118        let properties = LayerProperties::default().with_opacity(opacity);
119        if !movement {
120            return properties;
121        }
122        let absence = 1.0 - presence;
123        properties
124            .with_translation(Vector::new(
125                self.offset.x * absence,
126                self.offset.y * absence,
127            ))
128            .with_scale(lerp(self.scale, 1.0, presence).max(0.0))
129    }
130
131    /// How much of its space content takes at `presence`, heading to
132    /// `target`: the presence itself while collapsing with movement,
133    /// otherwise all of it while any of the content is there.
134    fn space(&self, presence: f32, target: f32, movement: bool) -> f32 {
135        if self.collapse && movement {
136            presence.clamp(0.0, 1.0)
137        } else if target > ABSENT || presence > ABSENT {
138            1.0
139        } else {
140            0.0
141        }
142    }
143
144    fn spec(&self, entering: bool) -> AnimationSpec {
145        if entering { self.enter } else { self.exit }
146    }
147
148    /// Whether entering (or leaving) takes any time under the motion policy,
149    /// so leaving content stays around for it.
150    fn animates(&self, entering: bool) -> bool {
151        let spec = self.spec(entering);
152        !spec.with_policy(motion_policy()).is_instant()
153    }
154}
155
156impl Default for PresenceTransition {
157    fn default() -> Self {
158        Self::new()
159    }
160}
161
162fn lerp(from: f32, to: f32, t: f32) -> f32 {
163    from + (to - from) * t
164}
165
166fn main_extent(size: Size, axis: Axis) -> f32 {
167    match axis {
168        Axis::Horizontal => size.width,
169        Axis::Vertical => size.height,
170    }
171}
172
173fn cross_extent(size: Size, axis: Axis) -> f32 {
174    match axis {
175        Axis::Horizontal => size.height,
176        Axis::Vertical => size.width,
177    }
178}
179
180fn from_main_cross(main: f32, cross: f32, axis: Axis) -> Size {
181    match axis {
182        Axis::Horizontal => Size::new(main, cross),
183        Axis::Vertical => Size::new(cross, main),
184    }
185}
186
187/// Where content is in its enter or exit.
188#[derive(Debug, Clone, Copy, PartialEq)]
189struct PresenceMotion {
190    presence: Motion<f32>,
191    /// Whether the running transition may scale, slide, and collapse; fixed
192    /// when it starts, from the motion policy.
193    movement: bool,
194}
195
196impl PresenceMotion {
197    fn new(present: bool) -> Self {
198        Self {
199            presence: Motion::new(if present { 1.0 } else { 0.0 })
200                .invalidating(InvalidationKind::Effect),
201            movement: true,
202        }
203    }
204
205    fn target(&self) -> f32 {
206        self.presence.target()
207    }
208
209    fn is_present(&self) -> bool {
210        self.target() > 0.5
211    }
212
213    fn space(&self, transition: &PresenceTransition, time: f64) -> f32 {
214        transition.space(self.presence.at(time), self.target(), self.movement)
215    }
216
217    fn is_gone(&self, time: f64) -> bool {
218        !self.is_present() && !self.presence.is_animating(&time) && self.presence.at(time) <= ABSENT
219    }
220
221    /// Start toward present or absent, `delay` seconds from `time`. Returns
222    /// when the transition ends, if one runs.
223    fn start(
224        &mut self,
225        present: bool,
226        time: f64,
227        delay: f64,
228        transition: &PresenceTransition,
229    ) -> Option<f64> {
230        self.movement = motion_policy().allows_movement();
231        let target = if present { 1.0 } else { 0.0 };
232        self.presence
233            .start_after(target, time, delay, transition.spec(present))
234    }
235}
236
237/// Keep a layer showing a presence transition updated until `until`: its
238/// opacity always, and its scale and offset when the transition moves.
239fn track_presence(ctx: &mut MeasureCtx, layer: WidgetId, until: f64, motion: &PresenceMotion) {
240    ctx.track_motion_for(layer, until, InvalidationKind::Effect);
241    if motion.movement {
242        ctx.track_motion_for(layer, until, InvalidationKind::Transform);
243    }
244}
245
246/// Keep the widget laying out content in a presence transition measured as
247/// the content's space changes: every frame while it collapses, otherwise
248/// once when the transition ends.
249fn track_space(
250    ctx: &mut MeasureCtx,
251    until: f64,
252    motion: &PresenceMotion,
253    transition: &PresenceTransition,
254) {
255    if transition.collapse && motion.movement {
256        ctx.track_motion(until, InvalidationKind::Measure);
257    } else {
258        ctx.track_motion_end(until, InvalidationKind::Measure);
259    }
260}
261
262/// Shows or hides one child, animating it in and out.
263///
264/// A hidden child takes no space and stays retained, keeping its state for
265/// when it shows again. Drive visibility with [`Presence::shown_from`]; with
266/// [`Presence::appear`] the child also animates in when first laid out.
267pub struct Presence {
268    child: SingleChild,
269    shown_source: Option<Arc<dyn Observable<bool>>>,
270    shown_reader: Option<Box<dyn Fn() -> bool>>,
271    transition: PresenceTransition,
272    collapse_axis: Axis,
273    delay: f64,
274    appear: bool,
275    initialized: bool,
276    motion: PresenceMotion,
277}
278
279impl Presence {
280    pub fn new<W>(child: W) -> Self
281    where
282        W: Widget + 'static,
283    {
284        Self {
285            child: SingleChild::new(child),
286            shown_source: None,
287            shown_reader: None,
288            transition: PresenceTransition::new(),
289            collapse_axis: Axis::Vertical,
290            delay: 0.0,
291            appear: false,
292            initialized: false,
293            motion: PresenceMotion::new(true),
294        }
295    }
296
297    /// Start shown or hidden, without animating.
298    pub fn shown(mut self, shown: bool) -> Self {
299        self.motion = PresenceMotion::new(shown);
300        self.child.child_mut().set_inert(!shown);
301        self
302    }
303
304    /// Follow `source`: animate in when it becomes true and out when it
305    /// becomes false.
306    pub fn shown_from<O>(mut self, source: O) -> Self
307    where
308        O: Observable<bool> + 'static,
309    {
310        let shown = source.get();
311        self.shown_source = Some(Arc::new(source));
312        self.shown(shown)
313    }
314
315    /// Follow `shown`, read when the window redraws and on layout: animate in
316    /// when it returns true and out when it returns false. Prefer
317    /// [`Presence::shown_from`], which updates without polling.
318    pub fn shown_when<F>(mut self, shown: F) -> Self
319    where
320        F: Fn() -> bool + 'static,
321    {
322        let initial = shown();
323        self.shown_reader = Some(Box::new(shown));
324        self.shown(initial)
325    }
326
327    /// Animate in when first laid out, if shown then.
328    pub fn appear(mut self, appear: bool) -> Self {
329        self.appear = appear;
330        self
331    }
332
333    pub fn transition(mut self, transition: PresenceTransition) -> Self {
334        self.transition = transition;
335        self
336    }
337
338    /// Grow and shrink the space the child takes along `axis` as it enters
339    /// and leaves.
340    pub fn collapse(mut self, axis: Axis) -> Self {
341        self.transition.collapse = true;
342        self.collapse_axis = axis;
343        self
344    }
345
346    /// Wait `delay` seconds before entering or leaving.
347    pub fn delay(mut self, delay: f64) -> Self {
348        self.delay = delay.max(0.0);
349        self
350    }
351
352    pub fn is_shown(&self) -> bool {
353        self.motion.is_present()
354    }
355
356    fn set_shown(&mut self, shown: bool, ctx: &mut MeasureCtx) {
357        if shown == self.motion.is_present() {
358            return;
359        }
360        self.child.child_mut().set_inert(!shown);
361        let time = ctx.frame_time();
362        let own = ctx.widget_id();
363        if let Some(until) = self.motion.start(shown, time, self.delay, &self.transition) {
364            track_presence(ctx, own, until, &self.motion);
365            track_space(ctx, until, &self.motion, &self.transition);
366        }
367        // An instant change shows right away.
368        for kind in [
369            InvalidationKind::Paint,
370            InvalidationKind::Effect,
371            InvalidationKind::Transform,
372        ] {
373            ctx.request(InvalidationRequest::new(
374                InvalidationTarget::Widget(own),
375                kind,
376            ));
377        }
378    }
379}
380
381impl Widget for Presence {
382    fn event(&mut self, ctx: &mut EventCtx, _event: &Event) {
383        if self
384            .shown_reader
385            .as_ref()
386            .is_some_and(|shown| shown() != self.motion.is_present())
387        {
388            ctx.request_measure();
389        }
390    }
391
392    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
393        if let Some(source) = &self.shown_source {
394            let shown = ctx.observe(source.as_ref());
395            self.set_shown(shown, ctx);
396        }
397        if let Some(shown) = self.shown_reader.as_ref().map(|shown| shown()) {
398            self.set_shown(shown, ctx);
399        }
400        if !self.initialized {
401            self.initialized = true;
402            if self.appear && self.motion.is_present() {
403                self.motion = PresenceMotion::new(false);
404                self.set_shown(true, ctx);
405            }
406        }
407
408        let time = ctx.frame_time();
409        let space = self.motion.space(&self.transition, time);
410        if space <= 0.0 {
411            return constraints.clamp(Size::ZERO);
412        }
413        let size = self.child.measure(ctx, constraints);
414        if space >= 1.0 {
415            return size;
416        }
417        let collapsed = match self.collapse_axis {
418            Axis::Horizontal => Size::new(size.width * space, size.height),
419            Axis::Vertical => Size::new(size.width, size.height * space),
420        };
421        constraints.clamp(collapsed)
422    }
423
424    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
425        // The child keeps its full size while the space it takes collapses.
426        let size = self.child.child().measured_size();
427        self.child
428            .arrange(ctx, Rect::from_origin_size(bounds.origin, size));
429    }
430
431    fn paint(&self, ctx: &mut PaintCtx) {
432        if self.motion.presence.get(ctx) > ABSENT || self.motion.is_present() {
433            self.child.paint(ctx);
434        }
435    }
436
437    fn semantics(&self, ctx: &mut SemanticsCtx) {
438        self.child.semantics(ctx);
439    }
440
441    fn layer_options(&self) -> LayerOptions {
442        LayerOptions {
443            paint_boundary: PaintBoundaryMode::Explicit,
444            composition_mode: LayerCompositionMode::Normal,
445        }
446    }
447
448    fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
449        self.transition
450            .layer_properties(self.motion.presence.at(frame_time), self.motion.movement)
451    }
452
453    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
454        self.child.visit_children(visitor);
455    }
456
457    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
458        self.child.visit_children_mut(visitor);
459    }
460}
461
462/// What a [`KeyedStack`] item's layer shows: its presence and how far it is
463/// from where it was arranged while it moves.
464#[derive(Debug, Clone, Copy, PartialEq)]
465struct ItemMotion {
466    presence: PresenceMotion,
467    offset: Motion<Vector>,
468}
469
470/// The layer around each [`KeyedStack`] item. The stack owns the motion; the
471/// layer presents it.
472struct ItemLayer {
473    child: SingleChild,
474    motion: Rc<Cell<ItemMotion>>,
475    transition: Rc<Cell<PresenceTransition>>,
476}
477
478impl Widget for ItemLayer {
479    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
480        self.child.measure(ctx, constraints)
481    }
482
483    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
484        self.child.arrange(ctx, bounds);
485    }
486
487    fn paint(&self, ctx: &mut PaintCtx) {
488        self.child.paint(ctx);
489    }
490
491    fn semantics(&self, ctx: &mut SemanticsCtx) {
492        self.child.semantics(ctx);
493    }
494
495    fn layer_options(&self) -> LayerOptions {
496        LayerOptions {
497            paint_boundary: PaintBoundaryMode::Explicit,
498            composition_mode: LayerCompositionMode::Normal,
499        }
500    }
501
502    fn layer_properties_at(&self, frame_time: f64) -> LayerProperties {
503        let motion = self.motion.get();
504        let properties = self.transition.get().layer_properties(
505            motion.presence.presence.at(frame_time),
506            motion.presence.movement,
507        );
508        properties.with_translation(properties.translation + motion.offset.at(frame_time))
509    }
510
511    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
512        self.child.visit_children(visitor);
513    }
514
515    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
516        self.child.visit_children_mut(visitor);
517    }
518}
519
520struct StackEntry<K, T> {
521    key: K,
522    value: Signal<T>,
523    layer: WidgetPod,
524    motion: Rc<Cell<ItemMotion>>,
525    /// Where the item was on screen before the latest reorder, until it is
526    /// arranged in its new place.
527    moved_from: Option<Point>,
528}
529
530impl<K, T> StackEntry<K, T> {
531    fn motion(&self) -> ItemMotion {
532        self.motion.get()
533    }
534
535    fn update(&self, change: impl FnOnce(&mut ItemMotion)) {
536        let mut motion = self.motion.get();
537        change(&mut motion);
538        self.motion.set(motion);
539    }
540
541    fn is_leaving(&self) -> bool {
542        !self.motion().presence.is_present()
543    }
544}
545
546type BuildItem<K, T> = Box<dyn Fn(&K, Signal<T>) -> Box<dyn Widget>>;
547
548/// A row or column of children kept in step with a list of keyed items.
549///
550/// Each item's widget is built once and kept while its key stays in the list,
551/// updating through the [`Signal`] it was built with. New items animate in,
552/// one after another with a [`Stagger`]; removed items animate out while the
553/// gap they leave closes; items that change places glide to their new
554/// positions. An item added back while it is still leaving turns around and
555/// comes back.
556pub struct KeyedStack<K, T> {
557    axis: Axis,
558    spacing: f32,
559    alignment: Alignment,
560    items: Arc<dyn Observable<Vec<T>>>,
561    key_for: Box<dyn Fn(&T) -> K>,
562    build: BuildItem<K, T>,
563    transition: Rc<Cell<PresenceTransition>>,
564    stagger: Stagger,
565    move_spec: Option<AnimationSpec>,
566    appear: bool,
567    entries: Vec<StackEntry<K, T>>,
568    last_items: Option<Vec<T>>,
569    arranged: bool,
570}
571
572impl<K, T> KeyedStack<K, T>
573where
574    K: Clone + Eq + Hash + 'static,
575    T: Clone + PartialEq + 'static,
576{
577    /// A stack along `axis` of the items in `items`, identified by
578    /// `key_for` and built by `build`.
579    pub fn new<O, KF, B, W>(axis: Axis, items: O, key_for: KF, build: B) -> Self
580    where
581        O: Observable<Vec<T>> + 'static,
582        KF: Fn(&T) -> K + 'static,
583        B: Fn(&K, Signal<T>) -> W + 'static,
584        W: Widget + 'static,
585    {
586        let motion = DefaultTheme::default().motion;
587        Self {
588            axis,
589            spacing: 0.0,
590            alignment: Alignment::Stretch,
591            items: Arc::new(items),
592            key_for: Box::new(key_for),
593            build: Box::new(move |key, value| Box::new(build(key, value))),
594            transition: Rc::new(Cell::new(PresenceTransition::new().collapse(true))),
595            stagger: motion.stagger(),
596            move_spec: Some(motion.layout_spec()),
597            appear: false,
598            entries: Vec::new(),
599            last_items: None,
600            arranged: false,
601        }
602    }
603
604    pub fn vertical<O, KF, B, W>(items: O, key_for: KF, build: B) -> Self
605    where
606        O: Observable<Vec<T>> + 'static,
607        KF: Fn(&T) -> K + 'static,
608        B: Fn(&K, Signal<T>) -> W + 'static,
609        W: Widget + 'static,
610    {
611        Self::new(Axis::Vertical, items, key_for, build)
612    }
613
614    pub fn horizontal<O, KF, B, W>(items: O, key_for: KF, build: B) -> Self
615    where
616        O: Observable<Vec<T>> + 'static,
617        KF: Fn(&T) -> K + 'static,
618        B: Fn(&K, Signal<T>) -> W + 'static,
619        W: Widget + 'static,
620    {
621        Self::new(Axis::Horizontal, items, key_for, build)
622    }
623
624    pub fn gap(mut self, gap: f32) -> Self {
625        self.spacing = gap.max(0.0);
626        self
627    }
628
629    /// How items line up across the stack. `Stretch`, the default, makes
630    /// them all as wide (or tall) as the stack.
631    pub fn alignment(mut self, alignment: Alignment) -> Self {
632        self.alignment = alignment;
633        self
634    }
635
636    /// How items enter and leave. The stack collapses the space of leaving
637    /// items unless the transition turns `collapse` off.
638    pub fn transition(self, transition: PresenceTransition) -> Self {
639        self.transition.set(transition);
640        self
641    }
642
643    /// Delays for items that arrive together; [`Stagger::NONE`] brings them
644    /// in at once.
645    pub fn stagger(mut self, stagger: Stagger) -> Self {
646        self.stagger = stagger;
647        self
648    }
649
650    /// How items glide to new places, or `None` to move them at once.
651    pub fn move_spec(mut self, spec: Option<AnimationSpec>) -> Self {
652        self.move_spec = spec;
653        self
654    }
655
656    /// Animate the first items in too, instead of showing them at once.
657    pub fn appear(mut self, appear: bool) -> Self {
658        self.appear = appear;
659        self
660    }
661
662    /// The items shown, and those still leaving, in order.
663    pub fn len(&self) -> usize {
664        self.entries.len()
665    }
666
667    pub fn is_empty(&self) -> bool {
668        self.entries.is_empty()
669    }
670
671    fn new_entry(&self, key: K, item: T) -> StackEntry<K, T> {
672        let value = Signal::named("Keyed stack item", item);
673        let motion = Rc::new(Cell::new(ItemMotion {
674            presence: PresenceMotion::new(false),
675            offset: Motion::new(Vector::ZERO)
676                .invalidating(InvalidationKind::Transform)
677                .movement(),
678        }));
679        let child = WidgetPod::new_boxed((self.build)(&key, value.clone()));
680        let layer = WidgetPod::new(ItemLayer {
681            child: SingleChild::from_pod(child),
682            motion: Rc::clone(&motion),
683            transition: Rc::clone(&self.transition),
684        });
685        StackEntry {
686            key,
687            value,
688            layer,
689            motion,
690            moved_from: None,
691        }
692    }
693
694    fn reconcile(&mut self, items: Vec<T>, ctx: &mut MeasureCtx) {
695        let time = ctx.frame_time();
696        let transition = self.transition.get();
697        let first = self.last_items.is_none();
698
699        let previous_keys = self
700            .entries
701            .iter()
702            .map(|entry| entry.key.clone())
703            .collect::<Vec<_>>();
704        let mut previous = std::mem::take(&mut self.entries)
705            .into_iter()
706            .map(|entry| (entry.key.clone(), entry))
707            .collect::<HashMap<_, _>>();
708
709        // Listed items, in their new order.
710        let mut order = Vec::with_capacity(items.len());
711        let mut next = HashMap::with_capacity(items.len());
712        let mut arrivals = Vec::new();
713        for item in items {
714            let key = (self.key_for)(&item);
715            if next.contains_key(&key) {
716                continue;
717            }
718            let entry = match previous.remove(&key) {
719                Some(mut entry) => {
720                    entry.value.set(item);
721                    if entry.is_leaving() {
722                        // Back while still leaving: turn around.
723                        arrivals.push(key.clone());
724                    } else if self.arranged && self.move_spec.is_some() {
725                        let offset = entry.motion().offset.at(time);
726                        entry.moved_from = Some(entry.layer.bounds().origin + offset);
727                    }
728                    entry
729                }
730                None => {
731                    let entry = self.new_entry(key.clone(), item);
732                    if first && !self.appear {
733                        entry.update(|motion| motion.presence = PresenceMotion::new(true));
734                    } else {
735                        arrivals.push(key.clone());
736                    }
737                    entry
738                }
739            };
740            order.push(key.clone());
741            next.insert(key, entry);
742        }
743
744        // Unlisted items leave from where they were: after the item that
745        // preceded them.
746        for (index, key) in previous_keys.iter().enumerate() {
747            let Some(mut entry) = previous.remove(key) else {
748                continue;
749            };
750            if !entry.is_leaving() {
751                if !transition.animates(false) {
752                    continue;
753                }
754                entry.layer.set_inert(true);
755                entry.moved_from = None;
756                let layer = entry.layer.id();
757                let mut motion = entry.motion();
758                if let Some(until) = motion.presence.start(false, time, 0.0, &transition) {
759                    track_presence(ctx, layer, until, &motion.presence);
760                    track_space(ctx, until, &motion.presence, &transition);
761                }
762                entry.motion.set(motion);
763            }
764            let position = previous_keys[..index]
765                .iter()
766                .rev()
767                .find_map(|earlier| order.iter().position(|placed| placed == earlier))
768                .map_or(0, |position| position + 1);
769            order.insert(position, key.clone());
770            next.insert(key.clone(), entry);
771        }
772
773        let arriving = arrivals.len();
774        for (index, key) in arrivals.iter().enumerate() {
775            let Some(entry) = next.get_mut(key) else {
776                continue;
777            };
778            entry.layer.set_inert(false);
779            let delay = self.stagger.delay(index, arriving);
780            let layer = entry.layer.id();
781            let mut motion = entry.motion();
782            if let Some(until) = motion.presence.start(true, time, delay, &transition) {
783                track_presence(ctx, layer, until, &motion.presence);
784                track_space(ctx, until, &motion.presence, &transition);
785            }
786            entry.motion.set(motion);
787        }
788
789        self.entries = order
790            .into_iter()
791            .filter_map(|key| next.remove(&key))
792            .collect();
793        ctx.request_paint();
794        ctx.request_semantics();
795    }
796
797    fn child_constraints(&self, constraints: Constraints) -> Constraints {
798        let cross = cross_extent(constraints.max, self.axis);
799        let min_cross = if self.alignment == Alignment::Stretch && cross.is_finite() {
800            cross
801        } else {
802            0.0
803        };
804        Constraints::new(
805            from_main_cross(0.0, min_cross, self.axis),
806            from_main_cross(f32::INFINITY, cross, self.axis),
807        )
808    }
809}
810
811impl<K, T> Widget for KeyedStack<K, T>
812where
813    K: Clone + Eq + Hash + 'static,
814    T: Clone + PartialEq + 'static,
815{
816    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
817        let items = ctx.observe(self.items.as_ref());
818        if self.last_items.as_ref() != Some(&items) {
819            self.reconcile(items.clone(), ctx);
820            self.last_items = Some(items);
821        }
822
823        let time = ctx.frame_time();
824        let before = self.entries.len();
825        self.entries
826            .retain(|entry| !(entry.is_leaving() && entry.motion().presence.is_gone(time)));
827        if self.entries.len() != before {
828            ctx.request_paint();
829        }
830
831        let transition = self.transition.get();
832        let child_constraints = self.child_constraints(constraints);
833        let mut main = 0.0_f32;
834        let mut cross = 0.0_f32;
835        let mut widest_space = 0.0_f32;
836        for entry in &mut self.entries {
837            let size = entry.layer.measure(ctx, child_constraints);
838            let space = entry.motion().presence.space(&transition, time);
839            main += (main_extent(size, self.axis) + self.spacing) * space;
840            cross = cross.max(cross_extent(size, self.axis) * space.min(1.0));
841            widest_space = widest_space.max(space);
842        }
843        main = (main - self.spacing * widest_space).max(0.0);
844        constraints.clamp(from_main_cross(main, cross, self.axis))
845    }
846
847    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
848        let time = ctx.frame_time();
849        let transition = self.transition.get();
850        let available_cross = cross_extent(bounds.size, self.axis);
851        let mut position = 0.0_f32;
852        for entry in &mut self.entries {
853            let size = entry.layer.measured_size();
854            let child_cross = cross_extent(size, self.axis);
855            let cross_offset = match self.alignment {
856                Alignment::Start | Alignment::Stretch => 0.0,
857                Alignment::Center => (available_cross - child_cross) * 0.5,
858                Alignment::End => available_cross - child_cross,
859            };
860            let offset = from_main_cross(position, cross_offset, self.axis);
861            let origin = bounds.origin + Vector::new(offset.width, offset.height);
862
863            if let Some(from) = entry.moved_from.take()
864                && let Some(spec) = self.move_spec
865            {
866                let delta = from - origin;
867                if delta.x.abs() > 0.5 || delta.y.abs() > 0.5 {
868                    // Present the item where it was, then glide it home.
869                    let layer = entry.layer.id();
870                    let mut motion = entry.motion();
871                    motion.offset.jump_to(delta);
872                    match motion.offset.start(Vector::ZERO, time, spec) {
873                        Some(until) => {
874                            ctx.track_motion_for(layer, until, InvalidationKind::Transform)
875                        }
876                        None => motion.offset.jump_to(Vector::ZERO),
877                    }
878                    entry.motion.set(motion);
879                }
880            }
881
882            entry
883                .layer
884                .arrange(ctx, Rect::from_origin_size(origin, size));
885            let space = entry.motion().presence.space(&transition, time);
886            position += (main_extent(size, self.axis) + self.spacing) * space;
887        }
888        self.arranged = true;
889    }
890
891    fn paint(&self, ctx: &mut PaintCtx) {
892        for entry in &self.entries {
893            entry.layer.paint(ctx);
894        }
895    }
896
897    fn semantics(&self, ctx: &mut SemanticsCtx) {
898        for entry in &self.entries {
899            entry.layer.semantics(ctx);
900        }
901    }
902
903    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
904        for entry in &self.entries {
905            visitor.visit(&entry.layer);
906        }
907    }
908
909    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
910        for entry in &mut self.entries {
911            visitor.visit(&mut entry.layer);
912        }
913    }
914}
915
916#[cfg(test)]
917mod tests {
918    use super::*;
919    use sui_core::{Color, Event, WindowEvent, WindowId};
920    use sui_runtime::{
921        Application, MotionPreference, RenderOutput, Runtime, WidgetGraphSnapshot, WindowBuilder,
922        reset_motion_settings, set_app_motion_preference,
923    };
924
925    use crate::Flex;
926
927    /// A block `height` tall that paints white.
928    struct Block(f32);
929
930    impl Widget for Block {
931        fn measure(&mut self, _ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
932            constraints.clamp(Size::new(constraints.min.width.max(40.0), self.0))
933        }
934
935        fn paint(&self, ctx: &mut PaintCtx) {
936            ctx.fill_bounds(Color::WHITE);
937        }
938
939        fn accepts_focus(&self) -> bool {
940            true
941        }
942    }
943
944    fn app(root: impl Widget + 'static) -> (Runtime, WindowId) {
945        reset_motion_settings();
946        let mut runtime = Application::new()
947            .window(WindowBuilder::new().root(root))
948            .build()
949            .unwrap();
950        let window = runtime.window_ids()[0];
951        runtime
952            .handle_event(
953                window,
954                Event::Window(WindowEvent::Resized(Size::new(200.0, 400.0))),
955            )
956            .unwrap();
957        runtime.render(window).unwrap();
958        (runtime, window)
959    }
960
961    fn frame(runtime: &mut Runtime, window: WindowId, time: f64) -> RenderOutput {
962        runtime.tick(time);
963        for (ready_window, event) in runtime.drain_ready_events() {
964            runtime.handle_event(ready_window, event).unwrap();
965        }
966        runtime.render(window).unwrap()
967    }
968
969    fn graph(runtime: &Runtime, window: WindowId) -> WidgetGraphSnapshot {
970        runtime.widget_graph(window).unwrap()
971    }
972
973    fn nodes_named<'a>(
974        graph: &'a WidgetGraphSnapshot,
975        name: &str,
976    ) -> Vec<&'a sui_runtime::WidgetNodeSnapshot> {
977        graph
978            .nodes
979            .iter()
980            .filter(|node| node.widget_name.ends_with(name))
981            .collect()
982    }
983
984    fn layer_properties(output: &RenderOutput, widget: WidgetId) -> Option<LayerProperties> {
985        let mut found = None;
986        output.frame.scene.visit_layers(&mut |layer| {
987            if layer.widget_id() == widget {
988                found = Some(layer.descriptor.properties);
989            }
990        });
991        found
992    }
993
994    fn items_stack(items: &Signal<Vec<u32>>) -> KeyedStack<u32, u32> {
995        KeyedStack::vertical(items.clone(), |item| *item, |_, _| Block(20.0))
996            .gap(10.0)
997            .stagger(Stagger::NONE)
998    }
999
1000    fn item_tops(runtime: &Runtime, window: WindowId) -> Vec<f32> {
1001        nodes_named(&graph(runtime, window), "ItemLayer")
1002            .iter()
1003            .map(|node| node.bounds.y())
1004            .collect()
1005    }
1006
1007    #[test]
1008    fn presence_fades_out_then_takes_no_space() {
1009        let shown = Signal::new(true);
1010        let root = Flex::vertical()
1011            .with_child(Presence::new(Block(30.0)).shown_from(shown.clone()))
1012            .with_child(Block(20.0));
1013        let (mut runtime, window) = app(root);
1014        let exit = DefaultTheme::default().motion.exit_spec().duration();
1015
1016        shown.set(false);
1017        let start = frame(&mut runtime, window, 1.0);
1018        let graph_now = graph(&runtime, window);
1019        let presence = nodes_named(&graph_now, "Presence")[0];
1020        let blocks = nodes_named(&graph_now, "Block");
1021        assert!(blocks[0].inert && !blocks[0].accepts_focus && !blocks[0].hit_test);
1022        assert!(!blocks[1].inert);
1023        assert_eq!(
1024            layer_properties(&start, presence.id).map(|properties| properties.opacity),
1025            Some(1.0)
1026        );
1027
1028        let midway = frame(&mut runtime, window, 1.0 + exit * 0.5);
1029        let opacity = layer_properties(&midway, presence.id)
1030            .expect("the presence layer")
1031            .opacity;
1032        assert!(opacity > 0.0 && opacity < 1.0, "fading: {opacity}");
1033        // Without collapse, the child keeps its space until it is gone.
1034        assert_eq!(
1035            nodes_named(&graph(&runtime, window), "Block")[1].bounds.y(),
1036            30.0
1037        );
1038
1039        frame(&mut runtime, window, 1.0 + exit + 0.01);
1040        assert_eq!(
1041            nodes_named(&graph(&runtime, window), "Block")[1].bounds.y(),
1042            0.0
1043        );
1044        assert!(
1045            runtime
1046                .semantics(window)
1047                .unwrap()
1048                .iter()
1049                .all(|node| node.id != blocks[0].id)
1050        );
1051
1052        shown.set(true);
1053        frame(&mut runtime, window, 2.0);
1054        let graph_now = graph(&runtime, window);
1055        assert!(!nodes_named(&graph_now, "Block")[0].inert);
1056        assert_eq!(nodes_named(&graph_now, "Block")[1].bounds.y(), 30.0);
1057    }
1058
1059    #[test]
1060    fn collapsing_presence_closes_its_space_smoothly() {
1061        let shown = Signal::new(true);
1062        let root = Flex::vertical()
1063            .with_child(
1064                Presence::new(Block(40.0))
1065                    .shown_from(shown.clone())
1066                    .collapse(Axis::Vertical),
1067            )
1068            .with_child(Block(20.0));
1069        let (mut runtime, window) = app(root);
1070        let exit = DefaultTheme::default().motion.exit_spec().duration();
1071
1072        shown.set(false);
1073        frame(&mut runtime, window, 1.0);
1074        frame(&mut runtime, window, 1.0 + exit * 0.5);
1075        let below = nodes_named(&graph(&runtime, window), "Block")[1].bounds.y();
1076        assert!(below > 0.0 && below < 40.0, "the gap is closing: {below}");
1077        frame(&mut runtime, window, 1.0 + exit + 0.01);
1078        assert_eq!(
1079            nodes_named(&graph(&runtime, window), "Block")[1].bounds.y(),
1080            0.0
1081        );
1082        assert_eq!(runtime.next_wakeup_time(window).unwrap(), None);
1083    }
1084
1085    #[test]
1086    fn reduced_motion_fades_without_collapsing_or_scaling() {
1087        let shown = Signal::new(true);
1088        let root = Flex::vertical()
1089            .with_child(
1090                Presence::new(Block(40.0))
1091                    .shown_from(shown.clone())
1092                    .collapse(Axis::Vertical),
1093            )
1094            .with_child(Block(20.0));
1095        let (mut runtime, window) = app(root);
1096        set_app_motion_preference(Some(MotionPreference::Reduced));
1097        let exit = DefaultTheme::default().motion.exit_spec().duration();
1098
1099        shown.set(false);
1100        frame(&mut runtime, window, 1.0);
1101        let midway = frame(&mut runtime, window, 1.0 + exit * 0.5);
1102        let presence = nodes_named(&graph(&runtime, window), "Presence")[0].id;
1103        let properties = layer_properties(&midway, presence).expect("the presence layer");
1104        assert!(properties.opacity < 1.0);
1105        assert_eq!(properties.scale, LayerProperties::default().scale);
1106        assert_eq!(
1107            nodes_named(&graph(&runtime, window), "Block")[1].bounds.y(),
1108            40.0
1109        );
1110        frame(&mut runtime, window, 1.0 + exit + 0.01);
1111        assert_eq!(
1112            nodes_named(&graph(&runtime, window), "Block")[1].bounds.y(),
1113            0.0
1114        );
1115        reset_motion_settings();
1116    }
1117
1118    #[test]
1119    fn presence_can_animate_in_when_it_first_appears() {
1120        let root = Flex::vertical().with_child(Presence::new(Block(30.0)).appear(true));
1121        let (mut runtime, window) = app(root);
1122        let enter = DefaultTheme::default().motion.entrance_spec().duration();
1123        let presence = nodes_named(&graph(&runtime, window), "Presence")[0].id;
1124        let start = frame(&mut runtime, window, 0.0);
1125        let opacity = layer_properties(&start, presence).expect("layer").opacity;
1126        assert!(opacity < 0.5, "starts faded out: {opacity}");
1127        let end = frame(&mut runtime, window, enter + 0.01);
1128        assert_eq!(
1129            layer_properties(&end, presence).expect("layer").opacity,
1130            1.0
1131        );
1132    }
1133
1134    #[test]
1135    fn keyed_stack_shows_its_first_items_without_animating() {
1136        let items = Signal::new(vec![1, 2, 3]);
1137        let (runtime, window) = app(items_stack(&items));
1138        assert_eq!(item_tops(&runtime, window), vec![0.0, 30.0, 60.0]);
1139        assert_eq!(runtime.next_wakeup_time(window).unwrap(), None);
1140    }
1141
1142    #[test]
1143    fn removed_items_leave_while_the_gap_closes() {
1144        let items = Signal::new(vec![1, 2, 3]);
1145        let (mut runtime, window) = app(items_stack(&items));
1146        let exit = DefaultTheme::default().motion.exit_spec().duration();
1147        let blocks_before = nodes_named(&graph(&runtime, window), "Block")
1148            .iter()
1149            .map(|node| node.id)
1150            .collect::<Vec<_>>();
1151
1152        items.set(vec![1, 3]);
1153        frame(&mut runtime, window, 1.0);
1154        let graph_now = graph(&runtime, window);
1155        let layers = nodes_named(&graph_now, "ItemLayer");
1156        assert_eq!(layers.len(), 3, "the removed item stays while it leaves");
1157        assert!(layers[1].inert && !layers[0].inert && !layers[2].inert);
1158        assert_eq!(item_tops(&runtime, window), vec![0.0, 30.0, 60.0]);
1159
1160        frame(&mut runtime, window, 1.0 + exit * 0.5);
1161        let tops = item_tops(&runtime, window);
1162        assert!(
1163            tops[2] < 60.0 && tops[2] > 30.0,
1164            "the next item moves up: {tops:?}"
1165        );
1166
1167        frame(&mut runtime, window, 1.0 + exit + 0.01);
1168        assert_eq!(item_tops(&runtime, window), vec![0.0, 30.0]);
1169        let remaining = nodes_named(&graph(&runtime, window), "Block")
1170            .iter()
1171            .map(|node| node.id)
1172            .collect::<Vec<_>>();
1173        assert_eq!(remaining, vec![blocks_before[0], blocks_before[2]]);
1174    }
1175
1176    #[test]
1177    fn inserted_items_grow_in_one_after_another() {
1178        let items = Signal::new(vec![1]);
1179        let root = items_stack(&items).stagger(Stagger::new(0.1));
1180        let (mut runtime, window) = app(root);
1181        let enter = DefaultTheme::default().motion.entrance_spec().duration();
1182
1183        items.set(vec![1, 2, 3]);
1184        frame(&mut runtime, window, 1.0);
1185        let layers = nodes_named(&graph(&runtime, window), "ItemLayer")
1186            .iter()
1187            .map(|node| node.id)
1188            .collect::<Vec<_>>();
1189        assert_eq!(item_tops(&runtime, window)[1], 30.0);
1190
1191        let early = frame(&mut runtime, window, 1.0 + enter * 0.5);
1192        let second = layer_properties(&early, layers[1]).expect("layer").opacity;
1193        let third = layer_properties(&early, layers[2]).expect("layer").opacity;
1194        assert!(second > 0.0, "the first arrival is fading in: {second}");
1195        assert!(third < second, "the next one follows: {third} < {second}");
1196
1197        frame(&mut runtime, window, 1.0 + 0.1 + enter + 0.01);
1198        assert_eq!(item_tops(&runtime, window), vec![0.0, 30.0, 60.0]);
1199        assert_eq!(runtime.next_wakeup_time(window).unwrap(), None);
1200    }
1201
1202    #[test]
1203    fn reordered_items_glide_to_their_new_places() {
1204        let items = Signal::new(vec![1, 2, 3]);
1205        let (mut runtime, window) = app(items_stack(&items));
1206        let layers = nodes_named(&graph(&runtime, window), "ItemLayer")
1207            .iter()
1208            .map(|node| node.id)
1209            .collect::<Vec<_>>();
1210        let glide = DefaultTheme::default().motion.layout_spec().duration();
1211
1212        items.set(vec![3, 2, 1]);
1213        let start = frame(&mut runtime, window, 1.0);
1214        // Layout settles at once; the layers start where the items were.
1215        let order = nodes_named(&graph(&runtime, window), "ItemLayer")
1216            .iter()
1217            .map(|node| node.id)
1218            .collect::<Vec<_>>();
1219        assert_eq!(order, vec![layers[2], layers[1], layers[0]]);
1220        let first = layer_properties(&start, layers[2]).expect("layer");
1221        assert_eq!(first.translation.y, 60.0);
1222        assert_eq!(
1223            layer_properties(&start, layers[1])
1224                .expect("layer")
1225                .translation
1226                .y,
1227            0.0
1228        );
1229
1230        let midway = frame(&mut runtime, window, 1.0 + glide * 0.5);
1231        let y = layer_properties(&midway, layers[2])
1232            .expect("layer")
1233            .translation
1234            .y;
1235        assert!(y > 0.0 && y < 60.0, "gliding up: {y}");
1236        let end = frame(&mut runtime, window, 1.0 + glide + 0.01);
1237        assert_eq!(
1238            layer_properties(&end, layers[2])
1239                .expect("layer")
1240                .translation
1241                .y,
1242            0.0
1243        );
1244    }
1245
1246    #[test]
1247    fn an_item_added_back_while_leaving_turns_around() {
1248        let items = Signal::new(vec![1, 2]);
1249        let (mut runtime, window) = app(items_stack(&items));
1250        let exit = DefaultTheme::default().motion.exit_spec().duration();
1251        let enter = DefaultTheme::default().motion.entrance_spec().duration();
1252        let layer = nodes_named(&graph(&runtime, window), "ItemLayer")[1].id;
1253
1254        items.set(vec![1]);
1255        frame(&mut runtime, window, 1.0);
1256        frame(&mut runtime, window, 1.0 + exit * 0.5);
1257        items.set(vec![1, 2]);
1258        frame(&mut runtime, window, 1.0 + exit * 0.5);
1259        let graph_now = graph(&runtime, window);
1260        let layers = nodes_named(&graph_now, "ItemLayer");
1261        assert_eq!(layers[1].id, layer, "the same widget comes back");
1262        assert!(!layers[1].inert);
1263
1264        let end = frame(&mut runtime, window, 1.0 + exit + enter + 0.01);
1265        assert_eq!(layer_properties(&end, layer).expect("layer").opacity, 1.0);
1266        assert_eq!(item_tops(&runtime, window), vec![0.0, 30.0]);
1267    }
1268}