Skip to main content

cranpose_ui/widgets/
animated_content.rs

1//! `AnimatedContent`: content that changes with a transition.
2//!
3//! Mirrors Jetpack Compose's `AnimatedContent` from
4//! `androidx.compose.animation`. Each content the container shows has its
5//! own progress, from `0.0` (gone) to `1.0` (at rest), which its layer reads
6//! while it draws: a running transition moves layers and recomposes nothing.
7//! Content that left is removed on the frame its exit ends, and a
8//! [`SizeTransform`] animates the container's size in layout.
9//!
10//! Content that a change brings composes as pausable content: past the
11//! frame's composition budget it composes over the next frames, and the
12//! change waits with what shows until the content is complete, so a large
13//! screen does not stop the frames that come before it.
14
15use std::{
16    cell::{Cell, RefCell},
17    rc::Rc,
18};
19
20use cranpose_animation::{Animatable, AnimationType};
21use cranpose_core::{
22    MutableState, NodeId, PausableContent, RuntimeHandle, internal::FrameCallbackRegistration,
23    remember, with_current_composer, with_key, with_pausable_content,
24};
25use cranpose_ui_graphics::{Size, WindowCoordinates};
26use cranpose_ui_layout::{
27    Constraints, LayoutDirection, LayoutModifierMeasureResult, Measurable, Measurables,
28    MeasurePolicy, MeasureResult, MeasureScope, Placement,
29};
30
31use crate::{
32    composable,
33    modifier::{GraphicsLayer, Modifier},
34    widgets::{
35        animated_visibility::{ContainerFrame, EnterTransition, ExitTransition, TransitionEffects},
36        box_widget::{Box, BoxSpec},
37        layout::Layout,
38        shared_transition::{ProvideSharedEntry, SharedEntry, in_shared_transition},
39    },
40};
41
42/// Progress below which leaving content is gone and leaves the composition.
43const GONE: f32 = 0.001;
44
45/// How an [`AnimatedContent`] changes from one content to the next.
46///
47/// Mirrors Jetpack Compose's `ContentTransform`: build one with
48/// `enter.together_with(exit)` and add a size animation with
49/// [`using`](Self::using).
50#[derive(Clone, Debug, PartialEq)]
51pub struct ContentTransform {
52    /// Transition that plays on the content that comes in.
53    pub enter: EnterTransition,
54    /// Transition that plays on the content that goes out.
55    pub exit: ExitTransition,
56    /// How the container's size follows the content's; `None` keeps the
57    /// container as large as the largest content during the change.
58    pub size_transform: Option<SizeTransform>,
59}
60
61impl ContentTransform {
62    /// Animates the container's size with `size_transform`. Compose's
63    /// `transform using SizeTransform()`.
64    pub fn using(mut self, size_transform: SizeTransform) -> Self {
65        self.size_transform = Some(size_transform);
66        self
67    }
68}
69
70/// Animates an [`AnimatedContent`]'s size from the content that leaves to
71/// the content that comes. Compose's `SizeTransform`.
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct SizeTransform {
74    /// Whether content outside the animating size is clipped.
75    pub clip: bool,
76    /// Animation that drives the size change.
77    pub animation: AnimationType,
78}
79
80impl Default for SizeTransform {
81    fn default() -> Self {
82        Self {
83            clip: true,
84            animation: AnimationType::default(),
85        }
86    }
87}
88
89/// A gesture part of the way from the current content toward another, as
90/// predictive back is: the content `toward` shows at `fraction` and the
91/// current content at `1.0 - fraction`, each with the transition from the
92/// current content to `toward`.
93#[derive(Clone, Debug, PartialEq)]
94pub struct ContentSeek<T> {
95    /// The content that the gesture heads toward.
96    pub toward: T,
97    /// How far the gesture has come toward `toward`, from 0.0 (still at the current content) to 1.0
98    /// (at `toward`).
99    pub fraction: f32,
100}
101
102/// How far one content is in the container, and how it shows on the way.
103pub(crate) struct EntryMotion {
104    progress: RefCell<Animatable<f32>>,
105    size: Rc<Cell<Size>>,
106    /// The container that slides across its edge measure from.
107    container: Rc<Cell<ContainerFrame>>,
108    effects: RefCell<TransitionEffects>,
109    // Whether the last composition of the entry gave its content a layout
110    // node for a size change.
111    sized: Cell<bool>,
112    animation: Cell<AnimationType>,
113    /// Whether the content goes, rather than comes or rests.
114    pub(crate) leaving: Cell<bool>,
115    /// Where the content's box is, its layer included, inside a shared
116    /// transition layout.
117    coordinates: Rc<Cell<WindowCoordinates>>,
118}
119
120impl EntryMotion {
121    pub(crate) fn progress(&self) -> f32 {
122        self.progress.borrow().state().value()
123    }
124
125    fn layer(&self) -> GraphicsLayer {
126        self.effects
127            .borrow()
128            .layer(self.progress(), self.size.get(), self.container.get())
129    }
130
131    // Where the content of size `full` lies and how large its box is, as its
132    // size change and its slide put them at the current progress. Reading the
133    // progress makes the layout measure again on each frame the transition
134    // moves.
135    pub(crate) fn fit(
136        &self,
137        full: Size,
138        constraints: Constraints,
139        density: f32,
140        direction: LayoutDirection,
141    ) -> LayoutModifierMeasureResult {
142        let progress = self.progress();
143        let effects = self.effects.borrow();
144        let Some(change) = effects.size_change() else {
145            return LayoutModifierMeasureResult::with_size(full);
146        };
147        let (width, height) = {
148            let size = change.size_at(full, progress, density);
149            constraints.constrain(size.width, size.height)
150        };
151        let size = Size::new(width, height);
152        let (x, y) = change.offset(full, size, direction, density);
153        let (slide_x, slide_y) = effects.slide(progress, full, self.container.get());
154        LayoutModifierMeasureResult::new(size, x + slide_x, y + slide_y)
155    }
156
157    // Whether the entry's transition changes its size, which its content
158    // composes a layout node for.
159    fn changes_size(&self) -> bool {
160        self.effects.borrow().size_change().is_some()
161    }
162
163    // Whether the entry's transition changes its size and its content has
164    // no layout node for that yet.
165    fn lacks_size_node(&self) -> bool {
166        self.changes_size() && !self.sized.get()
167    }
168
169    fn set_effects(&self, effects: &TransitionEffects) {
170        self.effects.borrow_mut().clone_from(effects);
171    }
172
173    // Animates toward `target` unless it already runs there or rests there;
174    // an animation that takes no time puts it there at once, in the frame
175    // of the change. Composition calls it, and reads nothing it would
176    // recompose by.
177    fn animate_to(&self, target: f32) {
178        let mut progress = self.progress.borrow_mut();
179        let settled = if progress.is_running() {
180            progress.target()
181        } else {
182            progress.state().get_non_reactive()
183        };
184        if (settled - target).abs() <= f32::EPSILON {
185            return;
186        }
187        match self.animation.get() {
188            AnimationType::Tween(spec) if spec.duration_millis == 0 && spec.delay_millis == 0 => {
189                progress.snapTo(target);
190            }
191            animation => progress.animateTo(target, animation),
192        }
193    }
194
195    fn snap_to(&self, target: f32) {
196        self.progress.borrow_mut().snapTo(target);
197    }
198
199    /// Shown in full with nothing running: the content a change leaves
200    /// takes the change's exit transition only from here.
201    fn at_rest(&self) -> bool {
202        let progress = self.progress.borrow();
203        !progress.is_running() && progress.state().get_non_reactive() >= 1.0 - GONE
204    }
205
206    fn gone(&self) -> bool {
207        let progress = self.progress.borrow();
208        !progress.is_running() && progress.state().get_non_reactive() <= GONE
209    }
210}
211
212struct Entry<T> {
213    id: u64,
214    value: T,
215    motion: Rc<EntryMotion>,
216    // The content a change brought, which may compose across frames; none
217    // for the first content, which composes at once.
218    content: Option<PausableContent>,
219}
220
221impl<T> Entry<T> {
222    fn is_complete(&self) -> bool {
223        self.content
224            .as_ref()
225            .is_none_or(PausableContent::is_complete)
226    }
227}
228
229// Tells the container's measure policy which child is content that a
230// change brought: it neither measures nor places it until it is complete.
231#[derive(Debug, PartialEq)]
232struct ChangedContent(PausableContent);
233
234type ContentFn<T> = Box<dyn FnMut(T)>;
235
236struct ContentState<T> {
237    runtime: RuntimeHandle,
238    /// Leaving content first, the current content last, on top.
239    entries: RefCell<Vec<Entry<T>>>,
240    next_id: Cell<u64>,
241    last_target: RefCell<Option<T>>,
242    content: RefCell<Option<ContentFn<T>>>,
243    size_transform: Cell<Option<SizeTransform>>,
244    size: RefCell<Option<Animatable<Size>>>,
245    /// Where the container is, inside a shared transition layout.
246    coordinates: Rc<Cell<WindowCoordinates>>,
247    /// The container's size from its last measure, where a size animation
248    /// starts, and its layout direction.
249    frame: Rc<Cell<ContainerFrame>>,
250    node: Rc<Cell<Option<NodeId>>>,
251    // Bumped when leaving content is removed or content a change brought
252    // completes, so the container recomposes without the one or with the
253    // other.
254    entries_changed: MutableState<u64>,
255    watcher: RefCell<Option<FrameCallbackRegistration>>,
256}
257
258impl<T: Clone + PartialEq + 'static> ContentState<T> {
259    fn new(runtime: RuntimeHandle) -> Self {
260        Self {
261            entries_changed: MutableState::with_runtime(0, runtime.clone()),
262            runtime,
263            entries: RefCell::new(Vec::new()),
264            next_id: Cell::new(0),
265            last_target: RefCell::new(None),
266            content: RefCell::new(None),
267            size_transform: Cell::new(None),
268            size: RefCell::new(None),
269            frame: Rc::default(),
270            coordinates: Rc::default(),
271            node: Rc::default(),
272            watcher: RefCell::new(None),
273        }
274    }
275
276    fn push(
277        &self,
278        value: T,
279        progress: f32,
280        effects: TransitionEffects,
281        animation: AnimationType,
282        content: Option<PausableContent>,
283    ) {
284        let id = self.next_id.get();
285        self.next_id.set(id.wrapping_add(1));
286        self.entries.borrow_mut().push(Entry {
287            id,
288            value,
289            motion: Rc::new(EntryMotion {
290                progress: RefCell::new(Animatable::new(progress, self.runtime.clone())),
291                size: Rc::new(Cell::new(Size::ZERO)),
292                container: Rc::clone(&self.frame),
293                effects: RefCell::new(effects),
294                sized: Cell::new(false),
295                animation: Cell::new(animation),
296                leaving: Cell::new(false),
297                coordinates: Rc::default(),
298            }),
299            content,
300        });
301    }
302
303    // Content for a change to compose, which may take frames: once it
304    // completes, the container recomposes to start the change and measures
305    // again with the content it skipped until then.
306    fn changed_content(&self) -> PausableContent {
307        let changed = self.entries_changed;
308        let node = Rc::clone(&self.node);
309        PausableContent::new(move || {
310            changed.update(|count| *count = count.wrapping_add(1));
311            if let Some(node) = node.get() {
312                crate::schedule_measure_repass(node);
313            }
314        })
315    }
316
317    /// Gives the entry that shows the content of `value` that state, and
318    /// answers whether there is one: a state with the key of a content shown
319    /// changes it in place.
320    fn show(&self, value: &T, same: &dyn Fn(&T, &T) -> bool) -> bool {
321        let mut entries = self.entries.borrow_mut();
322        let Some(entry) = entries.iter_mut().find(|entry| same(&entry.value, value)) else {
323            return false;
324        };
325        if entry.value != *value {
326            entry.value = value.clone();
327        }
328        true
329    }
330
331    /// Brings the entries to `target`: it comes in with the transition from
332    /// the previous target, everything else leaves, and a seek holds both
333    // ends where the gesture is. While the content of `target` is not
334    // complete, everything stays as it is and the answer is `false`.
335    fn sync(
336        &self,
337        target: &T,
338        seek: Option<&ContentSeek<T>>,
339        transition: &dyn Fn(&T, &T) -> ContentTransform,
340        same: &dyn Fn(&T, &T) -> bool,
341    ) -> bool {
342        let seek = seek.filter(|seek| !same(&seek.toward, target));
343        if !self.admit(target, seek, transition, same) {
344            return false;
345        }
346        let previous = self.last_target.replace(Some(target.clone()));
347        let change = previous
348            .filter(|previous| !same(previous, target))
349            .map(|previous| transition(&previous, target));
350        if let Some(change) = &change {
351            self.size_transform.set(change.size_transform);
352        }
353        let seeking = seek.map(|seek| (seek, transition(target, &seek.toward)));
354        if let Some((seek, _)) = &seeking
355            && !self.show(&seek.toward, same)
356        {
357            self.push(
358                seek.toward.clone(),
359                0.0,
360                TransitionEffects::default(),
361                AnimationType::default(),
362                Some(self.changed_content()),
363            );
364        }
365        self.aim(target, seeking.as_ref(), change.as_ref(), same);
366        true
367    }
368
369    // Keeps the entries that may still show and brings one for `target`.
370    // Answers whether the content of `target` is complete.
371    fn admit(
372        &self,
373        target: &T,
374        seek: Option<&ContentSeek<T>>,
375        transition: &dyn Fn(&T, &T) -> ContentTransform,
376        same: &dyn Fn(&T, &T) -> bool,
377    ) -> bool {
378        // Content that never showed leaves once no change heads for it.
379        self.entries.borrow_mut().retain(|entry| {
380            entry.is_complete()
381                || same(&entry.value, target)
382                || seek.is_some_and(|seek| same(&entry.value, &seek.toward))
383        });
384        let first = self.entries.borrow().is_empty();
385        if !self.show(target, same) {
386            let enter = self
387                .last_target
388                .borrow()
389                .as_ref()
390                .filter(|previous| !same(previous, target))
391                .map_or_else(EnterTransition::none, |previous| {
392                    transition(previous, target).enter
393                });
394            let progress = if first { 1.0 } else { 0.0 };
395            let content = (!first).then(|| self.changed_content());
396            self.push(
397                target.clone(),
398                progress,
399                enter.effects().clone(),
400                enter.animation(),
401                content,
402            );
403        }
404        self.entries
405            .borrow()
406            .iter()
407            .find(|entry| same(&entry.value, target))
408            .is_some_and(Entry::is_complete)
409    }
410
411    // Sets each entry moving toward where `change` or the seek puts it:
412    // the content of `target` comes in and the rest leaves.
413    fn aim(
414        &self,
415        target: &T,
416        seeking: Option<&(&ContentSeek<T>, ContentTransform)>,
417        change: Option<&ContentTransform>,
418        same: &dyn Fn(&T, &T) -> bool,
419    ) {
420        let mut entries = self.entries.borrow_mut();
421        for entry in entries.iter_mut() {
422            let motion = &entry.motion;
423            if same(&entry.value, target) {
424                // New content took its enter transition when it was added;
425                // content that turns back runs its own transition backward.
426                // A gesture that seeks away from it makes it the content that
427                // goes, for the shared elements in it.
428                entry.motion.leaving.set(seeking.is_some());
429                match seeking {
430                    Some((seek, seek_change)) => {
431                        motion.set_effects(seek_change.exit.effects());
432                        motion.snap_to(1.0 - seek.fraction.clamp(0.0, 1.0));
433                    }
434                    None => motion.animate_to(1.0),
435                }
436            } else if let Some((seek, seek_change)) =
437                seeking.filter(|(seek, _)| same(&seek.toward, &entry.value))
438            {
439                entry.motion.leaving.set(false);
440                motion.set_effects(seek_change.enter.effects());
441                motion.animation.set(seek_change.enter.animation());
442                motion.snap_to(seek.fraction.clamp(0.0, 1.0));
443            } else {
444                if !entry.motion.leaving.replace(true)
445                    && let Some(change) = change.filter(|_| motion.at_rest())
446                {
447                    motion.set_effects(change.exit.effects());
448                    motion.animation.set(change.exit.animation());
449                }
450                motion.animate_to(0.0);
451            }
452        }
453        // The current content draws on top.
454        if let Some(index) = entries.iter().position(|entry| same(&entry.value, target)) {
455            let current = entries.remove(index);
456            entries.push(current);
457        }
458    }
459
460    // Drops content whose exit already ended, as an exit that takes no time
461    // does in the pass of its change. Says whether it dropped any.
462    fn drop_gone(&self) -> bool {
463        let mut entries = self.entries.borrow_mut();
464        let before = entries.len();
465        // The current content is last; a seek all the way does not remove it.
466        let current = entries.last().map(|entry| entry.id);
467        entries.retain(|entry| {
468            Some(entry.id) == current || !(entry.motion.leaving.get() && entry.motion.gone())
469        });
470        before != entries.len()
471    }
472
473    /// Notes the layout direction when a slide toward the start or the end
474    /// needs it.
475    fn note_direction(&self) {
476        let uses_direction = self
477            .entries
478            .borrow()
479            .iter()
480            .any(|entry| entry.motion.effects.borrow().uses_direction());
481        if uses_direction {
482            let frame = self.frame.get();
483            self.frame.set(ContainerFrame {
484                rtl: crate::layout_direction::layout_direction().is_rtl(),
485                ..frame
486            });
487        }
488    }
489
490    // Whether an entry took a transition that changes its size after its
491    // content composed, so that the content composes again with a node for it.
492    fn lacks_size_node(&self) -> bool {
493        self.entries
494            .borrow()
495            .iter()
496            .any(|entry| entry.motion.lacks_size_node())
497    }
498
499    fn animating(&self) -> bool {
500        self.entries
501            .borrow()
502            .iter()
503            .any(|entry| entry.motion.leaving.get())
504            || self
505                .size
506                .borrow()
507                .as_ref()
508                .is_some_and(Animatable::is_running)
509    }
510}
511
512/// Removes leaving content on the frame its exit ends, and measures the
513/// container again while its size animates.
514fn watch<T: Clone + PartialEq + 'static>(state: &Rc<ContentState<T>>) {
515    if state.watcher.borrow().is_some() || !state.animating() {
516        return;
517    }
518    let weak = Rc::downgrade(state);
519    let registration = state.runtime.frame_clock().with_frame_nanos(move |_| {
520        let Some(state) = weak.upgrade() else {
521            return;
522        };
523        state.watcher.borrow_mut().take();
524        if state.drop_gone() {
525            state
526                .entries_changed
527                .update(|count| *count = count.wrapping_add(1));
528        }
529        if state
530            .size
531            .borrow()
532            .as_ref()
533            .is_some_and(Animatable::is_running)
534            && let Some(node) = state.node.get()
535        {
536            crate::schedule_measure_repass(node);
537            crate::request_render_invalidation();
538        }
539        watch(&state);
540    });
541    *state.watcher.borrow_mut() = Some(registration);
542}
543
544struct StateHandle<T>(Rc<ContentState<T>>);
545
546impl<T> Clone for StateHandle<T> {
547    fn clone(&self) -> Self {
548        Self(Rc::clone(&self.0))
549    }
550}
551
552impl<T> PartialEq for StateHandle<T> {
553    fn eq(&self, other: &Self) -> bool {
554        Rc::ptr_eq(&self.0, &other.0)
555    }
556}
557
558/// Changes `content` with a transition when `target_state` changes.
559///
560/// `transition_spec` receives the state that goes and the state that comes,
561/// and answers how they change: `fade_in().together_with(fade_out())`,
562/// with `.using(SizeTransform::default())` to animate the size between
563/// them. The first content shows at rest. Content that leaves stays
564/// composed until its exit ends; a change back while it leaves brings it
565/// back from where it was.
566///
567/// Mirrors Jetpack Compose:
568/// `AnimatedContent(targetState, transitionSpec = { ... }) { state -> ... }`.
569#[composable(no_skip)]
570pub fn AnimatedContent<T, F>(
571    target_state: T,
572    transition_spec: impl Fn(&T, &T) -> ContentTransform + 'static,
573    content: F,
574) where
575    T: Clone + PartialEq + 'static,
576    F: FnMut(T) + 'static,
577{
578    SeekableAnimatedContent(target_state, None, transition_spec, content);
579}
580
581/// [`AnimatedContent`] where `content_key` tells contents apart: a target
582/// whose key is the key of the content shown changes that content in place,
583/// with the new state and without a transition — Compose's `contentKey`.
584#[composable(no_skip)]
585pub fn AnimatedContentWithKey<T, K, F>(
586    target_state: T,
587    content_key: impl Fn(&T) -> K + 'static,
588    transition_spec: impl Fn(&T, &T) -> ContentTransform + 'static,
589    content: F,
590) where
591    T: Clone + PartialEq + 'static,
592    K: PartialEq,
593    F: FnMut(T) + 'static,
594{
595    animated_content(
596        target_state,
597        None,
598        &transition_spec,
599        &|a, b| content_key(a) == content_key(b),
600        content,
601    );
602}
603
604/// [`AnimatedContent`] that a gesture can hold part of the way toward
605/// another state, as predictive back does: while `seek` is set, its
606/// `toward` content shows at its fraction. When the gesture ends the change
607/// finishes or goes back from where it stood, depending on whether the
608/// target became `toward`.
609#[composable(no_skip)]
610pub fn SeekableAnimatedContent<T, F>(
611    target_state: T,
612    seek: Option<ContentSeek<T>>,
613    transition_spec: impl Fn(&T, &T) -> ContentTransform + 'static,
614    content: F,
615) where
616    T: Clone + PartialEq + 'static,
617    F: FnMut(T) + 'static,
618{
619    animated_content(
620        target_state,
621        seek,
622        &transition_spec,
623        &|a, b| a == b,
624        content,
625    );
626}
627
628/// The body of the animated content composables; `same` says whether two
629/// states show the same content.
630fn animated_content<T, F>(
631    target_state: T,
632    seek: Option<ContentSeek<T>>,
633    transition_spec: &dyn Fn(&T, &T) -> ContentTransform,
634    same: &dyn Fn(&T, &T) -> bool,
635    content: F,
636) where
637    T: Clone + PartialEq + 'static,
638    F: FnMut(T) + 'static,
639{
640    let state = remember(|| {
641        let runtime = with_current_composer(cranpose_core::Composer::runtime_handle);
642        StateHandle(Rc::new(ContentState::<T>::new(runtime)))
643    })
644    .with(StateHandle::clone);
645    *state.0.content.borrow_mut() = Some(Box::new(content));
646    let changed = state
647        .0
648        .sync(&target_state, seek.as_ref(), transition_spec, same);
649    if changed {
650        state.0.drop_gone();
651    }
652    state.0.note_direction();
653    watch(&state.0);
654    // Subscribes this scope to removals of content that left and to content
655    // that completed.
656    state.0.entries_changed.get();
657    // Inside a shared transition layout the container and its contents say
658    // where they are, which costs the layer fast paths; elsewhere they don't.
659    let shared = in_shared_transition();
660    let policy = ContentMeasurePolicy(state.clone());
661    let shown = state.clone();
662    let node = Layout(container_modifier(&state.0, shared), policy, move || {
663        compose_entries(&shown, shared);
664    });
665    state.0.node.set(Some(node));
666    // Content that completed as it composed changes in this pass; content it
667    // replaces at once leaves in a recomposition of this frame.
668    if !changed
669        && state
670            .0
671            .sync(&target_state, seek.as_ref(), transition_spec, same)
672    {
673        let dropped = state.0.drop_gone();
674        if dropped || state.0.lacks_size_node() {
675            cranpose_core::recompose_current_scope_again();
676        }
677        state.0.note_direction();
678        watch(&state.0);
679    }
680}
681
682// The container clips when its size transform asks, and says where it is
683// inside a shared transition layout.
684fn container_modifier<T>(state: &ContentState<T>, shared: bool) -> Modifier {
685    let clip = state
686        .size_transform
687        .get()
688        .is_some_and(|transform| transform.clip);
689    let modifier = if clip {
690        Modifier::empty().clip_to_bounds()
691    } else {
692        Modifier::empty()
693    };
694    if shared {
695        modifier.report_window_coordinates(Rc::clone(&state.coordinates))
696    } else {
697        modifier
698    }
699}
700
701// Composes the content of each entry, keyed by the entry, in the order the
702// entries draw. Each entry is read in a borrow of its own, which ends
703// before its content composes.
704fn compose_entries<T: Clone + PartialEq + 'static>(state: &StateHandle<T>, shared: bool) {
705    for index in 0.. {
706        let entry = state.0.entries.borrow().get(index).map(|entry| {
707            (
708                entry.id,
709                entry.value.clone(),
710                Rc::clone(&entry.motion),
711                entry.content.clone(),
712            )
713        });
714        let Some((id, value, motion, pausable)) = entry else {
715            break;
716        };
717        let state = state.clone();
718        with_key(&id, move || {
719            compose_entry(state, value, &motion, pausable, shared);
720        });
721    }
722}
723
724// Composes the content of one entry in a box that its transition moves.
725fn compose_entry<T: Clone + PartialEq + 'static>(
726    state: StateHandle<T>,
727    value: T,
728    motion: &Rc<EntryMotion>,
729    pausable: Option<PausableContent>,
730    shared: bool,
731) {
732    let layer = Rc::clone(motion);
733    let entry = match &pausable {
734        Some(content) => Modifier::empty().layout_data(ChangedContent(content.clone())),
735        None => Modifier::empty(),
736    };
737    let entry = if shared {
738        entry.report_window_coordinates(Rc::clone(&motion.coordinates))
739    } else {
740        entry
741    };
742    // The layer comes before the size change, so that it bounds the size
743    // that the transition gives and the clip cuts at it.
744    let entry = entry.graphics_layer(move || layer.layer());
745    // The size change measures the content at its full size, and the size
746    // reporter inside it reports that size.
747    let sized = motion.changes_size();
748    motion.sized.set(sized);
749    let entry = if sized {
750        entry.size_change(
751            Rc::clone(motion),
752            crate::layout_direction::layout_direction(),
753        )
754    } else {
755        entry
756    };
757    let entry = entry.report_size(Rc::clone(&motion.size));
758    let shared_entry = shared.then(|| SharedEntry {
759        motion: Rc::clone(motion),
760        entry: Rc::clone(&motion.coordinates),
761        container: Rc::clone(&state.0.coordinates),
762    });
763    Box(entry, BoxSpec::new(), move || {
764        let compose = || {
765            if let Some(content) = state.0.content.borrow_mut().as_mut() {
766                content(value.clone());
767            }
768        };
769        let compose = || match shared_entry.clone() {
770            Some(entry) => ProvideSharedEntry(entry, compose),
771            None => compose(),
772        };
773        match &pausable {
774            Some(content) => with_pausable_content(content, compose),
775            None => compose(),
776        }
777    });
778}
779
780// Whether `measurable` is content a change brought that is not complete.
781fn is_composing(measurable: &dyn Measurable) -> bool {
782    measurable
783        .parent_data()
784        .layout_data::<ChangedContent>()
785        .is_some_and(|content| !content.0.is_complete())
786}
787
788/// Places every content at the top start; the container is as large as the
789/// largest content, or follows the current content's size through a
790/// [`SizeTransform`].
791struct ContentMeasurePolicy<T>(StateHandle<T>);
792
793impl<T> Clone for ContentMeasurePolicy<T> {
794    fn clone(&self) -> Self {
795        Self(self.0.clone())
796    }
797}
798
799impl<T> PartialEq for ContentMeasurePolicy<T> {
800    fn eq(&self, other: &Self) -> bool {
801        self.0 == other.0
802    }
803}
804
805impl<T: Clone + PartialEq + 'static> MeasurePolicy for ContentMeasurePolicy<T> {
806    fn measure(
807        &self,
808        _scope: &dyn MeasureScope,
809        measurables: Measurables<'_>,
810        constraints: Constraints,
811    ) -> MeasureResult {
812        let state = &self.0.0;
813        let loose = Constraints {
814            min_width: 0.0,
815            min_height: 0.0,
816            ..constraints
817        };
818        let mut largest = Size::ZERO;
819        let mut current = Size::ZERO;
820        let mut placements = Vec::with_capacity(measurables.len());
821        for measurable in measurables
822            .iter()
823            .filter(|measurable| !is_composing(*measurable))
824        {
825            let placeable = measurable.measure(loose);
826            let size = Size::new(placeable.width(), placeable.height());
827            largest = Size::new(
828                largest.width.max(size.width),
829                largest.height.max(size.height),
830            );
831            // The current content is the last.
832            current = size;
833            placements.push(Placement::new(placeable.node_id(), 0.0, 0.0, 0.0));
834        }
835        let size = match state.size_transform.get() {
836            Some(transform) => {
837                let mut animated = state.size.borrow_mut();
838                let animated = animated.get_or_insert_with(|| {
839                    Animatable::new(state.frame.get().size, state.runtime.clone())
840                });
841                if animated.target() != current {
842                    animated.animateTo(current, transform.animation);
843                }
844                animated.state().value()
845            }
846            None => {
847                state.size.borrow_mut().take();
848                largest
849            }
850        };
851        let size = Size::new(
852            size.width
853                .clamp(constraints.min_width, constraints.max_width),
854            size.height
855                .clamp(constraints.min_height, constraints.max_height),
856        );
857        state.frame.set(ContainerFrame {
858            size,
859            ..state.frame.get()
860        });
861        MeasureResult::new(size, placements)
862    }
863
864    fn min_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32 {
865        measurables
866            .iter()
867            .filter(|measurable| !is_composing(*measurable))
868            .map(|measurable| measurable.min_intrinsic_width(height))
869            .fold(0.0, f32::max)
870    }
871
872    fn max_intrinsic_width(&self, measurables: Measurables<'_>, height: f32) -> f32 {
873        measurables
874            .iter()
875            .filter(|measurable| !is_composing(*measurable))
876            .map(|measurable| measurable.max_intrinsic_width(height))
877            .fold(0.0, f32::max)
878    }
879
880    fn min_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32 {
881        measurables
882            .iter()
883            .filter(|measurable| !is_composing(*measurable))
884            .map(|measurable| measurable.min_intrinsic_height(width))
885            .fold(0.0, f32::max)
886    }
887
888    fn max_intrinsic_height(&self, measurables: Measurables<'_>, width: f32) -> f32 {
889        measurables
890            .iter()
891            .filter(|measurable| !is_composing(*measurable))
892            .map(|measurable| measurable.max_intrinsic_height(width))
893            .fold(0.0, f32::max)
894    }
895}