1use std::sync::{Arc, LazyLock};
11
12use indexmap::IndexMap;
13use crate::catalog::CatalogView;
14use crate::generated::{catalog as gc, themes as gt};
15use crate::types::{MacroDef, MacroTemplate, TemplateChild};
16pub use crate::types::{PartSpec, Props};
17
18pub const RECIPE_STATES: &[&str] = gt::RECIPE_STATES;
20pub const RECIPE_KEYS: &[&str] = gt::RECIPE_KEYS;
22
23#[derive(serde::Deserialize)]
24struct RecipesFile {
25 native: IndexMap<String, PartSpec>,
26}
27
28static NATIVE_PARTS: LazyLock<IndexMap<String, PartSpec>> =
30 LazyLock::new(|| serde_json::from_str::<RecipesFile>(gc::RECIPES_JSON).expect("recipes.json").native);
31
32fn push_unique(list: &mut Vec<String>, value: &str) {
33 if !list.iter().any(|v| v == value) {
34 list.push(value.to_string());
35 }
36}
37
38fn walk_template(tpl: &MacroTemplate, parts: &mut Vec<String>, props: &mut Vec<String>) {
39 push_unique(parts, &tpl.part);
40 if let Some(recipe) = &tpl.recipe {
41 for key in recipe.keys() {
42 push_unique(props, key);
43 }
44 }
45 for child in tpl.children.iter().flatten() {
46 if let TemplateChild::Node(node) = child {
47 walk_template(node, parts, props);
48 }
49 }
50 for slot in tpl.slots.iter().flat_map(|s| s.values()) {
52 if let TemplateChild::Node(node) = slot {
53 walk_template(node, parts, props);
54 }
55 }
56}
57
58pub fn macro_parts(def: &MacroDef) -> PartSpec {
60 let mut parts = Vec::new();
61 let mut props = Vec::new();
62 for p in &def.recipe_props {
63 push_unique(&mut props, p);
64 }
65 walk_template(&def.root, &mut parts, &mut props);
66 PartSpec { parts, props }
67}
68
69pub fn recipe_parts(view: &CatalogView) -> IndexMap<String, PartSpec> {
73 let mut out = IndexMap::new();
74 for (name, def) in &view.components {
75 if def.is_macro() {
76 if let Some(m) = view.macros.get(name) {
77 out.insert(name.clone(), macro_parts(m));
78 }
79 continue;
80 }
81 let spec = if let Some(native) = NATIVE_PARTS.get(name) {
82 native.clone()
83 } else if let Some(declared) = &def.recipe {
84 declared.clone()
85 } else {
86 PartSpec {
87 parts: vec!["root".into()],
88 props: def
89 .props
90 .iter()
91 .filter(|(_, p)| p.type_ == "enum" || p.type_ == "boolean")
92 .map(|(k, _)| k.clone())
93 .collect(),
94 }
95 };
96 out.insert(name.clone(), spec);
97 }
98 out
99}
100
101#[derive(Debug, Clone)]
104pub struct RecipeIndex {
105 pub parts: IndexMap<String, PartSpec>,
106 defaults: IndexMap<String, Props>,
108 known: IndexMap<String, ()>,
110}
111
112static CORE_INDEX: LazyLock<Arc<RecipeIndex>> = LazyLock::new(|| Arc::new(RecipeIndex::new(&CatalogView::core())));
113
114impl RecipeIndex {
115 pub fn new(view: &CatalogView) -> RecipeIndex {
116 let parts = recipe_parts(view);
117 let mut defaults = IndexMap::new();
118 let mut known = IndexMap::new();
119 for (name, def) in &view.components {
120 known.insert(name.clone(), ());
121 let Some(spec) = parts.get(name) else { continue };
122 let mut d = Props::new();
123 for prop in &spec.props {
124 if let Some(v) = def.props.get(prop).and_then(|p| p.default.as_ref()) {
125 if !v.is_null() {
126 d.insert(prop.clone(), v.clone());
127 }
128 }
129 }
130 defaults.insert(name.clone(), d);
131 }
132 RecipeIndex { parts, defaults, known }
133 }
134
135 pub fn core() -> Arc<RecipeIndex> {
137 CORE_INDEX.clone()
138 }
139
140 pub fn part_spec(&self, component: &str) -> Option<&PartSpec> {
141 self.parts.get(component)
142 }
143
144 pub fn native_recipe_props(&self, component: &str, props: &Props) -> Props {
148 let mut out = Props::new();
149 let (Some(spec), true) = (self.parts.get(component), self.known.contains_key(component)) else {
150 return out;
151 };
152 let defaults = self.defaults.get(component);
153 for name in &spec.props {
154 let value = match props.get(name) {
155 Some(v) if !v.is_null() => Some(v),
156 _ => defaults.and_then(|d| d.get(name)),
157 };
158 if let Some(v) = value {
159 out.insert(name.clone(), v.clone());
160 }
161 }
162 out
163 }
164}
165
166pub fn native_recipe_props(component: &str, props: &Props) -> Props {
168 CORE_INDEX.native_recipe_props(component, props)
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174 use serde_json::{json, Value};
175
176 #[test]
177 fn every_component_has_parts_macro_parts_come_from_the_templates() {
178 let index = RecipeIndex::core();
179 let parts = &index.parts;
180 assert_eq!(parts["Badge"].parts, ["root", "icon", "label"]);
181 assert_eq!(parts["Badge"].props, ["variant"]);
182 assert_eq!(parts["Meter"].props, ["tone"]);
183 assert_eq!(parts["Row"].props, ["selected", "density", "surface", "depth"]);
184 assert_eq!(parts["Section"].props, ["tint", "tree", "open", "collapsible"]);
185 assert_eq!(parts["Segmented"].parts, ["root", "item", "icon", "label", "badge"]);
186 assert_eq!(parts["Menu"].props, ["openOn"]);
187 assert!(parts["Switch"].parts.iter().any(|p| p == "track"));
188 assert_eq!(parts["Button"].props, ["variant", "size", "disabled", "loading"]);
189 assert_eq!(parts.len(), 93);
193 assert!(parts["Carousel"].parts.iter().any(|p| p == "thumbnail"));
194 assert!(parts["Carousel"].props.iter().any(|p| p == "counter"));
195 assert!(parts["DockCard"].parts.iter().any(|p| p == "trigger"));
196 }
197
198 #[test]
199 fn recipe_keys_are_a_subset_of_the_box_visual_keys_plus_the_box_keys_and_native() {
200 let style: Value = serde_json::from_str(gc::STYLE_JSON).unwrap();
201 let mut allowed: Vec<String> = style["visual"].as_object().unwrap().keys().cloned().collect();
202 for k in ["padding", "paddingHorizontal", "paddingVertical", "gap", "width", "height", "minWidth", "minHeight", "native"] {
203 allowed.push(k.into());
204 }
205 for key in RECIPE_KEYS {
206 assert!(allowed.iter().any(|a| a == key), "{key}");
207 }
208 assert!(RECIPE_STATES.contains(&"hover"));
209 }
210
211 #[test]
212 fn native_props_fill_catalog_defaults() {
213 let index = RecipeIndex::core();
214 let props = json!({"text": "x", "variant": "muted"});
215 let out = index.native_recipe_props("Text", props.as_object().unwrap());
216 assert_eq!(out.get("variant"), Some(&json!("muted")));
217 assert!(out.get("text").is_none());
218 assert!(index.native_recipe_props("Nope", &Props::new()).is_empty());
219 }
220}