use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
validate::{Validate, Validator},
Attribute, Color, Geometry, Location,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Element {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<Color>,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub metadata: serde_json::Map<String, Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attributes: Vec<Attribute>,
pub geometry: Geometry,
}
impl Element {
pub fn new(name: impl Into<String>, geometry: impl Into<Geometry>) -> Self {
Self {
name: name.into(),
description: Default::default(),
metadata: Default::default(),
attributes: Default::default(),
geometry: geometry.into(),
color: None,
}
}
pub fn valid_locations(&self) -> &'static [Location] {
self.geometry.valid_locations()
}
pub fn location_len(&self, location: Location) -> Option<u64> {
self.geometry.location_len(location)
}
}
impl Validate for Element {
fn validate_inner(&mut self, val: &mut Validator) {
val.enter("Element")
.name(&self.name)
.obj(&mut self.geometry)
.objs(&mut self.attributes)
.unique(
self.attributes.iter().map(|a| &a.name),
"attributes[..]::name",
false,
)
.attrs_on_geometry(&self.attributes, &self.geometry);
}
}