hypen-engine 0.4.81

A Rust implementation of the Hypen engine
Documentation
use crate::ir::NodeId;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;

/// Monotonic counter for compact, stable node-ID serialization.
static NEXT_ID: AtomicU64 = AtomicU64::new(1);

/// Maps SlotMap `NodeId` keys to compact integer strings.
/// Once a NodeId is assigned a string, it keeps it for the lifetime of the
/// process.  This avoids depending on slotmap's `Debug` output format.
static NODE_ID_MAP: Mutex<Option<HashMap<NodeId, String>>> = Mutex::new(None);

/// Stable, compact serialization for NodeId.
///
/// Returns a short numeric string (e.g. `"1"`, `"42"`) instead of the
/// previous `"NodeId(0v1)"` Debug format.  The mapping is deterministic
/// per NodeId for the lifetime of the process.
///
/// # Stability
///
/// This is an internal implementation detail. External consumers should
/// treat node ID strings in patches as opaque identifiers.
#[doc(hidden)]
#[inline]
pub fn node_id_str(id: NodeId) -> String {
    let mut guard = NODE_ID_MAP.lock().unwrap();
    let map = guard.get_or_insert_with(HashMap::new);
    map.entry(id)
        .or_insert_with(|| NEXT_ID.fetch_add(1, Ordering::Relaxed).to_string())
        .clone()
}

/// Platform-agnostic patch operations for updating the UI.
///
/// Patches are the **wire protocol** between the Hypen engine and platform
/// renderers (DOM, Canvas, iOS UIKit, Android Views). Every mutation to the
/// UI tree is expressed as an ordered sequence of `Patch` values.
///
/// # Serialization
///
/// Patches serialize to JSON with a `"type"` discriminator and **camelCase**
/// field names for direct JavaScript consumption:
///
/// ```json
/// {"type": "create", "id": "1", "elementType": "Text", "props": {"0": "Hello"}}
/// {"type": "insert", "parentId": "root", "id": "1", "beforeId": null}
/// ```
///
/// # Node IDs
///
/// Node IDs are opaque string identifiers (currently compact integers like
/// `"1"`, `"42"`). Renderers must treat them as opaque — the format may
/// change between versions. The special parent ID `"root"` refers to the
/// renderer's root container.
///
/// # Ordering
///
/// Within a single render cycle, patches are ordered such that:
/// 1. `Create` always precedes `Insert` for the same node
/// 2. `SetProp`/`SetText` follow `Create` for new nodes
/// 3. `Remove` is always the last operation for a given node
/// 4. `Insert`/`Move` specify position via `before_id` (`None` = append)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Patch {
    /// Create a new element node with initial properties.
    ///
    /// The renderer should allocate a platform-native element and store it by
    /// `id`. The node is not yet visible — a subsequent `Insert` attaches it.
    #[serde(rename_all = "camelCase")]
    Create {
        /// Opaque node identifier
        id: String,
        /// Element type name (e.g. `"Text"`, `"Column"`, `"Button"`)
        element_type: String,
        /// Initial properties. Key `"0"` is the positional text content.
        props: indexmap::IndexMap<String, Value>,
    },

    /// Update a single property on an existing node.
    #[serde(rename_all = "camelCase")]
    SetProp {
        id: String,
        /// Property name (e.g. `"color"`, `"fontSize"`)
        name: String,
        /// New value
        value: Value,
    },

    /// Remove a property from an existing node (revert to default).
    #[serde(rename_all = "camelCase")]
    RemoveProp {
        id: String,
        /// Property name to remove
        name: String,
    },

    /// Set the text content of a node.
    ///
    /// **Reserved for future use — not currently emitted by the engine.**
    /// The reconciler represents text changes as `SetProp { name: "0", ... }`
    /// (the positional content slot), so no production code path constructs
    /// a `SetText` patch today. Renderers must still handle this variant for
    /// forward compatibility; removing it would break the wire format.
    #[serde(rename_all = "camelCase")]
    SetText {
        id: String,
        /// New text content
        text: String,
    },

    /// Insert a node as a child of `parent_id`.
    ///
    /// If `before_id` is `Some`, insert before that sibling. If `None`, append.
    #[serde(rename_all = "camelCase")]
    Insert {
        /// Parent node ID, or `"root"` for the root container
        parent_id: String,
        id: String,
        /// Insert before this sibling, or `null` to append
        before_id: Option<String>,
    },

    /// Move an already-inserted node to a new position within its parent.
    #[serde(rename_all = "camelCase")]
    Move {
        parent_id: String,
        id: String,
        before_id: Option<String>,
    },

    /// Remove a node from the tree and deallocate it.
    #[serde(rename_all = "camelCase")]
    Remove { id: String },
}

impl Patch {
    pub fn create(
        id: NodeId,
        element_type: String,
        props: indexmap::IndexMap<String, Value>,
    ) -> Self {
        Self::Create {
            id: node_id_str(id),
            element_type,
            props,
        }
    }

    pub fn set_prop(id: NodeId, name: String, value: Value) -> Self {
        Self::SetProp {
            id: node_id_str(id),
            name,
            value,
        }
    }

    pub fn remove_prop(id: NodeId, name: String) -> Self {
        Self::RemoveProp {
            id: node_id_str(id),
            name,
        }
    }

    pub fn set_text(id: NodeId, text: String) -> Self {
        Self::SetText {
            id: node_id_str(id),
            text,
        }
    }

    pub fn insert(parent_id: NodeId, id: NodeId, before_id: Option<NodeId>) -> Self {
        Self::Insert {
            parent_id: node_id_str(parent_id),
            id: node_id_str(id),
            before_id: before_id.map(node_id_str),
        }
    }

    /// Insert a root node into the "root" container
    pub fn insert_root(id: NodeId) -> Self {
        Self::Insert {
            parent_id: "root".to_string(),
            id: node_id_str(id),
            before_id: None,
        }
    }

    pub fn move_node(parent_id: NodeId, id: NodeId, before_id: Option<NodeId>) -> Self {
        Self::Move {
            parent_id: node_id_str(parent_id),
            id: node_id_str(id),
            before_id: before_id.map(node_id_str),
        }
    }

    pub fn remove(id: NodeId) -> Self {
        Self::Remove {
            id: node_id_str(id),
        }
    }
}