swiftui-native 0.0.1

SwiftUI from pure Rust — no Swift bridge, no shim, only swift-runtime calls
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
//! A view tree parsed at run time, from text the binary has never seen.
//!
//! Every other example in this directory writes its screen in Rust: the view
//! types are chosen when the example is compiled, and changing the screen means
//! building again. That is what a SwiftUI app is too — `VStack { Text("hi") }`
//! is a *type*, `VStack<TupleView<(Text,)>>`, fixed at compile time.
//!
//! This module has no idea what it is going to build. It reads a string,
//! decides which SwiftUI types to instantiate, asks the Swift runtime for their
//! metadata, and assembles the tree. Nothing about the result is in the
//! binary — the same executable renders any screen the text describes.
//!
//! The format is small on purpose. It is not the point; being able to *have* a
//! format is:
//!
//! ```text
//! // a comment
//! vstack spacing=16 pad=20 {
//!   text "System" style=large_title bold
//!   hstack spacing=8 {
//!     text "left"
//!     spacer
//!     text "right" color=gray
//!   }
//!   divider
//!   progress 0.4
//!   button "Refresh"
//! }
//! ```
//!
//! Errors are returned rather than panicked on: the text comes from outside, so
//! a mistake in it is an ordinary event, not a bug. [`build`] reports the line
//! it gave up on, which is what a person editing the file needs.

#![allow(dead_code)]

use swiftui_native::prelude::*;
use swiftui_native::views;

/// One node of the parsed tree: a name, its arguments, and its children.
#[derive(Debug, Clone)]
pub struct Node {
    pub name: String,
    /// The bare argument, if the node had one — `text "hello"` or `progress 0.4`.
    pub value: Option<String>,
    /// `key=value` pairs, in the order they were written.
    pub attrs: Vec<(String, String)>,
    pub children: Vec<Node>,
    /// The 1-based line the node started on, for error messages.
    pub line: usize,
}

impl Node {
    fn attr(&self, key: &str) -> Option<&str> {
        self.attrs.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
    }

    /// A flag written either bare (`bold`) or as `bold=true`.
    fn flag(&self, key: &str) -> bool {
        self.attrs.iter().any(|(k, v)| k == key && (v.is_empty() || v == "true"))
    }

    fn f64_attr(&self, key: &str) -> Option<f64> {
        self.attr(key).and_then(|v| v.parse().ok())
    }
}

// ── Tokeniser ────────────────────────────────────────────────────────────

#[derive(Debug, PartialEq)]
enum Tok {
    Word(String),
    Str(String),
    Eq,
    Open,
    Close,
}

struct Lexer<'a> {
    rest: &'a str,
    line: usize,
}

impl<'a> Lexer<'a> {
    fn new(src: &'a str) -> Self {
        Self { rest: src, line: 1 }
    }

    /// The next token and the line it started on.
    fn next(&mut self) -> Result<Option<(Tok, usize)>, String> {
        loop {
            let mut chars = self.rest.char_indices();
            match chars.next() {
                None => return Ok(None),
                Some((_, '\n')) => {
                    self.line += 1;
                    self.rest = &self.rest[1..];
                }
                Some((_, c)) if c.is_whitespace() => {
                    self.rest = &self.rest[c.len_utf8()..];
                }
                // `//` to end of line. Not `#`: a colour is written `#1d2b53`,
                // and treating `#` as a comment silently ate the rest of the
                // line — which showed up as a whole screen falling back to the
                // error view rather than as a parse error.
                Some((_, '/')) if self.rest.as_bytes().get(1) == Some(&b'/') => {
                    let end = self.rest.find('\n').unwrap_or(self.rest.len());
                    self.rest = &self.rest[end..];
                }
                Some((_, '{')) => {
                    self.rest = &self.rest[1..];
                    return Ok(Some((Tok::Open, self.line)));
                }
                Some((_, '}')) => {
                    self.rest = &self.rest[1..];
                    return Ok(Some((Tok::Close, self.line)));
                }
                Some((_, '=')) => {
                    self.rest = &self.rest[1..];
                    return Ok(Some((Tok::Eq, self.line)));
                }
                Some((_, '"')) => {
                    let line = self.line;
                    let body = &self.rest[1..];
                    let end = body.find('"').ok_or_else(|| {
                        format!("line {line}: string is never closed")
                    })?;
                    let s = body[..end].to_string();
                    self.line += s.matches('\n').count();
                    self.rest = &body[end + 1..];
                    return Ok(Some((Tok::Str(s), line)));
                }
                Some((_, _)) => {
                    let line = self.line;
                    let end = self
                        .rest
                        .find(|c: char| c.is_whitespace() || "{}=\"".contains(c))
                        .unwrap_or(self.rest.len());
                    let w = self.rest[..end].to_string();
                    self.rest = &self.rest[end..];
                    return Ok(Some((Tok::Word(w), line)));
                }
            }
        }
    }
}

