1use crate::value::Value;
11
12pub const UI_KEY: &str = "$ui";
14pub const MAX_COLLECTED_BLOCKS: usize = 32;
16const MAX_SCAN_DEPTH: usize = 3;
18
19pub fn ui_block_kind(value: &Value) -> Option<&str> {
30 value.as_object()?.get(UI_KEY)?.as_str()
31}
32
33pub 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}