use serde::{Deserialize, Serialize};
pub const FORMAT_VERSION: u32 = 10;
pub const OPENS_PROP: &str = "opens";
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Catalogue {
pub format: u32,
pub toolkit: String,
pub components: Vec<Description>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub enums: Vec<EnumDescription>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub icons: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnumDescription {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub doc: String,
pub cases: Vec<CaseDescription>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CaseDescription {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub doc: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<FieldDescription>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FieldDescription {
pub name: String,
pub ty: Type,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default: Option<Value>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub doc: String,
}
impl Catalogue {
#[must_use]
pub fn get(&self, name: &str) -> Option<&Description> {
self.components.iter().find(|c| c.name == name)
}
#[must_use]
pub fn names(&self) -> Vec<&str> {
self.components.iter().map(|c| c.name.as_str()).collect()
}
pub fn from_json(text: &str) -> Result<Self, String> {
let catalogue: Self = serde_json::from_str(text).map_err(|e| e.to_string())?;
if catalogue.format != FORMAT_VERSION {
return Err(format!(
"component catalogue format {} is not the supported {FORMAT_VERSION}",
catalogue.format
));
}
Ok(catalogue)
}
#[must_use]
pub fn to_json(&self) -> String {
let mut text = serde_json::to_string_pretty(self).unwrap_or_default();
text.push('\n');
text
}
}
#[must_use]
pub fn catalogue() -> &'static Catalogue {
static CATALOGUE: std::sync::OnceLock<Catalogue> = std::sync::OnceLock::new();
CATALOGUE.get_or_init(|| {
#[expect(
clippy::expect_used,
reason = "the shipped catalogue is written by the toolkit and read back by its tests"
)]
Catalogue::from_json(SHIPPED).expect("the shipped component catalogue reads")
})
}
pub const SHIPPED: &str = include_str!("../components.json");
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Description {
pub name: String,
pub doc: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub props: Vec<Prop>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub parts: Vec<Part>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub events: Vec<Event>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub bindings: Vec<Binding>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub state: Vec<State>,
pub semantics: Semantics,
}
impl Description {
#[must_use]
pub fn prop(&self, name: &str) -> Option<&Prop> {
self.props.iter().find(|p| p.name == name)
}
#[must_use]
pub fn part(&self, name: &str) -> Option<&Part> {
self.parts.iter().find(|s| s.name == name)
}
#[must_use]
pub fn default_part(&self) -> Option<&Part> {
self.parts.iter().find(|s| s.default)
}
#[must_use]
pub fn event(&self, name: &str) -> Option<&Event> {
self.events.iter().find(|e| e.name == name)
}
#[must_use]
pub fn binding(&self, name: &str) -> Option<&Binding> {
self.bindings.iter().find(|b| b.name == name)
}
#[must_use]
pub fn state(&self, name: &str) -> Option<&State> {
self.state.iter().find(|s| s.name == name)
}
pub fn positional(&self) -> impl Iterator<Item = &Prop> {
self.props.iter().filter(|p| p.positional)
}
#[must_use]
pub fn summary(&self) -> &str {
first_line(&self.doc)
}
}
#[must_use]
pub fn first_line(doc: &str) -> &str {
doc.lines().next().unwrap_or("").trim()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Companion {
Kind,
Time,
}
#[must_use]
pub fn companion(name: &str) -> Option<(&str, Companion)> {
let (prop, said) = name.rsplit_once(':')?;
let companion = match said {
"as" => Companion::Kind,
"time" => Companion::Time,
_ => return None,
};
Some((prop, companion))
}
#[allow(
clippy::struct_excessive_bools,
reason = "each flag is a separate part of the schema, set by its author"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Prop {
pub name: String,
pub doc: String,
#[serde(rename = "type")]
pub ty: Type,
#[serde(default, skip_serializing_if = "is_false")]
pub required: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub positional: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub data: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub identity: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Part {
pub name: String,
pub doc: String,
pub accepts: Accepts,
#[serde(default, skip_serializing_if = "is_false")]
pub many: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub default: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub when_open: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Accepts {
View,
Component(String),
OneOf(Vec<String>),
}
impl Accepts {
#[must_use]
pub fn reads_components(&self) -> bool {
!matches!(self, Self::View)
}
#[must_use]
pub fn takes(&self, name: &str) -> bool {
match self {
Self::View => true,
Self::Component(want) => want == name,
Self::OneOf(names) => names.iter().any(|want| want == name),
}
}
#[must_use]
pub fn show(&self) -> String {
match self {
Self::View => "a view".to_owned(),
Self::Component(name) => format!("`ui.{name}`"),
Self::OneOf(names) => names
.iter()
.map(|name| format!("`ui.{name}`"))
.collect::<Vec<_>>()
.join(", "),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Event {
pub name: String,
pub doc: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<Type>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<Type>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub press: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub name: String,
pub doc: String,
#[serde(rename = "type")]
pub ty: Type,
pub merge: Merge,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Merge {
Register,
Splice,
Rich,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct State {
pub name: String,
pub doc: String,
#[serde(rename = "type")]
pub ty: Type,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Semantics {
pub role: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub label: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub presents: Option<String>,
#[serde(default, skip_serializing_if = "is_false")]
pub attaches: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_in_gallery: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Type {
Text,
Int,
Float,
Bool,
Actor,
Resource,
Time,
Icon,
Picture,
File,
RichText,
Choice {
name: String,
cases: Vec<String>,
},
Option(Box<Type>),
List(Box<Type>),
Set(Box<Type>),
Map {
key: Box<Type>,
value: Box<Type>,
},
Action,
Cases {
name: String,
},
Enum,
Link,
}
impl Type {
#[must_use]
pub fn show(&self) -> String {
match self {
Self::Text => "Text".into(),
Self::Int => "Int".into(),
Self::Float => "Float".into(),
Self::Bool => "Bool".into(),
Self::Actor => "Actor".into(),
Self::Resource => "a resource".into(),
Self::Time => "Time".into(),
Self::Icon => "Icon".into(),
Self::Picture => "Picture".into(),
Self::File => "File".into(),
Self::RichText => "RichText".into(),
Self::Choice { name, .. } | Self::Cases { name } => name.clone(),
Self::Option(inner) => format!("Option<{}>", inner.show()),
Self::List(inner) => format!("List<{}>", inner.show()),
Self::Set(inner) => format!("Set<{}>", inner.show()),
Self::Map { key, value } => format!("Map<{}, {}>", key.show(), value.show()),
Self::Action => "Action".into(),
Self::Enum => "a case of an enum".into(),
Self::Link => "Link".into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Value {
Text(String),
Int(i64),
Float(f64),
Bool(bool),
Actor {
identity: tilo_action_policy::Actor,
name: String,
#[serde(default)]
hue: Option<u8>,
#[serde(default)]
picture: Option<String>,
},
Resource(String),
Icon(String),
Picture(Picture),
File(File),
Choice(String),
Rich(crate::rich::RichText),
None,
List(Vec<Value>),
Map(Vec<(Value, Value)>),
Action(Offered),
Case {
case: String,
fields: Vec<(String, Value)>,
},
Link {
reference: String,
title: String,
},
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Picture {
pub src: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct File {
pub name: String,
pub media: String,
pub size: i64,
pub url: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Offered {
pub label: String,
pub icon: Option<String>,
pub primary: bool,
pub destructive: bool,
pub on: Option<bool>,
pub key: Option<String>,
pub event: String,
}
impl Value {
#[must_use]
pub fn kind(&self) -> &'static str {
match self {
Self::Text(_) => "Text",
Self::Int(_) => "Int",
Self::Float(_) => "Float",
Self::Bool(_) => "Bool",
Self::Actor { .. } => "Actor",
Self::Resource(_) => "a resource",
Self::Icon(_) => "Icon",
Self::Picture(_) => "a picture",
Self::File(_) => "a file",
Self::Choice(_) | Self::Case { .. } => "a case",
Self::Rich(_) => "RichText",
Self::None => "nothing",
Self::List(_) => "List",
Self::Map(_) => "Map",
Self::Action(_) => "Action",
Self::Link { .. } => "Link",
}
}
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes a reference"
)]
fn is_false(flag: &bool) -> bool {
!*flag
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_shipped_catalogue_reads_and_names_each_component_once() {
let catalogue = catalogue();
let mut names = catalogue.names();
let all = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), all, "a component is described once");
assert!(catalogue.get("ListRow").is_some());
}
#[test]
fn a_catalogue_of_another_format_is_refused() {
let mut other = catalogue().clone();
other.format = FORMAT_VERSION + 1;
let text = serde_json::to_string(&other).unwrap_or_default();
assert!(Catalogue::from_json(&text).is_err());
}
}