// ── Parser ───────────────────────────────────────────────────────────────

/// Every token, up front.
///
/// The grammar needs to look at the token *after* a word to know whether the
/// word is an attribute name, a flag, or the next sibling — and after an `=`
/// it needs the one after that. Streaming it with a single pushback slot was
/// wrong in a way that misparsed `text "a" text "b"` as one node, so the whole
/// list is materialised and walked by index.
fn tokens(src: &str) -> Result<Vec<(Tok, usize)>, String> {
    let mut lex = Lexer::new(src);
    let mut out = Vec::new();
    while let Some(t) = lex.next()? {
        out.push(t);
    }
    Ok(out)
}

struct Parser {
    toks: Vec<(Tok, usize)>,
    at: usize,
}

impl Parser {
    fn peek(&self) -> Option<&Tok> {
        self.toks.get(self.at).map(|(t, _)| t)
    }

    fn peek_at(&self, n: usize) -> Option<&Tok> {
        self.toks.get(self.at + n).map(|(t, _)| t)
    }

    fn line(&self) -> usize {
        self.toks.get(self.at).map_or_else(
            || self.toks.last().map_or(1, |(_, l)| *l),
            |(_, l)| *l,
        )
    }

    fn bump(&mut self) -> Option<(Tok, usize)> {
        if self.at < self.toks.len() {
            self.at += 1;
            // Cheaper than cloning the whole vector: take the token out and
            // leave a placeholder, since nothing reads a consumed slot.
            Some(core::mem::replace(&mut self.toks[self.at - 1], (Tok::Eq, 0)))
        } else {
            None
        }
    }

    /// Nodes until end of input or a `}`, which is left unconsumed.
    fn nodes(&mut self) -> Result<Vec<Node>, String> {
        let mut out = Vec::new();
        loop {
            match self.peek() {
                None | Some(Tok::Close) => return Ok(out),
                Some(Tok::Word(_)) => out.push(self.node()?),
                Some(other) => {
                    return Err(format!(
                        "line {}: expected a view name, found {other:?}",
                        self.line()
                    ))
                }
            }
        }
    }

