euv-core 0.47.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Convenience constructors for `SlotKey`.
impl SlotKey {
    /// Creates a `SlotKey` from a borrowed string slice.
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical slot identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed slot key.
    #[must_use]
    pub fn from_str_key(key: &str) -> Self {
        Self::new(key.to_string())
    }

    /// Formats the scoped slot identifier binding this logical slot under a specific route instance.
    ///
    /// # Arguments
    ///
    /// - `&str` - Normalized route path or route instance identifier.
    ///
    /// # Returns
    ///
    /// - `String` - Route-scoped slot key preventing cross-route version leakage.
    #[must_use]
    pub fn scoped_for_route(&self, route: &str) -> String {
        let normalized: String = normalize_dynamic_route(route);
        format!("{normalized}::{}", self.get_key())
    }
}

/// Telemetry inspection helpers on `DynamicFrameMetrics`.
impl DynamicFrameMetrics {
    /// Captures the current cumulative dynamic boundary counters.
    ///
    /// # Returns
    ///
    /// - `Self` - Snapshot of dynamic module calls, serializations, and manifest lookups.
    #[must_use]
    pub fn snapshot() -> Self {
        let calls: u64 = DYNAMIC_MODULE_CALL_COUNT.with(|c: &Cell<u64>| c.get());
        let serializations: u64 = DYNAMIC_SERIALIZATION_COUNT.with(|c: &Cell<u64>| c.get());
        let lookups: u64 = DYNAMIC_MANIFEST_LOOKUP_COUNT.with(|c: &Cell<u64>| c.get());
        Self::new(calls, serializations, lookups)
    }

    /// Computes the non-negative counter delta between `self` (after) and `before`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Earlier baseline snapshot.
    ///
    /// # Returns
    ///
    /// - `Self` - Delta occurred between `before` and `self`.
    #[must_use]
    pub fn delta_since(self, before: Self) -> Self {
        Self::new(
            self.get_dynamic_module_calls()
                .saturating_sub(before.get_dynamic_module_calls()),
            self.get_boundary_serializations()
                .saturating_sub(before.get_boundary_serializations()),
            self.get_manifest_lookups()
                .saturating_sub(before.get_manifest_lookups()),
        )
    }

    /// Records one dynamic module boundary invocation on the active UI thread.
    pub(crate) fn record_module_call() {
        DYNAMIC_MODULE_CALL_COUNT.with(|c: &Cell<u64>| c.set(c.get().saturating_add(1)));
    }

    /// Records one cross-boundary serialization/deserialization step on the active UI thread.
    pub(crate) fn record_serialization() {
        DYNAMIC_SERIALIZATION_COUNT.with(|c: &Cell<u64>| c.set(c.get().saturating_add(1)));
    }

    /// Records one manifest or slot-binding lookup on the active UI thread.
    pub(crate) fn record_manifest_lookup() {
        DYNAMIC_MANIFEST_LOOKUP_COUNT.with(|c: &Cell<u64>| c.set(c.get().saturating_add(1)));
    }
}

/// Reference strongly-typed dynamic component contract implementation for `ProductCardContract`.
impl DynamicComponentContract for ProductCardContract {
    type Props = ProductCardProps;
    type Event = ProductCardEvent;

    const INTERFACE_ID: &'static str = PRODUCT_CARD_INTERFACE_ID;
    const INTERFACE_VERSION: u32 = PRODUCT_CARD_INTERFACE_VERSION;
    const STATE_SCHEMA_VERSION: u32 = PRODUCT_CARD_STATE_SCHEMA_VERSION;

