1use std::collections::HashMap;
41
42use aylis_core::{Color, ColorRef, FontSpec, FontWeight, Look, Metric, PointF, PropEnum, Shadow, Style, StyleProps, Theme};
43use serde_json::{Map, Value};
44
45use crate::value::{bounds, bounds_value, describe, number, object};
46use crate::{Error, Result};
47
48const STATES: [&str; 5] = ["hover", "pressed", "focused", "checked", "disabled"];
49
50pub fn load_theme(json: &str) -> Result<Theme> {
52 let value: Value = serde_json::from_str(json.trim_start_matches('\u{feff}'))?;
53 theme_from_value(&value)
54}
55
56pub fn save_theme(theme: &Theme) -> String {
58 serde_json::to_string_pretty(&theme_to_value(theme)).expect("valores JSON sempre serializam")
59}
60
61pub fn theme_from_value(value: &Value) -> Result<Theme> {
62 let root = object(value, "o tema").map_err(fail(""))?;
63 let name = root.get("name").and_then(Value::as_str).unwrap_or("");
64 let mut theme = match root.get("base") {
65 None => Theme::new(name),
66 Some(base) => {
67 let base = base.as_str().ok_or_else(|| fail(" > base")("\"base\" deve ser o nome de um tema".into()))?;
68 let mut t = aylis_core::themes::builtin(base)
69 .cloned()
70 .ok_or_else(|| fail(" > base")(format!("tema '{base}' não existe na biblioteca")))?;
71 t.name = name.to_string();
72 t
73 }
74 };
75 for (key, value) in root {
76 let path = format!(" > {key}");
77 match key.as_str() {
78 "name" | "$schema" | "base" => {}
79 "family" => theme.family = value.as_str().ok_or_else(|| fail(&path)("\"family\" deve ser texto".into()))?.to_string(),
80 "dark" => theme.dark = value.as_bool().ok_or_else(|| fail(&path)("\"dark\" deve ser true/false".into()))?,
81 "look" => {
82 let name = value.as_str().ok_or_else(|| fail(&path)("\"look\" deve ser texto".into()))?;
83 let index = Look::NAMES.iter().position(|n| *n == name).ok_or_else(|| {
84 fail(&path)(format!("look '{name}' desconhecido; use um de: {}", Look::NAMES.join(", ")))
85 })?;
86 theme.look = Look::from_index(index).unwrap_or_default();
87 }
88 "colors" => {
89 let mut named = Vec::new();
92 for (token, v) in object(value, "colors").map_err(fail(&path))? {
93 let text = v.as_str().ok_or_else(|| fail(&path)(format!("'{token}': esperado \"#RRGGBB\" ou o nome de uma cor")))?;
94 if aylis_core::palette::is_named(text) {
95 named.push((token.clone(), text.to_string()));
96 } else {
97 let color = Color::from_hex(text).ok_or_else(|| fail(&path)(format!("'{token}': cor inválida '{text}'")))?;
98 theme.colors.insert(token.clone(), color);
99 }
100 }
101 while !named.is_empty() {
102 let before = named.len();
103 named.retain(|(token, text)| match theme.resolve_color(text) {
104 Some(c) => {
105 theme.colors.insert(token.clone(), c);
106 false
107 }
108 None => true,
109 });
110 if named.len() == before {
111 let (token, text) = &named[0];
112 return Err(fail(&path)(format!("'{token}': cor desconhecida '{text}'")));
113 }
114 }
115 }
116 "fonts" => {
117 for (token, v) in object(value, "fonts").map_err(fail(&path))? {
118 theme.fonts.insert(token.clone(), font(v).map_err(|m| fail(&path)(format!("'{token}': {m}")))?);
119 }
120 }
121 "radius" => theme.radius = metrics(value).map_err(fail(&path))?,
122 "spacing" => theme.spacing = metrics(value).map_err(fail(&path))?,
123 "durations" => theme.durations = metrics(value).map_err(fail(&path))?,
124 "shadows" => {
125 for (token, v) in object(value, "shadows").map_err(fail(&path))? {
126 theme.shadows.insert(token.clone(), shadow(v).map_err(|m| fail(&path)(format!("'{token}': {m}")))?);
127 }
128 }
129 "components" => {
130 for (class, v) in object(value, "components").map_err(fail(&path))? {
131 let name = v.as_str().ok_or_else(|| fail(&path)(format!("'{class}': esperado o nome de um tema")))?;
132 theme.mix(class, name);
133 }
134 }
135 "styles" => {
136 for (class, v) in object(value, "styles").map_err(fail(&path))? {
137 let style = style(v).map_err(|m| fail(&format!("{path} > {class}"))(m))?;
138 theme.set_style(class, style);
139 }
140 }
141 other => {
142 return Err(fail("")(format!(
143 "chave desconhecida '{other}' (use name, base, family, dark, look, colors, fonts, radius, spacing, durations, shadows, styles, components)"
144 )));
145 }
146 }
147 }
148 if !root.contains_key("dark") && root.get("base").is_none() {
151 let bg = theme.color("background");
152 let luminance = 0.2126 * bg.r as f32 + 0.7152 * bg.g as f32 + 0.0722 * bg.b as f32;
153 theme.dark = bg.a > 0 && luminance < 110.0;
154 }
155 Ok(theme)
156}
157
158fn fail(path: &str) -> impl Fn(String) -> Error + '_ {
159 move |message| Error::Structure { path: format!("tema{path}"), message }
160}
161
162pub fn theme_to_value(theme: &Theme) -> Value {
163 let mut root = Map::new();
164 root.insert("name".into(), Value::String(theme.name.clone()));
165 if !theme.family.is_empty() {
166 root.insert("family".into(), Value::String(theme.family.clone()));
167 }
168 if theme.dark {
169 root.insert("dark".into(), Value::Bool(true));
170 }
171 if theme.look != Look::Aylis {
172 root.insert("look".into(), Value::String(Look::NAMES[theme.look.index()].to_string()));
173 }
174 root.insert("colors".into(), sorted(&theme.colors, |c| Value::String(c.to_hex())));
175 root.insert("fonts".into(), sorted(&theme.fonts, font_value));
176 root.insert("radius".into(), sorted(&theme.radius, |v| number(*v as f64)));
177 root.insert("spacing".into(), sorted(&theme.spacing, |v| number(*v as f64)));
178 root.insert("durations".into(), sorted(&theme.durations, |v| number(*v as f64)));
179 root.insert("styles".into(), sorted(&theme.styles, style_value));
180 if !theme.shadows.is_empty() {
181 root.insert("shadows".into(), sorted(&theme.shadows, shadow_value));
182 }
183 if !theme.components.is_empty() {
184 root.insert("components".into(), sorted(&theme.components, |n| Value::String(n.clone())));
185 }
186 Value::Object(root)
187}
188
189fn sorted<T>(map: &HashMap<String, T>, f: impl Fn(&T) -> Value) -> Value {
190 let mut keys: Vec<&String> = map.keys().collect();
191 keys.sort();
192 Value::Object(keys.into_iter().map(|k| (k.clone(), f(&map[k]))).collect())
193}
194
195fn metrics(value: &Value) -> Result<HashMap<String, f32>, String> {
196 object(value, "a lista de medidas")?
197 .iter()
198 .map(|(k, v)| {
199 v.as_f64().map(|f| (k.clone(), f as f32)).ok_or_else(|| format!("'{k}': esperado número, recebido {}", describe(v)))
200 })
201 .collect()
202}
203
204const WEIGHTS: [(&str, FontWeight); 7] = [
207 ("thin", FontWeight::Thin),
208 ("light", FontWeight::Light),
209 ("normal", FontWeight::Normal),
210 ("medium", FontWeight::Medium),
211 ("semi_bold", FontWeight::SemiBold),
212 ("bold", FontWeight::Bold),
213 ("black", FontWeight::Black),
214];
215
216fn font(value: &Value) -> Result<FontSpec, String> {
217 let mut f = FontSpec::default();
218 for (key, v) in object(value, "a fonte")? {
219 match key.as_str() {
220 "family" => f.family = v.as_str().ok_or("\"family\" deve ser texto")?.to_string(),
221 "size" => f.size = v.as_f64().ok_or("\"size\" deve ser número")? as f32,
222 "italic" => f.italic = v.as_bool().ok_or("\"italic\" deve ser true/false")?,
223 "weight" => {
224 let name = v.as_str().ok_or("\"weight\" deve ser texto")?;
225 f.weight = WEIGHTS
226 .iter()
227 .find(|(n, _)| *n == name)
228 .map(|(_, w)| *w)
229 .ok_or_else(|| format!("peso '{name}' inválido; use um de: {}", WEIGHTS.map(|(n, _)| n).join(", ")))?;
230 }
231 other => return Err(format!("chave desconhecida '{other}' (use family, size, weight, italic)")),
232 }
233 }
234 Ok(f)
235}
236
237fn font_value(f: &FontSpec) -> Value {
238 let mut map = Map::new();
239 map.insert("family".into(), Value::String(f.family.clone()));
240 map.insert("size".into(), number(f.size as f64));
241 let weight = WEIGHTS.iter().find(|(_, w)| *w == f.weight).map_or("normal", |(n, _)| n);
242 map.insert("weight".into(), Value::String(weight.into()));
243 if f.italic {
244 map.insert("italic".into(), Value::Bool(true));
245 }
246 Value::Object(map)
247}
248
249fn shadow(value: &Value) -> Result<Shadow, String> {
252 let mut sh = Shadow::new(Color::rgba(0, 0, 0, 40), 8.0, 0.0, 2.0);
253 for (key, v) in object(value, "a sombra")? {
254 match key.as_str() {
255 "color" => {
256 let text = v.as_str().ok_or("\"color\" deve ser \"#RRGGBBAA\"")?;
257 sh.color = Color::from_hex(text).ok_or_else(|| format!("cor inválida '{text}'"))?;
258 }
259 "blur" => sh.blur = v.as_f64().ok_or("\"blur\" deve ser número")? as f32,
260 "spread" => sh.spread = v.as_f64().ok_or("\"spread\" deve ser número")? as f32,
261 "offset" => match v.as_array().map(Vec::as_slice) {
262 Some([x, y]) => {
263 sh.offset = PointF::new(
264 x.as_f64().ok_or("deslocamento deve ser número")? as f32,
265 y.as_f64().ok_or("deslocamento deve ser número")? as f32,
266 );
267 }
268 _ => return Err("\"offset\" deve ser [x, y]".into()),
269 },
270 other => return Err(format!("chave desconhecida '{other}' (use color, blur, offset, spread)")),
271 }
272 }
273 Ok(sh)
274}
275
276fn shadow_value(sh: &Shadow) -> Value {
277 let mut map = Map::new();
278 map.insert("color".into(), Value::String(sh.color.to_hex()));
279 map.insert("blur".into(), number(sh.blur as f64));
280 map.insert("offset".into(), Value::Array(vec![number(sh.offset.x as f64), number(sh.offset.y as f64)]));
281 if sh.spread != 0.0 {
282 map.insert("spread".into(), number(sh.spread as f64));
283 }
284 Value::Object(map)
285}
286
287fn style(value: &Value) -> Result<Style, String> {
290 let obj = object(value, "o estilo")?;
291 let mut style = Style::new(style_props(obj, true)?);
292 for state in STATES {
293 if let Some(v) = obj.get(state) {
294 let props = style_props(object(v, state)?, false).map_err(|m| format!("{state}: {m}"))?;
295 match state {
296 "hover" => style.hover = props,
297 "pressed" => style.pressed = props,
298 "focused" => style.focused = props,
299 "checked" => style.checked = props,
300 _ => style.disabled = props,
301 }
302 }
303 }
304 Ok(style)
305}
306
307fn style_props(obj: &Map<String, Value>, allow_states: bool) -> Result<StyleProps, String> {
308 let mut p = StyleProps::default();
309 for (key, v) in obj {
310 match key.as_str() {
311 "fill" => p.fill = Some(color_ref(v)?),
312 "text" => p.text = Some(color_ref(v)?),
313 "border_color" => p.border_color = Some(color_ref(v)?),
314 "border_width" => p.border_width = Some(v.as_f64().ok_or("\"border_width\" deve ser número")? as f32),
315 "border" => match v.as_array().map(Vec::as_slice) {
316 Some([color, width]) => {
317 p.border_color = Some(color_ref(color)?);
318 p.border_width = Some(width.as_f64().ok_or("largura da borda deve ser número")? as f32);
319 }
320 _ => return Err("\"border\" deve ser [cor, largura]".into()),
321 },
322 "radius" => p.radius = Some(metric(v)?),
323 "transition" => p.transition = Some(metric(v)?),
324 "padding" => p.padding = Some(bounds(v)?),
325 "font" => p.font = Some(v.as_str().ok_or("\"font\" deve ser o nome de uma fonte do tema")?.to_string()),
326 "opacity" => p.opacity = Some(v.as_f64().ok_or("\"opacity\" deve ser número")? as f32),
327 "shadow" => p.shadow = Some(v.as_str().ok_or("\"shadow\" deve ser o nome de uma sombra do tema")?.to_string()),
328 "material" => p.material = Some(v.as_str().ok_or("\"material\" deve ser glass, frosted ou none")?.to_string()),
329 "text_case" => p.text_case = Some(v.as_str().ok_or("\"text_case\" deve ser upper, lower ou none")?.to_string()),
330 "letter_spacing" => p.letter_spacing = Some(v.as_f64().ok_or("\"letter_spacing\" deve ser número")? as f32),
331 "gap" => p.gap = Some(v.as_f64().ok_or("\"gap\" deve ser número (0 cola as partes)")? as f32),
332 "border_sides" => p.border_sides = Some(bounds(v)?),
333 "border_style" => p.border_style = Some(v.as_str().ok_or("\"border_style\" deve ser solid, dashed ou dotted")?.to_string()),
334 "line_height" => p.line_height = Some(v.as_f64().ok_or("\"line_height\" deve ser número (1.5 = uma vez e meia a fonte)")? as f32),
335 "font_size" => p.font_size = Some(v.as_f64().ok_or("\"font_size\" deve ser número")? as f32),
336 "italic" => p.italic = Some(v.as_bool().ok_or("\"italic\" deve ser true/false")?),
337 "font_weight" => {
338 let name = v.as_str().ok_or("\"font_weight\" deve ser texto")?;
339 p.font_weight = Some(
340 WEIGHTS
341 .iter()
342 .find(|(n, _)| *n == name)
343 .map(|(_, w)| *w)
344 .ok_or_else(|| format!("peso '{name}' inválido; use um de: {}", WEIGHTS.map(|(n, _)| n).join(", ")))?,
345 );
346 }
347 state if allow_states && STATES.contains(&state) => {}
348 other => {
349 return Err(format!(
350 "chave desconhecida '{other}' (use fill, text, border, border_color, border_width, border_sides, \
351 border_style, radius, padding, font, font_weight, font_size, italic, line_height, opacity, transition, shadow, \
352 material, text_case, letter_spacing, gap{})",
353 if allow_states { " e os estados hover, pressed, focused, checked, disabled" } else { "" }
354 ));
355 }
356 }
357 }
358 Ok(p)
359}
360
361fn color_ref(v: &Value) -> Result<ColorRef, String> {
362 let text = v.as_str().ok_or_else(|| format!("cor deve ser texto, recebido {}", describe(v)))?;
363 if text.trim_start().starts_with('#') {
364 Color::from_hex(text).map(ColorRef::Value).ok_or_else(|| format!("cor inválida '{text}'"))
365 } else {
366 Ok(ColorRef::Token(text.to_string()))
367 }
368}
369
370fn metric(v: &Value) -> Result<Metric, String> {
371 match v {
372 Value::String(s) => Ok(Metric::Token(s.clone())),
373 Value::Number(n) => Ok(Metric::Value(n.as_f64().unwrap_or(0.0) as f32)),
374 other => Err(format!("esperado token (texto) ou número, recebido {}", describe(other))),
375 }
376}
377
378fn style_value(style: &Style) -> Value {
379 let mut map = props_value(&style.base);
380 for (state, props) in [
381 ("hover", &style.hover),
382 ("pressed", &style.pressed),
383 ("focused", &style.focused),
384 ("checked", &style.checked),
385 ("disabled", &style.disabled),
386 ] {
387 if *props != StyleProps::default() {
388 map.insert(state.into(), Value::Object(props_value(props)));
389 }
390 }
391 Value::Object(map)
392}
393
394fn props_value(p: &StyleProps) -> Map<String, Value> {
395 let color = |c: &ColorRef| match c {
396 ColorRef::Token(t) => Value::String(t.clone()),
397 ColorRef::Value(c) => Value::String(c.to_hex()),
398 };
399 let metric = |m: &Metric| match m {
400 Metric::Token(t) => Value::String(t.clone()),
401 Metric::Value(v) => number(*v as f64),
402 };
403 let mut map = Map::new();
404 if let Some(c) = &p.fill {
405 map.insert("fill".into(), color(c));
406 }
407 if let Some(c) = &p.text {
408 map.insert("text".into(), color(c));
409 }
410 match (&p.border_color, p.border_width) {
411 (Some(c), Some(w)) => {
412 map.insert("border".into(), Value::Array(vec![color(c), number(w as f64)]));
413 }
414 (Some(c), None) => {
415 map.insert("border_color".into(), color(c));
416 }
417 (None, Some(w)) => {
418 map.insert("border_width".into(), number(w as f64));
419 }
420 (None, None) => {}
421 }
422 if let Some(m) = &p.radius {
423 map.insert("radius".into(), metric(m));
424 }
425 if let Some(b) = p.padding {
426 map.insert("padding".into(), bounds_value(b));
427 }
428 if let Some(f) = &p.font {
429 map.insert("font".into(), Value::String(f.clone()));
430 }
431 if let Some(o) = p.opacity {
432 map.insert("opacity".into(), number(o as f64));
433 }
434 if let Some(m) = &p.transition {
435 map.insert("transition".into(), metric(m));
436 }
437 if let Some(t) = &p.shadow {
438 map.insert("shadow".into(), Value::String(t.clone()));
439 }
440 if let Some(m) = &p.material {
441 map.insert("material".into(), Value::String(m.clone()));
442 }
443 if let Some(t) = &p.text_case {
444 map.insert("text_case".into(), Value::String(t.clone()));
445 }
446 if let Some(l) = p.letter_spacing {
447 map.insert("letter_spacing".into(), number(l as f64));
448 }
449 if let Some(g) = p.gap {
450 map.insert("gap".into(), number(g as f64));
451 }
452 if let Some(b) = p.border_sides {
453 map.insert("border_sides".into(), bounds_value(b));
454 }
455 if let Some(b) = &p.border_style {
456 map.insert("border_style".into(), Value::String(b.clone()));
457 }
458 if let Some(l) = p.line_height {
459 map.insert("line_height".into(), number(l as f64));
460 }
461 if let Some(w) = p.font_weight {
462 if let Some((name, _)) = WEIGHTS.iter().find(|(_, x)| *x == w) {
463 map.insert("font_weight".into(), Value::String((*name).to_string()));
464 }
465 }
466 if let Some(s) = p.font_size {
467 map.insert("font_size".into(), number(s as f64));
468 }
469 if let Some(i) = p.italic {
470 map.insert("italic".into(), Value::Bool(i));
471 }
472 map
473}