ferro-json-ui 0.2.20

JSON-based server-driven UI schema types for Ferro
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Top-level view container for JSON-UI.
//!
//! A `JsonUiView` is the root structure that defines a complete page.
//! It contains the schema version, optional layout and title, and the
//! component tree. Views can be built programmatically or parsed from JSON.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::component::ComponentNode;

/// Schema version identifier for JSON-UI views.
pub const SCHEMA_VERSION: &str = "ferro-json-ui/v1";

/// Top-level JSON-UI view container.
///
/// Every JSON-UI response is a `JsonUiView` containing a component tree.
/// The `$schema` field identifies the schema version for compatibility.
///
/// # Example
///
/// ```rust
/// use ferro_json_ui::JsonUiView;
///
/// let view = JsonUiView::new()
///     .title("Dashboard")
///     .layout("app");
///
/// let json = view.to_json().unwrap();
/// assert!(json.contains("ferro-json-ui/v1"));
/// ```
// JsonSchema skipped: contains Vec<ComponentNode> — Component has custom Serialize/Deserialize
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonUiView {
    #[serde(rename = "$schema")]
    pub schema: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layout: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
    pub data: serde_json::Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub errors: Option<HashMap<String, Vec<String>>>,
    pub components: Vec<ComponentNode>,
}

impl JsonUiView {
    /// Create a new view with the current schema version and empty components.
    pub fn new() -> Self {
        Self {
            schema: SCHEMA_VERSION.to_string(),
            layout: None,
            title: None,
            data: serde_json::Value::Null,
            errors: None,
            components: vec![],
        }
    }

    /// Set the view title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the view data payload.
    pub fn data(mut self, data: serde_json::Value) -> Self {
        self.data = data;
        self
    }

    /// Set the validation errors map.
    pub fn errors(mut self, errors: HashMap<String, Vec<String>>) -> Self {
        self.errors = Some(errors);
        self
    }

    /// Set the layout name.
    pub fn layout(mut self, layout: impl Into<String>) -> Self {
        self.layout = Some(layout.into());
        self
    }

    /// Add a single component to the view.
    pub fn component(mut self, node: ComponentNode) -> Self {
        self.components.push(node);
        self
    }

    /// Set all components at once, replacing any existing.
    pub fn components(mut self, nodes: Vec<ComponentNode>) -> Self {
        self.components = nodes;
        self
    }

    /// Parse a view from a JSON string.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Serialize the view to a compact JSON string.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Serialize the view to a pretty-printed JSON string.
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

impl Default for JsonUiView {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::action::{Action, HttpMethod};
    use crate::component::*;
    use crate::visibility::{Visibility, VisibilityCondition, VisibilityOperator};

    #[test]
    fn schema_field_serializes_as_dollar_schema() {
        let view = JsonUiView::new();
        let json = serde_json::to_value(&view).unwrap();
        assert_eq!(json["$schema"], "ferro-json-ui/v1");
        assert!(json.get("schema").is_none());
    }

    #[test]
    fn builder_produces_valid_json() {
        let view = JsonUiView::new()
            .title("Users")
            .layout("app")
            .component(ComponentNode {
                key: "header".to_string(),
                component: Component::Card(CardProps {
                    title: "User Management".to_string(),
                    description: None,
                    children: vec![],
                    footer: vec![],
                    max_width: None,
                }),
                action: None,
                visibility: None,
            });

        let json = view.to_json().unwrap();
        assert!(json.contains("\"$schema\":\"ferro-json-ui/v1\""));
        assert!(json.contains("\"title\":\"Users\""));
        assert!(json.contains("\"layout\":\"app\""));
        assert!(json.contains("\"type\":\"Card\""));
    }