    fn node(&mut self) -> Result<Node, String> {
        let (name, line) = match self.bump() {
            Some((Tok::Word(w), l)) => (w, l),
            other => return Err(format!("internal: node() on {other:?}")),
        };
        let mut node =
            Node { name, value: None, attrs: Vec::new(), children: Vec::new(), line };

        loop {
            match self.peek() {
                // A string argument, once, before any attribute.
                Some(Tok::Str(_)) if node.value.is_none() && node.attrs.is_empty() => {
                    if let Some((Tok::Str(s), _)) = self.bump() {
                        node.value = Some(s);
                    }
                }
                Some(Tok::Word(w)) => {
                    // `w=` makes it an attribute whatever else it looks like.
                    if matches!(self.peek_at(1), Some(Tok::Eq)) {
                        let key = w.clone();
                        self.bump();
                        self.bump();
                        let value = match self.bump() {
                            Some((Tok::Word(v), _)) | Some((Tok::Str(v), _)) => v,
                            other => {
                                return Err(format!(
                                    "line {line}: `{key}=` wants a value, found {other:?}"
                                ))
                            }
                        };
                        node.attrs.push((key, value));
                        continue;
                    }
                    // A bare word before any attribute is the argument, for
                    // the nodes that take one: `progress 0.4`, `color #1d2b53`.
                    // Restricted to those nodes so that a flag on a node with
                    // no argument — `divider`, `spacer` — is still a flag.
                    // `#1d2b53` was being taken as a flag, which silently gave
                    // the card the default grey instead of navy.
                    if node.value.is_none()
                        && node.attrs.is_empty()
                        && VALUED.contains(&node.name.as_str())
                    {
                        if let Some((Tok::Word(v), _)) = self.bump() {
                            node.value = Some(v);
                        }
                        continue;
                    }
                    // Otherwise a known name starts the next sibling and
                    // anything else is a flag on this node. Unknown words are
                    // flags so that `build` reports them with a line number
                    // rather than the parser guessing.
                    if is_known(w) {
                        return Ok(node);
                    }
                    if let Some((Tok::Word(f), _)) = self.bump() {
                        node.attrs.push((f, String::new()));
                    }
                }
                Some(Tok::Open) => {
                    self.bump();
                    node.children = self.nodes()?;
                    match self.bump() {
                        Some((Tok::Close, _)) => {}
                        _ => {
                            return Err(format!(
                                "line {line}: `{}` is never closed",
                                node.name
                            ))
                        }
                    }
                    return Ok(node);
                }
                None | Some(Tok::Close) => return Ok(node),
                Some(Tok::Str(s)) => {
                    return Err(format!(
                        "line {}: `{}` already has a value; {s:?} is extra",
                        self.line(),
                        node.name
                    ))
                }
                Some(Tok::Eq) => {
                    return Err(format!("line {}: `=` with nothing before it", self.line()))
                }
            }
        }
    }
}

/// Parse a spec into a forest. Most specs are one tree; a file may hold several.
pub fn parse(src: &str) -> Result<Vec<Node>, String> {
    let mut p = Parser { toks: tokens(src)?, at: 0 };
    let out = p.nodes()?;
    if p.at < p.toks.len() {
        return Err(format!("line {}: unexpected `}}`", p.line()));
    }
    Ok(out)
}

/// Whether a word names a view this module can build.
///
/// Used to tell a sibling apart from a flag. An unknown word is taken as a flag
/// and reported by [`build`], which knows the line.
fn is_known(w: &str) -> bool {
    NAMES.contains(&w)
}

/// The nodes that take a bare argument, as opposed to only attributes.
///
/// `text` and `button` normally take a quoted string, but a one-word label
/// needs no quotes, so they are here too.
const VALUED: &[&str] =
    &["text", "button", "color", "image", "progress", "gauge", "label"];

/// Every view name the format accepts.
///
/// Public so a tool can list what a spec may contain — `dynamic_ui --names`
/// prints this, which is the closest the format has to documentation that
/// cannot go out of date.
pub const NAMES: &[&str] = &[
    "vstack", "hstack", "zstack", "text", "spacer", "divider", "button",
    "color", "image", "rect", "circle", "capsule", "progress", "gauge",
    "group_box", "list", "scroll", "form", "label",
    // Controls bound to named slots. What makes reloading useful rather than
    // only impressive: the slot outlives the view tree, so a toggle stays on
    // while the file around it is rewritten.
    "toggle", "slider", "stepper", "field",
];

// ── Named state, shared across rebuilds ──────────────────────────────────

/// The slots `@name` refers to.
///
/// Keyed by name and created on first sight, so a spec rebuilt from changed
/// text finds the same `BoundState` it had before — which is the difference
/// between reloading a screen and resetting it. `BoundState` is `Arc`-backed,
/// so handing the same one to a freshly built control is all it takes.
///
/// Three maps rather than one of an enum: the controls take
/// `&BoundState<bool>`, `&BoundState<f64>` and `&BoundState<String>`, and a
/// slot's type is fixed by the first control that claims it.
#[derive(Default)]
struct Slots {
    flags: std::collections::HashMap<String, views::BoundState<bool>>,
    numbers: std::collections::HashMap<String, views::BoundState<f64>>,
    strings: std::collections::HashMap<String, views::BoundState<String>>,
}

