1use 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
42const GONE: f32 = 0.001;
44
45#[derive(Clone, Debug, PartialEq)]
51pub struct ContentTransform {
52 pub enter: EnterTransition,
54 pub exit: ExitTransition,
56 pub size_transform: Option<SizeTransform>,
59}
60
61impl ContentTransform {
62 pub fn using(mut self, size_transform: SizeTransform) -> Self {
65 self.size_transform = Some(size_transform);
66 self
67 }
68}
69
70#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct SizeTransform {
74 pub clip: bool,
76 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#[derive(Clone, Debug, PartialEq)]
94pub struct ContentSeek<T> {
95 pub toward: T,
97 pub fraction: f32,
100}
101
102pub(crate) struct EntryMotion {
104 progress: RefCell<Animatable<f32>>,
105 size: Rc<Cell<Size>>,
106 container: Rc<Cell<ContainerFrame>>,
108 effects: RefCell<TransitionEffects>,
109 sized: Cell<bool>,
112 animation: Cell<AnimationType>,
113 pub(crate) leaving: Cell<bool>,
115 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 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 fn changes_size(&self) -> bool {
160 self.effects.borrow().size_change().is_some()
161 }
162
163 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 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 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 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#[derive(Debug, PartialEq)]
232struct ChangedContent(PausableContent);
233
234type ContentFn<T> = Box<dyn FnMut(T)>;
235
236struct ContentState<T> {
237 runtime: RuntimeHandle,
238 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 coordinates: Rc<Cell<WindowCoordinates>>,
247 frame: Rc<Cell<ContainerFrame>>,
250 node: Rc<Cell<Option<NodeId>>>,
251 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 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 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 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 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 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 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 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 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 fn drop_gone(&self) -> bool {
463 let mut entries = self.entries.borrow_mut();
464 let before = entries.len();
465 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 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 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
512fn 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#[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#[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#[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
628fn 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 state.0.entries_changed.get();
657 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 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
682fn 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
701fn 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
724fn 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 let entry = entry.graphics_layer(move || layer.layer());
745 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
780fn 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
788struct 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 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}