    #[test]
    fn round_trip_build_to_json_from_json() {
        let original = JsonUiView::new()
            .title("Dashboard")
            .layout("app")
            .component(ComponentNode {
                key: "alert".to_string(),
                component: Component::Alert(AlertProps {
                    message: "Welcome".to_string(),
                    variant: AlertVariant::Success,
                    title: None,
                }),
                action: None,
                visibility: None,
            })
            .component(ComponentNode {
                key: "content".to_string(),
                component: Component::Text(TextProps {
                    content: "Hello world".to_string(),
                    element: TextElement::H1,
                }),
                action: None,
                visibility: None,
            });

        let json = original.to_json().unwrap();
        let parsed = JsonUiView::from_json(&json).unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn from_json_full_example() {
        // Based on the research doc example
        let json = r#"{
            "$schema": "ferro-json-ui/v1",
            "layout": "app",
            "title": "Users",
            "components": [
                {
                    "key": "header",
                    "type": "Card",
                    "title": "User Management",
                    "children": [
                        {
                            "key": "create-btn",
                            "type": "Button",
                            "label": "Create User",
                            "variant": "default",
                            "action": {
                                "handler": "users.create",
                                "method": "POST"
                            }
                        }
                    ]
                },
                {
                    "key": "users-table",
                    "type": "Table",
                    "columns": [
                        {"key": "name", "label": "Name"},
                        {"key": "email", "label": "Email"},
                        {"key": "created_at", "label": "Created", "format": "date"}
                    ],
                    "data_path": "/data/users",
                    "visibility": {
                        "path": "/data/users",
                        "operator": "not_empty"
                    }
                }
            ]
        }"#;
        let view = JsonUiView::from_json(json).unwrap();
        assert_eq!(view.schema, "ferro-json-ui/v1");
        assert_eq!(view.title.as_deref(), Some("Users"));
        assert_eq!(view.layout.as_deref(), Some("app"));
        assert_eq!(view.components.len(), 2);

        // Verify first component is a Card
        assert_eq!(view.components[0].key, "header");
        match &view.components[0].component {
            Component::Card(props) => {
                assert_eq!(props.title, "User Management");
                assert_eq!(props.children.len(), 1);
                // Verify nested button
                match &props.children[0].component {
                    Component::Button(bp) => assert_eq!(bp.label, "Create User"),
                    _ => panic!("expected Button child"),
                }
            }
            _ => panic!("expected Card"),
        }

        // Verify second component is a Table with visibility
        assert_eq!(view.components[1].key, "users-table");
        match &view.components[1].component {
            Component::Table(props) => {
                assert_eq!(props.columns.len(), 3);
                assert_eq!(props.data_path, "/data/users");
            }
            _ => panic!("expected Table"),
        }
        assert!(view.components[1].visibility.is_some());
    }

    #[test]
    fn empty_view_serializes() {
        let view = JsonUiView::new();
        let json = view.to_json().unwrap();
        let parsed = JsonUiView::from_json(&json).unwrap();
        assert_eq!(parsed.schema, SCHEMA_VERSION);
        assert!(parsed.title.is_none());
        assert!(parsed.layout.is_none());
        assert!(parsed.components.is_empty());
    }

    #[test]
    fn to_json_pretty_is_readable() {
        let view = JsonUiView::new().title("Test");
        let pretty = view.to_json_pretty().unwrap();
        assert!(pretty.contains('\n'));
        assert!(pretty.contains("  "));
    }

    #[test]
    fn components_method_replaces_existing() {
        let view = JsonUiView::new()
            .component(ComponentNode {
                key: "first".to_string(),
                component: Component::Text(TextProps {
                    content: "first".to_string(),
                    element: TextElement::P,
                }),
                action: None,
                visibility: None,
            })
            .components(vec![ComponentNode {
                key: "replaced".to_string(),
                component: Component::Text(TextProps {
                    content: "replaced".to_string(),
                    element: TextElement::P,
                }),
                action: None,
                visibility: None,
            }]);
        assert_eq!(view.components.len(), 1);
        assert_eq!(view.components[0].key, "replaced");
    }

    #[test]
    fn complex_view_with_action_and_visibility() {
        let view = JsonUiView::new()
            .title("Admin Panel")
            .component(ComponentNode {
                key: "delete-btn".to_string(),
                component: Component::Button(ButtonProps {
                    label: "Delete All".to_string(),
                    variant: ButtonVariant::Destructive,
                    size: Size::Default,
                    disabled: Some(false),
                    icon: None,
                    icon_position: None,
                    button_type: None,
                }),
                action: Some(Action {
                    handler: "admin.delete_all".to_string(),
                    url: None,
                    method: HttpMethod::Delete,
                    confirm: None,
                    on_success: None,
                    on_error: None,
                    target: None,
                }),
                visibility: Some(Visibility::Condition(VisibilityCondition {
                    path: "/auth/user/role".to_string(),
                    operator: VisibilityOperator::Eq,
                    value: Some(serde_json::Value::String("admin".to_string())),
                })),
            });

        let json = view.to_json().unwrap();
        let parsed = JsonUiView::from_json(&json).unwrap();
        assert_eq!(view, parsed);
    }

