1use crate::schema::*;
6
7#[derive(Debug, Clone)]
9pub struct ValidationError {
10 pub path: String,
11 pub message: String,
12}
13
14impl std::fmt::Display for ValidationError {
15 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16 write!(f, "{}: {}", self.path, self.message)
17 }
18}
19
20impl std::error::Error for ValidationError {}
21
22pub trait Validate {
24 fn validate(&self, path: &str) -> Vec<ValidationError>;
25}
26
27impl Validate for UiResponse {
28 fn validate(&self, path: &str) -> Vec<ValidationError> {
29 let mut errors = Vec::new();
30
31 if self.components.is_empty() {
32 errors.push(ValidationError {
33 path: path.to_string(),
34 message: "UiResponse must have at least one component".to_string(),
35 });
36 }
37
38 for (i, component) in self.components.iter().enumerate() {
39 errors.extend(component.validate(&format!("{}.components[{}]", path, i)));
40 }
41
42 errors
43 }
44}
45
46impl Validate for Text {
47 fn validate(&self, path: &str) -> Vec<ValidationError> {
48 let mut errors = Vec::new();
49 if self.content.is_empty() {
50 errors.push(ValidationError {
51 path: format!("{}.content", path),
52 message: "Text content cannot be empty".to_string(),
53 });
54 }
55 errors
56 }
57}
58
59impl Validate for Button {
60 fn validate(&self, path: &str) -> Vec<ValidationError> {
61 let mut errors = Vec::new();
62 if self.label.is_empty() {
63 errors.push(ValidationError {
64 path: format!("{}.label", path),
65 message: "Button label cannot be empty".to_string(),
66 });
67 }
68 if self.action_id.is_empty() {
69 errors.push(ValidationError {
70 path: format!("{}.action_id", path),
71 message: "Button action_id cannot be empty".to_string(),
72 });
73 }
74 errors
75 }
76}
77
78impl Validate for TextInput {
79 fn validate(&self, path: &str) -> Vec<ValidationError> {
80 let mut errors = Vec::new();
81 if self.name.is_empty() {
82 errors.push(ValidationError {
83 path: format!("{}.name", path),
84 message: "TextInput name cannot be empty".to_string(),
85 });
86 }
87 if let (Some(min), Some(max)) = (self.min_length, self.max_length)
88 && min > max
89 {
90 errors.push(ValidationError {
91 path: format!("{}.min_length", path),
92 message: "min_length cannot be greater than max_length".to_string(),
93 });
94 }
95 errors
96 }
97}
98
99impl Validate for NumberInput {
100 fn validate(&self, path: &str) -> Vec<ValidationError> {
101 let mut errors = Vec::new();
102 if self.name.is_empty() {
103 errors.push(ValidationError {
104 path: format!("{}.name", path),
105 message: "NumberInput name cannot be empty".to_string(),
106 });
107 }
108 if let (Some(min), Some(max)) = (self.min, self.max)
109 && min > max
110 {
111 errors.push(ValidationError {
112 path: format!("{}.min", path),
113 message: "min cannot be greater than max".to_string(),
114 });
115 }
116 errors
117 }
118}
119
120impl Validate for Select {
121 fn validate(&self, path: &str) -> Vec<ValidationError> {
122 let mut errors = Vec::new();
123 if self.name.is_empty() {
124 errors.push(ValidationError {
125 path: format!("{}.name", path),
126 message: "Select name cannot be empty".to_string(),
127 });
128 }
129 if self.options.is_empty() {
130 errors.push(ValidationError {
131 path: format!("{}.options", path),
132 message: "Select must have at least one option".to_string(),
133 });
134 }
135 errors
136 }
137}
138
139impl Validate for Table {
140 fn validate(&self, path: &str) -> Vec<ValidationError> {
141 let mut errors = Vec::new();
142 if self.columns.is_empty() {
143 errors.push(ValidationError {
144 path: format!("{}.columns", path),
145 message: "Table must have at least one column".to_string(),
146 });
147 }
148 errors
149 }
150}
151
152impl Validate for Chart {
153 fn validate(&self, path: &str) -> Vec<ValidationError> {
154 let mut errors = Vec::new();
155 if self.data.is_empty() {
156 errors.push(ValidationError {
157 path: format!("{}.data", path),
158 message: "Chart must have data".to_string(),
159 });
160 }
161 if self.y_keys.is_empty() {
162 errors.push(ValidationError {
163 path: format!("{}.y_keys", path),
164 message: "Chart must have at least one y_key".to_string(),
165 });
166 }
167 errors
168 }
169}
170
171impl Validate for Card {
172 fn validate(&self, path: &str) -> Vec<ValidationError> {
173 let mut errors = Vec::new();
174 for (i, child) in self.content.iter().enumerate() {
175 errors.extend(child.validate(&format!("{}.content[{}]", path, i)));
176 }
177 if let Some(footer) = &self.footer {
178 for (i, child) in footer.iter().enumerate() {
179 errors.extend(child.validate(&format!("{}.footer[{}]", path, i)));
180 }
181 }
182 errors
183 }
184}
185
186impl Validate for Modal {
187 fn validate(&self, path: &str) -> Vec<ValidationError> {
188 let mut errors = Vec::new();
189 for (i, child) in self.content.iter().enumerate() {
190 errors.extend(child.validate(&format!("{}.content[{}]", path, i)));
191 }
192 errors
193 }
194}
195
196impl Validate for Stack {
197 fn validate(&self, path: &str) -> Vec<ValidationError> {
198 let mut errors = Vec::new();
199 for (i, child) in self.children.iter().enumerate() {
200 errors.extend(child.validate(&format!("{}.children[{}]", path, i)));
201 }
202 errors
203 }
204}
205
206impl Validate for Grid {
207 fn validate(&self, path: &str) -> Vec<ValidationError> {
208 let mut errors = Vec::new();
209 for (i, child) in self.children.iter().enumerate() {
210 errors.extend(child.validate(&format!("{}.children[{}]", path, i)));
211 }
212 errors
213 }
214}
215
216impl Validate for Tabs {
217 fn validate(&self, path: &str) -> Vec<ValidationError> {
218 let mut errors = Vec::new();
219 if self.tabs.is_empty() {
220 errors.push(ValidationError {
221 path: format!("{}.tabs", path),
222 message: "Tabs must have at least one tab".to_string(),
223 });
224 }
225 errors
226 }
227}
228
229impl Validate for Scene3d {
230 fn validate(&self, path: &str) -> Vec<ValidationError> {
231 let mut errors = Vec::new();
232 if self.objects.is_empty() || self.objects.len() > 64 {
233 errors.push(ValidationError {
234 path: format!("{}.objects", path),
235 message: "Scene3d requires between 1 and 64 objects".to_string(),
236 });
237 }
238 if !(240..=960).contains(&self.height) {
239 errors.push(ValidationError {
240 path: format!("{}.height", path),
241 message: "Scene3d height must be between 240 and 960 pixels".to_string(),
242 });
243 }
244 if !(20.0..=90.0).contains(&self.camera.fov) {
245 errors.push(ValidationError {
246 path: format!("{}.camera.fov", path),
247 message: "Scene3d camera fov must be between 20 and 90 degrees".to_string(),
248 });
249 }
250 let model_count = self
251 .objects
252 .iter()
253 .filter(|object| matches!(object, SceneObject::Model(_)))
254 .count();
255 if model_count > 8 {
256 errors.push(ValidationError {
257 path: format!("{}.objects", path),
258 message: "Scene3d supports at most 8 model assets".to_string(),
259 });
260 }
261 for (index, object) in self.objects.iter().enumerate() {
262 let (id, scale) = match object {
263 SceneObject::Primitive(value) => (&value.id, value.scale),
264 SceneObject::Model(value) => {
265 if value.asset_id.trim().is_empty() || value.asset_id.contains(['/', '\\']) {
266 errors.push(ValidationError {
267 path: format!("{}.objects[{}].asset_id", path, index),
268 message: "model asset_id must reference one approved kit asset"
269 .to_string(),
270 });
271 }
272 (&value.id, value.scale)
273 }
274 };
275 if id.trim().is_empty() {
276 errors.push(ValidationError {
277 path: format!("{}.objects[{}].id", path, index),
278 message: "scene object id must not be empty".to_string(),
279 });
280 }
281 if scale
282 .iter()
283 .any(|value| !value.is_finite() || *value <= 0.0 || *value > 100.0)
284 {
285 errors.push(ValidationError {
286 path: format!("{}.objects[{}].scale", path, index),
287 message: "scene object scale values must be finite and between 0 and 100"
288 .to_string(),
289 });
290 }
291 }
292 errors
293 }
294}
295
296impl Validate for Component {
297 fn validate(&self, path: &str) -> Vec<ValidationError> {
298 match self {
299 Component::Text(t) => t.validate(path),
300 Component::Button(b) => b.validate(path),
301 Component::TextInput(t) => t.validate(path),
302 Component::NumberInput(n) => n.validate(path),
303 Component::Select(s) => s.validate(path),
304 Component::Table(t) => t.validate(path),
305 Component::Chart(c) => c.validate(path),
306 Component::Scene3d(scene) => scene.validate(path),
307 Component::Card(c) => c.validate(path),
308 Component::Modal(m) => m.validate(path),
309 Component::Stack(s) => s.validate(path),
310 Component::Grid(g) => g.validate(path),
311 Component::Tabs(t) => t.validate(path),
312 _ => Vec::new(),
314 }
315 }
316}
317
318pub fn validate_ui_response(ui: &UiResponse) -> Result<(), Vec<ValidationError>> {
320 let errors = ui.validate("UiResponse");
321 if errors.is_empty() {
322 Ok(())
323 } else {
324 Err(errors)
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn test_empty_response_fails() {
334 let ui = UiResponse::new(vec![]);
335 let result = validate_ui_response(&ui);
336 assert!(result.is_err());
337 }
338
339 #[test]
340 fn test_valid_text_passes() {
341 let ui = UiResponse::new(vec![Component::Text(Text {
342 id: None,
343 content: "Hello".to_string(),
344 variant: TextVariant::Body,
345 })]);
346 let result = validate_ui_response(&ui);
347 assert!(result.is_ok());
348 }
349
350 #[test]
351 fn test_empty_button_label_fails() {
352 let ui = UiResponse::new(vec![Component::Button(Button {
353 id: None,
354 label: "".to_string(),
355 action_id: "click".to_string(),
356 variant: ButtonVariant::Primary,
357 disabled: false,
358 icon: None,
359 })]);
360 let result = validate_ui_response(&ui);
361 assert!(result.is_err());
362 }
363
364 #[test]
365 fn test_scene_3d_enforces_object_budget_and_height() {
366 let ui = UiResponse::new(vec![Component::Scene3d(Scene3d {
367 id: Some("network".to_string()),
368 title: Some("Network".to_string()),
369 description: None,
370 height: 120,
371 background: SceneBackground::Surface,
372 camera: SceneCamera::default(),
373 objects: vec![],
374 auto_rotate: false,
375 controls: true,
376 fallback: Some("Use the table view.".to_string()),
377 })]);
378 let errors = validate_ui_response(&ui).expect_err("invalid scene should fail");
379 assert!(errors.iter().any(|error| error.path.ends_with(".objects")));
380 assert!(errors.iter().any(|error| error.path.ends_with(".height")));
381 }
382}