Skip to main content

hypen_engine/reconcile/
patch.rs

1use crate::ir::NodeId;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::HashMap;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::Mutex;
7
8/// Monotonic counter for compact, stable node-ID serialization.
9static NEXT_ID: AtomicU64 = AtomicU64::new(1);
10
11/// Maps SlotMap `NodeId` keys to compact integer strings.
12/// Once a NodeId is assigned a string, it keeps it for the lifetime of the
13/// process.  This avoids depending on slotmap's `Debug` output format.
14static NODE_ID_MAP: Mutex<Option<HashMap<NodeId, String>>> = Mutex::new(None);
15
16/// Stable, compact serialization for NodeId.
17///
18/// Returns a short numeric string (e.g. `"1"`, `"42"`) instead of the
19/// previous `"NodeId(0v1)"` Debug format.  The mapping is deterministic
20/// per NodeId for the lifetime of the process.
21///
22/// # Stability
23///
24/// This is an internal implementation detail. External consumers should
25/// treat node ID strings in patches as opaque identifiers.
26#[doc(hidden)]
27#[inline]
28pub fn node_id_str(id: NodeId) -> String {
29    let mut guard = NODE_ID_MAP.lock().unwrap();
30    let map = guard.get_or_insert_with(HashMap::new);
31    map.entry(id)
32        .or_insert_with(|| NEXT_ID.fetch_add(1, Ordering::Relaxed).to_string())
33        .clone()
34}
35
36/// Platform-agnostic patch operations for updating the UI.
37///
38/// Patches are the **wire protocol** between the Hypen engine and platform
39/// renderers (DOM, Canvas, iOS UIKit, Android Views). Every mutation to the
40/// UI tree is expressed as an ordered sequence of `Patch` values.
41///
42/// # Serialization
43///
44/// Patches serialize to JSON with a `"type"` discriminator and **camelCase**
45/// field names for direct JavaScript consumption:
46///
47/// ```json
48/// {"type": "create", "id": "1", "elementType": "Text", "props": {"0": "Hello"}}
49/// {"type": "insert", "parentId": "root", "id": "1", "beforeId": null}
50/// ```
51///
52/// # Node IDs
53///
54/// Node IDs are opaque string identifiers (currently compact integers like
55/// `"1"`, `"42"`). Renderers must treat them as opaque — the format may
56/// change between versions. The special parent ID `"root"` refers to the
57/// renderer's root container.
58///
59/// # Ordering
60///
61/// Within a single render cycle, patches are ordered such that:
62/// 1. `Create` always precedes `Insert` for the same node
63/// 2. `SetProp`/`SetText` follow `Create` for new nodes
64/// 3. `Remove` is always the last operation for a given node
65/// 4. `Insert`/`Move` specify position via `before_id` (`None` = append)
66#[derive(Debug, Clone, Serialize, Deserialize)]
67#[serde(tag = "type", rename_all = "camelCase")]
68pub enum Patch {
69    /// Create a new element node with initial properties.
70    ///
71    /// The renderer should allocate a platform-native element and store it by
72    /// `id`. The node is not yet visible — a subsequent `Insert` attaches it.
73    #[serde(rename_all = "camelCase")]
74    Create {
75        /// Opaque node identifier
76        id: String,
77        /// Element type name (e.g. `"Text"`, `"Column"`, `"Button"`)
78        element_type: String,
79        /// Initial properties. Key `"0"` is the positional text content.
80        props: indexmap::IndexMap<String, Value>,
81    },
82
83    /// Update a single property on an existing node.
84    #[serde(rename_all = "camelCase")]
85    SetProp {
86        id: String,
87        /// Property name (e.g. `"color"`, `"fontSize"`)
88        name: String,
89        /// New value
90        value: Value,
91    },
92
93    /// Remove a property from an existing node (revert to default).
94    #[serde(rename_all = "camelCase")]
95    RemoveProp {
96        id: String,
97        /// Property name to remove
98        name: String,
99    },
100
101    /// Set the text content of a node.
102    #[serde(rename_all = "camelCase")]
103    SetText {
104        id: String,
105        /// New text content
106        text: String,
107    },
108
109    /// Insert a node as a child of `parent_id`.
110    ///
111    /// If `before_id` is `Some`, insert before that sibling. If `None`, append.
112    #[serde(rename_all = "camelCase")]
113    Insert {
114        /// Parent node ID, or `"root"` for the root container
115        parent_id: String,
116        id: String,
117        /// Insert before this sibling, or `null` to append
118        before_id: Option<String>,
119    },
120
121    /// Move an already-inserted node to a new position within its parent.
122    #[serde(rename_all = "camelCase")]
123    Move {
124        parent_id: String,
125        id: String,
126        before_id: Option<String>,
127    },
128
129    /// Remove a node from the tree and deallocate it.
130    #[serde(rename_all = "camelCase")]
131    Remove { id: String },
132}
133
134impl Patch {
135    pub fn create(
136        id: NodeId,
137        element_type: String,
138        props: indexmap::IndexMap<String, Value>,
139    ) -> Self {
140        Self::Create {
141            id: node_id_str(id),
142            element_type,
143            props,
144        }
145    }
146
147    pub fn set_prop(id: NodeId, name: String, value: Value) -> Self {
148        Self::SetProp {
149            id: node_id_str(id),
150            name,
151            value,
152        }
153    }
154
155    pub fn remove_prop(id: NodeId, name: String) -> Self {
156        Self::RemoveProp {
157            id: node_id_str(id),
158            name,
159        }
160    }
161
162    pub fn set_text(id: NodeId, text: String) -> Self {
163        Self::SetText {
164            id: node_id_str(id),
165            text,
166        }
167    }
168
169    pub fn insert(parent_id: NodeId, id: NodeId, before_id: Option<NodeId>) -> Self {
170        Self::Insert {
171            parent_id: node_id_str(parent_id),
172            id: node_id_str(id),
173            before_id: before_id.map(node_id_str),
174        }
175    }
176
177    /// Insert a root node into the "root" container
178    pub fn insert_root(id: NodeId) -> Self {
179        Self::Insert {
180            parent_id: "root".to_string(),
181            id: node_id_str(id),
182            before_id: None,
183        }
184    }
185
186    pub fn move_node(parent_id: NodeId, id: NodeId, before_id: Option<NodeId>) -> Self {
187        Self::Move {
188            parent_id: node_id_str(parent_id),
189            id: node_id_str(id),
190            before_id: before_id.map(node_id_str),
191        }
192    }
193
194    pub fn remove(id: NodeId) -> Self {
195        Self::Remove {
196            id: node_id_str(id),
197        }
198    }
199}