Skip to main content

pax_std/core/
import_settings.rs

1use std::iter;
2use std::rc::Rc;
3
4use pax_engine::api::Duration;
5use pax_engine::{pax, Property};
6use pax_runtime::api::{borrow, use_RefCell, Layer};
7use pax_runtime::{
8    BaseInstance, ExpandedNode, InstanceFlags, InstanceNode, InstantiationArgs, RuntimeContext,
9};
10
11use_RefCell!();
12
13/// Mounts a non-rendering subtree whose component descendants export selector settings.
14/// `transition=SettingsTransition::Ease(400ms, TransitionCurve::InOutQuad)`
15/// eases changes to effective settings after the initial appearance. Explicit
16/// inline values, property timelines, and two-way bindings retain ownership.
17#[pax]
18#[engine_import_path("pax_engine")]
19#[primitive("pax_std::core::import_settings::ImportSettingsInstance")]
20pub struct ImportSettings {
21    /// Optional motion for changes to effective imported settings. Each new
22    /// target starts a full-duration transition from the currently displayed value.
23    pub transition: Property<SettingsTransition>,
24}
25
26/// Motion shared by the settings exported from one ImportSettings instance.
27/// Named timeline playback is intentionally not supported yet.
28#[pax]
29#[engine_import_path("pax_engine")]
30pub enum SettingsTransition {
31    /// Apply settings immediately (the default).
32    #[default]
33    None,
34    /// Interpolate changed settings using this duration and easing curve.
35    /// Nonpositive or non-finite durations apply the destination immediately.
36    Ease(Duration, TransitionCurve),
37}
38
39/// Built-in easing curves for automatic settings transitions.
40#[pax]
41#[engine_import_path("pax_engine")]
42pub enum TransitionCurve {
43    /// Constant progress.
44    #[default]
45    Linear,
46    /// Retain the source until the duration ends.
47    Hold,
48    /// Accelerate from rest.
49    InQuad,
50    /// Decelerate into the destination.
51    OutQuad,
52    /// Accelerate, then decelerate.
53    InOutQuad,
54    /// Move back before accelerating forward.
55    InBack,
56    /// Overshoot, then settle.
57    OutBack,
58    /// Anticipation and overshoot.
59    InOutBack,
60}
61
62impl TransitionCurve {
63    fn name(&self) -> &'static str {
64        match self {
65            Self::Linear => "Linear",
66            Self::Hold => "Hold",
67            Self::InQuad => "InQuad",
68            Self::OutQuad => "OutQuad",
69            Self::InOutQuad => "InOutQuad",
70            Self::InBack => "InBack",
71            Self::OutBack => "OutBack",
72            Self::InOutBack => "InOutBack",
73        }
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use pax_engine::api::{CoercionRules, ToPaxValue};
81
82    #[test]
83    fn transition_policy_round_trips_through_typed_values() {
84        let policy = SettingsTransition::Ease(
85            Duration::Milliseconds(400.into()),
86            TransitionCurve::InOutQuad,
87        );
88        let SettingsTransition::Ease(duration, curve) =
89            SettingsTransition::try_coerce(policy.to_pax_value()).unwrap()
90        else {
91            panic!("expected enabled policy");
92        };
93        assert_eq!(duration, Duration::Milliseconds(400.into()));
94        assert_eq!(curve.name(), "InOutQuad");
95    }
96}
97
98pub struct ImportSettingsInstance {
99    base: BaseInstance,
100}
101
102impl InstanceNode for ImportSettingsInstance {
103    fn instantiate(args: InstantiationArgs) -> Rc<Self>
104    where
105        Self: Sized,
106    {
107        Rc::new(Self {
108            base: BaseInstance::new(
109                args,
110                InstanceFlags {
111                    invisible_to_slot: false,
112                    invisible_to_raycasting: true,
113                    layer: Layer::DontCare,
114                    is_component: false,
115                    is_slot: false,
116                },
117            ),
118        })
119    }
120
121    fn handle_mount(
122        self: Rc<Self>,
123        expanded_node: &Rc<ExpandedNode>,
124        context: &Rc<RuntimeContext>,
125    ) {
126        let transition =
127            expanded_node.with_properties_unwrapped(|properties: &mut ImportSettings| {
128                properties.transition.local()
129            });
130        let dependencies = [transition.untyped()];
131        *expanded_node.import_settings_transition.borrow_mut() =
132            Some(pax_engine::api::LocalProperty::computed_with_name(
133                move || match transition.get() {
134                    SettingsTransition::None => None,
135                    SettingsTransition::Ease(duration, curve) => {
136                        Some(pax_runtime::SettingsTransitionConfig {
137                            duration,
138                            curve: curve.name(),
139                        })
140                    }
141                },
142                &dependencies,
143                "imported settings transition",
144            ));
145        let env = Rc::clone(&expanded_node.stack);
146        let children = borrow!(self.base().get_instance_children());
147        let sidecar_children = expanded_node.create_children_detached(
148            children.iter().cloned().zip(iter::repeat(env)),
149            context,
150            &Rc::downgrade(expanded_node),
151        );
152        let sidecar_children = expanded_node.attach_sidecar_children(
153            sidecar_children,
154            context,
155            &expanded_node.parent_frame,
156        );
157        for child in sidecar_children.iter() {
158            child.recurse_control_flow_expansion(context);
159        }
160    }
161
162    fn handle_unmount(&self, expanded_node: &Rc<ExpandedNode>, context: &Rc<RuntimeContext>) {
163        let sidecar_children = std::mem::take(&mut *expanded_node.sidecar_children.borrow_mut());
164        for child in sidecar_children {
165            child.recurse_unmount(context);
166        }
167    }
168
169    fn resolve_debug(
170        &self,
171        f: &mut std::fmt::Formatter,
172        _expanded_node: Option<&ExpandedNode>,
173    ) -> std::fmt::Result {
174        f.debug_struct("ImportSettings").finish()
175    }
176
177    fn base(&self) -> &BaseInstance {
178        &self.base
179    }
180}