1use std::collections::{BTreeMap, BTreeSet, HashMap};
5use std::rc::Rc;
6use std::sync::Arc;
7
8use crate::Problem;
9use crate::fonts::{self, Family, FontFile, FontFiles, FontId};
10use crate::parse::{self, Child, Element, Pos, TextPart, Value};
11use crate::scene::{
12 Align, Color, Files, Fill, Image, ImageFiles, ImageId, Kind, Layout, Node, Origin, Rgba, Scene,
13 Shadow, Size, TextAlign, TextStyle, Vector,
14};
15use crate::tree::NodeId;
16
17pub fn resolve(files: &dyn Files, path: &str) -> Result<Scene, Vec<Problem>> {
19 resolved(files, path).map(|(scene, ..)| scene)
20}
21
22fn resolved(files: &dyn Files, path: &str) -> Result<(Scene, Record, Vec<String>), Vec<Problem>> {
26 let mut r = Resolver::new(files);
27 let root = r.design(path, &[], None, "", None);
28 if r.problems.is_empty() {
29 let scene = Scene::new(
30 root.expect("no problems means a root"),
31 r.images,
32 r.fonts,
33 r.themed,
34 );
35 Ok((scene, r.record, r.read))
36 } else {
37 Err(r.problems)
38 }
39}
40
41impl<'a> Resolver<'a> {
42 fn new(files: &'a dyn Files) -> Resolver<'a> {
44 Resolver {
45 files,
46 problems: Vec::new(),
47 read: Vec::new(),
48 stack: Vec::new(),
49 missing: Vec::new(),
50 depth: 0,
51 images: ImageFiles::new(),
52 by_path: HashMap::new(),
53 fonts: FontFiles::new(),
54 families: HashMap::new(),
55 themes: HashMap::new(),
56 themed: false,
57 instance: Vec::new(),
58 record: Record::default(),
59 current: None,
60 own_only: false,
61 elements: 0,
62 }
63 }
64}
65
66struct Resolver<'a> {
69 files: &'a dyn Files,
71 problems: Vec<Problem>,
73 read: Vec<String>,
76 stack: Vec<String>,
79 missing: Vec<String>,
82 depth: usize,
84 images: ImageFiles,
86 by_path: HashMap<String, Result<ImageId, String>>,
88 fonts: FontFiles,
90 families: HashMap<String, (Found, bool)>,
94 themes: HashMap<String, Rc<Themes>>,
97 themed: bool,
99 instance: Vec<u32>,
102 record: Record,
104 current: Option<NodeId>,
107 own_only: bool,
110 elements: usize,
112}
113
114#[derive(Debug, Clone, Default)]
117struct Record {
118 instances: BTreeMap<Vec<u32>, Instance>,
121 by_file: HashMap<String, BTreeSet<Vec<u32>>>,
123 readers: HashMap<String, BTreeSet<Vec<u32>>>,
126 reads: BTreeMap<Vec<u32>, BTreeSet<String>>,
128 themed: BTreeSet<NodeId>,
130 parses: HashMap<String, Arc<parse::File>>,
132}
133
134impl Record {
135 fn read_by(&mut self, key: &str, id: &[u32]) {
137 self.readers
138 .entry(key.to_string())
139 .or_default()
140 .insert(id.to_vec());
141 self.reads
142 .entry(id.to_vec())
143 .or_default()
144 .insert(key.to_string());
145 }
146
147 fn forget(&mut self, id: &[u32]) {
149 if let Some(keys) = self.reads.remove(id) {
150 for key in keys {
151 if let Some(readers) = self.readers.get_mut(&key) {
152 readers.remove(id);
153 if readers.is_empty() {
154 self.readers.remove(&key);
155 }
156 }
157 }
158 }
159 }
160}
161
162#[derive(Debug, Clone)]
166struct Instance {
167 file: String,
169 props: Arc<Props>,
172 imports: Arc<HashMap<String, String>>,
175 parent: Option<Layout>,
177 caller: Option<Caller>,
180 root: NodeId,
182}
183
184#[derive(Debug, Clone)]
187struct Caller {
188 file: String,
190 overrides: Vec<(parse::Attr, String)>,
193}
194
195fn writes_theme(v: &Value) -> bool {
197 match v {
198 Value::Theme(..) => true,
199 Value::Str(s, _) => s.starts_with("linear-gradient(") && s.contains("theme."),
200 Value::Array(items) => items.iter().any(writes_theme),
201 Value::Object(fields) => fields.iter().any(|(_, v)| writes_theme(v)),
202 _ => false,
203 }
204}
205
206fn themes_chain(path: &str) -> Vec<String> {
209 let mut out = Vec::new();
210 let mut folder = path.rsplit_once('/').map(|(f, _)| f);
211 while let Some(f) = folder {
212 out.push(format!("{f}/{THEMES_FILE}"));
213 folder = f.rsplit_once('/').map(|(f, _)| f);
214 }
215 out.push(THEMES_FILE.to_string());
216 out
217}
218
219#[derive(Debug, Clone, Default)]
223struct Themes {
224 found: bool,
226 light: BTreeMap<String, Rgba>,
228 dark: BTreeMap<String, Rgba>,
230 fonts: BTreeMap<String, ThemesFont>,
232}
233
234#[derive(Debug, Clone)]
237struct ThemesFont {
238 written: String,
240 at: Option<String>,
243 origin: Origin,
245}
246
247struct ThemesFile {
250 light: BTreeMap<String, Rgba>,
252 dark: BTreeMap<String, Rgba>,
254 fonts: BTreeMap<String, ThemesFont>,
256}
257
258pub const THEMES_FILE: &str = "themes.yml";
260
261const MAX_DEPTH: usize = parse::MAX_DEPTH;
264
265#[derive(Debug, Clone)]
268struct Given {
269 value: Value,
272 by: String,
274}
275
276type Props = HashMap<String, Given>;
278
279type Found = Option<Result<Rc<Family>, String>>;
282
283impl Resolver<'_> {
284 fn read_now(&mut self, key: &str) {
287 if let Some(node) = &self.current {
288 let node = node.0.clone();
289 self.record.read_by(key, &node);
290 }
291 }
292
293 fn problem(&mut self, file: &str, pos: Pos, message: String) {
295 self.problems.push(Problem {
296 file: file.to_string(),
297 pos,
298 message,
299 });
300 }
301
302 fn bind_element(&mut self, path: &str, el: &mut Element) {
305 self.bind_own(path, el);
306 for child in &mut el.children {
307 if let Child::Element(e) = child {
308 self.bind_element(path, e);
309 }
310 }
311 }
312
313 fn bind_own(&mut self, path: &str, el: &mut Element) {
316 let themed = el.attrs.iter().any(|a| writes_theme(&a.value));
317 let props_themed = el
318 .attrs
319 .iter()
320 .any(|a| a.name == "props" && writes_theme(&a.value));
321 for attr in &mut el.attrs {
322 self.bind(path, &mut attr.value);
323 }
324 if themed {
325 let mut id = self.instance.clone();
326 id.push(el.id);
327 for file in themes_chain(path) {
328 self.record.read_by(&file, &id);
329 }
330 }
331 if props_themed {
335 let instance = self.instance.clone();
336 for file in themes_chain(path) {
337 self.record.read_by(&file, &instance);
338 }
339 }
340 }
341
342 fn bind(&mut self, path: &str, value: &mut Value) {
346 match value {
347 Value::Theme(name, pos) => {
348 let (light, dark) = self
351 .theme_color(path, name, *pos)
352 .map_or(("#0000".into(), "#0000".into()), |(l, d)| (hex(l), hex(d)));
353 *value = Value::Themed {
354 light,
355 dark,
356 written: format!("theme.{name}"),
357 };
358 }
359 Value::Str(s, pos) if s.starts_with("linear-gradient(") && s.contains("theme.") => {
360 let (mut light, mut dark) = (String::new(), String::new());
361 let mut rest = s.as_str();
362 let mut col = pos.col + 1;
363 while let Some(at) = rest.find("theme.") {
364 let before = &rest[..at];
365 light.push_str(before);
366 dark.push_str(before);
367 col += before.chars().count() as u32;
368 let after = &rest[at + "theme.".len()..];
369 let len = after
370 .find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-'))
371 .unwrap_or(after.len());
372 let name = &after[..len];
373 let at_ref = Pos {
374 line: pos.line,
375 col,
376 };
377 match self.theme_color(path, name, at_ref) {
378 Some((l, d)) => {
379 light.push_str(&hex(l));
380 dark.push_str(&hex(d));
381 }
382 None => {
384 light.push_str("#0000");
385 dark.push_str("#0000");
386 }
387 }
388 col += ("theme.".len() + name.chars().count()) as u32;
389 rest = &after[len..];
390 }
391 light.push_str(rest);
392 dark.push_str(rest);
393 *value = Value::Themed {
394 light,
395 dark,
396 written: format!("\"{s}\""),
397 };
398 }
399 Value::Array(items) => {
400 for item in items {
401 self.bind(path, item);
402 }
403 }
404 Value::Object(fields) => {
405 for (_, v) in fields {
406 self.bind(path, v);
407 }
408 }
409 _ => {}
410 }
411 }
412
413 fn theme_color(&mut self, path: &str, name: &str, pos: Pos) -> Option<(Rgba, Rgba)> {
416 let folder = path.rsplit_once('/').map_or("", |(folder, _)| folder);
417 let themes = self.themes(folder);
418 let problem = if !themes.found {
419 format!(
420 "theme.{name}: no {THEMES_FILE} with kind: themes in this design's folder or above it"
421 )
422 } else {
423 match (themes.light.get(name), themes.dark.get(name)) {
424 (Some(l), Some(d)) => return Some((*l, *d)),
425 (None, None) => {
426 let mut names: Vec<&String> =
427 themes.light.keys().chain(themes.dark.keys()).collect();
428 names.sort();
429 names.dedup();
430 let names: Vec<&str> = names.iter().map(|n| n.as_str()).collect();
431 if names.is_empty() {
432 format!("theme.{name}: the themes have no colors")
433 } else {
434 format!(
435 "theme.{name}: the themes have no {name}; they have {}",
436 names.join(", ")
437 )
438 }
439 }
440 (Some(_), None) => format!(
441 "theme.{name}: only the light theme has {name}; a name needs a color in both"
442 ),
443 (None, Some(_)) => format!(
444 "theme.{name}: only the dark theme has {name}; a name needs a color in both"
445 ),
446 }
447 };
448 self.problem(path, pos, problem);
449 None
450 }
451
452 fn themes(&mut self, folder: &str) -> Rc<Themes> {
456 if let Some(themes) = self.themes.get(folder) {
457 return themes.clone();
458 }
459 let above = match folder.rsplit_once('/') {
460 Some((parent, _)) => self.themes(parent),
461 None if folder.is_empty() => Rc::new(Themes::default()),
462 None => self.themes(""),
463 };
464 let file = if folder.is_empty() {
465 THEMES_FILE.to_string()
466 } else {
467 format!("{folder}/{THEMES_FILE}")
468 };
469 let themes = match self.themes_file(&file) {
470 None => above,
471 Some(own) => {
472 let mut merged = (*above).clone();
473 merged.found = true;
474 merged.light.extend(own.light);
475 merged.dark.extend(own.dark);
476 merged.fonts.extend(own.fonts);
477 Rc::new(merged)
478 }
479 };
480 self.themes.insert(folder.to_string(), themes.clone());
481 themes
482 }
483
484 fn themes_file(&mut self, path: &str) -> Option<ThemesFile> {
488 let text = self.files.read(path)?;
489 if !self.read.iter().any(|p| p == path) {
490 self.read.push(path.to_string());
491 }
492 let mut file = ThemesFile {
493 light: BTreeMap::new(),
494 dark: BTreeMap::new(),
495 fonts: BTreeMap::new(),
496 };
497 let yaml: serde_yaml::Value = match serde_yaml::from_str(&text) {
498 Ok(yaml) => yaml,
499 Err(e) => {
500 if !text.lines().any(|l| l.trim() == "kind: themes") {
502 return None;
503 }
504 let pos = e.location().map_or(Pos { line: 1, col: 1 }, |l| Pos {
505 line: l.line() as u32,
506 col: l.column() as u32,
507 });
508 self.problem(path, pos, format!("this themes file isn't valid YAML: {e}"));
509 return Some(file);
510 }
511 };
512 let serde_yaml::Value::Mapping(top) = yaml else {
513 return None;
514 };
515 if top.get("kind").and_then(|k| k.as_str()) != Some("themes") {
516 return None;
517 }
518 let start = Pos { line: 1, col: 1 };
519 for (key, value) in &top {
520 let key = key.as_str().unwrap_or_default();
521 let theme = match key {
522 "kind" => continue,
523 "light" => &mut file.light,
524 "dark" => &mut file.dark,
525 "fonts" => {
526 self.themes_fonts(path, &text, value, &mut file.fonts);
527 continue;
528 }
529 other => {
530 let pos = key_pos(&text, None, other).unwrap_or(start);
531 self.problem(
532 path,
533 pos,
534 format!("{other}: a themes file has kind, fonts, light and dark only"),
535 );
536 continue;
537 }
538 };
539 let at = key_pos(&text, None, key).unwrap_or(start);
540 let serde_yaml::Value::Mapping(colors) = value else {
541 self.problem(
542 path,
543 at,
544 format!("{key}: expected a map of names to colors, like surface: \"#ffffff\""),
545 );
546 continue;
547 };
548 for (name, color) in colors {
549 let Some(name) = name.as_str() else {
550 self.problem(path, at, format!("{key}: a color's name is text"));
551 continue;
552 };
553 let pos = key_pos(&text, Some(key), name).unwrap_or(at);
554 if name.is_empty()
555 || name.starts_with(|c: char| c.is_ascii_digit() || c == '-')
556 || !name
557 .chars()
558 .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
559 {
560 self.problem(
561 path,
562 pos,
563 format!(
564 "{key}.{name}: a name holds letters, digits, _ and -, and starts with a letter"
565 ),
566 );
567 continue;
568 }
569 let value = match color {
570 serde_yaml::Value::String(s) => rgba(s),
571 serde_yaml::Value::Null => Err(
572 "no color: write it in quotes, \"#rrggbb\", as YAML reads # as a comment"
573 .to_string(),
574 ),
575 _ => Err("expected a color like \"#rrggbb\"".to_string()),
576 };
577 match value {
578 Ok(c) => {
579 theme.insert(name.to_string(), c);
580 }
581 Err(e) => self.problem(path, pos, format!("{key}.{name}: {e}")),
582 }
583 }
584 }
585 for needed in ["light", "dark"] {
586 if !top.contains_key(needed) {
587 self.problem(
588 path,
589 start,
590 format!("a themes file has a light and a dark theme; this one has no {needed}"),
591 );
592 }
593 }
594 Some(file)
595 }
596
597 fn themes_fonts(
601 &mut self,
602 path: &str,
603 text: &str,
604 value: &serde_yaml::Value,
605 into: &mut BTreeMap<String, ThemesFont>,
606 ) {
607 let start = Pos { line: 1, col: 1 };
608 let at = key_pos(text, None, "fonts").unwrap_or(start);
609 let serde_yaml::Value::Mapping(entries) = value else {
610 self.problem(
611 path,
612 at,
613 "fonts: expected a map of names to font files or folders, like figtree: ./fonts/Figtree".into(),
614 );
615 return;
616 };
617 for (name, written) in entries {
618 let Some(name) = name.as_str() else {
619 self.problem(path, at, "fonts: a font's name is text".into());
620 continue;
621 };
622 let pos = key_pos(text, Some("fonts"), name).unwrap_or(at);
623 if name.is_empty()
624 || !name
625 .chars()
626 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
627 {
628 self.problem(
629 path,
630 pos,
631 format!(
632 "fonts.{name}: a font's name holds lowercase letters, digits and - only"
633 ),
634 );
635 continue;
636 }
637 let Some(written) = written.as_str() else {
638 self.problem(
639 path,
640 pos,
641 format!("fonts.{name}: expected a path to a font file or a folder of one family's, like ./fonts/Figtree"),
642 );
643 continue;
644 };
645 into.insert(
646 name.to_string(),
647 ThemesFont {
648 written: written.to_string(),
649 at: join(path, written),
650 origin: Origin {
651 file: path.to_string(),
652 pos,
653 },
654 },
655 );
656 }
657 }
658
659 fn scope(
663 &mut self,
664 path: &str,
665 file: &parse::File,
666 ) -> Option<(HashMap<String, String>, Props)> {
667 let mut imports = HashMap::new();
668 for import in &file.imports {
669 if import.name == parse::THEME {
670 self.problem(
671 path,
672 import.pos,
673 format!(
674 "import {0} — {0} is the name of the design's themes",
675 import.name
676 ),
677 );
678 continue;
679 }
680 if ELEMENTS.contains(&import.name.as_str()) {
681 self.problem(
682 path,
683 import.pos,
684 format!("import {0} — {0} is a built-in element", import.name),
685 );
686 continue;
687 }
688 if imports.contains_key(&import.name) {
689 self.problem(
690 path,
691 import.pos,
692 format!("import {0} — {0} is already imported", import.name),
693 );
694 continue;
695 }
696 if !import.path.ends_with(".design") {
697 self.problem(
698 path,
699 import.pos,
700 format!("import {} — a design is a .design file", import.path),
701 );
702 continue;
703 }
704 match join(path, &import.path) {
705 Some(target) => {
706 if self.files.read(&target).is_none() {
708 self.problem(
709 path,
710 import.pos,
711 format!("import {} — no such file", import.path),
712 );
713 self.missing.push(target.clone());
714 }
715 imports.insert(import.name.clone(), target);
716 }
717 None => self.problem(
718 path,
719 import.pos,
720 format!("import {} — outside the served folder", import.path),
721 ),
722 }
723 }
724 if file.root.name != "Frame" {
725 self.problem(
726 path,
727 file.root.pos,
728 format!("the root element must be a Frame, not {}", file.root.name),
729 );
730 return None;
731 }
732 let mut props = Props::new();
734 if let Some(attr) = file.root.attrs.iter().find(|a| a.name == "props") {
735 match &attr.value {
736 Value::Object(fields) => {
737 for (k, v) in fields {
738 if k == parse::THEME {
739 self.problem(
740 path,
741 attr.pos,
742 format!(
743 "props: {k} is the name of the design's themes, not a prop"
744 ),
745 );
746 continue;
747 }
748 props.insert(
749 k.clone(),
750 Given {
751 value: v.clone(),
752 by: path.to_string(),
753 },
754 );
755 }
756 }
757 _ => self.problem(
758 path,
759 attr.pos,
760 "props: expected an object of defaults".into(),
761 ),
762 }
763 }
764 Some((imports, props))
765 }
766
767 fn design(
769 &mut self,
770 path: &str,
771 args: &[(parse::Attr, String)],
772 from: Option<(&str, Pos)>,
773 used_as: &str,
774 parent: Option<Layout>,
775 ) -> Option<Node> {
776 if self.stack.iter().any(|p| p == path) {
777 let (file, pos) = from.unwrap_or((path, Pos { line: 1, col: 1 }));
778 self.problem(file, pos, format!("{path} uses itself"));
779 return None;
780 }
781 let Some(source) = self.files.read(path) else {
782 if from.is_some() && self.missing.iter().any(|p| p == path) {
783 return None;
784 }
785 let (file, pos) = from.unwrap_or((path, Pos { line: 1, col: 1 }));
786 self.problem(file, pos, format!("{path} — no such file"));
787 return None;
788 };
789 if !self.read.iter().any(|p| p == path) {
790 self.read.push(path.to_string());
791 }
792 let mut file = match self.files.parse(path, &source) {
793 Ok(file) => {
794 self.record.parses.insert(path.to_string(), file.clone());
795 (*file).clone()
796 }
797 Err(mut problem) => {
798 problem.file = path.to_string();
799 self.problems.push(problem);
800 return None;
801 }
802 };
803 self.bind_element(path, &mut file.root);
806 let (imports, mut props) = self.scope(path, &file)?;
807 let (caller, caller_pos) = from.unwrap_or((path, file.root.pos));
808 let caller = caller.to_string();
809 let mut overrides = Vec::new();
810 for (arg, by) in args {
811 if matches!(
812 arg.name.as_str(),
813 "x" | "y" | "width" | "height" | "name" | "opacity" | "onClick"
814 ) {
815 overrides.push((arg.clone(), by.clone()));
816 } else if props.contains_key(&arg.name) {
817 props.insert(
818 arg.name.clone(),
819 Given {
820 value: arg.value.clone(),
821 by: by.clone(),
822 },
823 );
824 } else {
825 self.problem(
826 &caller,
827 arg.pos,
828 format!("{used_as} has no prop \"{}\"", arg.name),
829 );
830 }
831 }
832 let _ = caller_pos;
833 let key = self.instance.clone();
834 for target in imports.values() {
835 self.record.read_by(target, &key);
836 }
837 self.record.instances.insert(
838 key.clone(),
839 Instance {
840 file: path.to_string(),
841 props: Arc::new(props.clone()),
842 imports: Arc::new(imports.clone()),
843 parent,
844 caller: from.map(|_| Caller {
845 file: caller.clone(),
846 overrides: overrides.clone(),
847 }),
848 root: {
849 let mut id = key.clone();
850 id.push(file.root.id);
851 NodeId(id)
852 },
853 },
854 );
855 self.record
856 .by_file
857 .entry(path.to_string())
858 .or_default()
859 .insert(key);
860 self.stack.push(path.to_string());
861 let mut root = self.element(path, &file.root, &props, &imports, true, parent);
862 self.stack.pop();
863 if let Some(root) = root.as_mut() {
864 self.current = Some(root.id.clone());
865 for (attr, by) in &overrides {
866 self.common(&caller, by, root, attr, attr.value.clone());
868 self.fill_needs_layout(&caller, attr, &attr.value, parent);
869 self.place_needs_no_layout(&caller, attr, parent);
870 }
871 }
872 root
873 }
874
875 fn element(
879 &mut self,
880 path: &str,
881 el: &Element,
882 props: &Props,
883 imports: &HashMap<String, String>,
884 root: bool,
885 parent: Option<Layout>,
886 ) -> Option<Node> {
887 if self.depth >= MAX_DEPTH {
888 self.problem(path, el.pos, format!("nested more than {MAX_DEPTH} deep"));
889 return None;
890 }
891 self.depth += 1;
892 self.elements += 1;
893 let node = self.element_inner(path, el, props, imports, root, parent);
894 self.depth -= 1;
895 node
896 }
897
898 fn element_inner(
901 &mut self,
902 path: &str,
903 el: &Element,
904 props: &Props,
905 imports: &HashMap<String, String>,
906 root: bool,
907 parent: Option<Layout>,
908 ) -> Option<Node> {
909 let mut seen: Vec<&str> = Vec::new();
912 let mut attrs = Vec::new();
913 for attr in &el.attrs {
914 if seen.contains(&attr.name.as_str()) {
915 self.problem(path, attr.pos, format!("{} is given twice", attr.name));
916 } else {
917 seen.push(&attr.name);
918 attrs.push(attr);
919 }
920 }
921 if let Some(target) = imports.get(&el.name) {
922 if !el.children.is_empty() {
923 self.problem(path, el.pos, format!("{} takes no children", el.name));
924 }
925 let args: Vec<(parse::Attr, String)> = attrs
926 .iter()
927 .filter(|a| a.name != "key" || !self.key_ok(path, a))
928 .map(|a| {
929 let (value, by) = substitute(&a.value, props, path);
930 let arg = parse::Attr {
931 name: a.name.clone(),
932 value,
933 pos: a.pos,
934 };
935 (arg, by)
936 })
937 .collect();
938 let target = target.clone();
939 self.instance.push(el.id);
940 let node = self.design(&target, &args, Some((path, el.pos)), &el.name, parent);
941 self.instance.pop();
942 return node;
943 }
944 let kind = match el.name.as_str() {
945 "Frame" => Kind::Frame,
947 "Text" => Kind::Text,
948 "Rect" => Kind::Rect,
949 "Ellipse" => Kind::Ellipse,
950 "Vector" => Kind::Vector,
951 "Image" => Kind::Image,
952 other => {
953 self.problem(path, el.pos, format!("unknown element {other}"));
954 return None;
955 }
956 };
957 let mut node = Node::new(kind, &el.name);
958 let mut id = self.instance.clone();
959 id.push(el.id);
960 node.id = NodeId(id);
961 self.current = Some(node.id.clone());
962 let mut font = None;
965 for &attr in &attrs {
966 if attr.name == "props" {
967 if !root {
968 self.problem(
969 path,
970 attr.pos,
971 "props: only a design's root declares props".into(),
972 );
973 }
974 continue;
975 }
976 if root && matches!(attr.name.as_str(), "x" | "y") {
979 self.problem(
980 path,
981 attr.pos,
982 format!(
983 "{}: a design's root has no place of its own; place an instance with x and y where it is used",
984 attr.name
985 ),
986 );
987 continue;
988 }
989 let (value, by) = match &attr.value {
990 Value::Prop(p) => match props.get(p) {
991 Some(given) => (given.value.clone(), given.by.clone()),
992 None => {
993 self.problem(path, attr.pos, format!("{}: no prop \"{p}\"", attr.name));
994 continue;
995 }
996 },
997 v => (v.clone(), path.to_string()),
998 };
999 if has_theme(&value) {
1000 self.themed = true;
1001 self.record.themed.insert(node.id.clone());
1002 }
1003 self.fill_needs_layout(path, attr, &value, parent);
1004 self.place_needs_no_layout(path, attr, parent);
1005 if kind == Kind::Text && attr.name == "font" {
1006 font = Some((attr, value, by));
1007 continue;
1008 }
1009 self.attribute(path, &by, &mut node, attr, value);
1010 }
1011 match kind {
1012 Kind::Vector if !el.attrs.iter().any(|a| a.name == "d") => self.problem(
1013 path,
1014 el.pos,
1015 format!("{} needs a path, d=\"M…\"", node.name),
1016 ),
1017 Kind::Image if node.image.is_none() && !el.attrs.iter().any(|a| a.name == "src") => {
1018 self.problem(
1019 path,
1020 el.pos,
1021 format!("{} needs a file, src=\"…\"", node.name),
1022 )
1023 }
1024 _ => {}
1025 }
1026 if kind == Kind::Text {
1027 let mut content = String::new();
1028 for child in &el.children {
1029 match child {
1030 Child::Text(parts, pos) => {
1031 for part in parts {
1032 match part {
1033 TextPart::Literal(s) => content.push_str(s),
1034 TextPart::Prop(p) => match props.get(p).map(|g| &g.value) {
1035 Some(Value::Str(s, _)) => content.push_str(s),
1036 Some(Value::Num(n)) => content.push_str(&n.to_string()),
1037 _ => self.problem(path, *pos, format!("no text prop \"{p}\"")),
1038 },
1039 TextPart::Theme(name, at) => self.problem(
1040 path,
1041 *at,
1042 format!(
1043 "theme.{name} is a color, not text: give it to color={{theme.{name}}}"
1044 ),
1045 ),
1046 }
1047 }
1048 }
1049 Child::Element(e) => self.problem(path, e.pos, "Text holds text only".into()),
1050 }
1051 }
1052 let text = node.text.get_or_insert_with(default_text);
1053 text.content = content;
1054 let weight = text.weight;
1055 let weight_at = attrs.iter().find(|a| a.name == "weight").map(|a| a.pos);
1056 text.font = self.text_font(path, el.pos, font, weight, weight_at);
1057 } else {
1058 let mut keys: HashMap<&str, Pos> = HashMap::new();
1059 for child in &el.children {
1060 if let Child::Element(e) = child
1061 && let Some(k) = crate::ids::key(e)
1062 && keys.insert(k, e.pos).is_some()
1063 {
1064 let at = e
1065 .attrs
1066 .iter()
1067 .find(|a| a.name == "key")
1068 .map_or(e.pos, |a| a.pos);
1069 self.problem(path, at, format!("key: {k:?} is another sibling's key too"));
1070 }
1071 match child {
1072 Child::Element(_) if self.own_only => {}
1073 Child::Element(e) => {
1074 if kind != Kind::Frame {
1075 self.problem(path, e.pos, format!("{} takes no children", el.name));
1076 } else if let Some(n) =
1077 self.element(path, e, props, imports, false, Some(node.layout))
1078 {
1079 node.children.push(n);
1080 self.current = Some(node.id.clone());
1081 }
1082 }
1083 Child::Text(_, pos) => self.problem(
1084 path,
1085 *pos,
1086 format!("text belongs in a Text, not a {}", el.name),
1087 ),
1088 }
1089 }
1090 }
1091 Some(node)
1092 }
1093
1094 fn fill_needs_layout(
1097 &mut self,
1098 path: &str,
1099 attr: &parse::Attr,
1100 value: &Value,
1101 parent: Option<Layout>,
1102 ) {
1103 if parent == Some(Layout::None)
1104 && matches!(attr.name.as_str(), "width" | "height")
1105 && matches!(value, Value::Str(s, _) if s == "fill")
1106 {
1107 self.problem(
1108 path,
1109 attr.pos,
1110 format!(
1111 "{}: \"fill\" needs a parent with layout=\"row\" or \"column\"",
1112 attr.name
1113 ),
1114 );
1115 }
1116 }
1117
1118 fn place_needs_no_layout(&mut self, path: &str, attr: &parse::Attr, parent: Option<Layout>) {
1121 if matches!(parent, Some(Layout::Row | Layout::Column))
1122 && matches!(attr.name.as_str(), "x" | "y")
1123 {
1124 self.problem(
1125 path,
1126 attr.pos,
1127 format!(
1128 "{}: places a child only in a frame with layout=\"none\"",
1129 attr.name
1130 ),
1131 );
1132 }
1133 }
1134
1135 #[allow(clippy::unit_arg)]
1139 fn attribute(
1140 &mut self,
1141 path: &str,
1142 by: &str,
1143 node: &mut Node,
1144 attr: &parse::Attr,
1145 value: Value,
1146 ) {
1147 let kind = node.kind;
1148 let (at_file, at_pos) = written_at(path, by, attr, &value);
1151 let ok = match (attr.name.as_str(), kind) {
1152 ("x" | "y" | "width" | "height" | "name" | "opacity" | "onClick", _) => {
1153 self.common(path, by, node, attr, value);
1154 return;
1155 }
1156 ("key", _) => {
1157 self.key_ok(path, attr);
1158 return;
1159 }
1160 ("fill", k) if k != Kind::Text => fill(&value).map(|f| node.fill = Some(f)),
1161 ("stroke", k) if k != Kind::Text => color(&value).map(|c| node.stroke = Some(c)),
1162 ("strokeWidth", k) if k != Kind::Text => px(&value).map(|n| node.stroke_width = n),
1163 ("radius", k) if k != Kind::Text => match &value {
1164 Value::Num(_) => px(&value).map(|n| node.radius = [n; 4]),
1165 Value::Array(a) if a.len() == 4 => {
1166 pxs(a).map(|v| node.radius = [v[0], v[1], v[2], v[3]])
1167 }
1168 _ => Err("expected pixels or an array of 4".into()),
1169 },
1170 ("shadow", k) if k != Kind::Text => shadow(&value).map(|mut s| {
1171 s.at = Origin {
1172 file: path.to_string(),
1173 pos: attr.pos,
1174 };
1175 node.shadow = Some(s)
1176 }),
1177 ("clip", Kind::Frame) => match value {
1179 Value::Bool(b) => Ok(node.clip = b),
1180 _ => Err("expected true or false".into()),
1181 },
1182 ("layout", Kind::Frame) => match str_of(&value).as_deref() {
1183 Some("row") => Ok(node.layout = Layout::Row),
1184 Some("column") => Ok(node.layout = Layout::Column),
1185 Some("none") => Ok(node.layout = Layout::None),
1186 _ => Err("expected \"row\", \"column\" or \"none\"".into()),
1187 },
1188 ("gap", Kind::Frame) => px(&value).map(|n| node.gap = n),
1189 ("padding", Kind::Frame) => match &value {
1190 Value::Num(_) => px(&value).map(|n| node.padding = [n; 4]),
1191 Value::Array(a) if a.len() == 2 => {
1192 pxs(a).map(|v| node.padding = [v[0], v[1], v[0], v[1]])
1193 }
1194 Value::Array(a) if a.len() == 4 => {
1195 pxs(a).map(|v| node.padding = [v[0], v[1], v[2], v[3]])
1196 }
1197 other => Err(format!(
1198 "expected pixels or an array of 2 or 4, found {}",
1199 show(other)
1200 )),
1201 },
1202 ("align", Kind::Frame) => align(&value, false).map(|a| node.align = a),
1203 ("justify", Kind::Frame) => align(&value, true).map(|a| node.justify = a),
1204 ("size", Kind::Text) => {
1205 px(&value).map(|n| node.text.get_or_insert_with(default_text).size = n)
1206 }
1207 ("weight", Kind::Text) => match num(&value) {
1208 Ok(w) if fonts::WEIGHTS.iter().any(|&k| k as f32 == w) => {
1209 Ok(node.text.get_or_insert_with(default_text).weight = w as u16)
1210 }
1211 _ => Err("expected 100 to 900 in steps of 100".into()),
1212 },
1213 ("color", Kind::Text) => {
1214 color(&value).map(|c| node.text.get_or_insert_with(default_text).color = c)
1215 }
1216 ("lineHeight", Kind::Text) => {
1217 px(&value).map(|n| node.text.get_or_insert_with(default_text).line_height = n)
1218 }
1219 ("textAlign", Kind::Text) => match str_of(&value).as_deref() {
1220 Some("left") => {
1221 Ok(node.text.get_or_insert_with(default_text).align = TextAlign::Left)
1222 }
1223 Some("center") => {
1224 Ok(node.text.get_or_insert_with(default_text).align = TextAlign::Center)
1225 }
1226 Some("right") => {
1227 Ok(node.text.get_or_insert_with(default_text).align = TextAlign::Right)
1228 }
1229 _ => Err("expected \"left\", \"center\" or \"right\"".into()),
1230 },
1231 ("d", Kind::Vector) => match str_of(&value) {
1232 Some(d) => match path_numbers(&d).map_err(|e| e.to_string()).and_then(|()| {
1233 kurbo::BezPath::from_svg(&d).map_err(|e| format!("not SVG path data: {e}"))
1234 }) {
1235 Ok(_) => {
1236 let view_box = node.vector.as_ref().map(|v| v.view_box);
1237 let view_box = view_box.unwrap_or_else(|| bounds(&d));
1238 Ok(node.vector = Some(Vector { d, view_box }))
1239 }
1240 Err(e) => Err(e),
1241 },
1242 None => Err("expected SVG path data".into()),
1243 },
1244 ("viewBox", Kind::Vector) => match str_of(&value).as_deref().map(view_box) {
1245 Some(Ok(b)) => {
1246 let v = node.vector.get_or_insert_with(|| Vector {
1247 d: String::new(),
1248 view_box: b,
1249 });
1250 Ok(v.view_box = b)
1251 }
1252 Some(Err(e)) => Err(e),
1253 None => Err("expected \"minX minY width height\"".into()),
1254 },
1255 ("src", Kind::Image) => match str_of(&value) {
1256 Some(src) => match join(by, &src) {
1257 None => {
1258 let e = format!("src: {src} — outside the served folder");
1259 self.problem(&at_file, at_pos, e);
1260 return;
1261 }
1262 Some(at) => match self.image_file(&at) {
1263 None => {
1264 self.problem(&at_file, at_pos, format!("src: {src} — no such file"));
1265 return;
1266 }
1267 Some(Err(e)) => {
1268 self.problem(&at_file, at_pos, format!("src: {src} {e}"));
1269 return;
1270 }
1271 Some(Ok(id)) => {
1272 node.image = Some(Image {
1273 src: at,
1274 id,
1275 at: Origin {
1276 file: path.to_string(),
1277 pos: attr.pos,
1278 },
1279 });
1280 Ok(())
1281 }
1282 },
1283 },
1284 None => Err("expected a path".into()),
1285 },
1286 (name, _) => {
1287 self.problem(
1288 path,
1289 attr.pos,
1290 format!("{} takes no attribute {name}", node.name),
1291 );
1292 return;
1293 }
1294 };
1295 if let Err(e) = ok {
1296 self.problem(path, attr.pos, format!("{}: {e}", attr.name));
1297 }
1298 }
1299
1300 fn image_file(&mut self, at: &str) -> Option<Result<ImageId, String>> {
1304 self.read_now(at);
1305 if let Some(known) = self.by_path.get(at) {
1306 return Some(known.clone());
1307 }
1308 let file = self.files.image(at)?;
1309 if !self.read.iter().any(|p| p == at) {
1310 self.read.push(at.to_string());
1311 }
1312 let id = file.map(|file| {
1313 let id = file.id;
1314 self.images.entry(id).or_insert(file);
1315 id
1316 });
1317 self.by_path.insert(at.to_string(), id.clone());
1318 Some(id)
1319 }
1320
1321 fn text_font(
1328 &mut self,
1329 path: &str,
1330 pos: Pos,
1331 font: Option<(&parse::Attr, Value, String)>,
1332 weight: u16,
1333 weight_at: Option<Pos>,
1334 ) -> Option<FontId> {
1335 let Some((attr, value, by)) = font else {
1336 if !fonts::INTER_WEIGHTS.contains(&weight) {
1337 self.no_weight(
1338 path,
1339 pos,
1340 weight_at,
1341 weight,
1342 fonts::INTER,
1343 &fonts::INTER_WEIGHTS,
1344 );
1345 }
1346 return None;
1347 };
1348 let (file, at_pos) = written_at(path, &by, attr, &value);
1349 let Some(name) = str_of(&value) else {
1350 self.problem(
1351 &file,
1352 at_pos,
1353 "font: expected the name of a font the themes name, like \"figtree\"".into(),
1354 );
1355 return None;
1356 };
1357 let folder = by.rsplit_once('/').map_or("", |(folder, _)| folder);
1358 for file in themes_chain(&by) {
1359 self.read_now(&file);
1360 }
1361 let named = self.themes(folder).fonts.clone();
1362 let Some(entry) = named.get(&name) else {
1363 let problem = if named.is_empty() {
1364 format!(
1365 "font: no font named {name}; no {THEMES_FILE} in this design's folder or above it names fonts"
1366 )
1367 } else {
1368 let names: Vec<&str> = named.keys().map(String::as_str).collect();
1369 format!(
1370 "font: no font named {name}; the themes name {}",
1371 names.join(", ")
1372 )
1373 };
1374 self.problem(&file, at_pos, problem);
1375 return None;
1376 };
1377 let origin = entry.origin.clone();
1378 let Some(at) = entry.at.clone() else {
1379 let key = format!("{}\0{}", origin.file, name);
1380 if let std::collections::hash_map::Entry::Vacant(first) = self.families.entry(key) {
1381 first.insert((None, true));
1382 self.problem(
1383 &origin.file,
1384 origin.pos,
1385 format!(
1386 "fonts.{name}: {} — outside the served folder",
1387 entry.written
1388 ),
1389 );
1390 }
1391 return None;
1392 };
1393 self.read_now(&at);
1394 self.read_now(&format!("{at}/"));
1395 let (family, reported) = self.family(&at);
1396 let family = match family {
1397 Some(Ok(family)) => family,
1398 missing_or_bad => {
1399 if !reported {
1400 let problem = match missing_or_bad {
1401 Some(Err(e)) => format!("fonts.{name}: {} {e}", entry.written),
1402 _ => format!("fonts.{name}: {} — no such file or folder", entry.written),
1403 };
1404 self.problem(&origin.file, origin.pos, problem);
1405 if let Some(known) = self.families.get_mut(&at) {
1406 known.1 = true;
1407 }
1408 }
1409 return None;
1410 }
1411 };
1412 match family.face(weight) {
1413 Some(face) => {
1414 self.fonts.entry(face.id).or_insert_with(|| face.clone());
1415 Some(face.id)
1416 }
1417 None => {
1418 let has = family.weights();
1419 self.no_weight(path, pos, weight_at, weight, &family.name, &has);
1420 None
1421 }
1422 }
1423 }
1424
1425 fn no_weight(
1428 &mut self,
1429 path: &str,
1430 pos: Pos,
1431 weight_at: Option<Pos>,
1432 weight: u16,
1433 family: &str,
1434 has: &[u16],
1435 ) {
1436 let message = if has.is_empty() {
1437 format!(
1438 "weight: {family} has no {weight}; it has no weight from 100 to 900 in steps of 100"
1439 )
1440 } else {
1441 format!(
1442 "weight: {family} has no {weight}; it has {}",
1443 fonts::list(has)
1444 )
1445 };
1446 self.problem(path, weight_at.unwrap_or(pos), message);
1447 }
1448
1449 fn family(&mut self, at: &str) -> (Found, bool) {
1453 if let Some(known) = self.families.get(at) {
1454 return known.clone();
1455 }
1456 let family = match self.font_file(at) {
1457 Some(Ok(file)) => Some(Ok(Rc::new(Family {
1458 name: file.family.clone(),
1459 faces: vec![file],
1460 }))),
1461 Some(Err(e)) => Some(Err(e)),
1462 None => self.files.list(at).map(|names| {
1463 let mut faces = Vec::new();
1464 for name in names.into_iter().filter(|n| fonts::is_font_name(n)) {
1465 match self.font_file(&format!("{at}/{name}")) {
1466 Some(Ok(file)) => faces.push((name, file)),
1467 Some(Err(e)) => return Err(format!("holds {name}, which {e}")),
1468 None => {}
1470 }
1471 }
1472 Family::of_folder(faces).map(Rc::new)
1473 }),
1474 };
1475 self.families
1476 .insert(at.to_string(), (family.clone(), false));
1477 (family, false)
1478 }
1479
1480 fn font_file(&mut self, at: &str) -> Option<Result<Arc<FontFile>, String>> {
1483 let file = self.files.font(at)?;
1484 if !self.read.iter().any(|p| p == at) {
1485 self.read.push(at.to_string());
1486 }
1487 Some(file)
1488 }
1489
1490 fn interaction(&mut self, path: &str, action: &str) -> Result<String, String> {
1493 let Some((verb, target)) = action.split_once(' ') else {
1494 return Ok(action.to_string());
1495 };
1496 let target = target.trim();
1497 if !target.ends_with(".design") {
1498 return Err(format!("{action} — a design is a .design file"));
1499 }
1500 match join(path, target) {
1501 None => Err(format!("{action} — outside the served folder")),
1502 Some(at)
1503 if {
1504 self.read_now(&at);
1505 self.files.bytes(&at).is_none()
1506 } =>
1507 {
1508 Err(format!("{action} — no such file"))
1509 }
1510 Some(at) => Ok(format!("{verb} {at}")),
1511 }
1512 }
1513
1514 fn key_ok(&mut self, path: &str, attr: &parse::Attr) -> bool {
1518 if !matches!(attr.value, Value::Str(..)) {
1519 self.problem(path, attr.pos, "key: expected a string".into());
1520 }
1521 true
1522 }
1523
1524 fn common(&mut self, path: &str, by: &str, node: &mut Node, attr: &parse::Attr, value: Value) {
1528 let (at_file, at_pos) = written_at(path, by, attr, &value);
1529 let ok = match attr.name.as_str() {
1530 "x" => num(&value).map(|n| node.x = n),
1531 "y" => num(&value).map(|n| node.y = n),
1532 "width" => size(&value).map(|s| node.width = s),
1533 "height" => size(&value).map(|s| node.height = s),
1534 "name" => str_of(&value)
1535 .map(|s| node.name = s)
1536 .ok_or_else(|| "expected a string".into()),
1537 "opacity" => match value {
1538 Value::Num(n) if (0.0..=1.0).contains(&n) => {
1539 node.opacity = n as f32;
1540 Ok(())
1541 }
1542 other => Err(format!(
1543 "expected a number from 0 to 1, found {}",
1544 show(&other)
1545 )),
1546 },
1547 "onClick" => match str_of(&value).filter(|s| interaction_ok(s)) {
1548 Some(action) => match self.interaction(by, &action) {
1549 Ok(a) => {
1550 node.on_click = Some(a);
1551 Ok(())
1552 }
1553 Err(e) => {
1554 self.problem(&at_file, at_pos, format!("onClick: {e}"));
1555 return;
1556 }
1557 },
1558 None => Err(
1559 "expected \"navigate <path>\", \"back\", \"overlay <path>\" or \"close\""
1560 .into(),
1561 ),
1562 },
1563 _ => unreachable!(),
1564 };
1565 if let Err(e) = ok {
1566 self.problem(path, attr.pos, format!("{}: {e}", attr.name));
1567 }
1568 }
1569}
1570
1571fn default_text() -> TextStyle {
1574 TextStyle {
1575 font: None,
1576 content: String::new(),
1577 size: 14.0,
1578 weight: 400,
1579 color: Color::fixed(Rgba {
1580 r: 0x0f,
1581 g: 0x17,
1582 b: 0x2a,
1583 a: 255,
1584 }),
1585 line_height: 1.4,
1586 align: TextAlign::Left,
1587 }
1588}
1589
1590fn view_box(s: &str) -> Result<[f32; 4], String> {
1593 let v: Vec<f32> = s
1594 .split([' ', ','])
1595 .filter(|p| !p.is_empty())
1596 .map(|p| parse::number(p).map(|n| n as f32))
1597 .collect::<Result<_, _>>()?;
1598 match v[..] {
1599 [x, y, w, h] if w > 0.0 && h > 0.0 => Ok([x, y, w, h]),
1600 _ => Err("expected \"minX minY width height\"".into()),
1601 }
1602}
1603
1604fn path_numbers(d: &str) -> Result<(), String> {
1608 let b = d.as_bytes();
1609 let mut i = 0;
1610 let mut command = b' ';
1611 let mut param = 0;
1613 while i < b.len() {
1614 let c = b[i];
1615 if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
1616 command = c;
1617 param = 0;
1618 i += 1;
1619 continue;
1620 }
1621 if c.is_ascii_whitespace() || c == b',' {
1622 i += 1;
1623 continue;
1624 }
1625 if matches!(command, b'A' | b'a') && matches!(param % 7, 3 | 4) && matches!(c, b'0' | b'1')
1626 {
1627 param += 1;
1628 i += 1;
1629 continue;
1630 }
1631 let start = i;
1632 if matches!(b[i], b'+' | b'-') {
1633 i += 1;
1634 }
1635 let mut dot = false;
1636 while i < b.len() && (b[i].is_ascii_digit() || (b[i] == b'.' && !dot)) {
1637 dot |= b[i] == b'.';
1638 i += 1;
1639 }
1640 if i < b.len() && matches!(b[i], b'e' | b'E') {
1641 let mut j = i + 1;
1642 if j < b.len() && matches!(b[j], b'+' | b'-') {
1643 j += 1;
1644 }
1645 if j < b.len() && b[j].is_ascii_digit() {
1646 i = j;
1647 while i < b.len() && b[i].is_ascii_digit() {
1648 i += 1;
1649 }
1650 }
1651 }
1652 if i == start {
1653 return Ok(());
1655 }
1656 let s = &d[start..i];
1657 if let Ok(n) = s.parse::<f64>() {
1658 parse::in_range(s, n)?;
1659 }
1660 param += 1;
1661 }
1662 Ok(())
1663}
1664
1665fn bounds(d: &str) -> [f32; 4] {
1667 use kurbo::Shape;
1668 let b = kurbo::BezPath::from_svg(d)
1669 .map(|p| p.bounding_box())
1670 .unwrap_or_default();
1671 [
1672 b.x0 as f32,
1673 b.y0 as f32,
1674 (b.width() as f32).max(1.0),
1675 (b.height() as f32).max(1.0),
1676 ]
1677}
1678
1679fn interaction_ok(s: &str) -> bool {
1682 s == "back"
1683 || s == "close"
1684 || s.strip_prefix("navigate ")
1685 .or(s.strip_prefix("overlay "))
1686 .is_some_and(|p| !p.trim().is_empty())
1687}
1688
1689pub fn join(from: &str, relative: &str) -> Option<String> {
1692 let mut parts: Vec<&str> = from.split('/').filter(|p| !p.is_empty()).collect();
1693 parts.pop();
1694 for part in relative.split('/') {
1695 match part {
1696 "." | "" => {}
1697 ".." => {
1698 parts.pop()?;
1699 }
1700 p => parts.push(p),
1701 }
1702 }
1703 Some(parts.join("/"))
1704}
1705
1706fn substitute(value: &Value, props: &Props, path: &str) -> (Value, String) {
1709 match value {
1710 Value::Prop(p) => match props.get(p) {
1711 Some(given) => (given.value.clone(), given.by.clone()),
1712 None => (value.clone(), path.to_string()),
1713 },
1714 v => (v.clone(), path.to_string()),
1715 }
1716}
1717
1718fn written_at(path: &str, by: &str, attr: &parse::Attr, value: &Value) -> (String, Pos) {
1722 match value {
1723 Value::Str(_, pos) if by != path => (by.to_string(), *pos),
1724 _ => (path.to_string(), attr.pos),
1725 }
1726}
1727
1728fn show(v: &Value) -> String {
1731 match v {
1732 Value::Str(s, _) => format!("\"{s}\""),
1733 Value::Num(n) => n.to_string(),
1734 Value::Bool(b) => b.to_string(),
1735 Value::Array(_) => "an array".into(),
1736 Value::Object(_) => "an object".into(),
1737 Value::Prop(p) => p.clone(),
1738 Value::Theme(name, _) => format!("theme.{name}"),
1739 Value::Themed { written, .. } => written.clone(),
1740 }
1741}
1742
1743fn str_of(v: &Value) -> Option<String> {
1745 match v {
1746 Value::Str(s, _) => Some(s.clone()),
1747 _ => None,
1748 }
1749}
1750
1751fn key_pos(text: &str, under: Option<&str>, key: &str) -> Option<Pos> {
1756 let names = |line: &str, key: &str| {
1757 let line = line.trim_start();
1758 [
1759 format!("{key}:"),
1760 format!("\"{key}\":"),
1761 format!("'{key}':"),
1762 ]
1763 .iter()
1764 .any(|k| line.starts_with(k.as_str()))
1765 };
1766 let top = |line: &str| !line.starts_with([' ', '\t']) && !line.trim().is_empty();
1767 let mut inside = under.is_none();
1768 for (n, line) in text.lines().enumerate() {
1769 if line.trim_start().starts_with('#') {
1770 continue;
1771 }
1772 let pos = Pos {
1773 line: n as u32 + 1,
1774 col: (line.len() - line.trim_start().len()) as u32 + 1,
1775 };
1776 match under {
1777 None if top(line) && names(line, key) => return Some(pos),
1778 None => {}
1779 Some(block) if top(line) => inside = names(line, block),
1780 Some(_) if inside && names(line, key) => return Some(pos),
1781 Some(_) => {}
1782 }
1783 }
1784 None
1785}
1786
1787const ELEMENTS: [&str; 6] = ["Frame", "Text", "Rect", "Ellipse", "Vector", "Image"];
1789
1790fn num(v: &Value) -> Result<f32, String> {
1792 match v {
1793 Value::Num(n) => Ok(*n as f32),
1794 other => Err(format!("expected a number, found {}", show(other))),
1795 }
1796}
1797
1798fn px(v: &Value) -> Result<f32, String> {
1800 match v {
1801 Value::Num(n) if *n >= 0.0 => Ok(*n as f32),
1802 Value::Num(n) => Err(format!("expected a number of 0 or more, found {n}")),
1803 other => Err(format!("expected a number, found {}", show(other))),
1804 }
1805}
1806
1807fn pxs(a: &[Value]) -> Result<Vec<f32>, String> {
1809 a.iter().map(px).collect()
1810}
1811
1812fn size(v: &Value) -> Result<Size, String> {
1814 match v {
1815 Value::Num(n) if *n >= 0.0 => Ok(Size::Px(*n as f32)),
1816 Value::Num(n) => Err(format!("expected pixels of 0 or more, found {n}")),
1817 Value::Str(s, _) if s == "hug" => Ok(Size::Hug),
1818 Value::Str(s, _) if s == "fill" => Ok(Size::Fill),
1819 other => Err(format!(
1820 "expected pixels, \"hug\" or \"fill\", found {}",
1821 show(other)
1822 )),
1823 }
1824}
1825
1826fn align(v: &Value, justify: bool) -> Result<Align, String> {
1829 match str_of(v).as_deref() {
1830 Some("start") => Ok(Align::Start),
1831 Some("center") => Ok(Align::Center),
1832 Some("end") => Ok(Align::End),
1833 Some("space-between") if justify => Ok(Align::SpaceBetween),
1834 _ if justify => Err("expected \"start\", \"center\", \"end\" or \"space-between\"".into()),
1835 _ => Err("expected \"start\", \"center\" or \"end\"".into()),
1836 }
1837}
1838
1839fn color(v: &Value) -> Result<Color, String> {
1842 match v {
1843 Value::Str(s, _) => rgba(s).map(Color::fixed),
1844 Value::Themed { light, dark, .. } => Ok(Color {
1845 light: rgba(light)?,
1846 dark: rgba(dark)?,
1847 }),
1848 _ => Err(format!("expected a color, found {}", show(v))),
1849 }
1850}
1851
1852pub fn rgba(s: &str) -> Result<Rgba, String> {
1854 if s.starts_with("theme.") {
1855 return Err(format!(
1856 "{s} is a theme color: write it in braces, {{{s}}}, not in quotes"
1857 ));
1858 }
1859 let hex = s.strip_prefix('#').ok_or("expected a color like #rrggbb")?;
1860 if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
1861 return Err(format!("{s} is not a color"));
1862 }
1863 let d = |i: usize, n: usize| {
1864 u8::from_str_radix(&hex[i..i + n], 16).map_err(|_| format!("{s} is not a color"))
1865 };
1866 let dd = |i: usize| d(i, 1).map(|v| v * 17);
1867 match hex.len() {
1868 3 => Ok(Rgba {
1869 r: dd(0)?,
1870 g: dd(1)?,
1871 b: dd(2)?,
1872 a: 255,
1873 }),
1874 4 => Ok(Rgba {
1875 r: dd(0)?,
1876 g: dd(1)?,
1877 b: dd(2)?,
1878 a: dd(3)?,
1879 }),
1880 6 => Ok(Rgba {
1881 r: d(0, 2)?,
1882 g: d(2, 2)?,
1883 b: d(4, 2)?,
1884 a: 255,
1885 }),
1886 8 => Ok(Rgba {
1887 r: d(0, 2)?,
1888 g: d(2, 2)?,
1889 b: d(4, 2)?,
1890 a: d(6, 2)?,
1891 }),
1892 _ => Err(format!("{s} is not a color")),
1893 }
1894}
1895
1896fn hex(c: Rgba) -> String {
1898 format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
1899}
1900
1901fn fill(v: &Value) -> Result<Fill, String> {
1904 match v {
1905 Value::Str(s, _) => fill_of(s),
1906 Value::Themed { light, dark, .. } => match (fill_of(light)?, fill_of(dark)?) {
1909 (Fill::Solid(l), Fill::Solid(d)) => Ok(Fill::Solid(Color {
1910 light: l.light,
1911 dark: d.light,
1912 })),
1913 (
1914 Fill::Linear { angle, stops: l },
1915 Fill::Linear {
1916 stops: d,
1917 angle: dark_angle,
1918 },
1919 ) if angle == dark_angle && l.len() == d.len() => Ok(Fill::Linear {
1920 angle,
1921 stops: l
1922 .iter()
1923 .zip(&d)
1924 .map(|((l, at), (d, _))| {
1925 (
1926 Color {
1927 light: l.light,
1928 dark: d.light,
1929 },
1930 *at,
1931 )
1932 })
1933 .collect(),
1934 }),
1935 _ => Err(format!("{} is not the same fill in both themes", show(v))),
1936 },
1937 _ => Err(format!("expected a color or a gradient, found {}", show(v))),
1938 }
1939}
1940
1941fn fill_of(s: &str) -> Result<Fill, String> {
1943 let Some(inner) = s
1944 .strip_prefix("linear-gradient(")
1945 .and_then(|r| r.strip_suffix(')'))
1946 else {
1947 return rgba(s).map(|c| Fill::Solid(Color::fixed(c)));
1948 };
1949 let wrong =
1950 || format!("expected \"linear-gradient(<angle>deg, <color> <stop>%, …)\", found \"{s}\"");
1951 let mut parts = inner.split(',').map(str::trim);
1952 let angle = parts
1953 .next()
1954 .and_then(|a| a.strip_suffix("deg"))
1955 .ok_or_else(wrong)?;
1956 let angle = parse::number(angle.trim())? as f32;
1957 let mut stops = Vec::new();
1958 for part in parts {
1959 let (c, at) = part.split_once(' ').ok_or_else(wrong)?;
1960 let at = at.trim().strip_suffix('%').ok_or_else(wrong)?;
1961 let at = parse::number(at)? as f32;
1962 stops.push((Color::fixed(rgba(c)?), at / 100.0));
1963 }
1964 if stops.len() < 2 {
1965 return Err(wrong());
1966 }
1967 Ok(Fill::Linear { angle, stops })
1968}
1969
1970fn has_theme(v: &Value) -> bool {
1972 match v {
1973 Value::Themed { .. } | Value::Theme(..) => true,
1974 Value::Array(items) => items.iter().any(has_theme),
1975 Value::Object(fields) => fields.iter().any(|(_, v)| has_theme(v)),
1976 _ => false,
1977 }
1978}
1979
1980fn shadow(v: &Value) -> Result<Shadow, String> {
1983 let Value::Object(fields) = v else {
1984 return Err("expected { x, y, blur, spread, color }".into());
1985 };
1986 let mut s = Shadow {
1987 x: 0.0,
1988 y: 0.0,
1989 blur: 0.0,
1990 spread: 0.0,
1991 color: Color::fixed(Rgba {
1992 r: 0,
1993 g: 0,
1994 b: 0,
1995 a: 64,
1996 }),
1997 at: Origin::default(),
1998 };
1999 for (k, v) in fields {
2000 match k.as_str() {
2001 "x" => s.x = num(v)?,
2002 "y" => s.y = num(v)?,
2003 "blur" => s.blur = num(v)?,
2004 "spread" => s.spread = num(v)?,
2005 "color" => s.color = color(v)?,
2006 other => return Err(format!("a shadow has no {other}")),
2007 }
2008 }
2009 Ok(s)
2010}
2011
2012mod again;
2013
2014pub use again::{Outcome, Resolution};
2015
2016#[cfg(test)]
2017mod tests;