fn slots() -> &'static std::sync::Mutex<Slots> {
    static SLOTS: std::sync::OnceLock<std::sync::Mutex<Slots>> = std::sync::OnceLock::new();
    SLOTS.get_or_init(Default::default)
}

/// Write a flag slot from outside, as a control's user would.
///
/// The slot has to exist: creating one here would hide a spec that never
/// mentioned the name, which is the mistake this is used to check for.
pub fn set_flag(name: &str, value: bool) {
    slots()
        .lock()
        .expect("slots")
        .flags
        .get(name)
        .unwrap_or_else(|| panic!("no flag slot called {name:?}"))
        .set(value);
}

/// What one slot holds, whatever its type, or `None` if nothing claimed it.
///
/// Prefer this to scanning [`slot_summary`] when only one name matters: the
/// registry is global and a process with two specs in it — a test suite, say —
/// sees both.
pub fn slot_value(name: &str) -> Option<String> {
    let g = slots().lock().expect("slots");
    g.flags
        .get(name)
        .map(|v| v.get().to_string())
        .or_else(|| g.numbers.get(name).map(|v| format!("{:.2}", v.get())))
        .or_else(|| g.strings.get(name).map(|v| format!("{:?}", v.get())))
}

/// What every slot currently holds, for a status line or a test.
pub fn slot_summary() -> Vec<(String, String)> {
    let g = slots().lock().expect("slots");
    let mut out: Vec<(String, String)> = g
        .flags
        .iter()
        .map(|(k, v)| (k.clone(), v.get().to_string()))
        .chain(g.numbers.iter().map(|(k, v)| (k.clone(), format!("{:.2}", v.get()))))
        .chain(g.strings.iter().map(|(k, v)| (k.clone(), format!("{:?}", v.get()))))
        .collect();
    out.sort();
    out
}

/// The `@name` a control is bound to.
///
/// Written bare — `toggle "Dark" @dark` — which the parser sees as a flag,
/// since `@dark` is not a view name. Accepting `state=dark` too means a spec
/// generated by a program need not know about the sigil.
fn slot_name(node: &Node) -> Option<String> {
    if let Some(s) = node.attr("state") {
        return Some(s.to_string());
    }
    node.attrs
        .iter()
        .find_map(|(k, v)| v.is_empty().then(|| k.strip_prefix('@')).flatten())
        .map(str::to_string)
}

/// The slot a bound control names, or a message saying it must.
fn require_slot(node: &Node) -> Result<String, String> {
    slot_name(node).ok_or_else(|| {
        format!(
            "line {}: `{}` needs a slot to keep its value in — \
             write `{} @name`",
            node.line, node.name, node.name
        )
    })
}

fn flag_slot(name: &str, initial: bool) -> views::BoundState<bool> {
    slots()
        .lock()
        .expect("slots")
        .flags
        .entry(name.to_string())
        .or_insert_with(|| views::BoundState::new(initial))
        .clone()
}

fn number_slot(name: &str, initial: f64) -> views::BoundState<f64> {
    slots()
        .lock()
        .expect("slots")
        .numbers
        .entry(name.to_string())
        .or_insert_with(|| views::BoundState::new(initial))
        .clone()
}

fn string_slot(name: &str, initial: &str) -> views::BoundState<String> {
    slots()
        .lock()
        .expect("slots")
        .strings
        .entry(name.to_string())
        .or_insert_with(|| views::BoundState::new(initial.to_string()))
        .clone()
}

// ── Builder ──────────────────────────────────────────────────────────────

