use tilo_actions::ActionAddress;
use tilo_ui_graph::component::{Catalogue, Description, Type, companion};
use super::{
Binding, Event, MAX_CALL_PICTURE_BYTES, MAX_CALL_PICTURES, Node, Patch, ResourceRef, RowChange,
ToApp, ToUi, Value, Words,
};
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{what}{at}")]
pub struct Refused {
pub what: &'static str,
pub at: String,
}
impl Refused {
#[must_use]
pub fn invalid(what: &'static str) -> Self {
Self {
what,
at: String::new(),
}
}
#[must_use]
pub fn within(mut self, part: impl std::fmt::Display) -> Self {
self.at = format!(" in {part}{}", self.at);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PatchLimits {
pub nodes: u32,
pub depth: u32,
pub string_bytes: u32,
pub key_bytes: u32,
pub path: u32,
pub props: u32,
pub rows: u32,
pub messages: u32,
}
#[expect(
clippy::cast_possible_truncation,
reason = "one text's bytes, 8 MiB, fit a window's count of a string"
)]
const STRING_BYTES: u32 = tilo_actions::MAX_TEXT_BYTES as u32;
impl Default for PatchLimits {
fn default() -> Self {
Self {
nodes: 200_000,
depth: 128,
string_bytes: STRING_BYTES,
key_bytes: 4096,
path: 128,
props: 128,
rows: 8192,
messages: 65_536,
}
}
}
pub const NODE_ARGS: &[&str] = &[
"fill", "min", "max", "height", "aspect", "span", "lines", "truncate", "at", "lead", "x", "y",
];
pub const PRIMITIVES: &[&str] = &[
"stack",
"column",
"fragment",
"primary",
"secondary",
"item",
"row",
"grid",
"split",
"page",
"layers",
"scroll",
"spacer",
"divider",
"progress",
"form",
"field",
"toggle",
"choice",
"list",
"checkbox",
"date",
"image",
"embed",
"invocation",
"error",
"text",
PART,
];
pub const PART: &str = "part";
pub const COMPONENT_PREFIX: &str = "ui.";
#[must_use]
pub fn primitive(kind: &str) -> bool {
PRIMITIVES.contains(&kind)
}
pub struct Validator<'a> {
catalogue: &'a Catalogue,
limits: PatchLimits,
}
impl<'a> Validator<'a> {
#[must_use]
pub fn new(catalogue: &'a Catalogue, limits: PatchLimits) -> Self {
Self { catalogue, limits }
}
#[must_use]
pub fn limits(&self) -> &PatchLimits {
&self.limits
}
pub fn to_ui(&self, batch: &[ToUi]) -> Result<(), Refused> {
if batch.len() > self.limits.messages as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"messages in a batch"
)));
}
for message in batch {
self.message(message)?;
}
Ok(())
}
fn target(&self, target: &ResourceRef) -> Result<(), Refused> {
self.key(&target.id)?;
self.key(&target.ty)
}
fn carried(&self, bytes: usize, refused: &'static str) -> Result<(), Refused> {
if bytes > self.limits.string_bytes as usize {
return Err(Refused::invalid(refused));
}
Ok(())
}
#[allow(
clippy::too_many_lines,
reason = "one arm per message a window takes, read side by side as the protocol lists them"
)]
fn message(&self, message: &ToUi) -> Result<(), Refused> {
match message {
ToUi::Loading
| ToUi::Close
| ToUi::Front { shows: None, .. }
| ToUi::Ask(None)
| ToUi::Form(None)
| ToUi::Activate
| ToUi::Kept(_)
| ToUi::History(_)
| ToUi::Took { .. }
| ToUi::CloseWindow => Ok(()),
ToUi::Focus { key } => match key {
Some(key) => self.key(key),
None => Ok(()),
},
ToUi::Actions(catalogue) => {
self.carried(catalogue.len(), "over the limit of bytes in a catalogue")
}
ToUi::Heard(bytes) | ToUi::Outputs(bytes) => {
self.carried(bytes.len(), "over the limit of bytes in a message")
}
ToUi::CallPictures { shown, pictures } => {
if shown.len() > MAX_CALL_PICTURES || pictures.len() > MAX_CALL_PICTURES {
return Err(Refused::invalid("over the limit of pictures in a message"));
}
for shown in shown {
self.key(&shown.person)?;
}
for picture in pictures {
self.key(&picture.person)?;
self.key(&picture.stream)?;
if picture.object.is_empty() || picture.object.len() > MAX_CALL_PICTURE_BYTES {
return Err(Refused::invalid("a call picture is not one picture"));
}
}
Ok(())
}
ToUi::Desktop { action, argument } => {
self.key(action)?;
self.carried(argument.len(), "over the limit of bytes in a message")
}
ToUi::Page { request, .. } => {
if request.len() > super::MAX_PAGE_BYTES {
return Err(Refused::invalid(
"over the limit of bytes in a page request",
));
}
Ok(())
}
ToUi::Front {
shows: Some((_, target)),
..
} => self.target(target),
ToUi::Open { target, tree, .. } => {
self.key(&target.id)?;
self.key(&target.ty)?;
self.node(tree, 0)
}
ToUi::Patch { patches, .. } => {
if patches.len() > self.limits.messages as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"patches in a message"
)));
}
patches.iter().try_for_each(|patch| self.patch(patch))
}
ToUi::Bound { key, value, .. } => {
self.key(key)?;
self.value(value, 0)
}
ToUi::Rows {
list, keys, rows, ..
} => {
self.key(list)?;
if keys.len() > self.limits.rows as usize || rows.len() > self.limits.rows as usize
{
return Err(Refused::invalid(concat!(
"over the limit of ",
"rows in a message"
)));
}
keys.iter().try_for_each(|key| self.key(key))?;
rows.iter().try_for_each(|row| self.node(row, 1))
}
ToUi::Spaces { keys, .. } => {
if keys.len() > self.limits.rows as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"views in a message"
)));
}
keys.iter().try_for_each(|key| self.key(key))
}
ToUi::RowsChanged { list, changes, .. } => {
self.key(list)?;
if changes.len() > self.limits.rows as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"rows in a message"
)));
}
changes.iter().try_for_each(|change| match change {
RowChange::Inserted { key, .. } => self.key(key),
RowChange::Changed { row } => self.node(row, 1),
RowChange::Removed { .. } | RowChange::Moved { .. } | RowChange::Reset => {
Ok(())
}
})
}
ToUi::Notice { words, .. } => self.words(words),
ToUi::ShowRun { run } => self.key(run),
ToUi::Speak(language) => self.key(language),
ToUi::Ask(Some(ask)) => {
self.string(&ask.action)?;
self.string(&ask.invoker)
}
ToUi::Form(Some(form)) => {
self.string(&form.title)?;
self.string(&form.submit)?;
if let Some(error) = &form.error {
self.string(error)?;
}
if let Some((_, key)) = &form.from {
self.key(key)?;
}
if form.fields.len() > self.limits.messages as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"fields in a form"
)));
}
form.fields.iter().try_for_each(|(key, text)| {
self.key(key)?;
self.string(text)
})?;
self.node(&form.tree, 1)
}
}
}
fn patch(&self, patch: &Patch) -> Result<(), Refused> {
match patch {
Patch::SetRoot(node) => self.node(node, 0),
Patch::Insert { parent, node, .. } => {
self.path(parent)?;
self.node(node, parent.len().saturating_add(1))
}
Patch::Remove { parent, key } | Patch::Move { parent, key, .. } => {
self.path(parent)?;
self.key(key)
}
Patch::SetProp { path, name, value } => {
self.path(path)?;
self.key(name)?;
value
.as_ref()
.map_or(Ok(()), |value| self.value(value, path.len()))
}
Patch::SetBinding { path, binding } => {
self.path(path)?;
binding
.as_ref()
.map_or(Ok(()), |binding| self.binding(binding))
}
Patch::SetEvent {
path,
event,
action,
} => {
self.path(path)?;
self.key(event)?;
action.as_ref().map_or(Ok(()), |event| self.event(event))
}
Patch::SetAnchor { path, anchor } => {
self.path(path)?;
anchor.as_ref().map_or(Ok(()), |anchor| self.key(anchor))
}
Patch::SpliceProp {
path, name, insert, ..
} => {
self.path(path)?;
self.key(name)?;
if insert.len() > self.limits.rows as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"items of a list value"
)));
}
insert
.iter()
.try_for_each(|item| self.value(item, path.len().saturating_add(1)))
}
}
}
pub fn node(&self, node: &Node, depth: usize) -> Result<(), Refused> {
if depth > self.limits.depth as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"tree depth"
)));
}
self.key(&node.key)?;
if node.props.len() > self.limits.props as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"props of a node"
)));
}
if let Some(anchor) = &node.anchor {
self.key(anchor)?;
}
self.shape(node, depth)
.map_err(|refused| refused.within(format_args!("`{}` {}", node.kind, node.key)))?;
node.children
.iter()
.try_for_each(|child| self.node(child, depth.saturating_add(1)))
}
pub fn shape(&self, node: &Node, depth: usize) -> Result<(), Refused> {
if let Some(name) = node.kind.strip_prefix(COMPONENT_PREFIX) {
let description = self
.catalogue
.get(name)
.ok_or_else(|| Refused::invalid("a component the toolkit does not describe"))?;
return self.component(node, description, depth);
}
if !primitive(&node.kind) {
return Err(Refused::invalid("a kind of node the host does not build"));
}
for (name, value) in &node.props {
self.key(name)?;
self.value(value, depth)
.map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
}
for (name, event) in &node.events {
self.key(name)?;
self.event(event)?;
}
node.binding
.as_ref()
.map_or(Ok(()), |binding| self.binding(binding))
}
fn component(
&self,
node: &Node,
description: &Description,
depth: usize,
) -> Result<(), Refused> {
for (name, value) in &node.props {
self.prop(name, value, description, depth)
.map_err(|refused| refused.within(format_args!("prop `{name}`")))?;
}
self.parts(node, description)
}
fn prop(
&self,
name: &str,
value: &Value,
description: &Description,
depth: usize,
) -> Result<(), Refused> {
self.value(value, depth)?;
{
let declared = description
.prop(name)
.map(|prop| &prop.ty)
.or_else(|| description.state(name).map(|state| &state.ty))
.or_else(|| {
description
.event("change")
.and_then(|_| description.binding(name))
.map(|binding| &binding.ty)
});
match declared {
Some(ty) => {
if !fits(value, ty) {
return Err(Refused::invalid(
"a prop holding a value of another type than its component declares",
));
}
}
None if node_arg(name) => {}
None if name == "bind" => {
let Value::Text(bound) = value else {
return Err(Refused::invalid("a binding named by other than text"));
};
if description.binding(bound).is_none() {
return Err(Refused::invalid("a binding its component does not declare"));
}
}
None if companion(name).is_some_and(|(prop, _)| {
description.prop(prop).is_some() || description.state(prop).is_some()
}) => {}
None => {
return Err(Refused::invalid("a prop its component does not declare"));
}
}
}
Ok(())
}
fn parts(&self, node: &Node, description: &Description) -> Result<(), Refused> {
for (name, event) in &node.events {
if description.event(name).is_none()
&& description.binding(name).is_none()
&& !offers(description, name)
{
return Err(Refused::invalid("an event its component does not declare")
.within(format_args!("event `{name}`")));
}
self.event(event)?;
}
if let Some(binding) = &node.binding {
if description.bindings.is_empty() {
return Err(Refused::invalid("a binding on a component that takes none"));
}
self.binding(binding)?;
}
Ok(())
}
fn binding(&self, binding: &Binding) -> Result<(), Refused> {
self.string(&binding.name)?;
if let Some((target, field)) = &binding.field {
self.key(target)?;
self.key(field)?;
}
Ok(())
}
fn event(&self, event: &Event) -> Result<(), Refused> {
if let Some((target, field)) = &event.toggles {
self.key(target)?;
self.key(field)?;
}
if let Some(invoked) = &event.invokes {
self.key(&invoked.resource)?;
self.key(&invoked.action)?;
}
Ok(())
}
fn value(&self, value: &Value, depth: usize) -> Result<(), Refused> {
if depth > self.limits.depth as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"value depth"
)));
}
match value {
Value::Unit | Value::Int(_) | Value::Bool(_) => Ok(()),
Value::Float(number) if number.is_finite() => Ok(()),
Value::Float(_) => Err(Refused::invalid("a number that is not finite")),
Value::Text(text) | Value::Error(text) => self.string(text),
Value::Enum(case) => self.key(case),
Value::Case { case, fields } => {
self.key(case)?;
for (name, held) in fields {
self.key(name)?;
self.value(held, depth.saturating_add(1))?;
}
Ok(())
}
Value::List(items) => {
if items.len() > self.limits.rows as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"items of a list value"
)));
}
items
.iter()
.try_for_each(|item| self.value(item, depth.saturating_add(1)))
}
Value::Opt(held) => held
.as_deref()
.map_or(Ok(()), |held| self.value(held, depth.saturating_add(1))),
Value::Ref(resource) => {
self.key(&resource.id)?;
self.key(&resource.ty)
}
Value::Actor(who) => {
self.key(who.id.id())?;
self.string(&who.name)
}
Value::Map(entries) => {
if entries.len() > self.limits.rows as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"entries of a map value"
)));
}
entries.iter().try_for_each(|(key, value)| {
self.value(key, depth.saturating_add(1))?;
self.value(value, depth.saturating_add(1))
})
}
Value::Action(offered) => {
self.string(&offered.label)?;
self.key(&offered.event)?;
offered.icon.as_ref().map_or(Ok(()), |icon| self.key(icon))
}
Value::Picture(picture) => self.string(&picture.src),
Value::File(file) => {
self.string(&file.name)?;
self.key(&file.media)?;
self.string(&file.url)
}
Value::Link { reference, title } => {
self.string(reference)?;
self.string(title)
}
Value::Rich(rich) => {
if rich.blocks.len() > self.limits.rows as usize
|| rich.embeds.len() > self.limits.rows as usize
{
return Err(Refused::invalid(concat!(
"over the limit of ",
"paragraphs of rich text"
)));
}
rich.strings().try_for_each(|text| self.string(text))
}
}
}
fn words(&self, words: &Words) -> Result<(), Refused> {
match words {
Words::Plain(text) => self.string(text),
Words::Phrase { id, args } => {
self.key(id)?;
if args.len() > self.limits.props as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"arguments of a phrase"
)));
}
args.iter().try_for_each(|(name, value)| {
self.key(name)?;
self.string(value)
})
}
}
}
fn path(&self, path: &[String]) -> Result<(), Refused> {
if path.len() > self.limits.path as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"path length"
)));
}
path.iter().try_for_each(|key| self.key(key))
}
fn key(&self, key: &str) -> Result<(), Refused> {
if key.len() > self.limits.key_bytes as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"key length"
)));
}
Ok(())
}
fn resource(&self, resource: &ResourceRef) -> Result<(), Refused> {
self.key(&resource.id)?;
self.key(&resource.ty)
}
fn string(&self, text: &str) -> Result<(), Refused> {
if text.len() > self.limits.string_bytes as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"string length"
)));
}
Ok(())
}
pub fn to_app(&self, batch: &[ToApp]) -> Result<(), Refused> {
if batch.len() > self.limits.messages as usize {
return Err(Refused::invalid(concat!(
"over the limit of ",
"messages in a batch"
)));
}
for message in batch {
self.to_app_message(message)?;
}
Ok(())
}
fn to_app_message(&self, message: &ToApp) -> Result<(), Refused> {
self.to_app_targets(message)?;
self.to_app_payload(message)
}
fn to_app_targets(&self, message: &ToApp) -> Result<(), Refused> {
match message {
ToApp::Fire { key, event, .. } => {
self.key(key)?;
self.key(event)?;
}
ToApp::Toggle { target, key, .. }
| ToApp::Splice { target, key, .. }
| ToApp::Edit { target, key, .. }
| ToApp::EditRich { target, key, .. } => {
self.resource(target)?;
self.key(key)?;
}
ToApp::Resolve { key, .. } => self.key(key)?,
ToApp::Rows {
list, open, menu, ..
} => {
for key in std::iter::once(list).chain(open).chain(menu) {
self.key(key)?;
}
}
ToApp::Focus { at } => {
if let Some((_, key)) = at {
self.key(key)?;
}
}
ToApp::FormEdit { field, .. } => self.key(field)?,
ToApp::Open { .. }
| ToApp::OpenReference { .. }
| ToApp::Space { .. }
| ToApp::Invoke { .. }
| ToApp::Serving { .. }
| ToApp::PageAnswer { .. }
| ToApp::PagePrompt { .. }
| ToApp::Desktop { .. }
| ToApp::Back
| ToApp::Answer(_)
| ToApp::Undo
| ToApp::Redo
| ToApp::Composing(_)
| ToApp::Held(_)
| ToApp::SaveAgain
| ToApp::History { .. }
| ToApp::FormSubmit { .. }
| ToApp::FormCancel { .. } => {}
}
Ok(())
}
fn to_app_payload(&self, message: &ToApp) -> Result<(), Refused> {
match message {
ToApp::Fire {
value: Some(value), ..
} => self.value(value, 0),
ToApp::Splice { insert, .. } => self.string(insert),
ToApp::Edit { text, .. } | ToApp::FormEdit { text, .. } => self.string(text),
ToApp::EditRich { rich, .. } => self.value(&Value::Rich(rich.clone()), 0),
ToApp::Open { resource } => self.resource(resource),
ToApp::OpenReference { reference } => self.string(reference),
ToApp::Rows { start, end, .. } => {
if end < start || end.saturating_sub(*start) > self.limits.rows {
return Err(Refused::invalid(concat!(
"over the limit of ",
"rows in a message"
)));
}
Ok(())
}
ToApp::Space {
width, height, rem, ..
} => {
if !(width.is_finite()
&& height.is_finite()
&& *width >= 0.0
&& *height >= 0.0
&& rem.is_finite()
&& *rem > 0.0)
{
return Err(Refused::invalid("a space is no size"));
}
Ok(())
}
ToApp::Invoke { address, argument } => self.invoke(address, argument.as_deref()),
ToApp::Serving { call, invoker } => self.serving(call, invoker.as_deref()),
ToApp::PageAnswer { answer, .. } => {
if answer.len() > super::MAX_PAGE_BYTES {
return Err(Refused::invalid("over the limit of bytes in a page answer"));
}
Ok(())
}
ToApp::Desktop { layout } => {
if layout.len() > super::MAX_PAGE_BYTES {
return Err(Refused::invalid("over the limit of bytes in a layout"));
}
Ok(())
}
ToApp::PagePrompt { prompt } => {
if prompt.len() > self.limits.string_bytes as usize {
return Err(Refused::invalid(
"over the limit of bytes in a page's prompt",
));
}
Ok(())
}
_ => Ok(()),
}
}
fn invoke(&self, address: &ActionAddress, argument: Option<&str>) -> Result<(), Refused> {
self.key(&address.resource)?;
self.key(&address.action)?;
argument.map_or(Ok(()), |argument| self.string(argument))
}
fn serving(&self, call: &[u8], invoker: Option<&str>) -> Result<(), Refused> {
if call.len() > self.limits.string_bytes as usize {
return Err(Refused::invalid(
"a signed call is over the limit of a string",
));
}
invoker.map_or(Ok(()), |invoker| self.string(invoker))
}
}
#[must_use]
pub fn offered_event(prop: &str, index: usize) -> String {
format!("{prop}.{index}")
}
#[must_use]
pub fn offers(description: &Description, event: &str) -> bool {
fn holds_actions(ty: &Type) -> bool {
match ty {
Type::Action => true,
Type::Option(inner) | Type::List(inner) | Type::Set(inner) => holds_actions(inner),
Type::Map { value, .. } => holds_actions(value),
_ => false,
}
}
event
.rsplit_once('.')
.filter(|(_, index)| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()))
.and_then(|(prop, _)| description.prop(prop))
.is_some_and(|prop| holds_actions(&prop.ty))
}
fn node_arg(name: &str) -> bool {
let base = name
.strip_suffix(".rem")
.or_else(|| name.strip_suffix(".dp"))
.unwrap_or(name);
NODE_ARGS.contains(&base)
}
#[must_use]
pub fn fits(value: &Value, ty: &Type) -> bool {
match (ty, value) {
(Type::Option(_), Value::Opt(None) | Value::Unit)
| (Type::Int, Value::Int(_))
| (Type::Float, Value::Float(_) | Value::Int(_))
| (Type::Bool, Value::Bool(_) | Value::Int(_))
| (Type::Actor, Value::Actor(_))
| (Type::Resource, Value::Ref(_))
| (Type::Icon | Type::Time, Value::Text(_))
| (Type::Picture, Value::Picture(_))
| (Type::File, Value::File(_))
| (Type::Link, Value::Link { .. })
| (Type::RichText, Value::Rich(_))
| (Type::Action, Value::Action(_))
| (Type::Cases { .. }, Value::Case { .. }) => true,
(Type::Option(inner), Value::Opt(Some(held))) => fits(held, inner),
(Type::Option(inner), other) => fits(other, inner),
(_, Value::Opt(Some(held))) => fits(held, ty),
(
Type::Text,
Value::List(_)
| Value::Ref(_)
| Value::Rich(_)
| Value::Map(_)
| Value::Action(_)
| Value::Picture(_)
| Value::File(_)
| Value::Link { .. },
) => false,
(Type::Text, _) => true,
(Type::Choice { cases, .. }, Value::Text(case) | Value::Enum(case)) => cases.contains(case),
(Type::List(inner) | Type::Set(inner), Value::List(items)) => {
items.iter().all(|item| fits(item, inner))
}
(Type::Map { key, value }, Value::Map(entries)) => {
entries.iter().all(|(k, v)| fits(k, key) && fits(v, value))
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::super::Level;
use super::*;
fn validator() -> Validator<'static> {
Validator::new(
tilo_ui_graph::component::catalogue(),
PatchLimits::default(),
)
}
fn component(name: &str, key: &str, props: &[(&str, Value)]) -> Node {
let mut node = Node::empty(&format!("{COMPONENT_PREFIX}{name}"), key);
for (prop, value) in props {
node.props.insert((*prop).to_owned(), value.clone());
}
node
}
fn open(tree: Node) -> Vec<ToUi> {
vec![ToUi::Open {
level: Level::Root,
target: ResourceRef {
id: "doc".to_owned(),
ty: "notes.Notebook".to_owned(),
},
tree,
front: None,
capture_protected: false,
}]
}
#[test]
fn a_text_an_edit_keeps_is_one_a_window_carries() {
assert_eq!(
PatchLimits::default().string_bytes as usize,
tilo_actions::MAX_TEXT_BYTES
);
}
#[test]
fn a_tree_of_described_components_and_primitives_passes() {
let mut stack = Node::empty("stack", "s");
stack.props.insert("gap".to_owned(), Value::text("section"));
stack.props.insert("min.rem".to_owned(), Value::Float(12.0));
let mut button = component("Button", "b", &[("label", Value::text("Send"))]);
button.events.insert("press".to_owned(), Event::default());
stack.children = vec![
component(
"Text",
"t",
&[
("value", Value::text("2026-10-24")),
("value:as", Value::text("date")),
("role", Value::text("title")),
],
),
button,
];
assert_eq!(validator().to_ui(&open(stack)), Ok(()));
}
#[test]
fn a_day_reads_with_the_time_of_day_it_is_due_at() {
let row = component(
"ListRow",
"t",
&[
("title", Value::text("Call the landlord")),
("meta", Value::text("2026-11-03")),
("meta:as", Value::text("date")),
("meta:time", Value::text("2026-11-03T17:00:00Z")),
],
);
assert_eq!(validator().to_ui(&open(row)), Ok(()));
let mistyped = component(
"ListRow",
"t",
&[("title", Value::text("x")), ("meta:tmie", Value::text("x"))],
);
assert!(
validator().to_ui(&open(mistyped)).is_err(),
"a companion is a name the component declares a prop for, spelled as the host reads it"
);
}
#[test]
fn what_a_component_does_not_declare_is_refused() {
let unknown = component("Nothing", "x", &[]);
assert!(validator().to_ui(&open(unknown)).is_err());
let prop = component("Text", "t", &[("color", Value::text("red"))]);
assert!(validator().to_ui(&open(prop)).is_err());
let typed = component("Text", "t", &[("role", Value::text("shouting"))]);
assert!(
validator().to_ui(&open(typed)).is_err(),
"a case not declared"
);
let mut event = component("Text", "t", &[("value", Value::text("x"))]);
event.events.insert("press".to_owned(), Event::default());
assert!(validator().to_ui(&open(event)).is_err());
assert!(
validator()
.to_ui(&open(Node::empty("script", "s")))
.is_err()
);
}
#[test]
fn a_value_given_to_a_control_with_a_change_event_passes() {
let mut slider = component("Slider", "s", &[("value", Value::Float(0.4))]);
slider.events.insert("change".to_owned(), Event::default());
assert_eq!(validator().to_ui(&open(slider)), Ok(()));
let wrong = component("Slider", "s", &[("value", Value::text("loud"))]);
assert!(validator().to_ui(&open(wrong)).is_err());
}
#[test]
fn work_is_bounded() {
let limits = PatchLimits {
depth: 3,
key_bytes: 16,
..PatchLimits::default()
};
let checked = Validator::new(tilo_ui_graph::component::catalogue(), limits);
let mut deep = Node::empty("stack", "0");
for level in 1..6 {
deep = Node {
children: vec![deep],
..Node::empty("stack", &level.to_string())
};
}
assert_eq!(
checked.to_ui(&open(deep)).map_err(|refused| refused.what),
Err("over the limit of tree depth")
);
assert_eq!(
checked
.to_ui(&open(Node::empty(
"stack",
"a key far longer than sixteen bytes"
)))
.map_err(|refused| refused.what),
Err("over the limit of key length")
);
assert!(
validator()
.to_ui(&open(component(
"Text",
"t",
&[("value", Value::Float(f64::NAN))]
)))
.is_err()
);
}
}