Skip to main content

pax_runtime/
component.rs

1use std::cell::Ref;
2use std::collections::HashMap;
3use std::iter;
4use std::rc::Rc;
5
6use pax_runtime_api::{
7    borrow, borrow_mut, use_RefCell, Interpolatable, PaxValue, Property, ToPaxValue, Variable,
8};
9
10use_RefCell!();
11use crate::api::{Layer, Timeline};
12use crate::{
13    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstanceNodePtrList,
14    InstantiationArgs, RuntimeContext,
15};
16
17/// A render node with its own runtime context. Will push a frame
18/// to the runtime stack including the specified `projected_children` and
19/// a `PaxType` properties object.  `Component` is used at the root of
20/// applications, at the root of reusable components like `Stacker`, and
21/// in special applications like `Repeat` where it houses the `RepeatItem`
22/// properties attached to each of Repeat's virtual nodes.
23pub struct ComponentInstance {
24    pub template: InstanceNodePtrList,
25    pub timelines: Vec<Rc<RefCell<Timeline>>>,
26    base: BaseInstance,
27}
28
29// #[derive(Default)]
30// pub struct ComponentProperties {
31//     pub projected_children: BTreeSet<Rc<ExpandedNode>>,
32// }
33
34impl InstanceNode for ComponentInstance {
35    fn instantiate(mut args: InstantiationArgs) -> Rc<Self> {
36        let component_template = args.component_template.take();
37        let template = component_template.unwrap_or_default();
38        let base = BaseInstance::new(
39            args,
40            InstanceFlags {
41                invisible_to_slot: false,
42                invisible_to_raycasting: true,
43                layer: Layer::DontCare,
44                is_component: true,
45                is_slot: false,
46            },
47        );
48        Rc::new(ComponentInstance {
49            base,
50            template,
51            timelines: vec![],
52        })
53    }
54
55    fn handle_setup_projected_children(
56        self: Rc<Self>,
57        expanded_node: &Rc<ExpandedNode>,
58        context: &Rc<RuntimeContext>,
59    ) {
60        if let Some(containing_component) = expanded_node.containing_component.upgrade() {
61            let env = if let Some(stack_frame) =
62                ScrollPosition::create_builtin_if_exists(borrow!(expanded_node.properties_scope))
63            {
64                expanded_node.stack.push(stack_frame)
65            } else {
66                Rc::clone(&expanded_node.stack)
67            };
68            let children = borrow!(self.base().get_instance_children());
69            let children_with_env = children.iter().cloned().zip(iter::repeat(env));
70            let new_projected_children = containing_component.create_children_detached(
71                children_with_env,
72                context,
73                &Rc::downgrade(expanded_node),
74            );
75            *borrow_mut!(expanded_node.expanded_projected_children) = Some(new_projected_children);
76        }
77    }
78
79    fn handle_mount(
80        self: Rc<Self>,
81        expanded_node: &Rc<ExpandedNode>,
82        context: &Rc<RuntimeContext>,
83    ) {
84        let mut properties_scope = borrow_mut!(expanded_node.properties_scope);
85        properties_scope.insert(
86            "$suspended".to_string(),
87            Variable::new_from_typed_property(expanded_node.suspended.clone()),
88        );
89        let new_env = expanded_node.stack.push(properties_scope.clone());
90        let children = borrow!(self.template);
91        let children_with_envs = children.iter().cloned().zip(iter::repeat(new_env));
92        expanded_node.children.replace_with(Property::new_with_name(
93            expanded_node.generate_children(
94                children_with_envs,
95                context,
96                &expanded_node.parent_frame,
97                true,
98            ),
99            &format!("component (node id: {})", expanded_node.id.0),
100        ));
101    }
102
103    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
104        if let Some(projected_children) =
105            borrow_mut!(expanded_node.expanded_projected_children).take()
106        {
107            for projected_child in projected_children {
108                projected_child.recurse_unmount(context);
109            }
110        }
111    }
112
113    fn resolve_debug(
114        &self,
115        f: &mut std::fmt::Formatter,
116        _expanded_node: Option<&ExpandedNode>,
117    ) -> std::fmt::Result {
118        f.debug_struct("Component").finish()
119    }
120
121    fn base(&self) -> &BaseInstance {
122        &self.base
123    }
124
125    fn property_requires_occlusion_recompute(&self, _property_name: &str) -> bool {
126        // Components do not draw; state-driven occlusion changes surface through concrete children.
127        false
128    }
129
130    fn get_template(&self) -> Option<&InstanceNodePtrList> {
131        Some(&self.template)
132    }
133}
134
135#[derive(Debug, Clone, Default)]
136/// Built-in `$scroll_position` value synthesized for components inside scrollers.
137pub struct ScrollPosition {
138    pub x: f64,
139    pub y: f64,
140}
141
142impl Interpolatable for ScrollPosition {
143    fn interpolate(&self, other: &Self, t: f64) -> Self {
144        ScrollPosition {
145            x: self.x + (other.x - self.x) * t,
146            y: self.y + (other.y - self.y) * t,
147        }
148    }
149}
150
151impl ToPaxValue for ScrollPosition {
152    fn to_pax_value(self) -> PaxValue {
153        PaxValue::Object(
154            vec![
155                ("x".to_string(), self.x.to_pax_value()),
156                ("y".to_string(), self.y.to_pax_value()),
157            ]
158            .into_iter()
159            .collect(),
160        )
161    }
162}
163
164impl ScrollPosition {
165    /// Create a stack frame containing `$scroll_position` when scroll properties are present.
166    pub fn create_builtin_if_exists(
167        property_scope: Ref<HashMap<String, Variable>>,
168    ) -> Option<HashMap<String, Variable>> {
169        let scroll_pos_x: Property<f64> = Property::new_from_untyped(
170            property_scope
171                .get("scroll_pos_x")?
172                .get_untyped_property()
173                .clone(),
174        );
175        let scroll_pos_y: Property<f64> = Property::new_from_untyped(
176            property_scope
177                .get("scroll_pos_y")?
178                .get_untyped_property()
179                .clone(),
180        );
181        let deps = [scroll_pos_x.untyped(), scroll_pos_y.untyped()];
182        let scroll_position = Property::computed(
183            move || ScrollPosition {
184                x: scroll_pos_x.get(),
185                y: scroll_pos_y.get(),
186            },
187            &deps,
188        );
189
190        let scroll_position_var = Variable::new_from_typed_property(scroll_position);
191        let stack_frame = vec![("$scroll_position".to_string(), scroll_position_var)]
192            .into_iter()
193            .collect();
194        Some(stack_frame)
195    }
196}