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