Skip to main content

a2ui_base/model/
components_model.rs

1//! Flat map of ComponentModels for a single surface.
2
3use std::collections::HashMap;
4
5use super::component_model::ComponentModel;
6use crate::error::A2uiError;
7
8/// Manages all components in a surface as a flat HashMap.
9pub struct SurfaceComponentsModel {
10    components: HashMap<String, ComponentModel>,
11}
12
13impl Default for SurfaceComponentsModel {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl SurfaceComponentsModel {
20    pub fn new() -> Self {
21        Self {
22            components: HashMap::new(),
23        }
24    }
25
26    /// Get a component by ID.
27    pub fn get(&self, id: &str) -> Option<&ComponentModel> {
28        self.components.get(id)
29    }
30
31    /// Add or update a component.
32    /// If the component already exists with a different type, replaces it.
33    pub fn upsert(&mut self, component: ComponentModel) {
34        self.components.insert(component.id.clone(), component);
35    }
36
37    /// Remove a component by ID.
38    pub fn remove(&mut self, id: &str) {
39        self.components.remove(id);
40    }
41
42    /// Returns true if a component with the given ID exists.
43    pub fn contains(&self, id: &str) -> bool {
44        self.components.contains_key(id)
45    }
46
47    /// Get all components.
48    pub fn all(&self) -> &HashMap<String, ComponentModel> {
49        &self.components
50    }
51
52    /// Parse and add multiple components from raw JSON.
53    pub fn add_from_json(&mut self, raw_components: &[serde_json::Value]) -> Vec<Result<(), A2uiError>> {
54        raw_components
55            .iter()
56            .map(|raw| {
57                let model = ComponentModel::from_json(raw)?;
58                self.upsert(model);
59                Ok(())
60            })
61            .collect()
62    }
63
64    /// Returns the number of components.
65    #[allow(dead_code)]
66    pub fn len(&self) -> usize {
67        self.components.len()
68    }
69
70    /// Returns true if there are no components.
71    #[allow(dead_code)]
72    pub fn is_empty(&self) -> bool {
73        self.components.is_empty()
74    }
75}