1use std::cell::RefCell;
2use std::collections::HashMap;
3use std::hash::Hash;
4use std::iter;
5use std::rc::Rc;
6
7#[allow(unused)]
8use crate::*;
9use pax_engine::api::math::{Transform2, Vector2};
10use pax_engine::api::{Axis, EasingCurve, Numeric, Property, Size};
11use pax_engine::pax_manifest::cartridge_generation::TRANSITION_PHASE_ENTER;
12use pax_engine::*;
13use pax_runtime::api::{borrow, borrow_mut, Layer, NodeContext};
14use pax_runtime::{
15 bind_content_measurement_effect, measured_size_needs_update, resolve_padded_autosize_axis,
16 BaseInstance, Container, ContainerFrame, ContentMeasurementGeometry, ExpandedNode,
17 InstanceFlags, InstanceNode, InstantiationArgs, LayoutHull, ReceivedChildrenSource,
18 RuntimeContext,
19};
20
21const STACKER_REFLOW_FRAMES: u64 = 12;
22const STACKER_REFLOW_CURVE: ContainerReflowCurve = ContainerReflowCurve::OutQuad;
23
24#[pax]
29#[engine_import_path("pax_engine")]
30#[primitive("pax_std::layout::stacker::StackerInstance")]
31#[custom(Default)]
32pub struct Stacker {
33 pub direction: Property<StackerDirection>,
35
36 pub gutter: Property<Size>,
38
39 pub autosize: Property<bool>,
51 pub autosize_x: Property<Option<bool>>,
53 pub autosize_y: Property<Option<bool>>,
55
56 pub sizes: Property<Vec<Option<Size>>>,
59
60 pub exit_mode: Property<ContainerExitMode>,
62 pub reflow_transition: Property<ContainerReflowTransition>,
67}
68
69impl Default for Stacker {
70 fn default() -> Self {
71 Self {
72 direction: Property::new(StackerDirection::Vertical),
73 gutter: Property::new(Size::Pixels(Numeric::I32(0))),
74 autosize: Property::new(false),
75 autosize_x: Property::new(None),
76 autosize_y: Property::new(None),
77 sizes: Property::new(vec![]),
78 exit_mode: Property::new(ContainerExitMode::Flow),
79 reflow_transition: Property::new(ContainerReflowTransition::default()),
80 }
81 }
82}
83
84pub struct StackerInstance {
85 base: BaseInstance,
86}
87
88impl InstanceNode for StackerInstance {
89 fn instantiate(args: InstantiationArgs) -> Rc<Self>
90 where
91 Self: Sized,
92 {
93 Rc::new(Self {
94 base: BaseInstance::new(
95 args,
96 InstanceFlags {
97 invisible_to_slot: false,
98 invisible_to_raycasting: true,
99 layer: Layer::DontCare,
100 is_component: false,
101 is_slot: false,
102 },
103 ),
104 })
105 }
106
107 fn resolve_debug(
108 &self,
109 f: &mut std::fmt::Formatter,
110 _expanded_node: Option<&ExpandedNode>,
111 ) -> std::fmt::Result {
112 f.debug_struct("Stacker").finish()
113 }
114
115 fn base(&self) -> &BaseInstance {
116 &self.base
117 }
118
119 fn received_children_source(&self) -> ReceivedChildrenSource {
120 ReceivedChildrenSource::Projected
121 }
122
123 fn handle_setup_projected_children(
124 self: Rc<Self>,
125 expanded_node: &Rc<ExpandedNode>,
126 context: &Rc<RuntimeContext>,
127 ) {
128 if let Some(containing_component) = expanded_node.containing_component.upgrade() {
129 let env = Rc::clone(&expanded_node.stack);
130 let children = borrow!(self.base().get_instance_children());
131 let children_with_env = children.iter().cloned().zip(iter::repeat(env));
132 let new_projected_children = containing_component.create_children_detached(
133 children_with_env,
134 context,
135 &Rc::downgrade(expanded_node),
136 );
137 *borrow_mut!(expanded_node.expanded_projected_children) = Some(new_projected_children);
138 }
139 }
140
141 fn handle_mount(
142 self: Rc<Self>,
143 expanded_node: &Rc<ExpandedNode>,
144 context: &Rc<RuntimeContext>,
145 ) {
146 let weak_ref_self = Rc::downgrade(expanded_node);
147 let cloned_context = Rc::clone(context);
148 let parent_frame = expanded_node.parent_frame.clone();
149 let projected_children = expanded_node
150 .expanded_and_flattened_projected_children
151 .clone();
152 let deps = [projected_children.untyped()];
153 expanded_node
154 .children
155 .replace_with(Property::computed_with_name(
156 move || {
157 let Some(node) = weak_ref_self.upgrade() else {
158 panic!("ran evaluator after expanded node dropped (stacker children)")
159 };
160 node.attach_children(projected_children.get(), &cloned_context, &parent_frame)
161 },
162 &deps,
163 &format!("stacker_children (node id: {})", expanded_node.id.0),
164 ));
165 let _ = expanded_node.children.get();
166
167 expanded_node.with_properties_unwrapped(|properties: &mut Stacker| {
168 properties.bind_container(&expanded_node.get_node_context(context));
169 });
170 }
171
172 fn requires_non_reactive_update(&self, _expanded_node: &ExpandedNode) -> bool {
173 true
174 }
175
176 fn update(self: Rc<Self>, expanded_node: &Rc<ExpandedNode>, _context: &Rc<RuntimeContext>) {
177 expanded_node.compute_flattened_projected_children();
178 }
179}
180
181impl Container for Stacker {
182 fn bind_container(&self, ctx: &NodeContext) {
184 let sizes = self.sizes.clone();
185 let bound = ctx.bounds_self.clone();
186 let gutter = self.gutter.clone();
187 let direction = self.direction.clone();
188 let (padding_x, padding_y) = ctx
189 .expanded_node
190 .upgrade()
191 .map(|node| {
192 let common_props = node.get_common_properties();
193 let common_props = borrow!(common_props);
194 (
195 common_props.padding_x.clone(),
196 common_props.padding_y.clone(),
197 )
198 })
199 .unwrap_or_default();
200 let autosize = self.autosize.clone();
201 let autosize_x = self.autosize_x.clone();
202 let autosize_y = self.autosize_y.clone();
203 let exit_mode = self.exit_mode.clone();
204 let reflow_transition = self.reflow_transition.clone();
205 let bound_for_update = bound.clone();
206 let autosize_for_update = autosize.clone();
207 let autosize_x_for_update = autosize_x.clone();
208 let autosize_y_for_update = autosize_y.clone();
209 let received_children_for_update = ctx.received_children.clone();
210 let retained_received_children_for_update = ctx.retained_received_children.clone();
211 let direction_for_update = direction.clone();
212 let padding_x_for_update = padding_x.clone();
213 let padding_y_for_update = padding_y.clone();
214 let sizes_for_update = sizes.clone();
215 let gutter_for_update = gutter.clone();
216 let exit_mode_for_update = exit_mode.clone();
217 let reflow_transition_for_update = reflow_transition.clone();
218 let expanded_node = ctx.expanded_node.clone();
219 let prior_frames = Rc::new(RefCell::new(HashMap::new()));
220 let last_named_transition_warning = Rc::new(RefCell::new(None::<String>));
221 let update_layout = Rc::new(move || {
222 let received_children = received_children_for_update.get();
223 let retained_received_children = retained_received_children_for_update.get();
224 let outer_bounds = bound_for_update.get();
225 let direction = direction_for_update.get();
226 let padding_x_size = padding_x_for_update.get();
227 let padding_y_size = padding_y_for_update.get();
228 let padding_x = padding_x_size
229 .map(|padding| padding.evaluate(outer_bounds, Axis::X).max(0.0))
230 .unwrap_or(0.0);
231 let padding_y = padding_y_size
232 .map(|padding| padding.evaluate(outer_bounds, Axis::Y).max(0.0))
233 .unwrap_or(0.0);
234 let bounds = (
235 (outer_bounds.0 - (2.0 * padding_x)).max(0.0),
236 (outer_bounds.1 - (2.0 * padding_y)).max(0.0),
237 );
238 let gutter = gutter_for_update.get();
239 let sizes = sizes_for_update.get();
240 let autosize = autosize_for_update.get();
241 let autosize_x = autosize_x_for_update.get();
242 let autosize_y = autosize_y_for_update.get();
243 let exit_mode = exit_mode_for_update.get();
244 let reflow_transition = reflow_transition_for_update.get();
245 let reflow_kind = reflow_transition.kind.get();
246 if matches!(reflow_kind, ContainerReflowTransitionKind::Named) {
247 let name = reflow_transition.name.get();
248 if last_named_transition_warning.borrow().as_ref() != Some(&name) {
249 log::warn!(
250 "named stacker reflow transition '{}' is not implemented yet; falling back to snap",
251 name
252 );
253 *last_named_transition_warning.borrow_mut() = Some(name);
254 }
255 }
256
257 for breakout_child in received_children
258 .iter()
259 .chain(retained_received_children.iter())
260 .filter(|child| child.is_layout_breakout())
261 {
262 breakout_child.container_frame.set_if_neq(None);
263 }
264
265 let active_children: Vec<_> = received_children
266 .into_iter()
267 .filter(|child| !child.is_layout_breakout())
268 .collect();
269 let retained_children: Vec<_> = retained_received_children
270 .into_iter()
271 .filter(|child| !child.is_layout_breakout())
272 .collect();
273 let mut children: Vec<_> =
274 Vec::with_capacity(active_children.len() + retained_children.len());
275 children.extend(active_children.iter().cloned());
276 children.extend(retained_children.iter().cloned());
277
278 let Some(node) = expanded_node.upgrade() else {
279 return;
280 };
281 let common_props = node.get_common_properties();
282 let common_props = borrow!(common_props);
283 let width_explicit = common_props.width.get().is_some();
284 let height_explicit = common_props.height.get().is_some();
285 drop(common_props);
286
287 let active_measurements = active_children
288 .iter()
289 .map(|child| measure_child_bounds(&node, child))
290 .collect::<Vec<_>>();
291 let active_layout = compute_stacker_layout(
292 direction.clone(),
293 bounds,
294 gutter,
295 sizes.clone(),
296 autosize,
297 autosize_x,
298 autosize_y,
299 &active_measurements,
300 active_children.len(),
301 width_explicit,
302 height_explicit,
303 );
304
305 let mut snapshots: Vec<_> = active_children
306 .iter()
307 .map(|child| StackerChildSnapshot {
308 id: child.id,
309 exiting: false,
310 entering: child_enter_transition_active(child),
311 })
312 .collect();
313 snapshots.extend(retained_children.iter().map(|child| StackerChildSnapshot {
314 id: child.id,
315 exiting: true,
316 entering: false,
317 }));
318 let current_frames: HashMap<_, _> = children
319 .iter()
320 .filter_map(|child| child.container_frame.get().map(|frame| (child.id, frame)))
321 .collect();
322 let prior_frames_map = prior_frames.borrow().clone();
323 let flow_children =
324 flow_ordered_children(&snapshots, &prior_frames_map, ¤t_frames, &direction);
325 let flow_measurements = flow_children
326 .iter()
327 .filter_map(|snapshot| {
328 children
329 .iter()
330 .find(|child| child.id == snapshot.id)
331 .map(|child| measure_child_bounds(&node, child))
332 })
333 .collect::<Vec<_>>();
334 let flow_layout = compute_stacker_layout(
335 direction.clone(),
336 bounds,
337 gutter,
338 sizes.clone(),
339 autosize,
340 autosize_x,
341 autosize_y,
342 &flow_measurements,
343 flow_children.len(),
344 width_explicit,
345 height_explicit,
346 );
347
348 let plan = plan_stacker_layout_from_specs(
349 &snapshots,
350 &prior_frames_map,
351 ¤t_frames,
352 exit_mode,
353 reflow_kind,
354 &active_layout.cell_specs,
355 &flow_layout.cell_specs,
356 bounds,
357 direction,
358 gutter,
359 );
360
361 let mut next_frames = HashMap::new();
362 for child in &children {
363 let Some(placement) = plan
364 .placements
365 .iter()
366 .find(|placement| placement.id == child.id)
367 else {
368 child.container_frame.set_if_neq(None);
369 continue;
370 };
371
372 if placement.animate {
373 let frames = reflow_transition.frames.get();
374 if child.container_frame.get().is_none() {
375 if let Some(seed_frame) = placement.seed_frame {
376 child.container_frame.set_if_neq(Some(seed_frame));
377 }
378 }
379 child.container_frame.ease_to(
380 Some(placement.frame),
381 frames,
382 reflow_transition.curve.get().to_easing_curve(),
383 );
384 } else {
385 child.container_frame.set_if_neq(Some(placement.frame));
386 }
387
388 next_frames.insert(child.id, placement.frame);
389 }
390 *prior_frames.borrow_mut() = next_frames;
391
392 match expand_measured_size_for_padding(
393 active_layout.measured_size,
394 padding_x_size,
395 padding_y_size,
396 ) {
397 Some(measured_size) => {
398 if measured_size_needs_update(node.measured_size.get(), measured_size) {
399 node.set_measured_size(measured_size.0, measured_size.1);
400 }
401 }
402 None => {
403 if node.measured_size.get().is_some() {
404 node.measured_size.set(None);
405 }
406 }
407 }
408 });
409
410 update_layout();
411 let deps = [
412 bound.untyped(),
413 direction.untyped(),
414 padding_x.untyped(),
415 padding_y.untyped(),
416 sizes.untyped(),
417 gutter.untyped(),
418 autosize.untyped(),
419 autosize_x.untyped(),
420 autosize_y.untyped(),
421 exit_mode.untyped(),
422 reflow_transition.untyped(),
423 ctx.retained_received_children.untyped(),
424 ctx.retained_received_children_changed.untyped(),
425 ];
426 let Some(node) = ctx.expanded_node.upgrade() else {
427 return;
428 };
429 let update_layout_callback = Rc::clone(&update_layout);
430 bind_content_measurement_effect(
431 &node,
432 ctx,
433 "stacker layout",
434 ContentMeasurementGeometry::Intrinsic,
435 &deps,
436 move |_node, _ctx| {
437 update_layout_callback();
438 },
439 );
440 }
441}
442
443#[pax]
444#[engine_import_path("pax_engine")]
445pub enum ContainerExitMode {
447 #[default]
449 Flow,
450 Ghost,
453}
454
455#[pax]
456#[engine_import_path("pax_engine")]
457pub enum ContainerReflowTransitionKind {
459 #[default]
461 Snap,
462 Ease,
464 Named,
466}
467
468#[pax]
469#[engine_import_path("pax_engine")]
470pub enum ContainerReflowCurve {
472 #[default]
473 Linear,
474 Hold,
475 InQuad,
476 OutQuad,
477 InOutQuad,
478 InBack,
479 OutBack,
480 InOutBack,
481}
482
483impl ContainerReflowCurve {
484 fn to_easing_curve(self) -> EasingCurve {
485 match self {
486 Self::Linear => EasingCurve::Linear,
487 Self::Hold => EasingCurve::Hold,
488 Self::InQuad => EasingCurve::InQuad,
489 Self::OutQuad => EasingCurve::OutQuad,
490 Self::InOutQuad => EasingCurve::InOutQuad,
491 Self::InBack => EasingCurve::InBack,
492 Self::OutBack => EasingCurve::OutBack,
493 Self::InOutBack => EasingCurve::InOutBack,
494 }
495 }
496}
497
498#[pax]
499#[engine_import_path("pax_engine")]
500#[custom(Default)]
501pub struct ContainerReflowTransition {
503 pub kind: Property<ContainerReflowTransitionKind>,
505 pub frames: Property<u64>,
507 pub curve: Property<ContainerReflowCurve>,
509 pub name: Property<String>,
511}
512
513impl Default for ContainerReflowTransition {
514 fn default() -> Self {
515 Self {
516 kind: Property::new(ContainerReflowTransitionKind::Snap),
517 frames: Property::new(STACKER_REFLOW_FRAMES),
518 curve: Property::new(STACKER_REFLOW_CURVE),
519 name: Property::new(String::new()),
520 }
521 }
522}
523
524#[derive(Clone, Copy, Debug, PartialEq, Eq)]
525struct StackerChildSnapshot<Id> {
526 id: Id,
527 exiting: bool,
528 entering: bool,
529}
530
531#[derive(Clone, Copy, Debug, PartialEq)]
532struct StackerChildPlacement<Id> {
533 id: Id,
534 seed_frame: Option<ContainerFrame>,
535 frame: ContainerFrame,
536 animate: bool,
537}
538
539#[derive(Clone, Debug)]
540struct StackerLayoutPlan<Id> {
541 placements: Vec<StackerChildPlacement<Id>>,
542}
543
544#[cfg(test)]
545fn plan_stacker_layout<Id: Copy + Eq + Hash>(
546 children: &[StackerChildSnapshot<Id>],
547 prior_frames: &HashMap<Id, ContainerFrame>,
548 current_frames: &HashMap<Id, ContainerFrame>,
549 exit_mode: ContainerExitMode,
550 reflow_kind: ContainerReflowTransitionKind,
551 bounds: (f64, f64),
552 direction: StackerDirection,
553 gutter: Size,
554 sizes: Vec<Option<Size>>,
555) -> StackerLayoutPlan<Id> {
556 let active_children: Vec<_> = children
557 .iter()
558 .copied()
559 .filter(|child| !child.exiting)
560 .collect();
561 let active_cell_specs = compute_cell_specs(
562 active_children.len(),
563 bounds,
564 direction.clone(),
565 gutter,
566 sizes.clone(),
567 );
568 let flow_children: Vec<_> = match exit_mode {
569 ContainerExitMode::Flow => {
570 flow_ordered_children(children, prior_frames, current_frames, &direction)
571 }
572 ContainerExitMode::Ghost => active_children.clone(),
573 };
574 let flow_cell_specs = compute_cell_specs(
575 flow_children.len(),
576 bounds,
577 direction.clone(),
578 gutter,
579 sizes,
580 );
581 plan_stacker_layout_from_specs(
582 children,
583 prior_frames,
584 current_frames,
585 exit_mode,
586 reflow_kind,
587 &active_cell_specs,
588 &flow_cell_specs,
589 bounds,
590 direction,
591 gutter,
592 )
593}
594
595fn plan_stacker_layout_from_specs<Id: Copy + Eq + Hash>(
596 children: &[StackerChildSnapshot<Id>],
597 prior_frames: &HashMap<Id, ContainerFrame>,
598 current_frames: &HashMap<Id, ContainerFrame>,
599 exit_mode: ContainerExitMode,
600 reflow_kind: ContainerReflowTransitionKind,
601 active_cell_specs: &[StackerCell],
602 flow_cell_specs: &[StackerCell],
603 bounds: (f64, f64),
604 direction: StackerDirection,
605 gutter: Size,
606) -> StackerLayoutPlan<Id> {
607 let active_children: Vec<_> = children
608 .iter()
609 .copied()
610 .filter(|child| !child.exiting)
611 .collect();
612 let active_frames: HashMap<_, _> = active_children
613 .iter()
614 .zip(active_cell_specs.iter())
615 .map(|(child, cell)| (child.id, container_frame_for_cell(cell)))
616 .collect();
617
618 let flow_children: Vec<_> = match exit_mode {
619 ContainerExitMode::Flow => {
620 flow_ordered_children(children, prior_frames, current_frames, &direction)
621 }
622 ContainerExitMode::Ghost => active_children.clone(),
623 };
624 let flow_frames: HashMap<_, _> = flow_children
625 .iter()
626 .zip(flow_cell_specs.iter())
627 .map(|(child, cell)| (child.id, container_frame_for_cell(cell)))
628 .collect();
629 let virtual_entering_frames = match exit_mode {
630 ContainerExitMode::Flow => virtualize_flow_entering_children(
631 children,
632 &active_frames,
633 &flow_frames,
634 bounds,
635 &direction,
636 gutter,
637 ),
638 ContainerExitMode::Ghost => HashMap::new(),
639 };
640
641 let placements = children
642 .iter()
643 .filter_map(|child| {
644 let (seed_frame, frame) = match exit_mode {
645 ContainerExitMode::Flow
646 if child.exiting
647 && matches!(reflow_kind, ContainerReflowTransitionKind::Ease) =>
648 {
649 (
650 None,
651 prior_frames
652 .get(&child.id)
653 .copied()
654 .or_else(|| current_frames.get(&child.id).copied())?,
655 )
656 }
657 ContainerExitMode::Flow if child.exiting => {
658 (None, flow_frames.get(&child.id).copied()?)
659 }
660 ContainerExitMode::Flow
661 if matches!(reflow_kind, ContainerReflowTransitionKind::Ease) =>
662 {
663 (
664 child
665 .entering
666 .then(|| virtual_entering_frames.get(&child.id).copied())
667 .flatten(),
668 active_frames.get(&child.id).copied()?,
669 )
670 }
671 ContainerExitMode::Flow if child.entering => (
672 None,
673 virtual_entering_frames
674 .get(&child.id)
675 .copied()
676 .or_else(|| active_frames.get(&child.id).copied())?,
677 ),
678 ContainerExitMode::Flow => (None, flow_frames.get(&child.id).copied()?),
679 ContainerExitMode::Ghost if child.exiting => (
680 None,
681 prior_frames
682 .get(&child.id)
683 .copied()
684 .or_else(|| current_frames.get(&child.id).copied())?,
685 ),
686 ContainerExitMode::Ghost => (None, active_frames.get(&child.id).copied()?),
687 };
688
689 let animate = matches!(reflow_kind, ContainerReflowTransitionKind::Ease)
690 && !child.exiting
691 && seed_frame
692 .or_else(|| current_frames.get(&child.id).copied())
693 .or_else(|| prior_frames.get(&child.id).copied())
694 .map(|current| current != frame)
695 .unwrap_or(false);
696
697 Some(StackerChildPlacement {
698 id: child.id,
699 seed_frame,
700 frame,
701 animate,
702 })
703 })
704 .collect();
705
706 StackerLayoutPlan { placements }
707}
708
709fn child_enter_transition_active(child: &Rc<ExpandedNode>) -> bool {
710 let transition_config = borrow!(child.instance_node)
711 .base()
712 .transition_config()
713 .clone();
714 enter_transition_active(
715 child.transition_phase.get(),
716 child.transition_playhead.get(),
717 child.transition_playhead_millis.get(),
718 transition_config.enter_frame_count,
719 transition_config.enter_millis_count,
720 )
721}
722
723fn enter_transition_active(
724 phase: u64,
725 playhead: f64,
726 playhead_millis: f64,
727 enter_frame_count: u64,
728 enter_millis_count: Option<u64>,
729) -> bool {
730 if phase != TRANSITION_PHASE_ENTER {
731 return false;
732 }
733 match enter_millis_count {
734 Some(millis) => playhead_millis < millis as f64,
735 None => playhead < enter_frame_count as f64,
736 }
737}
738
739fn virtualize_flow_entering_children<Id: Copy + Eq + Hash>(
740 children: &[StackerChildSnapshot<Id>],
741 active_frames: &HashMap<Id, ContainerFrame>,
742 flow_frames: &HashMap<Id, ContainerFrame>,
743 bounds: (f64, f64),
744 direction: &StackerDirection,
745 gutter: Size,
746) -> HashMap<Id, ContainerFrame> {
747 if flow_frames.is_empty() {
752 return HashMap::new();
753 }
754
755 let active_bound = match direction {
756 StackerDirection::Horizontal => bounds.0,
757 StackerDirection::Vertical => bounds.1,
758 };
759 let gutter_px = resolve_size_px(gutter, active_bound);
760 let mut next_main_axis = flow_frames
761 .values()
762 .copied()
763 .map(|frame| frame_main_axis_end(frame, direction))
764 .fold(f64::NEG_INFINITY, f64::max);
765
766 let mut virtual_frames = HashMap::new();
767 for child in children
768 .iter()
769 .copied()
770 .filter(|child| child.entering && !child.exiting)
771 {
772 let Some(target_frame) = active_frames.get(&child.id).copied() else {
773 continue;
774 };
775 let frame =
776 with_frame_main_axis_position(target_frame, direction, next_main_axis + gutter_px);
777 next_main_axis = frame_main_axis_end(frame, direction);
778 virtual_frames.insert(child.id, frame);
779 }
780
781 virtual_frames
782}
783
784fn flow_ordered_children<Id: Copy + Eq + Hash>(
785 children: &[StackerChildSnapshot<Id>],
786 prior_frames: &HashMap<Id, ContainerFrame>,
787 current_frames: &HashMap<Id, ContainerFrame>,
788 direction: &StackerDirection,
789) -> Vec<StackerChildSnapshot<Id>> {
790 let mut active = Vec::new();
791 let mut exiting = Vec::new();
792 for child in children.iter().copied() {
793 if child.exiting {
794 exiting.push(child);
795 } else if child.entering {
796 continue;
797 } else {
798 active.push(child);
799 }
800 }
801
802 if exiting.is_empty() {
803 return active;
804 }
805
806 exiting.sort_by(|a, b| {
807 frame_main_axis_position_for_child(a.id, prior_frames, current_frames, direction)
808 .partial_cmp(&frame_main_axis_position_for_child(
809 b.id,
810 prior_frames,
811 current_frames,
812 direction,
813 ))
814 .unwrap_or(std::cmp::Ordering::Equal)
815 });
816
817 let mut merged = active;
818 for exiting_child in exiting {
819 let exiting_pos = frame_main_axis_position_for_child(
820 exiting_child.id,
821 prior_frames,
822 current_frames,
823 direction,
824 );
825 let insert_at = merged
826 .iter()
827 .position(|active_child| {
828 frame_main_axis_position_for_child(
829 active_child.id,
830 prior_frames,
831 current_frames,
832 direction,
833 ) > exiting_pos
834 })
835 .unwrap_or(merged.len());
836 merged.insert(insert_at, exiting_child);
837 }
838
839 merged
840}
841
842fn frame_main_axis_position_for_child<Id: Copy + Eq + Hash>(
843 id: Id,
844 prior_frames: &HashMap<Id, ContainerFrame>,
845 current_frames: &HashMap<Id, ContainerFrame>,
846 direction: &StackerDirection,
847) -> f64 {
848 prior_frames
849 .get(&id)
850 .copied()
851 .or_else(|| current_frames.get(&id).copied())
852 .map(|frame| frame_main_axis_position(frame, direction))
853 .unwrap_or(f64::INFINITY)
854}
855
856fn frame_main_axis_position(frame: ContainerFrame, direction: &StackerDirection) -> f64 {
857 match direction {
858 StackerDirection::Horizontal => frame.transform.m[4],
859 StackerDirection::Vertical => frame.transform.m[5],
860 }
861}
862
863fn frame_main_axis_end(frame: ContainerFrame, direction: &StackerDirection) -> f64 {
864 frame_main_axis_position(frame, direction)
865 + match direction {
866 StackerDirection::Horizontal => frame.bounds.0,
867 StackerDirection::Vertical => frame.bounds.1,
868 }
869}
870
871fn with_frame_main_axis_position(
872 frame: ContainerFrame,
873 direction: &StackerDirection,
874 main_axis_position: f64,
875) -> ContainerFrame {
876 let translated = match direction {
877 StackerDirection::Horizontal => {
878 Transform2::translate(Vector2::new(main_axis_position, frame.transform.m[5]))
879 }
880 StackerDirection::Vertical => {
881 Transform2::translate(Vector2::new(frame.transform.m[4], main_axis_position))
882 }
883 };
884 ContainerFrame {
885 transform: translated,
886 bounds: frame.bounds,
887 }
888}
889
890#[cfg(test)]
891fn compute_cell_specs(
892 cells: usize,
893 bounds: (f64, f64),
894 direction: StackerDirection,
895 gutter: Size,
896 mut sizes: Vec<Option<Size>>,
897) -> Vec<StackerCell> {
898 if cells == 0 {
899 return Vec::new();
900 }
901
902 let active_bound = match direction {
903 StackerDirection::Horizontal => bounds.0,
904 StackerDirection::Vertical => bounds.1,
905 };
906 let gutter_px = resolve_size_px(gutter, active_bound);
907 let usable_interior_space = active_bound - (cells.saturating_sub(1) as f64) * gutter_px;
908 let per_cell_space = usable_interior_space / cells as f64;
909
910 let mut cell_space = vec![per_cell_space; cells];
911 while sizes.len() < cell_space.len() {
912 sizes.push(None);
913 }
914
915 if !sizes.is_empty() {
916 let mut used_space = 0.0;
917 let mut remaining_cells = 0_usize;
918 for (i, size) in sizes.iter().take(cells).enumerate() {
919 if let Some(size) = size {
920 let space = resolve_size_px(*size, active_bound);
921 used_space += space;
922 cell_space[i] = space;
923 } else {
924 cell_space[i] = -1.0;
925 remaining_cells += 1;
926 }
927 }
928
929 if remaining_cells > 0 {
930 let remaining_per_cell_space =
931 ((usable_interior_space - used_space) / remaining_cells as f64).max(5.0);
932 for space in &mut cell_space {
933 if *space == -1.0 {
934 *space = remaining_per_cell_space;
935 }
936 }
937 }
938 }
939
940 let mut used_space = 0.0;
941 (0..cells)
942 .map(|i| {
943 let cell = match direction {
944 StackerDirection::Horizontal => StackerCell {
945 height_px: bounds.1,
946 width_px: cell_space[i],
947 x_px: i as f64 * gutter_px + used_space,
948 y_px: 0.0,
949 },
950 StackerDirection::Vertical => StackerCell {
951 height_px: cell_space[i],
952 width_px: bounds.0,
953 x_px: 0.0,
954 y_px: i as f64 * gutter_px + used_space,
955 },
956 };
957 used_space += cell_space[i];
958 cell
959 })
960 .collect()
961}
962
963fn resolve_size_px(size: Size, active_bound: f64) -> f64 {
964 match size {
965 Size::Pixels(pix) => pix.to_float(),
966 Size::Percent(per) => (Numeric::F64(active_bound) * (per / Numeric::F64(100.0))).to_float(),
967 Size::Combined(pix, per) => {
968 (pix + (Numeric::F64(active_bound) * (per / Numeric::F64(100.0)))).to_float()
969 }
970 }
971}
972
973fn container_frame_for_cell(cell: &StackerCell) -> ContainerFrame {
974 ContainerFrame {
975 transform: Transform2::translate(Vector2::new(cell.x_px, cell.y_px)),
976 bounds: (cell.width_px, cell.height_px),
977 }
978}
979
980#[derive(Clone, Copy, Debug, Default, PartialEq)]
981struct ChildMeasurement {
982 width: Option<f64>,
983 height: Option<f64>,
984}
985
986impl ChildMeasurement {
987 fn axis(&self, axis: Axis) -> Option<f64> {
988 match axis {
989 Axis::X => self.width,
990 Axis::Y => self.height,
991 }
992 }
993}
994
995struct StackerLayoutResult {
996 cell_specs: Vec<StackerCell>,
997 measured_size: Option<(f64, f64)>,
998}
999
1000fn expand_measured_size_for_padding(
1001 measured_size: Option<(f64, f64)>,
1002 padding_x: Option<Size>,
1003 padding_y: Option<Size>,
1004) -> Option<(f64, f64)> {
1005 let (width, height) = measured_size?;
1006 Some((
1007 resolve_padded_autosize_axis(width, padding_x)?,
1008 resolve_padded_autosize_axis(height, padding_y)?,
1009 ))
1010}
1011
1012fn compute_stacker_layout(
1013 direction: StackerDirection,
1014 bounds: (f64, f64),
1015 gutter: Size,
1016 sizes: Vec<Option<Size>>,
1017 autosize: bool,
1018 autosize_x: Option<bool>,
1019 autosize_y: Option<bool>,
1020 child_measurements: &[ChildMeasurement],
1021 slot_children_count: usize,
1022 width_explicit: bool,
1023 height_explicit: bool,
1024) -> StackerLayoutResult {
1025 let standard_cell_specs =
1026 compute_standard_cell_specs(&direction, bounds, gutter, &sizes, slot_children_count);
1027
1028 if !autosize {
1029 return StackerLayoutResult {
1030 cell_specs: standard_cell_specs,
1031 measured_size: None,
1032 };
1033 }
1034
1035 let (manage_x, manage_y) =
1036 resolve_stacker_autosize_axes(&direction, autosize, autosize_x, autosize_y);
1037 let (main_axis, cross_axis, autosize_main_axis, autosize_cross_axis) = match &direction {
1038 StackerDirection::Horizontal => (
1039 Axis::X,
1040 Axis::Y,
1041 manage_x && !width_explicit,
1042 manage_y && !height_explicit,
1043 ),
1044 StackerDirection::Vertical => (
1045 Axis::Y,
1046 Axis::X,
1047 manage_y && !height_explicit,
1048 manage_x && !width_explicit,
1049 ),
1050 };
1051
1052 let main_bound = axis_value(bounds, main_axis);
1053 let cross_bound = axis_value(bounds, cross_axis);
1054
1055 if autosize_main_axis && size_depends_on_parent(gutter) {
1056 return StackerLayoutResult {
1057 cell_specs: standard_cell_specs,
1058 measured_size: None,
1059 };
1060 }
1061
1062 let gutter_px = gutter.get_pixels(main_bound);
1063
1064 let mut main_sizes = Vec::with_capacity(slot_children_count);
1065 let mut cross_sizes = Vec::with_capacity(slot_children_count);
1066
1067 for index in 0..slot_children_count {
1068 let explicit_main = sizes
1069 .get(index)
1070 .copied()
1071 .flatten()
1072 .map(|size| {
1073 if autosize_main_axis && size_depends_on_parent(size) {
1074 None
1075 } else {
1076 Some(size.get_pixels(main_bound))
1077 }
1078 })
1079 .flatten();
1080
1081 let main_size = if let Some(explicit_main) = explicit_main {
1082 explicit_main
1083 } else if autosize_main_axis {
1084 let Some(measured_main) = child_measurements
1085 .get(index)
1086 .and_then(|measurement| measurement.axis(main_axis))
1087 else {
1088 return StackerLayoutResult {
1089 cell_specs: standard_cell_specs,
1090 measured_size: None,
1091 };
1092 };
1093 measured_main
1094 } else {
1095 match direction {
1096 StackerDirection::Horizontal => standard_cell_specs[index].width_px,
1097 StackerDirection::Vertical => standard_cell_specs[index].height_px,
1098 }
1099 };
1100
1101 let cross_size = if autosize_cross_axis {
1102 let Some(measured_cross) = child_measurements
1103 .get(index)
1104 .and_then(|measurement| measurement.axis(cross_axis))
1105 else {
1106 return StackerLayoutResult {
1107 cell_specs: standard_cell_specs,
1108 measured_size: None,
1109 };
1110 };
1111 measured_cross
1112 } else {
1113 cross_bound
1114 };
1115
1116 if !autosize_cross_axis && !cross_bound.is_finite() {
1117 return StackerLayoutResult {
1118 cell_specs: standard_cell_specs,
1119 measured_size: None,
1120 };
1121 }
1122
1123 main_sizes.push(main_size);
1124 cross_sizes.push(cross_size);
1125 }
1126
1127 let content_main = if slot_children_count == 0 {
1128 0.0
1129 } else {
1130 main_sizes.iter().sum::<f64>() + gutter_px * (slot_children_count.saturating_sub(1) as f64)
1131 };
1132 let content_cross = cross_sizes.iter().copied().fold(0.0, f64::max);
1133
1134 let mut cursor = 0.0;
1135 let cell_specs = (0..slot_children_count)
1136 .map(|index| {
1137 let main_size = main_sizes[index];
1138 let cross_size = cross_sizes[index];
1139 let cell = match &direction {
1140 StackerDirection::Horizontal => StackerCell {
1141 width_px: main_size,
1142 height_px: cross_size,
1143 x_px: cursor,
1144 y_px: 0.0,
1145 },
1146 StackerDirection::Vertical => StackerCell {
1147 width_px: cross_size,
1148 height_px: main_size,
1149 x_px: 0.0,
1150 y_px: cursor,
1151 },
1152 };
1153 cursor += main_size + gutter_px;
1154 cell
1155 })
1156 .collect();
1157
1158 let measured_size = if autosize_main_axis || autosize_cross_axis {
1159 Some(match &direction {
1160 StackerDirection::Horizontal => (
1161 if autosize_main_axis {
1162 content_main
1163 } else {
1164 bounds.0
1165 },
1166 if autosize_cross_axis {
1167 content_cross
1168 } else {
1169 bounds.1
1170 },
1171 ),
1172 StackerDirection::Vertical => (
1173 if autosize_cross_axis {
1174 content_cross
1175 } else {
1176 bounds.0
1177 },
1178 if autosize_main_axis {
1179 content_main
1180 } else {
1181 bounds.1
1182 },
1183 ),
1184 })
1185 } else {
1186 None
1187 };
1188
1189 StackerLayoutResult {
1190 cell_specs,
1191 measured_size,
1192 }
1193}
1194
1195fn resolve_axis_autosize(
1196 autosize: bool,
1197 axis_override: Option<bool>,
1198 default_when_enabled: bool,
1199) -> bool {
1200 axis_override.unwrap_or(autosize && default_when_enabled)
1201}
1202
1203fn resolve_stacker_autosize_axes(
1204 direction: &StackerDirection,
1205 autosize: bool,
1206 autosize_x: Option<bool>,
1207 autosize_y: Option<bool>,
1208) -> (bool, bool) {
1209 let (default_x, default_y) = match direction {
1210 StackerDirection::Horizontal => (true, false),
1211 StackerDirection::Vertical => (false, true),
1212 };
1213 (
1214 resolve_axis_autosize(autosize, autosize_x, default_x),
1215 resolve_axis_autosize(autosize, autosize_y, default_y),
1216 )
1217}
1218
1219fn compute_standard_cell_specs(
1220 direction: &StackerDirection,
1221 bounds: (f64, f64),
1222 gutter: Size,
1223 sizes: &[Option<Size>],
1224 slot_children_count: usize,
1225) -> Vec<StackerCell> {
1226 if slot_children_count == 0 {
1227 return vec![];
1228 }
1229
1230 let active_bound = axis_value(
1231 bounds,
1232 match direction {
1233 StackerDirection::Horizontal => Axis::X,
1234 StackerDirection::Vertical => Axis::Y,
1235 },
1236 );
1237 let gutter_px = gutter.get_pixels(active_bound);
1238 let usable_interior_space =
1239 active_bound - gutter_px * (slot_children_count.saturating_sub(1) as f64);
1240 let mut cell_space =
1241 vec![usable_interior_space / slot_children_count as f64; slot_children_count];
1242
1243 let mut used_space = 0.0;
1244 let mut remaining_indices = Vec::new();
1245 for (index, size) in sizes.iter().take(slot_children_count).enumerate() {
1246 if let Some(size) = size {
1247 let space = size.get_pixels(active_bound);
1248 used_space += space;
1249 cell_space[index] = space;
1250 } else {
1251 remaining_indices.push(index);
1252 }
1253 }
1254
1255 if !remaining_indices.is_empty() {
1256 let remaining_per_cell_space =
1257 ((usable_interior_space - used_space) / remaining_indices.len() as f64).max(5.0);
1258 for index in remaining_indices {
1259 cell_space[index] = remaining_per_cell_space;
1260 }
1261 }
1262
1263 let mut cursor = 0.0;
1264 (0..slot_children_count)
1265 .map(|index| {
1266 let space = cell_space[index];
1267 let cell = match direction {
1268 StackerDirection::Horizontal => StackerCell {
1269 width_px: space,
1270 height_px: bounds.1,
1271 x_px: cursor,
1272 y_px: 0.0,
1273 },
1274 StackerDirection::Vertical => StackerCell {
1275 width_px: bounds.0,
1276 height_px: space,
1277 x_px: 0.0,
1278 y_px: cursor,
1279 },
1280 };
1281 cursor += space + gutter_px;
1282 cell
1283 })
1284 .collect()
1285}
1286
1287fn measure_child_bounds(
1288 _parent: &std::rc::Rc<ExpandedNode>,
1289 child: &std::rc::Rc<ExpandedNode>,
1290) -> ChildMeasurement {
1291 child_measurement_from_hull(child.subtree_layout_hull.get())
1292}
1293
1294fn child_measurement_from_hull(hull: LayoutHull) -> ChildMeasurement {
1295 ChildMeasurement {
1296 width: hull.forward_extent_x(),
1297 height: hull.forward_extent_y(),
1298 }
1299}
1300
1301fn axis_value(bounds: (f64, f64), axis: Axis) -> f64 {
1302 match axis {
1303 Axis::X => bounds.0,
1304 Axis::Y => bounds.1,
1305 }
1306}
1307
1308fn size_depends_on_parent(size: Size) -> bool {
1309 const EPSILON: f64 = f64::EPSILON;
1310 match size {
1311 Size::Pixels(_) => false,
1312 Size::Percent(percent) => percent.to_float().abs() > EPSILON,
1313 Size::Combined(_, percent) => percent.to_float().abs() > EPSILON,
1314 }
1315}
1316
1317#[pax]
1319#[engine_import_path("pax_engine")]
1320pub struct StackerCell {
1321 pub x_px: f64,
1323 pub y_px: f64,
1325 pub width_px: f64,
1327 pub height_px: f64,
1329}
1330
1331#[pax]
1333#[engine_import_path("pax_engine")]
1334pub enum StackerDirection {
1335 #[default]
1337 Vertical,
1338 Horizontal,
1340}
1341
1342#[cfg(test)]
1343mod tests {
1344 use super::*;
1345
1346 fn assert_cell(cell: &StackerCell, x: f64, y: f64, width: f64, height: f64) {
1347 assert_eq!(cell.x_px, x);
1348 assert_eq!(cell.y_px, y);
1349 assert_eq!(cell.width_px, width);
1350 assert_eq!(cell.height_px, height);
1351 }
1352
1353 #[test]
1354 fn autosize_vertical_uses_child_measurements() {
1355 let layout = compute_stacker_layout(
1356 StackerDirection::Vertical,
1357 (120.0, 200.0),
1358 Size::Pixels(8.into()),
1359 vec![],
1360 true,
1361 Some(true),
1362 None,
1363 &[
1364 ChildMeasurement {
1365 width: Some(60.0),
1366 height: Some(24.0),
1367 },
1368 ChildMeasurement {
1369 width: Some(90.0),
1370 height: Some(40.0),
1371 },
1372 ],
1373 2,
1374 false,
1375 false,
1376 );
1377
1378 assert_eq!(layout.measured_size, Some((90.0, 72.0)));
1379 assert_eq!(layout.cell_specs.len(), 2);
1380 assert_cell(&layout.cell_specs[0], 0.0, 0.0, 60.0, 24.0);
1381 assert_cell(&layout.cell_specs[1], 0.0, 32.0, 90.0, 40.0);
1382 }
1383
1384 #[test]
1385 fn autosize_falls_back_when_main_axis_cannot_be_measured() {
1386 let layout = compute_stacker_layout(
1387 StackerDirection::Vertical,
1388 (120.0, 200.0),
1389 Size::Pixels(8.into()),
1390 vec![],
1391 true,
1392 None,
1393 None,
1394 &[
1395 ChildMeasurement {
1396 width: Some(60.0),
1397 height: None,
1398 },
1399 ChildMeasurement {
1400 width: Some(90.0),
1401 height: Some(40.0),
1402 },
1403 ],
1404 2,
1405 false,
1406 false,
1407 );
1408
1409 assert_eq!(layout.measured_size, None);
1410 assert_eq!(layout.cell_specs.len(), 2);
1411 assert_cell(&layout.cell_specs[0], 0.0, 0.0, 120.0, 96.0);
1412 assert_cell(&layout.cell_specs[1], 0.0, 104.0, 120.0, 96.0);
1413 }
1414
1415 #[test]
1416 fn autosize_uses_explicit_cross_axis_when_child_widths_fill_parent() {
1417 let layout = compute_stacker_layout(
1418 StackerDirection::Vertical,
1419 (160.0, 240.0),
1420 Size::Pixels(10.into()),
1421 vec![],
1422 true,
1423 None,
1424 None,
1425 &[
1426 ChildMeasurement {
1427 width: None,
1428 height: Some(30.0),
1429 },
1430 ChildMeasurement {
1431 width: None,
1432 height: Some(50.0),
1433 },
1434 ],
1435 2,
1436 true,
1437 false,
1438 );
1439
1440 assert_eq!(layout.measured_size, Some((160.0, 90.0)));
1441 assert_eq!(layout.cell_specs.len(), 2);
1442 assert_cell(&layout.cell_specs[0], 0.0, 0.0, 160.0, 30.0);
1443 assert_cell(&layout.cell_specs[1], 0.0, 40.0, 160.0, 50.0);
1444 }
1445
1446 #[test]
1447 fn autosize_defaults_to_extending_axis_only() {
1448 let vertical = compute_stacker_layout(
1449 StackerDirection::Vertical,
1450 (160.0, 240.0),
1451 Size::Pixels(10.into()),
1452 vec![],
1453 true,
1454 None,
1455 None,
1456 &[
1457 ChildMeasurement {
1458 width: None,
1459 height: Some(30.0),
1460 },
1461 ChildMeasurement {
1462 width: None,
1463 height: Some(50.0),
1464 },
1465 ],
1466 2,
1467 false,
1468 false,
1469 );
1470 assert_eq!(vertical.measured_size, Some((160.0, 90.0)));
1471
1472 let horizontal = compute_stacker_layout(
1473 StackerDirection::Horizontal,
1474 (160.0, 240.0),
1475 Size::Pixels(10.into()),
1476 vec![],
1477 true,
1478 None,
1479 None,
1480 &[
1481 ChildMeasurement {
1482 width: Some(30.0),
1483 height: None,
1484 },
1485 ChildMeasurement {
1486 width: Some(50.0),
1487 height: None,
1488 },
1489 ],
1490 2,
1491 false,
1492 false,
1493 );
1494 assert_eq!(horizontal.measured_size, Some((90.0, 240.0)));
1495 }
1496
1497 #[test]
1498 fn axis_overrides_can_disable_default_or_enable_cross_axis() {
1499 let layout = compute_stacker_layout(
1500 StackerDirection::Vertical,
1501 (120.0, 200.0),
1502 Size::Pixels(8.into()),
1503 vec![],
1504 true,
1505 Some(true),
1506 Some(false),
1507 &[
1508 ChildMeasurement {
1509 width: Some(60.0),
1510 height: Some(24.0),
1511 },
1512 ChildMeasurement {
1513 width: Some(90.0),
1514 height: Some(40.0),
1515 },
1516 ],
1517 2,
1518 false,
1519 false,
1520 );
1521
1522 assert_eq!(layout.measured_size, Some((90.0, 200.0)));
1523 assert_eq!(layout.cell_specs.len(), 2);
1524 assert_cell(&layout.cell_specs[0], 0.0, 0.0, 60.0, 96.0);
1525 assert_cell(&layout.cell_specs[1], 0.0, 104.0, 90.0, 96.0);
1526 }
1527
1528 #[test]
1529 fn child_measurement_uses_local_hull_extent() {
1530 let measurement = child_measurement_from_hull(LayoutHull::from_axis_ranges(
1531 Some((0.0, 60.0)),
1532 Some((0.0, 72.0)),
1533 ));
1534
1535 assert_eq!(measurement.width, Some(60.0));
1536 assert_eq!(measurement.height, Some(72.0));
1537 }
1538 use pax_engine::api::pax_value::{PaxAny, ToFromPaxAny};
1539 use pax_engine::api::{Platform, Property, TargetInfo, OS};
1540 use pax_engine::pax_manifest::cartridge_generation::{
1541 ComponentTransitionConfig, TRANSITION_PHASE_EXIT,
1542 };
1543 use pax_language::interpreter::{PaxAccessor, PaxExpression, PaxIdentifier, PaxPrimary};
1544 use pax_manifest::ExpressionInfo;
1545 use pax_runtime::api::CommonProperties;
1546 use pax_runtime::api::{PaxValue, ToPaxValue};
1547 use pax_runtime::{
1548 BaseInstance, CommonPropertiesInit, ComponentInstance, ExpandedNode, Globals,
1549 InstanceFlags, InstanceNode, InstantiationArgs, PropertiesInit, PropertiesScopeInit,
1550 RepeatInstance, RepeatProperties, RouteLocation, RuntimeContext,
1551 RuntimePropertiesStackFrame, TransformAndBounds,
1552 };
1553 use std::fmt;
1554
1555 fn frame(x: f64, y: f64, width: f64, height: f64) -> ContainerFrame {
1556 ContainerFrame {
1557 transform: Transform2::translate(Vector2::new(x, y)),
1558 bounds: (width, height),
1559 }
1560 }
1561
1562 fn test_globals() -> Globals {
1563 Globals {
1564 elapsed_frames: Property::new(0),
1565 elapsed_millis: Property::new(0),
1566 viewport: Property::new(TransformAndBounds {
1567 transform: Transform2::identity(),
1568 bounds: (100.0, 100.0),
1569 }),
1570 gyro: Property::new(Default::default()),
1571 accel: Property::new(Default::default()),
1572 route_location: Property::new(RouteLocation::root()),
1573 browser_allows_scroller_vector_layers: Property::new(true),
1574 browser_allows_nested_scroller_vector_layers: Property::new(true),
1575 platform: Platform::Unknown,
1576 os: OS::Unknown,
1577 target: TargetInfo::new(Platform::Unknown, OS::Unknown),
1578 get_elapsed_millis: Rc::new(|| 0),
1579 }
1580 }
1581
1582 fn default_properties_factory() -> Box<
1583 dyn Fn(
1584 Rc<RuntimePropertiesStackFrame>,
1585 Option<Rc<ExpandedNode>>,
1586 ) -> Option<Rc<RefCell<PaxAny>>>,
1587 > {
1588 Box::new(|_, _| Some(Rc::new(RefCell::new(PaxAny::Builtin(Default::default())))))
1589 }
1590
1591 fn default_common_properties_factory() -> Box<
1592 dyn Fn(
1593 Rc<RuntimePropertiesStackFrame>,
1594 Option<Rc<ExpandedNode>>,
1595 ) -> Option<Rc<RefCell<CommonProperties>>>,
1596 > {
1597 Box::new(|_, _| Some(Rc::new(RefCell::new(CommonProperties::default()))))
1598 }
1599
1600 fn component_args(template: Vec<Rc<dyn InstanceNode>>) -> InstantiationArgs {
1601 InstantiationArgs {
1602 prototypical_common_properties: CommonPropertiesInit::Factory(
1603 default_common_properties_factory(),
1604 ),
1605 prototypical_properties: PropertiesInit::Factory(default_properties_factory()),
1606 handler_registry: None,
1607 children: None,
1608 component_template: Some(RefCell::new(template)),
1609 component_settings: None,
1610 template_node_identifier: None,
1611 template_node_type_id: None,
1612 template_node_selector_info: None,
1613 transition_config: Default::default(),
1614 properties_scope: PropertiesScopeInit::None,
1615 }
1616 }
1617
1618 fn primitive_args(children: Vec<Rc<dyn InstanceNode>>) -> InstantiationArgs {
1619 InstantiationArgs {
1620 prototypical_common_properties: CommonPropertiesInit::Factory(
1621 default_common_properties_factory(),
1622 ),
1623 prototypical_properties: PropertiesInit::Factory(default_properties_factory()),
1624 handler_registry: None,
1625 children: Some(RefCell::new(children)),
1626 component_template: None,
1627 component_settings: None,
1628 template_node_identifier: None,
1629 template_node_type_id: None,
1630 template_node_selector_info: None,
1631 transition_config: Default::default(),
1632 properties_scope: PropertiesScopeInit::None,
1633 }
1634 }
1635
1636 fn stacker_args_with(
1637 children: Vec<Rc<dyn InstanceNode>>,
1638 stacker: Stacker,
1639 ) -> InstantiationArgs {
1640 InstantiationArgs {
1641 prototypical_common_properties: CommonPropertiesInit::Factory(
1642 default_common_properties_factory(),
1643 ),
1644 prototypical_properties: PropertiesInit::Factory(Box::new(move |_, _| {
1645 Some(Rc::new(RefCell::new(stacker.clone().to_pax_any())))
1646 })),
1647 handler_registry: None,
1648 children: Some(RefCell::new(children)),
1649 component_template: None,
1650 component_settings: None,
1651 template_node_identifier: None,
1652 template_node_type_id: None,
1653 template_node_selector_info: None,
1654 transition_config: Default::default(),
1655 properties_scope: PropertiesScopeInit::None,
1656 }
1657 }
1658
1659 fn stacker_args(children: Vec<Rc<dyn InstanceNode>>) -> InstantiationArgs {
1660 stacker_args_with(children, Stacker::default())
1661 }
1662
1663 fn horizontal_stacker_properties() -> Stacker {
1664 Stacker {
1665 direction: Property::new(StackerDirection::Horizontal),
1666 gutter: Property::new(Size::Pixels(10.into())),
1667 ..Default::default()
1668 }
1669 }
1670
1671 fn leaf_component_args(transition_config: ComponentTransitionConfig) -> InstantiationArgs {
1672 InstantiationArgs {
1673 prototypical_common_properties: CommonPropertiesInit::Factory(
1674 default_common_properties_factory(),
1675 ),
1676 prototypical_properties: PropertiesInit::Factory(default_properties_factory()),
1677 handler_registry: None,
1678 children: None,
1679 component_template: Some(RefCell::new(Vec::new())),
1680 component_settings: None,
1681 template_node_identifier: None,
1682 template_node_type_id: None,
1683 template_node_selector_info: None,
1684 transition_config,
1685 properties_scope: PropertiesScopeInit::None,
1686 }
1687 }
1688
1689 fn repeat_args(
1690 source: Property<PaxValue>,
1691 children: Vec<Rc<dyn InstanceNode>>,
1692 ) -> InstantiationArgs {
1693 let key_expression =
1694 ExpressionInfo::new(PaxExpression::Primary(Box::new(PaxPrimary::Identifier(
1695 PaxIdentifier::new("item"),
1696 vec![PaxAccessor::Struct("id".to_string())],
1697 ))));
1698 let source_for_factory = source.clone();
1699 InstantiationArgs {
1700 prototypical_common_properties: CommonPropertiesInit::Factory(
1701 default_common_properties_factory(),
1702 ),
1703 prototypical_properties: PropertiesInit::Factory(Box::new(move |_, expanded_node| {
1704 expanded_node.is_none().then(|| {
1705 Rc::new(RefCell::new(
1706 RepeatProperties {
1707 source_expression: source_for_factory.clone(),
1708 iterator_i_symbol: Property::new(Some("i".to_string())),
1709 iterator_elem_symbol: Property::new(Some("item".to_string())),
1710 repeat_key_expression: Some(key_expression.clone()),
1711 }
1712 .to_pax_any(),
1713 ))
1714 })
1715 })),
1716 handler_registry: None,
1717 children: Some(RefCell::new(children)),
1718 component_template: None,
1719 component_settings: None,
1720 template_node_identifier: None,
1721 template_node_type_id: None,
1722 template_node_selector_info: None,
1723 transition_config: Default::default(),
1724 properties_scope: PropertiesScopeInit::None,
1725 }
1726 }
1727
1728 fn item(id: &str) -> PaxValue {
1729 PaxValue::Object(
1730 vec![("id".to_string(), id.to_string().to_pax_value())]
1731 .into_iter()
1732 .collect(),
1733 )
1734 }
1735
1736 fn source(ids: &[&str]) -> PaxValue {
1737 PaxValue::Vec(ids.iter().map(|id| item(id)).collect())
1738 }
1739
1740 struct TestLeaf {
1741 base: BaseInstance,
1742 }
1743
1744 impl InstanceNode for TestLeaf {
1745 fn instantiate(args: InstantiationArgs) -> Rc<Self>
1746 where
1747 Self: Sized,
1748 {
1749 Rc::new(Self {
1750 base: BaseInstance::new(
1751 args,
1752 InstanceFlags {
1753 invisible_to_slot: false,
1754 invisible_to_raycasting: false,
1755 layer: Layer::DontCare,
1756 is_component: false,
1757 is_slot: false,
1758 },
1759 ),
1760 })
1761 }
1762
1763 fn resolve_debug(
1764 &self,
1765 f: &mut fmt::Formatter,
1766 _expanded_node: Option<&ExpandedNode>,
1767 ) -> fmt::Result {
1768 f.debug_struct("TestLeaf").finish()
1769 }
1770
1771 fn base(&self) -> &BaseInstance {
1772 &self.base
1773 }
1774 }
1775
1776 #[test]
1777 fn compute_cell_specs_returns_empty_for_zero_children() {
1778 assert!(compute_cell_specs(
1779 0,
1780 (200.0, 120.0),
1781 StackerDirection::Horizontal,
1782 Size::Pixels(8.into()),
1783 Vec::new(),
1784 )
1785 .is_empty());
1786 }
1787
1788 #[test]
1789 fn enter_transition_activity_ends_when_playhead_reaches_duration() {
1790 assert!(enter_transition_active(
1791 TRANSITION_PHASE_ENTER,
1792 5.0,
1793 80.0,
1794 10,
1795 None
1796 ));
1797 assert!(!enter_transition_active(
1798 TRANSITION_PHASE_ENTER,
1799 10.0,
1800 160.0,
1801 10,
1802 None
1803 ));
1804 assert!(!enter_transition_active(
1805 TRANSITION_PHASE_ENTER,
1806 15.0,
1807 240.0,
1808 10,
1809 None
1810 ));
1811 assert!(!enter_transition_active(
1812 TRANSITION_PHASE_EXIT,
1813 5.0,
1814 80.0,
1815 10,
1816 None
1817 ));
1818 assert!(enter_transition_active(
1819 TRANSITION_PHASE_ENTER,
1820 10.0,
1821 99.0,
1822 1,
1823 Some(100)
1824 ));
1825 }
1826
1827 #[test]
1828 fn stacker_reflow_defaults_to_snap() {
1829 assert!(matches!(
1830 ContainerReflowTransitionKind::default(),
1831 ContainerReflowTransitionKind::Snap
1832 ));
1833 assert!(matches!(
1834 ContainerReflowTransition::default().kind.get(),
1835 ContainerReflowTransitionKind::Snap
1836 ));
1837 assert!(matches!(
1838 Stacker::default().reflow_transition.get().kind.get(),
1839 ContainerReflowTransitionKind::Snap
1840 ));
1841 }
1842
1843 #[test]
1844 fn ghost_reflow_keeps_exit_frame_and_animates_survivors() {
1845 let children = vec![
1846 StackerChildSnapshot {
1847 id: 1_u32,
1848 exiting: false,
1849 entering: false,
1850 },
1851 StackerChildSnapshot {
1852 id: 2_u32,
1853 exiting: true,
1854 entering: false,
1855 },
1856 StackerChildSnapshot {
1857 id: 3_u32,
1858 exiting: false,
1859 entering: false,
1860 },
1861 ];
1862 let prior_frames = HashMap::from([
1863 (1_u32, frame(0.0, 0.0, 100.0, 30.0)),
1864 (2_u32, frame(0.0, 40.0, 100.0, 30.0)),
1865 (3_u32, frame(0.0, 80.0, 100.0, 30.0)),
1866 ]);
1867 let current_frames = prior_frames.clone();
1868
1869 let plan = plan_stacker_layout(
1870 &children,
1871 &prior_frames,
1872 ¤t_frames,
1873 ContainerExitMode::Ghost,
1874 ContainerReflowTransitionKind::Ease,
1875 (100.0, 70.0),
1876 StackerDirection::Vertical,
1877 Size::Pixels(10.into()),
1878 Vec::new(),
1879 );
1880
1881 assert_eq!(
1882 compute_cell_specs(
1883 2,
1884 (100.0, 70.0),
1885 StackerDirection::Vertical,
1886 Size::Pixels(10.into()),
1887 Vec::new()
1888 )
1889 .len(),
1890 2
1891 );
1892 assert_eq!(plan.placements.len(), 3);
1893 assert_eq!(plan.placements[0].id, 1_u32);
1894 assert_eq!(plan.placements[0].frame, frame(0.0, 0.0, 100.0, 30.0));
1895 assert!(!plan.placements[0].animate);
1896 assert_eq!(plan.placements[1].id, 2_u32);
1897 assert_eq!(plan.placements[1].frame, frame(0.0, 40.0, 100.0, 30.0));
1898 assert!(!plan.placements[1].animate);
1899 assert_eq!(plan.placements[2].id, 3_u32);
1900 assert_eq!(plan.placements[2].frame, frame(0.0, 40.0, 100.0, 30.0));
1901 assert!(plan.placements[2].animate);
1902 }
1903
1904 #[test]
1905 fn flow_mode_keeps_exiting_child_in_prior_slot() {
1906 let children = vec![
1907 StackerChildSnapshot {
1908 id: 1_u32,
1909 exiting: false,
1910 entering: false,
1911 },
1912 StackerChildSnapshot {
1913 id: 3_u32,
1914 exiting: false,
1915 entering: false,
1916 },
1917 StackerChildSnapshot {
1918 id: 2_u32,
1919 exiting: true,
1920 entering: false,
1921 },
1922 ];
1923 let prior_frames = HashMap::from([
1924 (1_u32, frame(0.0, 0.0, 100.0, 30.0)),
1925 (2_u32, frame(0.0, 40.0, 100.0, 30.0)),
1926 (3_u32, frame(0.0, 80.0, 100.0, 30.0)),
1927 ]);
1928 let current_frames = prior_frames.clone();
1929
1930 let plan = plan_stacker_layout(
1931 &children,
1932 &prior_frames,
1933 ¤t_frames,
1934 ContainerExitMode::Flow,
1935 ContainerReflowTransitionKind::Snap,
1936 (100.0, 110.0),
1937 StackerDirection::Vertical,
1938 Size::Pixels(10.into()),
1939 vec![
1940 Some(Size::Pixels(30.into())),
1941 Some(Size::Pixels(30.into())),
1942 Some(Size::Pixels(30.into())),
1943 ],
1944 );
1945
1946 assert_eq!(plan.placements.len(), 3);
1947 assert_eq!(plan.placements[0].id, 1_u32);
1948 assert_eq!(plan.placements[0].frame, frame(0.0, 0.0, 100.0, 30.0));
1949 assert_eq!(plan.placements[1].id, 3_u32);
1950 assert_eq!(plan.placements[1].frame, frame(0.0, 80.0, 100.0, 30.0));
1951 assert_eq!(plan.placements[2].id, 2_u32);
1952 assert_eq!(plan.placements[2].frame, frame(0.0, 40.0, 100.0, 30.0));
1953 }
1954
1955 #[test]
1956 fn flow_mode_places_entering_child_by_target_layout_not_overfull_flow_count() {
1957 let children = vec![
1958 StackerChildSnapshot {
1959 id: 1_u32,
1960 exiting: false,
1961 entering: false,
1962 },
1963 StackerChildSnapshot {
1964 id: 3_u32,
1965 exiting: false,
1966 entering: false,
1967 },
1968 StackerChildSnapshot {
1969 id: 4_u32,
1970 exiting: false,
1971 entering: true,
1972 },
1973 StackerChildSnapshot {
1974 id: 2_u32,
1975 exiting: true,
1976 entering: false,
1977 },
1978 ];
1979 let prior_frames = HashMap::from([
1980 (1_u32, frame(0.0, 0.0, 100.0, 30.0)),
1981 (2_u32, frame(0.0, 40.0, 100.0, 30.0)),
1982 (3_u32, frame(0.0, 80.0, 100.0, 30.0)),
1983 ]);
1984 let current_frames = prior_frames.clone();
1985
1986 let plan = plan_stacker_layout(
1987 &children,
1988 &prior_frames,
1989 ¤t_frames,
1990 ContainerExitMode::Flow,
1991 ContainerReflowTransitionKind::Snap,
1992 (100.0, 110.0),
1993 StackerDirection::Vertical,
1994 Size::Pixels(10.into()),
1995 vec![
1996 Some(Size::Pixels(30.into())),
1997 Some(Size::Pixels(30.into())),
1998 Some(Size::Pixels(30.into())),
1999 ],
2000 );
2001
2002 let entering = plan
2003 .placements
2004 .iter()
2005 .find(|placement| placement.id == 4_u32)
2006 .unwrap();
2007 assert_eq!(entering.frame, frame(0.0, 120.0, 100.0, 30.0));
2008 }
2009
2010 #[test]
2011 fn flow_mode_keeps_initial_entering_children_in_active_slots() {
2012 let children = vec![
2013 StackerChildSnapshot {
2014 id: 1_u32,
2015 exiting: false,
2016 entering: true,
2017 },
2018 StackerChildSnapshot {
2019 id: 2_u32,
2020 exiting: false,
2021 entering: true,
2022 },
2023 ];
2024
2025 let plan = plan_stacker_layout(
2026 &children,
2027 &HashMap::new(),
2028 &HashMap::new(),
2029 ContainerExitMode::Flow,
2030 ContainerReflowTransitionKind::Snap,
2031 (100.0, 70.0),
2032 StackerDirection::Vertical,
2033 Size::Pixels(10.into()),
2034 vec![Some(Size::Pixels(30.into())), Some(Size::Pixels(30.into()))],
2035 );
2036
2037 assert_eq!(plan.placements.len(), 2);
2038 assert_eq!(plan.placements[0].frame, frame(0.0, 0.0, 100.0, 30.0));
2039 assert_eq!(plan.placements[1].frame, frame(0.0, 40.0, 100.0, 30.0));
2040 }
2041
2042 #[test]
2043 fn flow_reflow_ease_marches_stable_and_entering_children_toward_active_layout() {
2044 let children = vec![
2045 StackerChildSnapshot {
2046 id: 1_u32,
2047 exiting: false,
2048 entering: false,
2049 },
2050 StackerChildSnapshot {
2051 id: 3_u32,
2052 exiting: false,
2053 entering: false,
2054 },
2055 StackerChildSnapshot {
2056 id: 4_u32,
2057 exiting: false,
2058 entering: true,
2059 },
2060 StackerChildSnapshot {
2061 id: 2_u32,
2062 exiting: true,
2063 entering: false,
2064 },
2065 ];
2066 let prior_frames = HashMap::from([
2067 (1_u32, frame(0.0, 0.0, 100.0, 30.0)),
2068 (2_u32, frame(0.0, 40.0, 100.0, 30.0)),
2069 (3_u32, frame(0.0, 80.0, 100.0, 30.0)),
2070 ]);
2071 let current_frames = prior_frames.clone();
2072
2073 let plan = plan_stacker_layout(
2074 &children,
2075 &prior_frames,
2076 ¤t_frames,
2077 ContainerExitMode::Flow,
2078 ContainerReflowTransitionKind::Ease,
2079 (100.0, 110.0),
2080 StackerDirection::Vertical,
2081 Size::Pixels(10.into()),
2082 vec![
2083 Some(Size::Pixels(30.into())),
2084 Some(Size::Pixels(30.into())),
2085 Some(Size::Pixels(30.into())),
2086 ],
2087 );
2088
2089 let stable = plan
2090 .placements
2091 .iter()
2092 .find(|placement| placement.id == 3_u32)
2093 .unwrap();
2094 assert_eq!(stable.seed_frame, None);
2095 assert_eq!(stable.frame, frame(0.0, 40.0, 100.0, 30.0));
2096 assert!(stable.animate);
2097
2098 let entering = plan
2099 .placements
2100 .iter()
2101 .find(|placement| placement.id == 4_u32)
2102 .unwrap();
2103 assert_eq!(entering.seed_frame, Some(frame(0.0, 120.0, 100.0, 30.0)));
2104 assert_eq!(entering.frame, frame(0.0, 80.0, 100.0, 30.0));
2105 assert!(entering.animate);
2106
2107 let exiting = plan
2108 .placements
2109 .iter()
2110 .find(|placement| placement.id == 2_u32)
2111 .unwrap();
2112 assert_eq!(exiting.seed_frame, None);
2113 assert_eq!(exiting.frame, frame(0.0, 40.0, 100.0, 30.0));
2114 assert!(!exiting.animate);
2115 }
2116
2117 #[test]
2118 fn flow_reflow_ease_keeps_exiting_child_on_prior_frame() {
2119 let children = vec![
2120 StackerChildSnapshot {
2121 id: 1_u32,
2122 exiting: false,
2123 entering: false,
2124 },
2125 StackerChildSnapshot {
2126 id: 2_u32,
2127 exiting: true,
2128 entering: false,
2129 },
2130 StackerChildSnapshot {
2131 id: 3_u32,
2132 exiting: false,
2133 entering: false,
2134 },
2135 ];
2136 let prior_frames = HashMap::from([
2137 (1_u32, frame(0.0, 0.0, 100.0, 30.0)),
2138 (2_u32, frame(0.0, 40.0, 100.0, 30.0)),
2139 (3_u32, frame(0.0, 80.0, 100.0, 30.0)),
2140 ]);
2141 let current_frames = HashMap::from([
2142 (1_u32, frame(0.0, 0.0, 100.0, 30.0)),
2143 (2_u32, frame(0.0, 40.0, 100.0, 30.0)),
2144 (3_u32, frame(0.0, 80.0, 100.0, 30.0)),
2145 ]);
2146
2147 let plan = plan_stacker_layout(
2148 &children,
2149 &prior_frames,
2150 ¤t_frames,
2151 ContainerExitMode::Flow,
2152 ContainerReflowTransitionKind::Ease,
2153 (100.0, 70.0),
2154 StackerDirection::Vertical,
2155 Size::Pixels(10.into()),
2156 Vec::new(),
2157 );
2158
2159 let exiting = plan
2160 .placements
2161 .iter()
2162 .find(|placement| placement.id == 2_u32)
2163 .unwrap();
2164 assert_eq!(exiting.frame, frame(0.0, 40.0, 100.0, 30.0));
2165 assert!(!exiting.animate);
2166 }
2167
2168 #[test]
2169 fn stacker_assigns_distinct_container_frames_to_projected_children() {
2170 let leaf_a: Rc<dyn InstanceNode> = TestLeaf::instantiate(primitive_args(Vec::new()));
2171 let leaf_b: Rc<dyn InstanceNode> = TestLeaf::instantiate(primitive_args(Vec::new()));
2172 let leaf_c: Rc<dyn InstanceNode> = TestLeaf::instantiate(primitive_args(Vec::new()));
2173 let stacker: Rc<dyn InstanceNode> = StackerInstance::instantiate(stacker_args_with(
2174 vec![leaf_a, leaf_b, leaf_c],
2175 horizontal_stacker_properties(),
2176 ));
2177 let root_component = ComponentInstance::instantiate(component_args(vec![stacker]));
2178 let context = Rc::new(RuntimeContext::new(test_globals()));
2179 let root = ExpandedNode::initialize_root(root_component, &context);
2180
2181 root.recurse_update(&context);
2182 let stacker_node = root.children.get().first().cloned().unwrap();
2183 let children = stacker_node.children.get();
2184 assert_eq!(children.len(), 3);
2185
2186 let x_positions: Vec<_> = children
2187 .iter()
2188 .map(|child| child.transform_and_bounds.get().transform.m[4])
2189 .collect();
2190 assert_eq!(x_positions.len(), 3);
2191 assert!((x_positions[0] - 0.0).abs() < 1e-9);
2192 assert!((x_positions[1] - 36.666666666666664).abs() < 1e-9);
2193 assert!((x_positions[2] - 73.33333333333333).abs() < 1e-9);
2194 }
2195
2196 #[test]
2197 fn stacker_assigns_distinct_container_frames_on_initial_mount() {
2198 let leaf_a: Rc<dyn InstanceNode> = TestLeaf::instantiate(primitive_args(Vec::new()));
2199 let leaf_b: Rc<dyn InstanceNode> = TestLeaf::instantiate(primitive_args(Vec::new()));
2200 let leaf_c: Rc<dyn InstanceNode> = TestLeaf::instantiate(primitive_args(Vec::new()));
2201 let stacker: Rc<dyn InstanceNode> = StackerInstance::instantiate(stacker_args_with(
2202 vec![leaf_a, leaf_b, leaf_c],
2203 horizontal_stacker_properties(),
2204 ));
2205 let root_component = ComponentInstance::instantiate(component_args(vec![stacker]));
2206 let context = Rc::new(RuntimeContext::new(test_globals()));
2207 let root = ExpandedNode::initialize_root(root_component, &context);
2208
2209 root.recurse_update(&context);
2210 let stacker_node = root.children.get().first().cloned().unwrap();
2211 let children = stacker_node.children.get();
2212 assert_eq!(children.len(), 3);
2213
2214 let x_positions: Vec<_> = children
2215 .iter()
2216 .map(|child| child.transform_and_bounds.get().transform.m[4])
2217 .collect();
2218 assert_eq!(x_positions.len(), 3);
2219 assert!((x_positions[0] - 0.0).abs() < 1e-9);
2220 assert!((x_positions[1] - 36.666666666666664).abs() < 1e-9);
2221 assert!((x_positions[2] - 73.33333333333333).abs() < 1e-9);
2222 }
2223
2224 #[test]
2225 fn stacker_assigns_distinct_container_frames_to_projected_component_children() {
2226 let component_a: Rc<dyn InstanceNode> =
2227 ComponentInstance::instantiate(component_args(Vec::new()));
2228 let component_b: Rc<dyn InstanceNode> =
2229 ComponentInstance::instantiate(component_args(Vec::new()));
2230 let component_c: Rc<dyn InstanceNode> =
2231 ComponentInstance::instantiate(component_args(Vec::new()));
2232 let stacker: Rc<dyn InstanceNode> = StackerInstance::instantiate(stacker_args_with(
2233 vec![component_a, component_b, component_c],
2234 horizontal_stacker_properties(),
2235 ));
2236 let root_component = ComponentInstance::instantiate(component_args(vec![stacker]));
2237 let context = Rc::new(RuntimeContext::new(test_globals()));
2238 let root = ExpandedNode::initialize_root(root_component, &context);
2239
2240 root.recurse_update(&context);
2241 let stacker_node = root.children.get().first().cloned().unwrap();
2242 let children = stacker_node.children.get();
2243 assert_eq!(children.len(), 3);
2244
2245 let x_positions: Vec<_> = children
2246 .iter()
2247 .map(|child| child.transform_and_bounds.get().transform.m[4])
2248 .collect();
2249 assert_eq!(x_positions.len(), 3);
2250 assert!((x_positions[0] - 0.0).abs() < 1e-9);
2251 assert!((x_positions[1] - 36.666666666666664).abs() < 1e-9);
2252 assert!((x_positions[2] - 73.33333333333333).abs() < 1e-9);
2253 }
2254
2255 #[test]
2256 fn stacker_retains_single_exiting_child_for_projected_keyed_repeat_changes() {
2257 let source_property = Property::new(source(&["a", "b", "c"]));
2258 let leaf: Rc<dyn InstanceNode> =
2259 ComponentInstance::instantiate(leaf_component_args(ComponentTransitionConfig {
2260 has_enter: true,
2261 enter_frame_count: 10,
2262 has_exit: true,
2263 exit_frame_count: 10,
2264 timeout_ms: 5_000,
2265 ..Default::default()
2266 }));
2267 let repeat: Rc<dyn InstanceNode> =
2268 RepeatInstance::instantiate(repeat_args(source_property.clone(), vec![leaf]));
2269 let stacker: Rc<dyn InstanceNode> =
2270 StackerInstance::instantiate(stacker_args(vec![repeat]));
2271 let root_component = ComponentInstance::instantiate(component_args(vec![stacker]));
2272 let context = Rc::new(RuntimeContext::new(test_globals()));
2273 let root = ExpandedNode::initialize_root(root_component, &context);
2274
2275 root.recurse_update(&context);
2276 let stacker_node = root.children.get().first().cloned().unwrap();
2277 let initial_active = borrow!(stacker_node.active_children).clone();
2278 assert_eq!(initial_active.len(), 3);
2279 let initial_ids: Vec<_> = initial_active.iter().map(|child| child.id).collect();
2280
2281 source_property.set(source(&["a", "c", "d"]));
2282 root.recurse_update(&context);
2283
2284 let active = borrow!(stacker_node.active_children).clone();
2285 let exiting = borrow!(stacker_node.exiting_children).clone();
2286 let node_ctx = stacker_node.get_node_context(&context);
2287 let received_children = node_ctx.received_children.get();
2288 let retained_received_children = node_ctx.retained_received_children.get();
2289 assert_eq!(active.len(), 3);
2290 assert_eq!(exiting.len(), 1);
2291 assert_eq!(received_children.len(), 3);
2292 assert_eq!(retained_received_children.len(), 1);
2293 assert_eq!(active[0].id, initial_ids[0]);
2294 assert_eq!(active[1].id, initial_ids[2]);
2295 assert_ne!(active[2].id, initial_ids[0]);
2296 assert_ne!(active[2].id, initial_ids[1]);
2297 assert_ne!(active[2].id, initial_ids[2]);
2298 assert_eq!(exiting[0].id, initial_ids[1]);
2299 assert_eq!(exiting[0].transition_phase.get(), TRANSITION_PHASE_EXIT);
2300 assert_eq!(received_children[0].id, initial_ids[0]);
2301 assert_eq!(received_children[1].id, initial_ids[2]);
2302 assert_eq!(retained_received_children[0].id, initial_ids[1]);
2303 }
2304}