Skip to main content

devpage_design/resolve/
mod.rs

1//! Syntax tree → scene: imports and props substituted, every attribute
2//! checked, typed and defaulted.
3
4use 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
17/// Resolves the design at `path`, reporting every problem found.
18pub fn resolve(files: &dyn Files, path: &str) -> Result<Scene, Vec<Problem>> {
19    resolved(files, path).map(|(scene, ..)| scene)
20}
21
22/// The design at `path` resolved, with the record of where each node came
23/// from and what it read — what resolving it again starts from — and the
24/// files it was made from.
25fn 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    /// A resolver reading from `files`, with nothing resolved yet.
43    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
66/// What resolving one design reads and finds: the files it reads through, the
67/// problems found, and the record of what each node came from.
68struct Resolver<'a> {
69    /// Where design files and what they name are read from.
70    files: &'a dyn Files,
71    /// Every problem found so far.
72    problems: Vec<Problem>,
73    /// Every file read so far, each once, in the order first read: what the
74    /// design is made from.
75    read: Vec<String>,
76    /// The design files being resolved, outermost first: one that uses itself
77    /// is among them.
78    stack: Vec<String>,
79    /// Imports already reported as `no such file`, so a use of one isn't
80    /// reported a second time.
81    missing: Vec<String>,
82    /// How many elements enclose the current one, across instances.
83    depth: usize,
84    /// Every image file the design shows, by id.
85    images: ImageFiles,
86    /// Each image file read so far, by its path.
87    by_path: HashMap<String, Result<ImageId, String>>,
88    /// Every font file the design's texts are set in, by id.
89    fonts: FontFiles,
90    /// Each font a `themes.yml` named and a text used so far, file or
91    /// folder, by its path, and whether its problem was reported yet: once
92    /// per resolve, however many texts use it.
93    families: HashMap<String, (Found, bool)>,
94    /// The themes each folder's designs use, merged from every `themes.yml`
95    /// from that folder up, by folder: read once per resolve.
96    themes: HashMap<String, Rc<Themes>>,
97    /// Whether a `theme.` reference reached a node.
98    themed: bool,
99    /// The element ids of the instances enclosing the element being
100    /// resolved, outermost first: the start of every id made here.
101    instance: Vec<u32>,
102    /// Where each node made came from and what it read.
103    record: Record,
104    /// The node whose attributes are being resolved: what each file read
105    /// now is read by.
106    current: Option<NodeId>,
107    /// Whether to resolve an element's own attributes only, leaving its
108    /// child elements alone: resolving one node again.
109    own_only: bool,
110    /// How many elements were resolved: the work resolving again counts.
111    elements: usize,
112}
113
114/// Where a resolved design's nodes came from and what they read: what
115/// [`Resolution`] resolves again from when a file changes.
116#[derive(Debug, Clone, Default)]
117struct Record {
118    /// Each instance, by the element ids leading to it — the root design's
119    /// is empty.
120    instances: BTreeMap<Vec<u32>, Instance>,
121    /// The instances of each design file.
122    by_file: HashMap<String, BTreeSet<Vec<u32>>>,
123    /// The nodes and instances that read each file — or folder, by its path
124    /// and a `/` — by id: a change to it resolves them again.
125    readers: HashMap<String, BTreeSet<Vec<u32>>>,
126    /// What each node or instance reads, so it can be forgotten.
127    reads: BTreeMap<Vec<u32>, BTreeSet<String>>,
128    /// The nodes a `theme.` reference reached.
129    themed: BTreeSet<NodeId>,
130    /// The parse each design file was resolved from.
131    parses: HashMap<String, Arc<parse::File>>,
132}
133
134impl Record {
135    /// `id`, a node's or an instance's, reads `key`.
136    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    /// `id` reads nothing any more.
148    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/// One use of a design file: the props its elements are resolved in, its
163/// imports, the layout of the frame it sits in, the caller's attributes laid
164/// over its root, and its root node's id.
165#[derive(Debug, Clone)]
166struct Instance {
167    /// The design file it uses.
168    file: String,
169    /// Its props, by name: the defaults its root declares, under what its
170    /// caller gives.
171    props: Arc<Props>,
172    /// Its file's imports: each element name's design file, from the top of the
173    /// served folder.
174    imports: Arc<HashMap<String, String>>,
175    /// The layout of the frame it sits in; `None` for the root design.
176    parent: Option<Layout>,
177    /// Where it is used and what is laid over its root; `None` for the root
178    /// design.
179    caller: Option<Caller>,
180    /// Its root node's id: the key of its use, then its root element's id.
181    root: NodeId,
182}
183
184/// The file an instance is used in, and the attributes it lays over the
185/// instance's root — `x`, `y`, `width` and the like — as given there.
186#[derive(Debug, Clone)]
187struct Caller {
188    /// The design file the instance is used in.
189    file: String,
190    /// The attributes laid over the instance's root, each with the file that
191    /// wrote its value.
192    overrides: Vec<(parse::Attr, String)>,
193}
194
195/// Whether a value as written names a theme color.
196fn 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
206/// Every `themes.yml` a design file at `path` reads its themes from: its
207/// folder's and each folder's above it.
208fn 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/// The themes a folder's designs use: every `themes.yml` with `kind: themes`
220/// from the top of the served folder down to it, merged — a lower file's
221/// names over a higher one's, theme by theme.
222#[derive(Debug, Clone, Default)]
223struct Themes {
224    /// Whether any such file was found.
225    found: bool,
226    /// The light theme's colors, by name.
227    light: BTreeMap<String, Rgba>,
228    /// The dark theme's colors, by name.
229    dark: BTreeMap<String, Rgba>,
230    /// The fonts the files name, by name, a lower file's over a higher one's.
231    fonts: BTreeMap<String, ThemesFont>,
232}
233
234/// A font a `themes.yml`'s `fonts` names: its path as written, its address —
235/// `None` when it leaves the served folder — and where it is written.
236#[derive(Debug, Clone)]
237struct ThemesFont {
238    /// Its path, as written.
239    written: String,
240    /// Its address, from the top of the served folder; `None` when it leaves
241    /// the served folder.
242    at: Option<String>,
243    /// Where in the `themes.yml` it is written.
244    origin: Origin,
245}
246
247/// One `themes.yml`'s two themes and the fonts it names, as far as they are
248/// valid.
249struct ThemesFile {
250    /// Its light theme's colors, by name.
251    light: BTreeMap<String, Rgba>,
252    /// Its dark theme's colors, by name.
253    dark: BTreeMap<String, Rgba>,
254    /// The fonts it names, by name.
255    fonts: BTreeMap<String, ThemesFont>,
256}
257
258/// The file a folder's themes are in.
259pub const THEMES_FILE: &str = "themes.yml";
260
261/// How deep a resolved design's tree may nest, counting through instances:
262/// the parser's own limit for one file, and so far beyond any real design.
263const MAX_DEPTH: usize = parse::MAX_DEPTH;
264
265/// A prop's value and the file that wrote it, which a path in it is
266/// relative to.
267#[derive(Debug, Clone)]
268struct Given {
269    /// The value, as the caller or the default gives it; a path in it is
270    /// still relative to `by`.
271    value: Value,
272    /// The design file that wrote it.
273    by: String,
274}
275
276/// The props an instance's elements are resolved in, by name.
277type Props = HashMap<String, Given>;
278
279/// A font a `font` names: its family, or why it can't be used; `None` when
280/// there is nothing there.
281type Found = Option<Result<Rc<Family>, String>>;
282
283impl Resolver<'_> {
284    /// The node being resolved reads the file `key` — a folder's listing
285    /// when it ends in `/`: a change to it resolves the node again.
286    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    /// Reports `message` at `pos` in `file`.
294    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    /// Binds every theme color written in `el` and the elements in it — in
303    /// `path`'s file — to that file's themes.
304    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    /// Binds the theme colors written in `el`'s own attributes, the node or
314    /// instance it makes reading `path`'s themes when there are any.
315    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        // A theme color among a design's `props` defaults reaches whatever
332        // reads that prop, anywhere in the design: the instance reads the
333        // themes, so a change to them resolves it again with its subtree.
334        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    /// Binds a value written in `path` to `path`'s themes: `theme.name` to
343    /// its two colors, and a gradient naming theme colors to one gradient
344    /// per theme.
345    fn bind(&mut self, path: &str, value: &mut Value) {
346        match value {
347            Value::Theme(name, pos) => {
348                // A problem already when there is none; any color keeps
349                // the rest of the design checked.
350                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                        // A problem already; any color keeps the rest checked.
383                        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    /// The two colors of `theme.name`, written at `pos` in `path`, from the
414    /// themes of `path`'s folder — or `None`, with the problem reported.
415    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    /// The themes the designs in `folder` use: its own `themes.yml` over
453    /// those of the folders above it, each read once per resolve — a missing
454    /// one too, so that creating it counts as a change.
455    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    /// The themes in the file at `path`, as far as they are valid, with its
485    /// problems reported; `None` when there is no such file or it isn't a
486    /// themes file — its `kind` isn't `themes`.
487    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                // Only a file that says it is a themes file is ours to report.
501                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    /// The fonts a `themes.yml` at `path` names in `value`, its `fonts`, each
598    /// a name and a path from that file; a bad entry is a problem at its
599    /// line.
600    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    /// A design file's imports, each to the file it names, and its root's
660    /// declared props — with the problems of either reported.
661    /// `None` when its root isn't a `Frame`.
662    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                    // Every import must exist, used or not.
707                    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        // Props: the root's declared defaults, overridden by the instance's.
733        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    /// The root node of the design at `path`, with `args` given to its props.
768    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        // Bound now, before any value leaves this file as a prop: a theme
804        // color is this file's, wherever it is used.
805        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                // The caller's own props are already substituted into these.
867                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    /// The node `el`, written in `path`, resolves to with `props` and `imports`
876    /// — a design's root when `root` — in a frame whose layout is `parent`;
877    /// `None` when it can't, or nests past [`MAX_DEPTH`].
878    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    /// [`Resolver::element`] once the depth is counted: an instance resolved as
899    /// its design, or a built-in element with its attributes and children.
900    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        // An attribute given twice is a problem, on an element or an instance
910        // alike; the first one counts.
911        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            // Keep in step with ELEMENTS.
946            "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        // A text's `font`, as given and by the file that wrote it, chosen a
963        // face from once its weight is known.
964        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            // Shown on its own a design has no parent to place it in, and used
977            // as an instance it goes where the instance's own x and y say.
978            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    /// `"fill"` takes the free space of a parent's auto layout, so a child of a
1095    /// frame with no layout can't have it.
1096    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    /// `x` and `y` place a child inside a frame with no layout; auto layout
1119    /// places its children itself, so there they would mean nothing.
1120    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    // Each arm sets a field and says whether the value fit: `Ok(field = v)`.
1136    /// Sets the field of `node` that `attr`, written in `path`, names to
1137    /// `value`, which `by` wrote, reporting a value that doesn't fit.
1138    #[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        // A path is relative to the file that wrote it, and its problem is
1149        // where it was written.
1150        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            // Only a frame has children to clip.
1178            ("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    /// The image file at `at`, by its content — read and decoded once per
1301    /// resolve however many `Image`s show it — or why it doesn't decode;
1302    /// `None` when there is no such file.
1303    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    /// The font file a `Text` written at `pos` in `path` is set in, for its
1322    /// `weight` — `None` for Inter, when it has no `font`. Its `font`, given
1323    /// as `value` by the file `by`, is a name the themes of `by`'s folder
1324    /// give a font. An unknown name is a problem where it is written; a font
1325    /// that can't be used, at its entry in the `themes.yml`, once; a weight
1326    /// the font lacks, at the `weight` — or the `Text`.
1327    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    /// The problem of a weight the font doesn't have: at the `Text`'s
1426    /// `weight`, or at the `Text` when it leaves the weight at 400.
1427    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    /// The font at `at` — one file, or a folder of one family's files — read
1450    /// and checked once per resolve, or why it can't be used; `None` when
1451    /// there is nothing there. Also whether its problem was reported yet.
1452    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                        // Gone since the folder was listed.
1469                        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    /// The font file at `at`, checked, or why it isn't one; `None` when there
1481    /// is no such file.
1482    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    /// An interaction with its path, if it has one, made relative to the top of
1491    /// the served folder instead of to `path`, the file it is written in.
1492    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    /// Whether `attr`, a `key`, is a string — the one value a parse can
1515    /// match siblings by — saying so where it isn't. True either way once
1516    /// it has been looked at, so an instance doesn't pass it on as a prop.
1517    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    /// Sets the attribute every element takes — `x`, `y`, `width`, `height`,
1525    /// `name`, `opacity` or `onClick` — that `attr`, written in `path`, names
1526    /// to `value`, which `by` wrote, reporting a value that doesn't fit.
1527    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
1571/// The style a `Text` starts from: 14 px at weight 400, `#0f172a` in both
1572/// themes, a line height of 1.4, left-aligned, in no `font`.
1573fn 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
1590/// A `viewBox`: `minX minY width height`, by spaces or commas, its width and
1591/// height above 0.
1592fn 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
1604/// Every number in SVG path data `d` held to the same limits as a design's
1605/// other numbers. A number here is SVG's — it may have an exponent — and an
1606/// arc's two flags are single digits that may be written run together.
1607fn path_numbers(d: &str) -> Result<(), String> {
1608    let b = d.as_bytes();
1609    let mut i = 0;
1610    let mut command = b' ';
1611    // Which parameter of the current command comes next.
1612    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            // Not a number: the path parser says what is wrong.
1654            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
1665/// A path's own bounds, the view box of a `Vector` that names none.
1666fn 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
1679/// Whether `s` is an `onClick` interaction: `back`, `close`, or `navigate` or
1680/// `overlay` with a path.
1681fn 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
1689/// A path relative to a design's file, from the top of the served folder, or
1690/// `None` when it climbs out of the served folder.
1691pub 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
1706/// `value`, written in `path`, with a prop put in its place, and the file
1707/// that wrote what it ends up as.
1708fn 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
1718/// Where a path in `attr`'s `value` was written: at the attribute, in
1719/// `path`, or — when the value came as a prop from another file, `by` — at
1720/// the string there.
1721fn 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
1728/// `v` as a problem names it: a string quoted, a number as Rust prints it
1729/// (`1.50` as `1.5`), a bool as written, a prop or theme color by name.
1730fn 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
1743/// The string `v` is; `None` when it is no string.
1744fn str_of(v: &Value) -> Option<String> {
1745    match v {
1746        Value::Str(s, _) => Some(s.clone()),
1747        _ => None,
1748    }
1749}
1750
1751/// Where `key` is written in a themes file's text: at the top level, or —
1752/// with `under` — inside that top-level key's block. YAML's values carry no
1753/// place, so a key is found by its text: on a line of its own, plain or in
1754/// quotes.
1755fn 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
1787/// The built-in elements; an import can't take one of their names.
1788const ELEMENTS: [&str; 6] = ["Frame", "Text", "Rect", "Ellipse", "Vector", "Image"];
1789
1790/// A number, of any sign.
1791fn 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
1798/// A length or a multiple that can't be negative: pixels, a size, a line height.
1799fn 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
1807/// A list of lengths that can't be negative, as [`px`] reads each.
1808fn pxs(a: &[Value]) -> Result<Vec<f32>, String> {
1809    a.iter().map(px).collect()
1810}
1811
1812/// A width or height: pixels of 0 or more, `"hug"` or `"fill"`.
1813fn 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
1826/// An alignment: `start`, `center` or `end` — and, for `justify`,
1827/// `space-between` too.
1828fn 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
1839/// A color: a `#…` one, the same in both themes, or a theme color bound to
1840/// its file's themes.
1841fn 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
1852/// A `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` color.
1853pub 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
1896/// `c` written as `#rrggbbaa`.
1897fn hex(c: Rgba) -> String {
1898    format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
1899}
1900
1901/// A fill: a color or a `linear-gradient(…)`, the same shape in both themes
1902/// when it holds theme colors.
1903fn fill(v: &Value) -> Result<Fill, String> {
1904    match v {
1905        Value::Str(s, _) => fill_of(s),
1906        // Each theme's string differs only in its colors, so the two fills
1907        // have the same shape.
1908        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
1941/// A fill written as a string, its colors the same in both themes.
1942fn 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
1970/// Whether a value holds a theme color, at any depth.
1971fn 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
1980/// A shadow: `{ x, y, blur, spread, color }`, each optional — `x`, `y`,
1981/// `blur` and `spread` 0 by default, the color black at a quarter alpha.
1982fn 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;