1use std::collections::BTreeMap;
14use std::sync::{Arc, LazyLock};
15
16use serde_json::{Map, Value, json};
17
18use super::drawn::DrawnChart;
19use super::scene::{DrawnDepth, DrawnScene};
20
21pub const FORMS_CATALOG_ID: &str = "https://adk-rust.com/a2ui/catalogs/forms/1.0/catalog.json";
23
24pub(crate) const LEFT_OUT: &[&str] = &["Image", "Icon", "Modal", "Video", "AudioPlayer"];
27
28const FORBIDDEN_PROPERTIES: &[&str] = &["action", "event", "checks"];
31
32const FORBIDDEN_FORMATS: &[&str] = &["uri", "uri-reference", "iri", "iri-reference", "url"];
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum ChildSlot {
40 One(&'static str),
42 Many(&'static str),
44 EachOf {
47 array: &'static str,
49 child: &'static str,
51 },
52}
53
54#[derive(Debug, Clone, Copy)]
58pub struct ResolvedComponent<'a> {
59 pub id: &'a str,
61 pub component: &'a str,
63 pub props: &'a Value,
65 pub children: usize,
68}
69
70impl ResolvedComponent<'_> {
71 pub fn str(&self, name: &str) -> Option<&str> {
73 self.props.get(name).and_then(Value::as_str)
74 }
75
76 pub fn get(&self, name: &str) -> Option<&Value> {
78 self.props.get(name)
79 }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum HomeText {
85 H1,
87 H2,
89 H3,
91 H4,
93 H5,
95 Caption,
97 #[default]
99 Body,
100}
101
102impl HomeText {
103 pub fn variant(self) -> &'static str {
105 match self {
106 Self::H1 => "h1",
107 Self::H2 => "h2",
108 Self::H3 => "h3",
109 Self::H4 => "h4",
110 Self::H5 => "h5",
111 Self::Caption => "caption",
112 Self::Body => "body",
113 }
114 }
115}
116
117#[derive(Debug, Clone, PartialEq)]
126#[non_exhaustive]
127pub enum HomeNode {
128 Text {
130 text: String,
132 variant: HomeText,
134 },
135 Row(Vec<HomeNode>),
137 Column(Vec<HomeNode>),
139 Card(Vec<HomeNode>),
141 Tabs(Vec<(String, HomeNode)>),
143 Divider,
145 Child(usize),
147 Chart(DrawnChart),
149 Scene(Box<HomeScene>),
151 Depth {
153 depth: DrawnDepth,
155 children: Vec<HomeNode>,
157 },
158}
159
160#[derive(Debug, Clone, PartialEq)]
162pub struct HomeScene {
163 pub scene: DrawnScene,
165 pub panels: Vec<HomePanel>,
167 pub text: Option<HomeNode>,
171}
172
173impl HomeScene {
174 pub fn new(scene: DrawnScene) -> Self {
176 Self { scene, panels: Vec::new(), text: None }
177 }
178}
179
180#[derive(Debug, Clone, PartialEq)]
182pub struct HomePanel {
183 pub anchor: String,
185 pub content: HomeNode,
187}
188
189impl HomeNode {
190 pub fn text(text: impl Into<String>) -> Self {
192 Self::Text { text: text.into(), variant: HomeText::Body }
193 }
194
195 pub fn caption(text: impl Into<String>) -> Self {
197 Self::Text { text: text.into(), variant: HomeText::Caption }
198 }
199
200 pub fn heading(level: u8, text: impl Into<String>) -> Self {
202 let variant = match level {
203 0 | 1 => HomeText::H1,
204 2 => HomeText::H2,
205 3 => HomeText::H3,
206 4 => HomeText::H4,
207 _ => HomeText::H5,
208 };
209 Self::Text { text: text.into(), variant }
210 }
211}
212
213pub trait ExtensionComponent: Send + Sync + 'static {
259 fn name(&self) -> &'static str;
262
263 fn schema(&self) -> Value;
267
268 fn children(&self) -> &'static [ChildSlot] {
271 &[]
272 }
273
274 fn usage(&self) -> &'static str;
276
277 fn allowed_parents(&self) -> &'static [&'static str] {
280 &[]
281 }
282
283 fn allowed_children(&self) -> &'static [&'static str] {
285 &[]
286 }
287
288 fn home(&self, component: &ResolvedComponent<'_>) -> Result<HomeNode, String>;
295}
296
297pub struct ExtensionSpec {
299 pub id: &'static str,
301 pub name: &'static str,
303 pub version: &'static str,
305 pub components: Vec<Arc<dyn ExtensionComponent>>,
307}
308
309impl std::fmt::Debug for ExtensionSpec {
310 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 f.debug_struct("ExtensionSpec")
312 .field("id", &self.id)
313 .field("components", &self.components.iter().map(|c| c.name()).collect::<Vec<_>>())
314 .finish_non_exhaustive()
315 }
316}
317
318#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
320#[error("extension catalog {catalog}: {detail}")]
321pub struct CatalogError {
322 pub catalog: String,
324 pub detail: String,
326}
327
328const COMMON_TYPES_ID: &str = "https://a2ui.org/specification/v0_9/common_types.json";
330
331const COMMON_TYPES_CATALOG: &str = "https://a2ui.org/specification/v0_9/catalog.json";
334
335const FORMS_DOCUMENT: &str = include_str!("catalogs/forms-1.0.json");
336const FORMS_DOCUMENT_V1_0: &str = include_str!("catalogs/forms-1.0.a2ui-1.0.json");
338#[cfg(test)]
340pub(crate) const COMMON_TYPES_V1_0: &str = include_str!("catalogs/common_types-1.0.json");
341#[cfg(test)]
342pub(crate) const CATALOG_DEFINITION_V1_0: &str =
343 include_str!("catalogs/catalog_definition-1.0.json");
344const COMMON_TYPES_DOCUMENT: &str = include_str!("catalogs/common_types-0.9.1.json");
345
346pub struct Catalog {
362 id: &'static str,
363 name: &'static str,
364 version: &'static str,
365 instructions: Option<String>,
366 document: Value,
367 components: BTreeMap<String, jsonschema::Validator>,
368 extensions: BTreeMap<String, Arc<dyn ExtensionComponent>>,
369}
370
371impl std::fmt::Debug for Catalog {
372 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373 f.debug_struct("Catalog")
374 .field("id", &self.id)
375 .field("components", &self.components.keys().collect::<Vec<_>>())
376 .field("extensions", &self.extensions.keys().collect::<Vec<_>>())
377 .finish_non_exhaustive()
378 }
379}
380
381static FORMS: LazyLock<Catalog> = LazyLock::new(|| {
382 Catalog::compile(FORMS_CATALOG_ID, "forms", "1.0", FORMS_DOCUMENT)
383 .unwrap_or_else(|error| panic!("the embedded forms 1.0 catalog does not compile: {error}"))
384});
385
386impl Catalog {
387 pub fn forms() -> &'static Catalog {
389 &FORMS
390 }
391
392 pub fn extend(spec: ExtensionSpec) -> Result<Catalog, CatalogError> {
406 let refuse = |detail: String| CatalogError { catalog: spec.id.to_string(), detail };
407 if spec.id == FORMS_CATALOG_ID {
408 return Err(refuse("its id is the forms catalog's".to_string()));
409 }
410 if spec.id.trim().is_empty()
411 || spec.name.trim().is_empty()
412 || spec.version.trim().is_empty()
413 {
414 return Err(refuse("it needs an id, a name and a version".to_string()));
415 }
416 if spec.components.is_empty() {
417 return Err(refuse("it adds no components".to_string()));
418 }
419 let forms = Catalog::forms();
420 let mut document = forms.document.clone();
421 document["$id"] = json!(spec.id);
422 document["catalogId"] = json!(spec.id);
423 document["title"] = json!(format!("{} {}", spec.name, spec.version));
424 document["description"] = json!(format!(
425 "The forms 1.0 catalog and the components of {} {}",
426 spec.name, spec.version
427 ));
428 let mut extensions: BTreeMap<String, Arc<dyn ExtensionComponent>> = BTreeMap::new();
429 for component in &spec.components {
430 let name = component.name();
431 if name.is_empty() || !name.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
432 return Err(refuse(format!(
433 "'{name}' is not a component name of letters and digits"
434 )));
435 }
436 if forms.has_component(name) {
437 return Err(refuse(format!("{name} is a forms component")));
438 }
439 if LEFT_OUT.contains(&name) {
440 return Err(refuse(format!("{name} is one of the components forms leaves out")));
441 }
442 if extensions.contains_key(name) {
443 return Err(refuse(format!("{name} is added twice")));
444 }
445 let schema = component.schema();
446 if let Some(why) = forbidden(&schema) {
447 return Err(refuse(format!("{name}'s schema {why}")));
448 }
449 document["components"][name] = schema;
450 if let Some(any) = document["$defs"]["anyComponent"]["oneOf"].as_array_mut() {
451 any.push(json!({ "$ref": format!("#/components/{name}") }));
452 }
453 extensions.insert(name.to_string(), Arc::clone(component));
454 }
455 let mut catalog = Catalog::compile_document(spec.id, spec.name, spec.version, document)
456 .map_err(refuse)?;
457 catalog.extensions = extensions;
458 Ok(catalog)
459 }
460
461 fn compile(
462 id: &'static str,
463 name: &'static str,
464 version: &'static str,
465 document: &str,
466 ) -> Result<Self, String> {
467 let document: Value = serde_json::from_str(document).map_err(|error| error.to_string())?;
468 Self::compile_document(id, name, version, document)
469 }
470
471 fn compile_document(
472 id: &'static str,
473 name: &'static str,
474 version: &'static str,
475 document: Value,
476 ) -> Result<Self, String> {
477 let common: Value =
478 serde_json::from_str(COMMON_TYPES_DOCUMENT).map_err(|error| error.to_string())?;
479 let registry = jsonschema::Registry::new()
480 .add(id, document.clone())
481 .and_then(|registry| registry.add(COMMON_TYPES_CATALOG, document.clone()))
482 .and_then(|registry| registry.add(COMMON_TYPES_ID, common))
483 .and_then(jsonschema::RegistryBuilder::prepare)
484 .map_err(|error| error.to_string())?;
485 let names: Vec<String> = document["components"]
486 .as_object()
487 .map(|components| components.keys().cloned().collect())
488 .unwrap_or_default();
489 let mut components = BTreeMap::new();
490 for component in names {
491 let schema = json!({ "$ref": format!("{id}#/components/{component}") });
492 let validator = jsonschema::options()
493 .with_registry(®istry)
494 .build(&schema)
495 .map_err(|error| format!("{component}: {error}"))?;
496 components.insert(component, validator);
497 }
498 Ok(Self {
499 id,
500 name,
501 version,
502 instructions: None,
503 document,
504 components,
505 extensions: BTreeMap::new(),
506 })
507 }
508
509 pub fn id(&self) -> &str {
511 self.id
512 }
513
514 pub fn label(&self) -> String {
516 format!("{} {}", self.name, self.version)
517 }
518
519 pub fn document(&self) -> &Value {
522 &self.document
523 }
524
525 #[must_use]
528 pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
529 self.instructions = Some(instructions.into());
530 self
531 }
532
533 pub fn document_for(&self, version: super::wire::A2uiVersion) -> Value {
551 if version == super::wire::A2uiVersion::V0_9_1 {
552 return self.document.clone();
553 }
554 if !self.is_extension() {
555 return serde_json::from_str(FORMS_DOCUMENT_V1_0).unwrap_or_default();
556 }
557 let mut components = Map::new();
558 for (name, extension) in &self.extensions {
559 let mut schema = schema_v1_0(&extension.schema());
560 if let Value::Object(map) = &mut schema {
561 let parents = extension.allowed_parents();
562 if !parents.is_empty() {
563 map.insert("allowedParents".to_string(), json!(parents));
564 }
565 let children = extension.allowed_children();
566 if !children.is_empty() {
567 map.insert("allowedChildren".to_string(), json!(children));
568 }
569 }
570 components.insert(name.clone(), schema);
571 }
572 let mut instructions: Vec<String> = self.usage().into_iter().map(str::to_string).collect();
573 if let Some(extra) = &self.instructions {
574 instructions.push(extra.clone());
575 }
576 json!({
577 "$schema": "https://json-schema.org/draft/2020-12/schema",
578 "$id": self.id,
579 "protocolVersion": "1.0",
580 "title": self.label(),
581 "description": format!(
582 "The components {} adds to {FORMS_CATALOG_ID}, which a surface mixes with it",
583 self.label()
584 ),
585 "catalogId": self.id,
586 "instructions": instructions.join("\n"),
587 "components": components,
588 })
589 }
590
591 pub fn components(&self) -> impl Iterator<Item = &str> {
593 self.components.keys().map(String::as_str)
594 }
595
596 pub fn functions(&self) -> impl Iterator<Item = &str> {
598 self.document["functions"]
599 .as_object()
600 .into_iter()
601 .flat_map(|functions| functions.keys().map(String::as_str))
602 }
603
604 pub fn has_component(&self, component: &str) -> bool {
606 self.components.contains_key(component)
607 }
608
609 pub fn extensions(&self) -> impl Iterator<Item = &str> {
611 self.extensions.keys().map(String::as_str)
612 }
613
614 pub fn is_extension(&self) -> bool {
616 !self.extensions.is_empty()
617 }
618
619 pub(crate) fn extension(&self, component: &str) -> Option<&dyn ExtensionComponent> {
621 self.extensions.get(component).map(|extension| extension.as_ref())
622 }
623
624 pub(crate) fn usage(&self) -> Vec<&'static str> {
627 self.extensions.values().map(|extension| extension.usage()).collect()
628 }
629
630 pub(crate) fn schema_error(&self, component: &str, value: &Value) -> Option<String> {
633 let validator = self.components.get(component)?;
634 validator.iter_errors(value).next().map(|error| {
635 let error = error.to_owned();
636 let error = specific(&error);
637 let at = error.instance_path().as_str();
638 let why = shortened(&error.to_string());
639 if at.is_empty() { why } else { format!("{at}: {why}") }
640 })
641 }
642}
643
644fn schema_v1_0(schema: &Value) -> Value {
650 fn refs(value: &Value) -> Value {
651 match value {
652 Value::Object(map) => Value::Object(
653 map.iter()
654 .map(|(key, value)| match (key.as_str(), value) {
655 ("$ref", Value::String(target)) => {
656 let relative = target
657 .split_once("common_types.json#")
658 .map(|(_, pointer)| format!("common_types.json#{pointer}"))
659 .unwrap_or_else(|| target.clone());
660 (key.clone(), Value::String(relative))
661 }
662 _ => (key.clone(), refs(value)),
663 })
664 .collect(),
665 ),
666 Value::Array(items) => Value::Array(items.iter().map(refs).collect()),
667 other => other.clone(),
668 }
669 }
670 let mut out = refs(schema);
671 if let Value::Object(map) = &mut out {
672 if let Some(Value::Object(properties)) = map.get_mut("properties") {
673 properties.remove("id");
674 }
675 if let Some(Value::Array(required)) = map.get_mut("required") {
676 required.retain(|name| name != "id");
677 }
678 if map.get("additionalProperties") == Some(&Value::Bool(false)) {
679 map.remove("additionalProperties");
680 }
681 if let Some(Value::Array(all)) = map.get_mut("allOf") {
682 all.retain(|part| {
683 let target = part.get("$ref").and_then(Value::as_str).unwrap_or_default();
684 !target.ends_with("/ComponentCommon")
685 && !target.ends_with("/CatalogComponentCommon")
686 });
687 if all.is_empty() {
688 map.remove("allOf");
689 }
690 }
691 }
692 out
693}
694
695fn specific<'e>(
699 error: &'e jsonschema::ValidationError<'static>,
700) -> &'e jsonschema::ValidationError<'static> {
701 let context = match error.kind() {
702 jsonschema::error::ValidationErrorKind::OneOfNotValid { context }
703 | jsonschema::error::ValidationErrorKind::AnyOf { context } => context,
704 _ => return error,
705 };
706 let deepest = context
707 .iter()
708 .flatten()
709 .map(specific)
710 .max_by_key(|cause| cause.instance_path().as_str().matches('/').count());
711 match deepest {
712 Some(cause)
713 if cause.instance_path().as_str().len() > error.instance_path().as_str().len() =>
714 {
715 cause
716 }
717 _ => error,
718 }
719}
720
721const MAX_SCHEMA_ERROR_CHARS: usize = 300;
723
724fn shortened(text: &str) -> String {
725 if text.chars().count() <= MAX_SCHEMA_ERROR_CHARS {
726 return text.to_string();
727 }
728 let kept: String = text.chars().take(MAX_SCHEMA_ERROR_CHARS).collect();
729 format!("{kept}…")
730}
731
732fn forbidden(schema: &Value) -> Option<String> {
734 match schema {
735 Value::Object(map) => {
736 for key in ["$defs", "definitions", "functions"] {
737 if map.contains_key(key) {
738 return Some(format!("declares {key}"));
739 }
740 }
741 if let Some(properties) = map.get("properties").and_then(Value::as_object)
742 && let Some(property) =
743 FORBIDDEN_PROPERTIES.iter().find(|name| properties.contains_key(**name))
744 {
745 return Some(format!("declares the property '{property}'"));
746 }
747 if let Some(format) = map.get("format").and_then(Value::as_str)
748 && FORBIDDEN_FORMATS.contains(&format)
749 {
750 return Some(format!("declares the string format '{format}'"));
751 }
752 map.values().find_map(forbidden)
753 }
754 Value::Array(items) => items.iter().find_map(forbidden),
755 _ => None,
756 }
757}
758
759#[derive(Clone)]
773pub struct Catalogs(Arc<Vec<&'static Catalog>>);
774
775impl Catalogs {
776 pub fn forms() -> Self {
778 Self(Arc::new(vec![Catalog::forms()]))
779 }
780
781 #[must_use]
783 pub fn with(self, catalog: &'static Catalog) -> Self {
784 if self.get(catalog.id()).is_some() {
785 return self;
786 }
787 let mut catalogs = (*self.0).clone();
788 catalogs.push(catalog);
789 Self(Arc::new(catalogs))
790 }
791
792 pub fn get(&self, id: &str) -> Option<&'static Catalog> {
794 self.0.iter().copied().find(|catalog| catalog.id() == id)
795 }
796
797 pub fn iter(&self) -> impl Iterator<Item = &'static Catalog> + '_ {
799 self.0.iter().copied()
800 }
801}
802
803impl Default for Catalogs {
804 fn default() -> Self {
805 Self::forms()
806 }
807}
808
809impl std::fmt::Debug for Catalogs {
810 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
811 f.debug_list().entries(self.0.iter().map(|catalog| catalog.id())).finish()
812 }
813}
814
815#[cfg(test)]
816mod tests {
817 use super::*;
818 use crate::genui::A2uiVersion;
819
820 fn v1_0_meta() -> jsonschema::Validator {
823 let meta: Value = serde_json::from_str(CATALOG_DEFINITION_V1_0).unwrap();
824 let common: Value = serde_json::from_str(COMMON_TYPES_V1_0).unwrap();
825 let catalog = json!({ "$defs": { "anyComponent": {}, "anyFunction": {} } });
828 let registry = jsonschema::Registry::new()
829 .add("https://a2ui.org/specification/v1_0/common_types.json", common)
830 .and_then(|registry| {
831 registry.add("https://a2ui.org/specification/v1_0/catalog.json", catalog)
832 })
833 .and_then(jsonschema::RegistryBuilder::prepare)
834 .unwrap();
835 jsonschema::options().with_registry(®istry).build(&meta).unwrap()
836 }
837
838 struct Gauge;
839
840 impl ExtensionComponent for Gauge {
841 fn name(&self) -> &'static str {
842 "Gauge"
843 }
844 fn schema(&self) -> Value {
845 json!({
846 "type": "object",
847 "allOf": [{ "$ref": "#/$defs/CatalogComponentCommon" }],
848 "properties": {
849 "id": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/ComponentId" },
850 "component": { "const": "Gauge" },
851 "label": { "$ref": "https://a2ui.org/specification/v0_9/common_types.json#/$defs/DynamicString" },
852 "value": { "type": "number" }
853 },
854 "required": ["id", "component", "label", "value"],
855 "additionalProperties": false
856 })
857 }
858 fn usage(&self) -> &'static str {
859 "Gauge: {label, value} one number on a dial"
860 }
861 fn allowed_parents(&self) -> &'static [&'static str] {
862 &["Card", "Column"]
863 }
864 fn home(&self, _gauge: &ResolvedComponent<'_>) -> Result<HomeNode, String> {
865 Ok(HomeNode::text("gauge"))
866 }
867 }
868
869 #[test]
870 fn catalogs_are_published_as_a2ui_1_0_documents_that_pass_the_1_0_meta_schema() {
871 let meta = v1_0_meta();
872 let forms = Catalog::forms().document_for(A2uiVersion::V1_0);
873 if let Some(error) = meta.iter_errors(&forms).next() {
874 panic!("forms 1.0 document: {error} at {}", error.instance_path());
875 }
876 assert_eq!(forms["functions"].as_object().unwrap().len(), 10);
877 assert!(forms["components"].get("Image").is_none());
878 assert!(forms["functions"].get("openUrl").is_none());
879 assert_eq!(forms["components"]["Text"]["properties"]["variant"]["enum"][2], "h3");
880 assert!(!forms["components"]["TextField"].to_string().contains("obscured"));
881
882 let gauges = Catalog::extend(ExtensionSpec {
883 id: "https://example.com/a2ui/catalogs/gauges/1.0/catalog.json",
884 name: "gauges",
885 version: "1.0",
886 components: vec![Arc::new(Gauge) as Arc<dyn ExtensionComponent>],
887 })
888 .unwrap()
889 .with_instructions("Use a gauge for one number against a known range.");
890 let document = gauges.document_for(A2uiVersion::V1_0);
891 if let Some(error) = meta.iter_errors(&document).next() {
892 panic!("extension 1.0 document: {error} at {}", error.instance_path());
893 }
894 assert_eq!(document["protocolVersion"], "1.0");
895 let gauge = &document["components"]["Gauge"];
896 assert!(document["components"].get("Text").is_none(), "only what the extension adds");
897 assert!(gauge["properties"].get("id").is_none());
898 assert_eq!(gauge["required"], json!(["component", "label", "value"]));
899 assert!(gauge.get("additionalProperties").is_none());
900 assert_eq!(gauge["properties"]["label"]["$ref"], "common_types.json#/$defs/DynamicString");
901 assert!(gauge.get("allOf").is_none(), "the envelope composes ComponentCommon");
902 assert_eq!(gauge["allowedParents"], json!(["Card", "Column"]));
903 assert!(document["instructions"].as_str().unwrap().contains("Gauge: {label, value}"));
904 assert!(document["instructions"].as_str().unwrap().contains("known range"));
905 assert!(gauges.document_for(A2uiVersion::V0_9_1)["components"]["Text"].is_object());
907 }
908
909 #[test]
910 fn the_forms_catalog_is_the_basic_catalog_without_what_can_fake_a_decision() {
911 let forms = Catalog::forms();
912 assert_eq!(
913 forms.components().collect::<Vec<_>>(),
914 vec![
915 "Button",
916 "Card",
917 "CheckBox",
918 "ChoicePicker",
919 "Column",
920 "DateTimeInput",
921 "Divider",
922 "List",
923 "Row",
924 "Slider",
925 "Tabs",
926 "Text",
927 "TextField"
928 ]
929 );
930 assert_eq!(
931 forms.functions().collect::<Vec<_>>(),
932 vec![
933 "and",
934 "email",
935 "formatString",
936 "length",
937 "not",
938 "numeric",
939 "or",
940 "pluralize",
941 "regex",
942 "required"
943 ]
944 );
945 assert_eq!(forms.document()["catalogId"], FORMS_CATALOG_ID);
946 }
947
948 #[test]
949 fn components_are_checked_against_their_schema() {
950 let forms = Catalog::forms();
951 let text = json!({ "id": "t", "component": "Text", "text": "Invoice INV-10" });
952 assert_eq!(forms.schema_error("Text", &text), None);
953 let bound = json!({ "id": "t", "component": "Text", "text": { "path": "/title" } });
954 assert_eq!(forms.schema_error("Text", &bound), None);
955 let extra = json!({ "id": "t", "component": "Text", "text": "x", "onClick": "y" });
956 assert!(forms.schema_error("Text", &extra).is_some());
957 let obscured = json!({
958 "id": "p", "component": "TextField", "label": "Password", "variant": "obscured"
959 });
960 assert!(forms.schema_error("TextField", &obscured).is_some());
961 let open = json!({
962 "id": "b", "component": "Button", "child": "t",
963 "action": { "functionCall": { "call": "openUrl", "args": { "url": "https://x.test" } } }
964 });
965 assert!(forms.schema_error("Button", &open).is_some(), "openUrl is not in the catalog");
966 }
967
968 #[test]
969 fn a_value_that_may_be_a_binding_or_a_list_names_what_broke_in_the_list() {
970 let forms = Catalog::forms();
971 let picker = json!({
972 "id": "c", "component": "ChoicePicker", "label": "Dock",
973 "options": [{ "label": "Dock 1", "value": "dock-1" }],
974 "value": ["dock-1", 5]
975 });
976 let error = forms.schema_error("ChoicePicker", &picker).expect("a number among strings");
977 assert!(error.starts_with("/value/1: "), "{error}");
978 assert!(!error.contains("oneOf"), "{error}");
979 }
980
981 #[test]
982 fn a_schema_error_quoting_a_long_value_is_shortened() {
983 let forms = Catalog::forms();
984 let long = json!({ "id": "t", "component": "Text", "text": vec![1; 400] });
985 let error = forms.schema_error("Text", &long).expect("a list is not text");
986 assert!(error.chars().count() <= MAX_SCHEMA_ERROR_CHARS + "/text: …".len(), "{error}");
987 assert!(error.ends_with('…'), "{error}");
988 }
989}