Skip to main content

graphrt_core/
ui.rs

1//! UI blocks: rich visual output (cards, charts, tables, stat tiles) that any node or
2//! tool can emit for a host to render.
3//!
4//! A UI block is a plain object whose `"$ui"` key names its kind, for example
5//! `{"$ui": "chart", "version": 1, ...}`. The engine treats blocks as ordinary values;
6//! this module only finds them, so hosts and nodes agree on one envelope. The block
7//! kinds, their schemas and their validation live in the `graphrt-ui` crate: hosts must
8//! validate a block there before rendering it.
9
10use crate::value::Value;
11
12/// Key that marks an object as a UI block; its value is the block kind.
13pub const UI_KEY: &str = "$ui";
14/// Most blocks [`collect_ui_blocks`] returns for one value.
15pub const MAX_COLLECTED_BLOCKS: usize = 32;
16/// How deep [`collect_ui_blocks`] looks into arrays and objects (the value itself is depth 0).
17const MAX_SCAN_DEPTH: usize = 3;
18
19/// The kind of a UI block (`"chart"`, `"adaptive_card"`...), or `None` when `value` is not one.
20///
21/// ```
22/// use graphrt_core::ui::ui_block_kind;
23/// use graphrt_core::value::Value;
24///
25/// let chart = Value::from_json(serde_json::json!({"$ui": "chart", "version": 1}));
26/// assert_eq!(ui_block_kind(&chart), Some("chart"));
27/// assert_eq!(ui_block_kind(&Value::from("chart")), None);
28/// ```
29pub fn ui_block_kind(value: &Value) -> Option<&str> {
30    value.as_object()?.get(UI_KEY)?.as_str()
31}
32
33/// UI blocks in `value`, in document order: the value itself when it is a block, otherwise
34/// blocks found in its array items and object fields, at most three levels down (a node's
35/// `data` output, a list of results, a `{"chart": {...}}` wrapper). The inside of a block
36/// is not searched, and at most [`MAX_COLLECTED_BLOCKS`] blocks are returned.
37///
38/// ```
39/// use graphrt_core::ui::collect_ui_blocks;
40/// use graphrt_core::value::Value;
41///
42/// let outputs = Value::from_json(serde_json::json!({
43///     "data": {"$ui": "stats", "version": 1, "items": []},
44///     "text": "done",
45/// }));
46/// assert_eq!(collect_ui_blocks(&outputs).len(), 1);
47/// ```
48pub fn collect_ui_blocks(value: &Value) -> Vec<Value> {
49    let mut blocks = Vec::new();
50    collect_into(value, 0, &mut blocks);
51    blocks
52}
53
54fn collect_into(value: &Value, depth: usize, blocks: &mut Vec<Value>) {
55    if blocks.len() >= MAX_COLLECTED_BLOCKS {
56        return;
57    }
58    if ui_block_kind(value).is_some() {
59        blocks.push(value.clone());
60        return;
61    }
62    if depth >= MAX_SCAN_DEPTH {
63        return;
64    }
65    match value {
66        Value::Array(items) => items.iter().for_each(|item| collect_into(item, depth + 1, blocks)),
67        Value::Object(fields) => fields.values().for_each(|field| collect_into(field, depth + 1, blocks)),
68        _ => {}
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use serde_json::json;
76
77    fn value(json: serde_json::Value) -> Value {
78        Value::from_json(json)
79    }
80
81    #[test]
82    fn block_kind_needs_a_string_ui_key() {
83        assert_eq!(ui_block_kind(&value(json!({"$ui": "table"}))), Some("table"));
84        assert_eq!(ui_block_kind(&value(json!({"$ui": 3}))), None);
85        assert_eq!(ui_block_kind(&value(json!({"ui": "table"}))), None);
86        assert_eq!(ui_block_kind(&value(json!([{"$ui": "table"}]))), None);
87    }
88
89    #[test]
90    fn collects_blocks_in_order_without_searching_inside_blocks() {
91        let found = collect_ui_blocks(&value(json!({
92            "first": {"$ui": "chart", "nested": {"$ui": "table"}},
93            "list": [{"$ui": "stats"}, "text", {"wrapper": {"$ui": "adaptive_card"}}],
94        })));
95        let kinds: Vec<_> = found.iter().filter_map(ui_block_kind).collect();
96        assert_eq!(kinds, ["chart", "stats", "adaptive_card"]);
97    }
98
99    #[test]
100    fn stops_at_the_depth_and_count_limits() {
101        assert_eq!(collect_ui_blocks(&value(json!({"a": {"b": {"c": {"$ui": "chart"}}}}))).len(), 1);
102        let too_deep = value(json!({"a": {"b": {"c": {"d": {"$ui": "chart"}}}}}));
103        assert!(collect_ui_blocks(&too_deep).is_empty());
104        let many = value(json!((0..40).map(|_| json!({"$ui": "chart"})).collect::<Vec<_>>()));
105        assert_eq!(collect_ui_blocks(&many).len(), MAX_COLLECTED_BLOCKS);
106    }
107}