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