/// Turn a parsed forest into one view.
///
/// Several roots are stacked, so a file that forgot its outer `vstack` still
/// renders rather than erroring.
pub fn build(nodes: &[Node]) -> Result<View, String> {
    match nodes {
        [] => Err("the spec is empty".to_string()),
        [one] => node_view(one),
        many => {
            let kids: Result<Vec<View>, String> = many.iter().map(node_view).collect();
            Ok(vstack_spacing(&kids?, 8.0))
        }
    }
}

fn children(node: &Node) -> Result<Vec<View>, String> {
    node.children.iter().map(node_view).collect()
}

fn node_view(node: &Node) -> Result<View, String> {
    let spacing = node.f64_attr("spacing").unwrap_or(8.0);
    let base = match node.name.as_str() {
        "vstack" => {
            let kids = children(node)?;
            match node.attr("align") {
                Some(a) => vstack_aligned_spacing(&kids, h_align(a, node.line)?, Some(spacing)),
                None => vstack_spacing(&kids, spacing),
            }
        }
        "hstack" => {
            let kids = children(node)?;
            match node.attr("align") {
                Some(a) => hstack_aligned_spacing(&kids, v_align(a, node.line)?, Some(spacing)),
                None => hstack_spacing(&kids, spacing),
            }
        }
        "zstack" => zstack_aligned(&children(node)?, align(node.attr("align").unwrap_or("center"), node.line)?),
        "text" => {
            let s = node.value.as_deref().unwrap_or("");
            let mut v = text(s);
            if let Some(style) = node.attr("style") {
                v = v.text_style(text_style(style, node.line)?);
            }
            if let Some(size) = node.f64_attr("size") {
                v = v.font_size(size);
            }
            if node.flag("bold") {
                v = v.bold();
            }
            if node.flag("italic") {
                v = v.italic();
            }
            if let Some(c) = node.attr("color") {
                v = match tint(c, node.line)? {
                    Tint::System(sc) => v.fg_system(sc),
                    Tint::Literal(lc) => v.fg(lc),
                };
            }
            v
        }
        "spacer" => spacer(),
        "divider" => divider(),
        // The action is a no-op on purpose: a spec read from a file has nowhere
        // to put behaviour, and pretending otherwise would be worse than a
        // button that visibly does nothing. `hot_reload.rs` is where a spec
        // gains behaviour, by being reloaded.
        "button" => button(node.value.as_deref().unwrap_or("Button"), || {}),
        "color" => color(parse_color(node.value.as_deref().unwrap_or("#808080"), node.line)?),
        "image" => system_image(node.value.as_deref().unwrap_or("star")).into_view(),
        "rect" => match node.attr("color") {
            Some(c) => match tint(c, node.line)? {
                Tint::System(sc) => rectangle_shape().fill_system(sc),
                Tint::Literal(lc) => rectangle_shape().fill(lc),
            },
            None => rectangle_shape().into_view(),
        },
        "circle" => match node.attr("color") {
            Some(c) => match tint(c, node.line)? {
                Tint::System(sc) => circle_shape().fill_system(sc),
                Tint::Literal(lc) => circle_shape().fill(lc),
            },
            None => circle_shape().into_view(),
        },
        "capsule" => match node.attr("color") {
            Some(c) => match tint(c, node.line)? {
                Tint::System(sc) => capsule_shape().fill_system(sc),
                Tint::Literal(lc) => capsule_shape().fill(lc),
            },
            None => capsule_shape().into_view(),
        },
        "progress" => progress(
            node.value.as_deref().and_then(|v| v.parse().ok()).unwrap_or(0.5),
            node.f64_attr("total").unwrap_or(1.0),
        ),
        "gauge" => gauge(
            node.value.as_deref().and_then(|v| v.parse().ok()).unwrap_or(0.5),
            node.f64_attr("min").unwrap_or(0.0),
            node.f64_attr("max").unwrap_or(1.0),
            text(node.attr("label").unwrap_or("")),
        ),
        "group_box" => group_box(stack_children(node)?),
        "list" => list(stack_children(node)?),
        "scroll" => stack_children(node)?.scroll(),
        "form" => form(stack_children(node)?),
        // Every bound control needs an explicit `@name`.
        //
        // Inventing one — from the line, or from position in the tree — looks
        // friendlier and is a trap: adding a line above a `toggle` would
        // change its derived name, and the control would silently reset on the
        // next reload. A name the file states is a name that survives the file
        // being edited, which is the entire point of the slots.
        "toggle" => toggle_bound(
            node.value.as_deref().unwrap_or("Toggle"),
            &flag_slot(&require_slot(node)?, node.flag("on")),
        ),
        "slider" => {
            let lo = node.f64_attr("min").unwrap_or(0.0);
            let hi = node.f64_attr("max").unwrap_or(1.0);
            slider_bound(
                &number_slot(&require_slot(node)?, node.f64_attr("value").unwrap_or(lo)),
                lo,
                hi,
            )
        }
        "stepper" => stepper_bound(
            node.value.as_deref().unwrap_or("Stepper"),
            &number_slot(&require_slot(node)?, node.f64_attr("value").unwrap_or(0.0)),
            node.f64_attr("min").unwrap_or(0.0),
            node.f64_attr("max").unwrap_or(100.0),
            node.f64_attr("step").unwrap_or(1.0),
        ),
        "field" => textfield_bound(
            node.value.as_deref().unwrap_or(""),
            &string_slot(&require_slot(node)?, node.attr("text").unwrap_or("")),
        ),
        "label" => label(
            node.value.as_deref().unwrap_or(""),
            node.attr("icon").unwrap_or("star"),
        ),
        other => {
            return Err(format!(
                "line {}: no view called `{other}`; try one of {}",
                node.line,
                NAMES.join(", ")
            ))
        }
    };
    decorate(base, node)
}