    /// Returns the WIT interface source for `euv:product-card/v1`.
    ///
    /// # Returns
    ///
    /// - `&'static str` - WIT interface text.
    fn wit_definition() -> &'static str {
        PRODUCT_CARD_WIT_DEF
    }

    /// Builds the compiled fallback `DynamicNodeSpec` for `ProductCardProps`.
    ///
    /// # Arguments
    ///
    /// - `&Self::Props` - Strongly-typed product card properties.
    ///
    /// # Returns
    ///
    /// - `DynamicNodeSpec` - Native fallback card tree.
    fn fallback_spec(props: &Self::Props) -> DynamicNodeSpec {
        let next_qty: u32 = props.get_quantity().saturating_add(1);
        let inc_payload: String =
            to_string(&ProductCardEvent::QuantityChanged { quantity: next_qty })
                .unwrap_or_default();
        let save_payload: String = to_string(&ProductCardEvent::SaveRequested {
            product_id: props.get_product_id().clone(),
            quantity: props.get_quantity(),
        })
        .unwrap_or_default();
        let mut inc_btn: DynamicNodeSpec = DynamicNodeSpec::button(
            PRODUCT_CARD_BTN_INC_LABEL.to_string(),
            format!("{TYPED_EVENT_ACTION_PREFIX}{PRODUCT_CARD_ACTION_INC}"),
        );
        inc_btn.set_payload(inc_payload);
        let mut save_btn: DynamicNodeSpec = DynamicNodeSpec::button(
            PRODUCT_CARD_BTN_SAVE_LABEL.to_string(),
            format!("{TYPED_EVENT_ACTION_PREFIX}{PRODUCT_CARD_ACTION_SAVE}"),
        );
        save_btn.set_payload(save_payload);
        DynamicNodeSpec::card(format!("Product {} (builtin)", props.get_product_id()))
            .child(DynamicNodeSpec::text(format!(
                "Quantity: {}",
                props.get_quantity()
            )))
            .child(DynamicNodeSpec::row().child(inc_btn).child(save_btn))
    }

    /// Decodes a `DynamicActionEvent` into a strongly-typed `ProductCardEvent`.
    ///
    /// # Arguments
    ///
    /// - `&DynamicActionEvent` - Incoming raw UI action.
    /// - `&Self::Props` - Active typed card properties.
    ///
    /// # Returns
    ///
    /// - `Option<Self::Event>` - Decoded strongly-typed event.
    fn decode_action(action: &DynamicActionEvent, props: &Self::Props) -> Option<Self::Event> {
        let act_name: &str = action.get_action().as_str();
        if act_name.starts_with(TYPED_EVENT_ACTION_PREFIX)
            && let Ok(parsed) = from_str::<ProductCardEvent>(action.get_payload())
        {
            return Some(parsed);
        }
        if act_name == PRODUCT_CARD_ACTION_INC {
            return Some(ProductCardEvent::QuantityChanged {
                quantity: props.get_quantity().saturating_add(1),
            });
        }
        if act_name == PRODUCT_CARD_ACTION_SAVE {
            return Some(ProductCardEvent::SaveRequested {
                product_id: props.get_product_id().clone(),
                quantity: props.get_quantity(),
            });
        }
        None
    }
}

/// Strongly-typed dynamic component mounting directly on `Context` (Sec 11.9).
impl Context {
    /// Mounts a compile-time strongly-typed dynamic component slot into the retained scene tree.
    ///
    /// Steady-state scrolling and rendering frames read directly from the retained `SceneTree`
    /// with zero dynamic module calls, zero boundary serialization, and zero manifest lookups.
    ///
    /// # Arguments
    ///
    /// - `SlotKey` - Logical instance slot position (may be route-scoped via `SlotKey::scoped_for_route`).
    /// - `C::Props` - Compile-time type-checked component properties.
    /// - `F` - Compile-time type-checked event handler closure receiving `C::Event`.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Mounted native scene node handle.
    pub fn mount_dynamic<C, F>(&mut self, slot_key: SlotKey, props: C::Props, on_event: F) -> NodeId
    where
        C: DynamicComponentContract,
        F: Fn(C::Event) + 'static,
    {
        let hub: DynamicUpdateHub = self.get_dynamic_hub().clone();
        let slot_id: String = slot_key.get_key().clone();
        let props_for_events: C::Props = props.clone();
        let slot_for_events: String = slot_id.clone();
        let handler_rc: Rc<dyn Fn(C::Event)> = Rc::new(on_event);
        hub.on_action(move |ev: &DynamicActionEvent| {
            if ev.get_source_id().as_str() == slot_for_events.as_str()
                && let Some(typed_event) = C::decode_action(ev, &props_for_events)
            {
                handler_rc(typed_event);
            }
        });
        let props_for_fallback: C::Props = props;
        let hub_for_fallback: DynamicUpdateHub = hub.clone();
        let slot_for_fallback: String = slot_id.clone();
        let mut slot: DynamicComponentSlot = DynamicComponentSlot::new(
            slot_id,
            Rc::new(move || {
                let spec: DynamicNodeSpec = C::fallback_spec(&props_for_fallback);
                mount_dynamic_spec(&spec, &slot_for_fallback, &hub_for_fallback)
            }),
        );
        slot.set_hub(Some(hub));
        slot.mount()
    }
}