1use crate::{UiDocument, UiGraphError, UiNode};
4use serde::{Deserialize, Serialize};
5
6#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
7#[serde(tag = "op", rename_all = "kebab-case", deny_unknown_fields)]
8pub enum UiGraphEdit {
9 Insert {
10 parent: String,
11 index: usize,
12 node: UiNode,
13 },
14 Remove {
15 id: String,
16 },
17 Replace {
18 id: String,
19 node: UiNode,
20 },
21 Move {
22 id: String,
23 parent: String,
24 index: usize,
25 },
26 SetProperty {
29 id: String,
30 property: String,
31 value: serde_json::Value,
32 },
33 UnsetProperty {
35 id: String,
36 property: String,
37 },
38}
39
40impl UiDocument {
41 pub fn apply_edit(&mut self, edit: UiGraphEdit) -> Result<(), UiGraphError> {
43 match edit {
44 UiGraphEdit::Insert {
45 parent,
46 index,
47 node,
48 } => self.insert_child(&parent, index, node),
49 UiGraphEdit::Remove { id } => {
50 let _ = self.remove_node(&id)?;
51 Ok(())
52 }
53 UiGraphEdit::Replace { id, node } => self.replace_node(&id, node),
54 UiGraphEdit::Move { id, parent, index } => self.move_node(&id, &parent, index),
55 UiGraphEdit::SetProperty {
56 id,
57 property,
58 value,
59 } => self.set_property(&id, &property, Some(value)),
60 UiGraphEdit::UnsetProperty { id, property } => self.set_property(&id, &property, None),
61 }
62 }
63
64 pub fn apply_edits(&mut self, edits: Vec<UiGraphEdit>) -> Result<(), UiGraphError> {
66 if edits.is_empty() {
67 return Err(UiGraphError::EmptyEditBatch);
68 }
69 let mut candidate = self.clone();
70 for (index, edit) in edits.into_iter().enumerate() {
71 candidate
72 .apply_edit(edit)
73 .map_err(|error| UiGraphError::EditFailed {
74 index: index.saturating_add(1),
75 message: error.to_string(),
76 })?;
77 }
78 candidate.validate()?;
79 *self = candidate;
80 Ok(())
81 }
82
83 pub fn set_property(
85 &mut self,
86 id: &str,
87 property: &str,
88 value: Option<serde_json::Value>,
89 ) -> Result<(), UiGraphError> {
90 let node = self
91 .node(id)
92 .cloned()
93 .ok_or_else(|| UiGraphError::UnknownNode(id.to_owned()))?;
94 let segments: Vec<_> = property.split('.').collect();
95 if segments.is_empty() || segments.iter().any(|segment| segment.is_empty()) {
96 return Err(UiGraphError::InvalidPropertyPath {
97 id: id.to_owned(),
98 property: property.to_owned(),
99 });
100 }
101 let mut serialized = serde_json::to_value(node)?;
102 let Some((leaf, parents)) = segments.split_last() else {
103 return Err(UiGraphError::InvalidPropertyPath {
104 id: id.to_owned(),
105 property: property.to_owned(),
106 });
107 };
108 let mut current = &mut serialized;
109 for segment in parents {
110 current = current
111 .as_object_mut()
112 .and_then(|object| object.get_mut(*segment))
113 .ok_or_else(|| UiGraphError::InvalidPropertyPath {
114 id: id.to_owned(),
115 property: property.to_owned(),
116 })?;
117 }
118 let object = current
119 .as_object_mut()
120 .ok_or_else(|| UiGraphError::InvalidPropertyPath {
121 id: id.to_owned(),
122 property: property.to_owned(),
123 })?;
124 if let Some(value) = value {
125 object.insert((*leaf).to_owned(), value);
126 } else if object.remove(*leaf).is_none() {
127 return Err(UiGraphError::UnknownProperty {
128 id: id.to_owned(),
129 property: property.to_owned(),
130 });
131 }
132 let replacement: UiNode = serde_json::from_value(serialized).map_err(|error| {
133 UiGraphError::InvalidPropertyValue {
134 id: id.to_owned(),
135 property: property.to_owned(),
136 message: error.to_string(),
137 }
138 })?;
139 self.replace_node(id, replacement)
140 }
141}
142
143pub fn parse_ui_graph_edits(source: &str) -> Result<Vec<UiGraphEdit>, UiGraphError> {
149 let edits: Vec<UiGraphEdit> = serde_json::from_str(source)?;
150 if edits.is_empty() {
151 return Err(UiGraphError::EmptyEditBatch);
152 }
153 Ok(edits)
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use crate::{UiTextRole, UiTextSource};
160
161 fn sample() -> UiDocument {
162 UiDocument::new(UiNode::Column {
163 id: "root".into(),
164 children: vec![UiNode::Text {
165 id: "title".into(),
166 text: UiTextSource::Static {
167 value: "Hello".into(),
168 },
169 role: UiTextRole::Title,
170 }],
171 gap: None,
172 no_padding: false,
173 intrinsic_height: false,
174 fill_remaining_height: false,
175 })
176 }
177
178 #[test]
179 fn set_property_and_batch_are_atomic() {
180 let mut document = sample();
181 document
182 .set_property("title", "text.value", Some(serde_json::json!("Projects")))
183 .unwrap();
184 assert!(matches!(
185 document.node("title"),
186 Some(UiNode::Text {
187 text: UiTextSource::Static { value },
188 ..
189 }) if value == "Projects"
190 ));
191
192 let before = document.clone();
193 let error = document
194 .apply_edits(vec![
195 UiGraphEdit::SetProperty {
196 id: "title".into(),
197 property: "text.value".into(),
198 value: serde_json::json!("Recent"),
199 },
200 UiGraphEdit::SetProperty {
201 id: "missing".into(),
202 property: "text.value".into(),
203 value: serde_json::json!("x"),
204 },
205 ])
206 .unwrap_err();
207 assert!(matches!(error, UiGraphError::EditFailed { index: 2, .. }));
208 assert_eq!(document, before);
209 }
210}