/// A container that takes a single child gets its children stacked.
fn stack_children(node: &Node) -> Result<View, String> {
    let kids = children(node)?;
    Ok(match kids.len() {
        1 => kids.into_iter().next().expect("one"),
        _ => vstack_spacing(&kids, node.f64_attr("spacing").unwrap_or(8.0)),
    })
}

/// The modifiers any node may carry, applied in a fixed order.
///
/// Order matters in SwiftUI — `.padding().background()` and
/// `.background().padding()` draw differently — so it is written down here
/// rather than left to the order the attributes happened to appear in.
fn decorate(mut v: View, node: &Node) -> Result<View, String> {
    if let Some(p) = node.f64_attr("pad") {
        v = v.padding(p);
    }
    if let Some(size) = node.attr("frame") {
        let (w, h) = parse_size(size, node.line)?;
        v = v.frame(w, h);
    }
    if let Some(o) = node.f64_attr("opacity") {
        v = v.opacity(o);
    }
    if let Some(c) = node.attr("bg") {
        let c = parse_color(c, node.line)?;
        v = v.bg(c);
    }
    if let Some(r) = node.f64_attr("corner") {
        v = v.corner_radius(r);
    }
    Ok(v)
}

// ── Value parsing ────────────────────────────────────────────────────────

fn parse_size(s: &str, line: usize) -> Result<(f64, f64), String> {
    let (w, h) = s
        .split_once('x')
        .ok_or_else(|| format!("line {line}: `frame={s}` should be WIDTHxHEIGHT"))?;
    let w = w.trim().parse().map_err(|_| format!("line {line}: `{w}` is not a number"))?;
    let h = h.trim().parse().map_err(|_| format!("line {line}: `{h}` is not a number"))?;
    Ok((w, h))
}

fn parse_color(s: &str, line: usize) -> Result<Color, String> {
    if let Some(hex) = s.strip_prefix('#') {
        let v = u32::from_str_radix(hex, 16)
            .map_err(|_| format!("line {line}: `#{hex}` is not a hex colour"))?;
        return Ok(Color::hex(v));
    }
    Ok(match s {
        "red" => Color::RED,
        "green" => Color::GREEN,
        "blue" => Color::BLUE,
        "white" => Color::WHITE,
        "black" => Color::BLACK,
        "dark" => Color::DARK,
        other => return Err(format!("line {line}: no colour called `{other}`")),
    })
}

