Skip to main content

euv_core/dynamic/contract/
impl.rs

1use super::*;
2
3/// Convenience constructors for `SlotKey`.
4impl SlotKey {
5    /// Creates a `SlotKey` from a borrowed string slice.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - Logical slot identifier.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Constructed slot key.
14    #[must_use]
15    pub fn from_str_key(key: &str) -> Self {
16        Self::new(key.to_string())
17    }
18
19    /// Formats the scoped slot identifier binding this logical slot under a specific route instance.
20    ///
21    /// # Arguments
22    ///
23    /// - `&str` - Normalized route path or route instance identifier.
24    ///
25    /// # Returns
26    ///
27    /// - `String` - Route-scoped slot key preventing cross-route version leakage.
28    #[must_use]
29    pub fn scoped_for_route(&self, route: &str) -> String {
30        let normalized: String = normalize_dynamic_route(route);
31        format!("{normalized}::{}", self.get_key())
32    }
33}
34
35/// Telemetry inspection helpers on `DynamicFrameMetrics`.
36impl DynamicFrameMetrics {
37    /// Captures the current cumulative dynamic boundary counters.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - Snapshot of dynamic module calls, serializations, and manifest lookups.
42    #[must_use]
43    pub fn snapshot() -> Self {
44        let calls: u64 = DYNAMIC_MODULE_CALL_COUNT.with(|c: &Cell<u64>| c.get());
45        let serializations: u64 = DYNAMIC_SERIALIZATION_COUNT.with(|c: &Cell<u64>| c.get());
46        let lookups: u64 = DYNAMIC_MANIFEST_LOOKUP_COUNT.with(|c: &Cell<u64>| c.get());
47        Self::new(calls, serializations, lookups)
48    }
49
50    /// Computes the non-negative counter delta between `self` (after) and `before`.
51    ///
52    /// # Arguments
53    ///
54    /// - `Self` - Earlier baseline snapshot.
55    ///
56    /// # Returns
57    ///
58    /// - `Self` - Delta occurred between `before` and `self`.
59    #[must_use]
60    pub fn delta_since(self, before: Self) -> Self {
61        Self::new(
62            self.get_dynamic_module_calls()
63                .saturating_sub(before.get_dynamic_module_calls()),
64            self.get_boundary_serializations()
65                .saturating_sub(before.get_boundary_serializations()),
66            self.get_manifest_lookups()
67                .saturating_sub(before.get_manifest_lookups()),
68        )
69    }
70
71    /// Records one dynamic module boundary invocation on the active UI thread.
72    pub(crate) fn record_module_call() {
73        DYNAMIC_MODULE_CALL_COUNT.with(|c: &Cell<u64>| c.set(c.get().saturating_add(1)));
74    }
75
76    /// Records one cross-boundary serialization/deserialization step on the active UI thread.
77    pub(crate) fn record_serialization() {
78        DYNAMIC_SERIALIZATION_COUNT.with(|c: &Cell<u64>| c.set(c.get().saturating_add(1)));
79    }
80
81    /// Records one manifest or slot-binding lookup on the active UI thread.
82    pub(crate) fn record_manifest_lookup() {
83        DYNAMIC_MANIFEST_LOOKUP_COUNT.with(|c: &Cell<u64>| c.set(c.get().saturating_add(1)));
84    }
85}
86
87/// Reference strongly-typed dynamic component contract implementation for `ProductCardContract`.
88impl DynamicComponentContract for ProductCardContract {
89    type Props = ProductCardProps;
90    type Event = ProductCardEvent;
91
92    const INTERFACE_ID: &'static str = PRODUCT_CARD_INTERFACE_ID;
93    const INTERFACE_VERSION: u32 = PRODUCT_CARD_INTERFACE_VERSION;
94    const STATE_SCHEMA_VERSION: u32 = PRODUCT_CARD_STATE_SCHEMA_VERSION;
95
96    /// Returns the WIT interface source for `euv:product-card/v1`.
97    ///
98    /// # Returns
99    ///
100    /// - `&'static str` - WIT interface text.
101    fn wit_definition() -> &'static str {
102        PRODUCT_CARD_WIT_DEF
103    }
104
105    /// Builds the compiled fallback `DynamicNodeSpec` for `ProductCardProps`.
106    ///
107    /// # Arguments
108    ///
109    /// - `&Self::Props` - Strongly-typed product card properties.
110    ///
111    /// # Returns
112    ///
113    /// - `DynamicNodeSpec` - Native fallback card tree.
114    fn fallback_spec(props: &Self::Props) -> DynamicNodeSpec {
115        let next_qty: u32 = props.get_quantity().saturating_add(1);
116        let inc_payload: String =
117            to_string(&ProductCardEvent::QuantityChanged { quantity: next_qty })
118                .unwrap_or_default();
119        let save_payload: String = to_string(&ProductCardEvent::SaveRequested {
120            product_id: props.get_product_id().clone(),
121            quantity: props.get_quantity(),
122        })
123        .unwrap_or_default();
124        let mut inc_btn: DynamicNodeSpec = DynamicNodeSpec::button(
125            PRODUCT_CARD_BTN_INC_LABEL.to_string(),
126            format!("{TYPED_EVENT_ACTION_PREFIX}{PRODUCT_CARD_ACTION_INC}"),
127        );
128        inc_btn.set_payload(inc_payload);
129        let mut save_btn: DynamicNodeSpec = DynamicNodeSpec::button(
130            PRODUCT_CARD_BTN_SAVE_LABEL.to_string(),
131            format!("{TYPED_EVENT_ACTION_PREFIX}{PRODUCT_CARD_ACTION_SAVE}"),
132        );
133        save_btn.set_payload(save_payload);
134        DynamicNodeSpec::card(format!("Product {} (builtin)", props.get_product_id()))
135            .child(DynamicNodeSpec::text(format!(
136                "Quantity: {}",
137                props.get_quantity()
138            )))
139            .child(DynamicNodeSpec::row().child(inc_btn).child(save_btn))
140    }
141
142    /// Decodes a `DynamicActionEvent` into a strongly-typed `ProductCardEvent`.
143    ///
144    /// # Arguments
145    ///
146    /// - `&DynamicActionEvent` - Incoming raw UI action.
147    /// - `&Self::Props` - Active typed card properties.
148    ///
149    /// # Returns
150    ///
151    /// - `Option<Self::Event>` - Decoded strongly-typed event.
152    fn decode_action(action: &DynamicActionEvent, props: &Self::Props) -> Option<Self::Event> {
153        let act_name: &str = action.get_action().as_str();
154        if act_name.starts_with(TYPED_EVENT_ACTION_PREFIX)
155            && let Ok(parsed) = from_str::<ProductCardEvent>(action.get_payload())
156        {
157            return Some(parsed);
158        }
159        if act_name == PRODUCT_CARD_ACTION_INC {
160            return Some(ProductCardEvent::QuantityChanged {
161                quantity: props.get_quantity().saturating_add(1),
162            });
163        }
164        if act_name == PRODUCT_CARD_ACTION_SAVE {
165            return Some(ProductCardEvent::SaveRequested {
166                product_id: props.get_product_id().clone(),
167                quantity: props.get_quantity(),
168            });
169        }
170        None
171    }
172}
173
174/// Strongly-typed dynamic component mounting directly on `Context` (Sec 11.9).
175impl Context {
176    /// Mounts a compile-time strongly-typed dynamic component slot into the retained scene tree.
177    ///
178    /// Steady-state scrolling and rendering frames read directly from the retained `SceneTree`
179    /// with zero dynamic module calls, zero boundary serialization, and zero manifest lookups.
180    ///
181    /// # Arguments
182    ///
183    /// - `SlotKey` - Logical instance slot position (may be route-scoped via `SlotKey::scoped_for_route`).
184    /// - `C::Props` - Compile-time type-checked component properties.
185    /// - `F` - Compile-time type-checked event handler closure receiving `C::Event`.
186    ///
187    /// # Returns
188    ///
189    /// - `NodeId` - Mounted native scene node handle.
190    pub fn mount_dynamic<C, F>(&mut self, slot_key: SlotKey, props: C::Props, on_event: F) -> NodeId
191    where
192        C: DynamicComponentContract,
193        F: Fn(C::Event) + 'static,
194    {
195        let hub: DynamicUpdateHub = self.get_dynamic_hub().clone();
196        let slot_id: String = slot_key.get_key().clone();
197        let props_for_events: C::Props = props.clone();
198        let slot_for_events: String = slot_id.clone();
199        let handler_rc: DynamicEventHandler<C::Event> = Rc::new(on_event);
200        hub.on_action(move |ev: &DynamicActionEvent| {
201            if ev.get_source_id().as_str() == slot_for_events.as_str()
202                && let Some(typed_event) = C::decode_action(ev, &props_for_events)
203            {
204                handler_rc(typed_event);
205            }
206        });
207        let props_for_fallback: C::Props = props;
208        let hub_for_fallback: DynamicUpdateHub = hub.clone();
209        let slot_for_fallback: String = slot_id.clone();
210        let mut slot: DynamicComponentSlot = DynamicComponentSlot::new(
211            slot_id,
212            Rc::new(move || {
213                let spec: DynamicNodeSpec = C::fallback_spec(&props_for_fallback);
214                mount_dynamic_spec(&spec, &slot_for_fallback, &hub_for_fallback)
215            }),
216        );
217        slot.set_hub(Some(hub));
218        slot.mount()
219    }
220}