    #[test]
    fn view_with_data_serializes_data_field() {
        let view = JsonUiView::new()
            .title("Users")
            .data(serde_json::json!({"users": [{"name": "Alice"}]}));

        let json = serde_json::to_value(&view).unwrap();
        assert!(json.get("data").is_some());
        assert_eq!(json["data"]["users"][0]["name"], "Alice");
    }

    #[test]
    fn view_without_data_omits_data_field() {
        let view = JsonUiView::new().title("Empty");
        let json = serde_json::to_value(&view).unwrap();
        // skip_serializing_if is_null means no data key in output
        assert!(json.get("data").is_none());
    }

    #[test]
    fn round_trip_with_data_preserves_nested_structures() {
        let data = serde_json::json!({
            "users": [
                {"id": 1, "name": "Alice", "roles": ["admin", "user"]},
                {"id": 2, "name": "Bob", "roles": ["user"]}
            ],
            "meta": {"total": 2, "page": 1}
        });
        let view = JsonUiView::new().title("Users").data(data);

        let json_str = view.to_json().unwrap();
        let parsed = JsonUiView::from_json(&json_str).unwrap();
        assert_eq!(view, parsed);
        assert_eq!(parsed.data["users"][0]["name"], "Alice");
        assert_eq!(parsed.data["meta"]["total"], 2);
    }

    #[test]
    fn builder_data_method_works() {
        let view = JsonUiView::new().data(serde_json::json!({"key": "value"}));
        assert_eq!(view.data["key"], "value");
    }

    #[test]
    fn view_with_errors_serializes() {
        let mut errors = std::collections::HashMap::new();
        errors.insert("email".to_string(), vec!["Required".to_string()]);
        let view = JsonUiView::new().errors(errors);
        let json = serde_json::to_value(&view).unwrap();
        assert!(json.get("errors").is_some());
        assert_eq!(json["errors"]["email"][0], "Required");
    }

    #[test]
    fn view_without_errors_omits_field() {
        let view = JsonUiView::new().title("Empty");
        let json = serde_json::to_value(&view).unwrap();
        assert!(json.get("errors").is_none());
    }

    #[test]
    fn errors_builder_method() {
        let mut errors = std::collections::HashMap::new();
        errors.insert("name".to_string(), vec!["Too short".to_string()]);
        let view = JsonUiView::new().errors(errors);
        assert!(view.errors.is_some());
        let errs = view.errors.unwrap();
        assert_eq!(errs["name"], vec!["Too short".to_string()]);
    }

    // ── JSON Schema generation tests ─────────────────────────────────────

    #[test]
    fn test_json_schema_for_table_props_generates() {
        use crate::component::TableProps;
        let schema = schemars::schema_for!(TableProps);
        let value = serde_json::to_value(&schema).unwrap();
        // Schema must be a valid object with title or properties
        assert!(
            value.is_object(),
            "schema should serialize to a JSON object"
        );
        // TableProps has required field `data_path`
        let schema_str = serde_json::to_string(&schema).unwrap();
        assert!(
            schema_str.contains("data_path"),
            "schema should reference data_path field"
        );
    }

    #[test]
    fn test_json_schema_for_stat_card_props_generates() {
        use crate::component::StatCardProps;
        let schema = schemars::schema_for!(StatCardProps);
        let value = serde_json::to_value(&schema).unwrap();
        assert!(
            value.is_object(),
            "schema should serialize to a JSON object"
        );
        let schema_str = serde_json::to_string(&schema).unwrap();
        assert!(
            schema_str.contains("label"),
            "schema should reference label field"
        );
        assert!(
            schema_str.contains("value"),
            "schema should reference value field"
        );
    }

    #[test]
    fn test_json_schema_for_action_generates() {
        use crate::action::Action;
        let schema = schemars::schema_for!(Action);
        let value = serde_json::to_value(&schema).unwrap();
        assert!(
            value.is_object(),
            "schema should serialize to a JSON object"
        );
        let schema_str = serde_json::to_string(&schema).unwrap();
        assert!(
            schema_str.contains("handler"),
            "schema should reference handler field"
        );
    }

    #[test]
    fn test_json_schema_for_visibility_generates() {
        use crate::visibility::Visibility;
        let schema = schemars::schema_for!(Visibility);
        let value = serde_json::to_value(&schema).unwrap();
        assert!(
            value.is_object(),
            "schema should serialize to a JSON object"
        );
    }
}