Skip to main content

kardia_include/
tree.rs

1//! Navigation in nested entry lists (JSON values; group members live in
2//! the group's `config`).
3
4use serde_json::Value;
5
6pub(crate) fn id_of(options: &Value) -> Option<&str> {
7    options.get("id").and_then(Value::as_str).filter(|id| !id.is_empty())
8}
9
10pub(crate) fn group_list(options: &Value) -> Option<&Vec<Value>> {
11    (options.get("group") == Some(&Value::Bool(true))).then(|| options.get("config")?.as_array())?
12}
13
14fn group_list_mut(options: &mut Value) -> Option<&mut Vec<Value>> {
15    if options.get("group") != Some(&Value::Bool(true)) {
16        return None;
17    }
18    options.get_mut("config")?.as_array_mut()
19}
20
21/// Where an entry is, and the group (`None`: the list itself) it is in.
22#[derive(Debug, Clone, PartialEq)]
23pub struct Flat {
24    pub parent: Option<String>,
25    pub position: usize,
26    pub options: Value,
27}
28
29/// Indexes every entry (nested group members included) by id.
30pub fn flatten(data: &[Value]) -> indexmap::IndexMap<String, Flat> {
31    fn walk(data: &[Value], parent: Option<&str>, result: &mut indexmap::IndexMap<String, Flat>) {
32        for (position, options) in data.iter().enumerate() {
33            if let Some(id) = id_of(options) {
34                let flat = Flat { parent: parent.map(String::from), position, options: options.clone() };
35                result.insert(id.to_string(), flat);
36            }
37            if let Some(list) = group_list(options) {
38                walk(list, id_of(options), result);
39            }
40        }
41    }
42    let mut result = indexmap::IndexMap::new();
43    walk(data, None, &mut result);
44    result
45}
46
47/// Index path of an entry: `[2, 0]` is the first member of the third entry's group.
48pub(crate) fn find(data: &[Value], id: &str) -> Option<Vec<usize>> {
49    for (index, options) in data.iter().enumerate() {
50        if id_of(options) == Some(id) {
51            return Some(vec![index]);
52        }
53        if let Some(list) = group_list(options)
54            && let Some(mut path) = find(list, id)
55        {
56            path.insert(0, index);
57            return Some(path);
58        }
59    }
60    None
61}
62
63pub(crate) fn get_mut<'a>(data: &'a mut [Value], path: &[usize]) -> Option<&'a mut Value> {
64    let (first, rest) = path.split_first()?;
65    let options = data.get_mut(*first)?;
66    if rest.is_empty() {
67        return Some(options);
68    }
69    get_mut(group_list_mut(options)?, rest)
70}
71
72/// The list containing the entry at `path`.
73fn list_mut<'a>(data: &'a mut Vec<Value>, path: &[usize]) -> Option<&'a mut Vec<Value>> {
74    match path.split_last() {
75        Some((_, [])) => Some(data),
76        Some((_, parent)) => group_list_mut(get_mut(data, parent)?),
77        None => None,
78    }
79}
80
81pub(crate) fn entry_mut<'a>(data: &'a mut [Value], id: &str) -> Option<&'a mut Value> {
82    let path = find(data, id)?;
83    get_mut(data, &path)
84}
85
86/// Removes an entry, returning its options.
87pub(crate) fn detach(data: &mut Vec<Value>, id: &str) -> Option<Value> {
88    let path = find(data, id)?;
89    let index = *path.last()?;
90    Some(list_mut(data, &path)?.remove(index))
91}
92
93/// Inserts under `parent` (a group id, or `None` for the list itself) at
94/// `position`, clamped. Returns false when the group does not exist.
95pub(crate) fn place(data: &mut Vec<Value>, options: Value, parent: Option<&str>, position: usize) -> bool {
96    let list = match parent {
97        None => data,
98        Some(parent) => {
99            let Some(group) = entry_mut(data, parent) else { return false };
100            if group.get("group") != Some(&Value::Bool(true)) {
101                return false;
102            }
103            let config =
104                group.as_object_mut().expect("entries are objects").entry("config").or_insert(Value::Array(Vec::new()));
105            if !config.is_array() {
106                *config = Value::Array(Vec::new());
107            }
108            config.as_array_mut().expect("just made an array")
109        }
110    };
111    list.insert(position.min(list.len()), options);
112    true
113}