/// What a `color=` word means.
///
/// SwiftUI has two different things called a colour: the semantic ones that
/// resolve against the appearance (`secondary`, `blue`) and literal values
/// (`white`, `#1d2b53`). They reach different modifiers, so which one a word
/// names has to be decided rather than assumed — and decided in one place,
/// because `text`, `rect`, `circle` and `capsule` all ask the same question.
/// They did not, at first: `rect color=#336699` reported "no system colour".
enum Tint {
    System(SystemColor),
    Literal(Color),
}

fn tint(s: &str, line: usize) -> Result<Tint, String> {
    match system_color(s, line) {
        Ok(sc) => Ok(Tint::System(sc)),
        // Not a semantic name, so it must be a literal — and if it is neither,
        // the literal parser has the better error message.
        Err(_) => Ok(Tint::Literal(parse_color(s, line)?)),
    }
}

fn system_color(s: &str, line: usize) -> Result<SystemColor, String> {
    Ok(match s {
        "red" => SystemColor::Red,
        "orange" => SystemColor::Orange,
        "yellow" => SystemColor::Yellow,
        "green" => SystemColor::Green,
        "mint" => SystemColor::Mint,
        "teal" => SystemColor::Teal,
        "cyan" => SystemColor::Cyan,
        "blue" => SystemColor::Blue,
        "indigo" => SystemColor::Indigo,
        "purple" => SystemColor::Purple,
        "pink" => SystemColor::Pink,
        "brown" => SystemColor::Brown,
        "gray" | "grey" => SystemColor::Gray,
        "primary" => SystemColor::Primary,
        "secondary" => SystemColor::Secondary,
        other => return Err(format!("line {line}: no system colour called `{other}`")),
    })
}

fn text_style(s: &str, line: usize) -> Result<TextStyle, String> {
    Ok(match s {
        "large_title" => TextStyle::LargeTitle,
        "title" => TextStyle::Title,
        "title2" => TextStyle::Title2,
        "title3" => TextStyle::Title3,
        "headline" => TextStyle::Headline,
        "subheadline" => TextStyle::Subheadline,
        "body" => TextStyle::Body,
        "callout" => TextStyle::Callout,
        "footnote" => TextStyle::Footnote,
        "caption" => TextStyle::Caption,
        "caption2" => TextStyle::Caption2,
        other => return Err(format!("line {line}: no text style called `{other}`")),
    })
}

fn align(s: &str, line: usize) -> Result<views::Alignment, String> {
    Ok(match s {
        "center" => views::Alignment::Center,
        "leading" => views::Alignment::Leading,
        "trailing" => views::Alignment::Trailing,
        "top" => views::Alignment::Top,
        "bottom" => views::Alignment::Bottom,
        "top_leading" => views::Alignment::TopLeading,
        "top_trailing" => views::Alignment::TopTrailing,
        "bottom_leading" => views::Alignment::BottomLeading,
        "bottom_trailing" => views::Alignment::BottomTrailing,
        other => return Err(format!("line {line}: no alignment called `{other}`")),
    })
}

fn h_align(s: &str, line: usize) -> Result<HorizontalAlignment, String> {
    Ok(match s {
        "leading" => HorizontalAlignment::Leading,
        "center" => HorizontalAlignment::Center,
        "trailing" => HorizontalAlignment::Trailing,
        other => return Err(format!("line {line}: no horizontal alignment called `{other}`")),
    })
}

fn v_align(s: &str, line: usize) -> Result<views::VerticalAlignment, String> {
    Ok(match s {
        "top" => views::VerticalAlignment::Top,
        "center" => views::VerticalAlignment::Center,
        "bottom" => views::VerticalAlignment::Bottom,
        "first_baseline" => views::VerticalAlignment::FirstTextBaseline,
        "last_baseline" => views::VerticalAlignment::LastTextBaseline,
        other => return Err(format!("line {line}: no vertical alignment called `{other}`")),
    })
}