Skip to main content

yog_cli/
yui_vm.rs

1//! View-model screens: a `.yui` whose `<Screen>` has `x:ViewModel="MyVm"`
2//! compiles into a `yog_kit::View` — the static widget tree (built by
3//! [`crate::yui`]'s generator), compiled `{x:Bind ...}` bindings patching
4//! it, commands, two-way text boxes and toggles, lists with item templates,
5//! and the `register`/`open`/`close` functions. See `docs/mvvm.md` in
6//! Yog-IDLE for the format.
7
8use std::collections::HashMap;
9use std::fmt::Write as _;
10
11use crate::yui::{self, Element, RAW_CALL, RAW_VALUE, UI_USE, err};
12
13/// The codegen version checked by `yog_kit::__codegen::require`.
14const CODEGEN: u32 = 1;
15
16const STATES: &[(&str, &str)] = &[
17    ("hover", "HOVER"),
18    ("pressed", "PRESSED"),
19    ("focused", "FOCUSED"),
20    ("selected", "SELECTED"),
21    ("checked", "CHECKED"),
22    ("disabled", "DISABLED"),
23];
24
25// ── binding expressions ──────────────────────────────────────────────────────
26
27#[derive(Debug, Clone, PartialEq)]
28enum Tok {
29    Ident(String),
30    Num(String),
31    Str(String),
32    PathSep,
33    Dot,
34    OptDot,
35    Open,
36    Close,
37    Comma,
38    Eq,
39    Ne,
40    Not,
41}
42
43fn lex(src: &str) -> Result<Vec<Tok>, String> {
44    let mut out = Vec::new();
45    let cs: Vec<char> = src.chars().collect();
46    let mut i = 0;
47    while i < cs.len() {
48        let c = cs[i];
49        let next = cs.get(i + 1).copied();
50        match c {
51            _ if c.is_whitespace() => i += 1,
52            _ if c.is_alphabetic() || c == '_' => {
53                let s = i;
54                while i < cs.len() && (cs[i].is_alphanumeric() || cs[i] == '_') {
55                    i += 1;
56                }
57                out.push(Tok::Ident(cs[s..i].iter().collect()));
58            }
59            _ if c.is_ascii_digit() || (c == '-' && next.is_some_and(|n| n.is_ascii_digit())) => {
60                let s = i;
61                i += 1;
62                while i < cs.len()
63                    && (cs[i].is_ascii_alphanumeric()
64                        || cs[i] == '_'
65                        || (cs[i] == '.' && cs.get(i + 1).is_some_and(|n| n.is_ascii_digit())))
66                {
67                    i += 1;
68                }
69                out.push(Tok::Num(cs[s..i].iter().collect()));
70            }
71            '\'' => {
72                let s = i + 1;
73                i += 1;
74                while i < cs.len() && cs[i] != '\'' {
75                    i += 1;
76                }
77                if i >= cs.len() {
78                    return Err("unterminated 'string'".into());
79                }
80                out.push(Tok::Str(cs[s..i].iter().collect()));
81                i += 1;
82            }
83            ':' if next == Some(':') => {
84                out.push(Tok::PathSep);
85                i += 2;
86            }
87            '?' if next == Some('.') => {
88                out.push(Tok::OptDot);
89                i += 2;
90            }
91            '=' if next == Some('=') => {
92                out.push(Tok::Eq);
93                i += 2;
94            }
95            '!' if next == Some('=') => {
96                out.push(Tok::Ne);
97                i += 2;
98            }
99            '!' => {
100                out.push(Tok::Not);
101                i += 1;
102            }
103            '.' => {
104                out.push(Tok::Dot);
105                i += 1;
106            }
107            '(' => {
108                out.push(Tok::Open);
109                i += 1;
110            }
111            ')' => {
112                out.push(Tok::Close);
113                i += 1;
114            }
115            ',' => {
116                out.push(Tok::Comma);
117                i += 1;
118            }
119            _ => {
120                return Err(format!(
121                    "unexpected `{c}` (bindings allow paths, calls, literals, !, == and !=; use a view-model method for anything else)"
122                ));
123            }
124        }
125    }
126    Ok(out)
127}
128
129#[derive(Debug, Clone)]
130struct Seg {
131    opt: bool,
132    name: String,
133    args: Option<Vec<Ex>>,
134}
135
136#[derive(Debug, Clone)]
137enum Head {
138    Ident(String, Option<Vec<Ex>>),
139    Type(String, Option<Vec<Ex>>),
140    Lit(String),
141    Paren(Box<Ex>),
142}
143
144#[derive(Debug, Clone)]
145enum Ex {
146    Post(Head, Vec<Seg>),
147    Not(Box<Ex>),
148    Cmp(Box<Ex>, &'static str, Box<Ex>),
149}
150
151struct ExParser {
152    toks: Vec<Tok>,
153    pos: usize,
154}
155
156impl ExParser {
157    fn peek(&self) -> Option<&Tok> {
158        self.toks.get(self.pos)
159    }
160    fn bump(&mut self) -> Option<Tok> {
161        let t = self.toks.get(self.pos).cloned();
162        self.pos += 1;
163        t
164    }
165    fn eat(&mut self, t: &Tok) -> bool {
166        if self.peek() == Some(t) {
167            self.pos += 1;
168            true
169        } else {
170            false
171        }
172    }
173    fn expr(&mut self) -> Result<Ex, String> {
174        let a = self.unary()?;
175        let op = if self.eat(&Tok::Eq) {
176            "=="
177        } else if self.eat(&Tok::Ne) {
178            "!="
179        } else {
180            return Ok(a);
181        };
182        let b = self.unary()?;
183        Ok(Ex::Cmp(Box::new(a), op, Box::new(b)))
184    }
185    fn unary(&mut self) -> Result<Ex, String> {
186        if self.eat(&Tok::Not) {
187            return Ok(Ex::Not(Box::new(self.postfix()?)));
188        }
189        self.postfix()
190    }
191    fn call(&mut self) -> Result<Option<Vec<Ex>>, String> {
192        if !self.eat(&Tok::Open) {
193            return Ok(None);
194        }
195        let mut args = Vec::new();
196        if self.eat(&Tok::Close) {
197            return Ok(Some(args));
198        }
199        loop {
200            args.push(self.expr()?);
201            if self.eat(&Tok::Close) {
202                return Ok(Some(args));
203            }
204            if !self.eat(&Tok::Comma) {
205                return Err("expected `,` or `)`".into());
206            }
207        }
208    }
209    fn postfix(&mut self) -> Result<Ex, String> {
210        let head = match self.bump() {
211            Some(Tok::Ident(id)) => {
212                if self.peek() == Some(&Tok::PathSep) {
213                    let mut path = id;
214                    while self.eat(&Tok::PathSep) {
215                        match self.bump() {
216                            Some(Tok::Ident(n)) => {
217                                path.push_str("::");
218                                path.push_str(&n);
219                            }
220                            _ => return Err("expected a name after `::`".into()),
221                        }
222                    }
223                    Head::Type(path, self.call()?)
224                } else if id == "true" || id == "false" {
225                    Head::Lit(id)
226                } else {
227                    Head::Ident(id.clone(), self.call()?)
228                }
229            }
230            Some(Tok::Num(n)) => Head::Lit(n),
231            Some(Tok::Str(s)) => Head::Lit(format!("{s:?}")),
232            Some(Tok::Open) => {
233                let e = self.expr()?;
234                if !self.eat(&Tok::Close) {
235                    return Err("expected `)`".into());
236                }
237                Head::Paren(Box::new(e))
238            }
239            Some(t) => return Err(format!("unexpected {t:?}")),
240            None => return Err("expected an expression".into()),
241        };
242        let mut segs = Vec::new();
243        loop {
244            let opt = if self.eat(&Tok::Dot) {
245                false
246            } else if self.eat(&Tok::OptDot) {
247                true
248            } else {
249                break;
250            };
251            let Some(Tok::Ident(name)) = self.bump() else {
252                return Err("expected a name after `.`".into());
253            };
254            let args = self.call()?;
255            segs.push(Seg { opt, name, args });
256        }
257        Ok(Ex::Post(head, segs))
258    }
259}
260
261fn parse_expr(src: &str) -> Result<Ex, String> {
262    let mut p = ExParser {
263        toks: lex(src)?,
264        pos: 0,
265    };
266    let e = p.expr()?;
267    if p.pos < p.toks.len() {
268        return Err(format!("unexpected {:?}", p.toks[p.pos]));
269    }
270    Ok(e)
271}
272
273/// Which names a binding sees.
274#[derive(Clone, Copy, PartialEq)]
275enum Scope {
276    Screen,
277    Template,
278}
279
280impl Ex {
281    fn has_opt(&self) -> bool {
282        match self {
283            Ex::Post(h, segs) => {
284                segs.iter()
285                    .any(|s| s.opt || s.args.iter().flatten().any(Ex::has_opt))
286                    || match h {
287                        Head::Ident(_, a) | Head::Type(_, a) => a.iter().flatten().any(Ex::has_opt),
288                        Head::Paren(e) => e.has_opt(),
289                        Head::Lit(_) => false,
290                    }
291            }
292            Ex::Not(e) => e.has_opt(),
293            Ex::Cmp(a, _, b) => a.has_opt() || b.has_opt(),
294        }
295    }
296
297    /// A field path (`search`, `vm.state.name`, `item.id`): assignable, and
298    /// passed by reference to type-path calls.
299    fn is_place(&self) -> bool {
300        match self {
301            Ex::Post(Head::Ident(n, None), segs) => {
302                n != "cx" && segs.iter().all(|s| !s.opt && s.args.is_none())
303            }
304            _ => false,
305        }
306    }
307
308    fn emit(&self, scope: Scope, command: bool) -> Result<String, String> {
309        let args = |a: &Option<Vec<Ex>>, by_ref: bool| -> Result<String, String> {
310            let Some(a) = a else {
311                return Ok(String::new());
312            };
313            let parts = a
314                .iter()
315                .map(|e| {
316                    let s = e.emit(scope, command)?;
317                    Ok(if by_ref && e.is_place() {
318                        format!("&{s}")
319                    } else {
320                        s
321                    })
322                })
323                .collect::<Result<Vec<_>, String>>()?;
324            Ok(format!("({})", parts.join(", ")))
325        };
326        Ok(match self {
327            Ex::Post(h, segs) => {
328                let mut s = match h {
329                    Head::Lit(l) => l.clone(),
330                    Head::Paren(e) => format!("({})", e.emit(scope, command)?),
331                    Head::Type(p, a) => format!("{p}{}", args(a, true)?),
332                    Head::Ident(n, a) => {
333                        let root = match (n.as_str(), scope) {
334                            ("vm", _) => "vm".to_string(),
335                            ("cx", _) if command => "cx".to_string(),
336                            ("cx", _) => return Err("`cx` is only available in commands".into()),
337                            ("item" | "index", Scope::Template) => n.clone(),
338                            ("item" | "index", Scope::Screen) => {
339                                return Err(format!("`{n}` is only available in item templates"));
340                            }
341                            (_, Scope::Screen) => format!("vm.{n}"),
342                            (_, Scope::Template) => format!("item.{n}"),
343                        };
344                        format!("{root}{}", args(a, false)?)
345                    }
346                };
347                for seg in segs {
348                    if seg.opt {
349                        s.push('?');
350                    }
351                    let _ = write!(s, ".{}{}", seg.name, args(&seg.args, false)?);
352                }
353                s
354            }
355            Ex::Not(e) => format!("!{}", e.emit(scope, command)?),
356            Ex::Cmp(a, op, b) => format!(
357                "{} {op} {}",
358                a.emit(scope, command)?,
359                b.emit(scope, command)?
360            ),
361        })
362    }
363}
364
365#[derive(Debug, Clone, Copy, PartialEq)]
366enum Mode {
367    OneWay,
368    TwoWay,
369}
370
371/// One `{x:Bind ...}` (or a `@Set.name` text, compiled as a binding).
372#[derive(Debug, Clone)]
373struct Binding {
374    /// The attribute value as written, for comments.
375    raw: String,
376    expr: Option<Ex>,
377    /// Pre-emitted Rust (resource texts).
378    rust: Option<String>,
379    mode: Mode,
380    bind_back: Option<String>,
381    fallback: Option<String>,
382}
383
384impl Binding {
385    /// The bound value as Rust in `scope`.
386    fn rust(&self, scope: Scope, el: &Element) -> Result<String, String> {
387        match (&self.rust, &self.expr) {
388            (Some(r), _) => Ok(r.clone()),
389            (None, Some(e)) => e
390                .emit(scope, false)
391                .map_err(|e| format!("line {}: {e}", el.line)),
392            (None, None) => unreachable!("a binding has an expression"),
393        }
394    }
395}
396
397/// Splits on commas outside parentheses and quotes.
398fn split_top(s: &str) -> Vec<&str> {
399    let (mut depth, mut quote, mut start) = (0i32, false, 0);
400    let mut out = Vec::new();
401    for (i, c) in s.char_indices() {
402        match c {
403            '\'' => quote = !quote,
404            '(' if !quote => depth += 1,
405            ')' if !quote => depth -= 1,
406            ',' if !quote && depth == 0 => {
407                out.push(&s[start..i]);
408                start = i + 1;
409            }
410            _ => {}
411        }
412    }
413    out.push(&s[start..]);
414    out
415}
416
417fn parse_binding(value: &str) -> Option<Result<Binding, String>> {
418    let inner = value.trim().strip_prefix("{x:Bind")?.strip_suffix('}')?;
419    Some((|| {
420        let mut b = Binding {
421            raw: value.to_string(),
422            expr: None,
423            rust: None,
424            mode: Mode::OneWay,
425            bind_back: None,
426            fallback: None,
427        };
428        for (i, part) in split_top(inner).into_iter().enumerate() {
429            let part = part.trim();
430            if i == 0 {
431                if part.is_empty() {
432                    return Err("empty binding — write {x:Bind expression}".to_string());
433                }
434                b.expr = Some(parse_expr(part).map_err(|e| format!("{value}: {e}"))?);
435                continue;
436            }
437            let Some((k, v)) = part.split_once('=') else {
438                return Err(format!(
439                    "{value}: expected Mode=, BindBack= or Fallback=, got `{part}`"
440                ));
441            };
442            let v = v.trim();
443            match k.trim() {
444                "Mode" => {
445                    b.mode = match v {
446                        "OneWay" | "OneTime" => Mode::OneWay,
447                        "TwoWay" => Mode::TwoWay,
448                        _ => return Err(format!("{value}: Mode is OneWay, OneTime or TwoWay")),
449                    }
450                }
451                "BindBack" => b.bind_back = Some(v.to_string()),
452                "Fallback" => b.fallback = Some(v.trim_matches('\'').to_string()),
453                other => return Err(format!("{value}: unknown binding option `{other}`")),
454            }
455        }
456        Ok(b)
457    })())
458}
459
460/// Compiles an attribute value `{x:Bind expr}` into a Rust expression that
461/// reads the view model `vm` (bare names become `vm.name`, `Type::f(x)`
462/// gets `&vm.x`, `a?.b` stays a `?`-chain — wrap it in a closure returning
463/// `Option`). `None` when `value` isn't a binding. Options (`Mode=`,
464/// `BindBack=`, `Fallback=`) are parsed and ignored here. Shared with the
465/// `.yui` component generator so there's one binding syntax.
466pub(crate) fn compile_bind(value: &str) -> Option<Result<String, String>> {
467    let b = match parse_binding(value)? {
468        Ok(b) => b,
469        Err(e) => return Some(Err(e)),
470    };
471    Some(b.expr.expect("parsed").emit(Scope::Screen, false))
472}
473
474// ── generator ────────────────────────────────────────────────────────────────
475
476/// What a bound attribute converts to and how it's applied.
477#[derive(Clone, Copy, PartialEq)]
478enum Target {
479    Text,
480    Placeholder,
481    Item,
482    Source,
483    Count,
484    Color(&'static str),
485    Enabled,
486    Visible,
487    Checked,
488    Size(&'static str),
489    Number(&'static str),
490    ScrollKey,
491}
492
493fn target(kind: &str, attr: &str) -> Option<Target> {
494    Some(match attr {
495        "text" if matches!(kind, "Label" | "Button" | "TextBox") => Target::Text,
496        "placeholder" if kind == "TextBox" => Target::Placeholder,
497        "item" if matches!(kind, "ItemSlot" | "InvSlot") => Target::Item,
498        "source" if matches!(kind, "Image" | "Surface") => Target::Source,
499        "count" if kind == "InvSlot" => Target::Count,
500        "bg" => Target::Color("bg"),
501        "color" => Target::Color("color"),
502        "focus_color" => Target::Color("focus_color"),
503        "enabled" => Target::Enabled,
504        "visible" => Target::Visible,
505        "checked" if kind == "Button" => Target::Checked,
506        "w" => Target::Size("w"),
507        "h" => Target::Size("h"),
508        "gap" => Target::Number("gap"),
509        "font_scale" => Target::Number("font_scale"),
510        "flex" => Target::Number("flex"),
511        "min_w" => Target::Number("min_w"),
512        "min_h" => Target::Number("min_h"),
513        "scroll_key" if kind == "ScrollView" => Target::ScrollKey,
514        _ => return None,
515    })
516}
517
518/// Where generated update code writes: the view or a template instance.
519struct Ctx {
520    scope: Scope,
521    /// `self.` or `inst.`
522    fields: &'static str,
523    /// The tree variable: `root` or `w`.
524    tree: &'static str,
525    /// List owner of actions (0 = screen).
526    owner: u16,
527    /// Slot fields declared (name, type) — for templates.
528    slots: Vec<(String, String)>,
529    update: String,
530}
531
532impl Ctx {
533    fn new(scope: Scope, fields: &'static str, tree: &'static str, owner: u16) -> Self {
534        Ctx {
535            scope,
536            fields,
537            tree,
538            owner,
539            slots: Vec::new(),
540            update: String::new(),
541        }
542    }
543}
544
545struct VmGen<'a> {
546    file: String,
547    mod_id: Option<&'a str>,
548    resources: HashMap<String, String>,
549    styles: HashMap<String, Vec<(String, String)>>,
550    ids: yui::Names,
551    /// View fields (name, type, init).
552    view_fields: Vec<(String, String, String)>,
553    parts: String,
554    dispatch: Vec<(String, String)>,
555    templates: String,
556    n_slots: usize,
557    n_lists: u16,
558    n_templates: usize,
559    n_scrollers: u16,
560    n_text_boxes: u16,
561    /// Next command slot per owner.
562    cmd_slots: HashMap<u16, u16>,
563}
564
565fn path_lit(path: &[u16]) -> String {
566    format!(
567        "&[{}]",
568        path.iter()
569            .map(u16::to_string)
570            .collect::<Vec<_>>()
571            .join(", ")
572    )
573}
574
575impl VmGen<'_> {
576    fn slot(&mut self, ctx: &mut Ctx, ty: &str) -> String {
577        let name = format!("b{}", self.n_slots);
578        self.n_slots += 1;
579        if ctx.scope == Scope::Template && ctx.fields == "inst." {
580            ctx.slots.push((name.clone(), ty.to_string()));
581        } else {
582            self.view_fields.push((
583                name.clone(),
584                format!("::yog_kit::bind::Slot<{ty}>"),
585                "::yog_kit::bind::Slot::new()".into(),
586            ));
587        }
588        name
589    }
590
591    fn next_cmd(&mut self, owner: u16) -> u16 {
592        let n = self.cmd_slots.entry(owner).or_insert(0);
593        let s = *n;
594        *n += 1;
595        s
596    }
597
598    /// Resolves `@local` resources, `x:Name` and `style` into plain attributes.
599    fn resolve(&self, el: &Element) -> Result<Element, String> {
600        let mut out = el.clone();
601        out.attrs.clear();
602        let mut style: Vec<(String, String)> = Vec::new();
603        for (k, v) in &el.attrs {
604            let v = match v.strip_prefix('@') {
605                Some(name) if !name.starts_with('@') && !name.contains('.') && !name.is_empty() => {
606                    match self.resources.get(name) {
607                        Some(r) => r.clone(),
608                        None if k == "style" => v.clone(),
609                        None => {
610                            return err(
611                                el,
612                                format!("{k}=\"{v}\": no resource `{name}` in <Screen.Resources>"),
613                            );
614                        }
615                    }
616                }
617                _ => v.clone(),
618            };
619            match k.as_str() {
620                "x:Name" => out.attrs.push(("id".into(), v)),
621                "style" => {
622                    let name = v.trim().trim_start_matches('@');
623                    let Some(s) = self.styles.get(name) else {
624                        return err(
625                            el,
626                            format!(
627                                "style=\"{v}\": no <Style x:Key=\"{name}\"> in <Screen.Resources>"
628                            ),
629                        );
630                    };
631                    style = s.clone();
632                }
633                _ => out.attrs.push((k.clone(), v)),
634            }
635        }
636        for (k, v) in style {
637            if !out.attrs.iter().any(|(ek, _)| *ek == k) {
638                out.attrs.push((k, v));
639            }
640        }
641        Ok(out)
642    }
643
644    fn collect_resources(&mut self, res: &Element) -> Result<(), String> {
645        let mut pending: Vec<&Element> = Vec::new();
646        for r in &res.children {
647            let Some(key) = r.attr("x:Key") else {
648                return err(r, "needs an x:Key");
649            };
650            if r.name == "Style" {
651                pending.push(r);
652                continue;
653            }
654            let Some(v) = r.attr("value") else {
655                return err(
656                    r,
657                    "needs a value (e.g. <Color x:Key=\"Accent\" value=\"#FFD700\"/>)",
658                );
659            };
660            self.resources.insert(key.to_string(), v.to_string());
661        }
662        // Styles, resolving based_on chains in any order.
663        while !pending.is_empty() {
664            let before = pending.len();
665            let mut rest = Vec::new();
666            for s in pending {
667                let key = s.attr("x:Key").unwrap_or_default().to_string();
668                let base = s
669                    .attr("based_on")
670                    .map(|b| b.trim().trim_start_matches('@').to_string());
671                let mut attrs: Vec<(String, String)> = match &base {
672                    Some(b) => match self.styles.get(b) {
673                        Some(a) => a.clone(),
674                        None => {
675                            rest.push(s);
676                            continue;
677                        }
678                    },
679                    None => Vec::new(),
680                };
681                for (k, v) in &s.attrs {
682                    if matches!(k.as_str(), "x:Key" | "target" | "based_on") {
683                        continue;
684                    }
685                    let v = match v.strip_prefix('@') {
686                        Some(n) if !n.contains('.') && !n.starts_with('@') => {
687                            self.resources.get(n).cloned().ok_or_else(|| {
688                                format!("line {}: <Style> {k}=\"{v}\": no resource `{n}`", s.line)
689                            })?
690                        }
691                        _ => v.clone(),
692                    };
693                    attrs.retain(|(ek, _)| ek != k);
694                    attrs.push((k.clone(), v));
695                }
696                self.styles.insert(key, attrs);
697            }
698            if rest.len() == before {
699                return err(rest[0], "based_on names an unknown (or circular) style");
700            }
701            pending = rest;
702        }
703        Ok(())
704    }
705
706    /// Converts and applies one bound attribute.
707    #[allow(clippy::too_many_arguments)]
708    fn bind_attr(
709        &mut self,
710        ctx: &mut Ctx,
711        el: &Element,
712        kind: &str,
713        key: &str,
714        b: &Binding,
715        path: &[u16],
716        text_box: Option<u16>,
717        scroller: Option<u16>,
718    ) -> Result<(), String> {
719        let Some(t) = target(kind, key) else {
720            return err(el, format!("{key} can't be bound"));
721        };
722        let expr = b.rust(ctx.scope, el)?;
723        let opt = b.expr.as_ref().is_some_and(Ex::has_opt);
724        let (ty, conv) = match t {
725            Target::Text | Target::Placeholder | Target::Item | Target::Source => {
726                ("String", "::yog_kit::bind::text(&(E))".to_string())
727            }
728            Target::Count => ("u32", "::yog_kit::bind::count(E)".into()),
729            Target::Color(_) => ("u32", "::yog_kit::bind::color(E)".into()),
730            Target::Enabled | Target::Visible | Target::Checked => {
731                ("bool", "::yog_kit::bind::flag(E)".into())
732            }
733            Target::Size(_) => ("::yog_api::ui::Units", "::yog_kit::bind::units(E)".into()),
734            Target::Number(_) => ("f32", "::yog_kit::bind::number(E)".into()),
735            Target::ScrollKey => ("u64", "::yog_kit::bind::key(&(E))".into()),
736        };
737        let value = if opt {
738            let fallback = match (&b.fallback, ty) {
739                (Some(f), "String") => format!("::std::string::String::from({f:?})"),
740                (Some(f), _) => f.clone(),
741                (None, _) => "::std::default::Default::default()".into(),
742            };
743            format!(
744                "(|| ::std::option::Option::Some({}))().unwrap_or_else(|| {fallback})",
745                conv.replace('E', &expr)
746            )
747        } else {
748            conv.replacen('E', &expr, 1)
749        };
750        let slot = self.slot(ctx, ty);
751        let f = format!("{}{slot}", ctx.fields);
752        let w = format!("{}.at_path_mut({})", ctx.tree, path_lit(path));
753        let apply = match t {
754            Target::Text if kind == "TextBox" => {
755                let Some(tb) = text_box else {
756                    return err(el, "text boxes in item templates aren't supported");
757                };
758                format!("u.set_text_box({tb}, {f}.get());")
759            }
760            Target::Text => {
761                format!("{w}.set_text(::std::clone::Clone::clone({f}.get())); u.relayout();")
762            }
763            Target::Placeholder => {
764                format!("::yog_kit::bind::set_placeholder({w}, {f}.get()); u.repaint();")
765            }
766            Target::Item => format!("::yog_kit::bind::set_item({w}, {f}.get()); u.repaint();"),
767            Target::Source => format!("::yog_kit::bind::set_source({w}, {f}.get()); u.relayout();"),
768            Target::Count => format!("::yog_kit::bind::set_count({w}, *{f}.get()); u.repaint();"),
769            Target::Color(c) => format!("{w}.style.{c} = *{f}.get(); u.repaint();"),
770            Target::Enabled => format!("{w}.enabled = *{f}.get(); u.repaint();"),
771            Target::Visible => format!("{w}.visible = *{f}.get(); u.relayout();"),
772            Target::Checked => {
773                format!("::yog_kit::bind::set_checked({w}, *{f}.get()); u.repaint();")
774            }
775            Target::Size(a) => format!("{w}.style.{a} = *{f}.get(); u.relayout();"),
776            Target::Number(a) => format!("{w}.style.{a} = *{f}.get(); u.relayout();"),
777            Target::ScrollKey => {
778                let Some(s) = scroller else {
779                    return err(el, "scroll_key needs a ScrollView outside item templates");
780                };
781                format!("u.reset_scroll({s});")
782            }
783        };
784        let _ = write!(
785            ctx.update,
786            "        // @yui {}:{} {key}=\"{}\"\n        if {f}.set({value}) {{ {apply} }}\n",
787            self.file,
788            el.line,
789            b.raw.replace('\n', " ")
790        );
791        Ok(())
792    }
793
794    /// The command statement for `expr`, in screen scope.
795    fn command(
796        &self,
797        el: &Element,
798        b: &Binding,
799        scope: Scope,
800        items: Option<&str>,
801    ) -> Result<String, String> {
802        let Some(e) = &b.expr else {
803            return err(el, "command needs {x:Bind method(...)}");
804        };
805        let line = el.line;
806        match scope {
807            Scope::Screen => Ok(format!(
808                "{};",
809                e.emit(Scope::Screen, true)
810                    .map_err(|m| format!("line {line}: {m}"))?
811            )),
812            Scope::Template => {
813                // vm.method(args) / cx.method(): item arguments are cloned
814                // out of the item first.
815                let Ex::Post(head, segs) = e else {
816                    return err(el, "command must be a call: vm.method(...) or cx.close()");
817                };
818                let rooted = matches!(head, Head::Ident(n, None) if n == "vm" || n == "cx");
819                let Some(last) = segs.last().filter(|s| s.args.is_some() && rooted) else {
820                    return err(
821                        el,
822                        "commands in item templates call the view model: write vm.method(...) (or cx....)",
823                    );
824                };
825                let args = last.args.clone().unwrap_or_default();
826                let mut call = e.clone();
827                if let Ex::Post(_, segs) = &mut call {
828                    let last = segs.last_mut().expect("checked");
829                    last.args = Some(
830                        (0..args.len())
831                            .map(|i| Ex::Post(Head::Lit(format!("__a{i}")), Vec::new()))
832                            .collect(),
833                    );
834                }
835                let call = call
836                    .emit(Scope::Template, true)
837                    .map_err(|m| format!("line {line}: {m}"))?;
838                if args.is_empty() {
839                    return Ok(format!("let _ = index; {call};"));
840                }
841                let items = items.expect("template has items");
842                let cloned = args
843                    .iter()
844                    .map(|a| {
845                        a.emit(Scope::Template, false)
846                            .map(|s| format!("::std::clone::Clone::clone(&({s}))"))
847                    })
848                    .collect::<Result<Vec<_>, _>>()
849                    .map_err(|m| format!("line {line}: {m}"))?;
850                let names: Vec<String> = (0..args.len()).map(|i| format!("__a{i}")).collect();
851                Ok(format!(
852                    "let __args = ::std::iter::IntoIterator::into_iter({items}).enumerate().nth(index as usize).map(|(index, item)| {{ let _ = (&index, &item); ({},) }});\n                if let ::std::option::Option::Some(({},)) = __args {{ {call}; }}",
853                    cloned.join(", "),
854                    names.join(", ")
855                ))
856            }
857        }
858    }
859
860    /// Compiles `el` at `path` in `ctx`; returns the static element.
861    fn element(
862        &mut self,
863        ctx: &mut Ctx,
864        el: &Element,
865        path: &[u16],
866        items: Option<&str>,
867    ) -> Result<Element, String> {
868        let el = &self.resolve(el)?;
869        let name = el.name.as_str();
870        let (kind, horizontal) = match name {
871            "ToggleButton" => ("Button", false),
872            "ListView" => ("ScrollView", false),
873            "ItemsControl" => (
874                "Column",
875                el.attr("orientation")
876                    .is_some_and(|o| o.trim() == "horizontal"),
877            ),
878            "ContentPresenter" => ("Column", false),
879            "Screen.Resources" | "DataTemplate" => return err(el, "isn't allowed here"),
880            k => (k, false),
881        };
882        let kind = if horizontal { "Row" } else { kind };
883        let is_list = matches!(name, "ListView" | "ItemsControl" | "ContentPresenter");
884        let screen = ctx.scope == Scope::Screen;
885
886        let mut out = Element {
887            name: kind.to_string(),
888            attrs: Vec::new(),
889            children: Vec::new(),
890            line: el.line,
891        };
892        let mut raw = 0;
893        let mut push_raw = |out: &mut Element, call: String| {
894            out.attrs.push((format!("{RAW_CALL}{raw}"), call));
895            raw += 1;
896        };
897        let mut patches: Vec<(&'static str, Vec<String>)> = Vec::new();
898        let mut bindings: Vec<(String, Binding)> = Vec::new();
899        let mut command: Option<Binding> = None;
900        let mut list_attrs: HashMap<String, String> = HashMap::new();
901
902        for (k, v) in &el.attrs {
903            let k = k.as_str();
904            if k.starts_with("d:") || matches!(k, "x:ViewModel" | "x:Create" | "x:DataType") {
905                continue;
906            }
907            if matches!(k, "on_click" | "on_change" | "on_submit") {
908                return err(
909                    el,
910                    format!(
911                        "{k}: view-model screens use command=\"{{x:Bind method()}}\" (and Mode=TwoWay text) instead"
912                    ),
913                );
914            }
915            if let Some((state, attr)) = k.split_once(':') {
916                let Some((_, flag)) = STATES.iter().find(|(s, _)| *s == state) else {
917                    return err(
918                        el,
919                        format!(
920                            "unknown attribute prefix `{state}:` (states: hover, pressed, focused, selected, checked, disabled)"
921                        ),
922                    );
923                };
924                let field = match attr {
925                    "bg" if yui::is_image_value(v) => {
926                        let src = yui::image_source(el, k, v.trim(), self.mod_id)?;
927                        format!("bg_image: ::std::option::Option::Some(::std::string::String::from({src:?}))")
928                    }
929                    "bg" | "color" | "focus_color" => {
930                        let c = yui::color_attr(el, k, v)?;
931                        format!("{attr}: ::std::option::Option::Some(0x{c:08X})")
932                    }
933                    "shadow" => format!(
934                        "shadow: ::std::option::Option::Some({})",
935                        yui::boolean(el, k, v)?
936                    ),
937                    _ => {
938                        return err(
939                            el,
940                            format!(
941                                "{k}: only paint attributes (bg, color, shadow, focus_color) take a state prefix"
942                            ),
943                        );
944                    }
945                };
946                match patches.iter_mut().find(|(f, _)| f == flag) {
947                    Some((_, fs)) => fs.push(field),
948                    None => patches.push((flag, vec![field])),
949                }
950                continue;
951            }
952            if let Some(b) = parse_binding(v) {
953                let b = b.map_err(|e| format!("line {}: {e}", el.line))?;
954                if k == "command" {
955                    command = Some(b);
956                } else if matches!(k, "items" | "content" | "key" | "selected") {
957                    if !is_list {
958                        return err(
959                            el,
960                            format!("{k} is for ListView, ItemsControl and ContentPresenter"),
961                        );
962                    }
963                    bindings.push((k.to_string(), b));
964                } else {
965                    bindings.push((k.to_string(), b));
966                }
967                continue;
968            }
969            match k {
970                "command" => return err(el, "command needs {x:Bind method(...)}"),
971                "items" | "content" | "key" | "selected" => {
972                    return err(el, format!("{k} needs a binding: {k}=\"{{x:Bind ...}}\""));
973                }
974                "item_height" | "orientation" if is_list => {
975                    list_attrs.insert(k.into(), v.clone());
976                }
977                "visible" => {
978                    let b = yui::boolean(el, k, v)?;
979                    push_raw(&mut out, format!("visible({b})"));
980                }
981                "checked" if kind == "Button" => {
982                    let b = yui::boolean(el, k, v)?;
983                    bindings.push((
984                        k.into(),
985                        Binding {
986                            raw: v.clone(),
987                            expr: Some(Ex::Post(Head::Lit(b.to_string()), Vec::new())),
988                            rust: None,
989                            mode: Mode::OneWay,
990                            bind_back: None,
991                            fallback: None,
992                        },
993                    ));
994                }
995                "text" | "placeholder"
996                    if v.starts_with('@') && !v.starts_with("@@") && v.len() > 1 =>
997                {
998                    // Looked up on every update, so it follows the language.
999                    bindings.push((
1000                        k.into(),
1001                        Binding {
1002                            raw: v.clone(),
1003                            expr: None,
1004                            rust: Some(yui::text_expr(v)),
1005                            mode: Mode::OneWay,
1006                            bind_back: None,
1007                            fallback: None,
1008                        },
1009                    ));
1010                }
1011                _ => out.attrs.push((k.to_string(), v.clone())),
1012            }
1013        }
1014        for (flag, fields) in patches {
1015            push_raw(
1016                &mut out,
1017                format!(
1018                    "state_style(::yog_api::ui::StateFlags::{flag}, ::yog_api::ui::StylePatch {{ {}, ..::std::default::Default::default() }})",
1019                    fields.join(", ")
1020                ),
1021            );
1022        }
1023        if let Some(id) = out.attr("id") {
1024            self.ids.push(id);
1025        }
1026
1027        // Interactive parts (screen scope only).
1028        let text_box = if kind == "TextBox" && screen {
1029            let n = self.n_text_boxes;
1030            self.n_text_boxes += 1;
1031            let _ = writeln!(self.parts, "        parts.text_box({});", path_lit(path));
1032            Some(n)
1033        } else {
1034            None
1035        };
1036        let scroller = if kind == "ScrollView" {
1037            if !screen {
1038                return err(el, "scroll views inside item templates aren't supported");
1039            }
1040            let n = self.n_scrollers;
1041            self.n_scrollers += 1;
1042            let _ = writeln!(self.parts, "        parts.scroller({});", path_lit(path));
1043            Some(n)
1044        } else {
1045            None
1046        };
1047
1048        // Commands and two-way toggles → an action.
1049        let toggle_place = bindings
1050            .iter()
1051            .find(|(k, b)| k == "checked" && b.mode == Mode::TwoWay)
1052            .map(|(_, b)| b.clone());
1053        if kind == "TextBox" {
1054            let tb = text_box.ok_or_else(|| {
1055                format!(
1056                    "line {}: text boxes in item templates aren't supported",
1057                    el.line
1058                )
1059            })?;
1060            if let Some((_, b)) = bindings.iter().find(|(k, _)| k == "text") {
1061                let write = match (&b.bind_back, b.mode, &b.expr) {
1062                    (Some(m), _, _) => Some(format!("vm.{m}(text);")),
1063                    (None, Mode::TwoWay, Some(e)) if e.is_place() => {
1064                        Some(format!("{} = text;", e.emit(Scope::Screen, false)?))
1065                    }
1066                    (None, Mode::TwoWay, _) => {
1067                        return err(
1068                            el,
1069                            "Mode=TwoWay needs a field (text=\"{x:Bind search, Mode=TwoWay}\") or BindBack=method",
1070                        );
1071                    }
1072                    _ => None,
1073                };
1074                if let Some(write) = write {
1075                    self.dispatch.push((
1076                        format!("::yog_kit::ViewEvent::TextChanged {{ slot: {tb}, text }}"),
1077                        write,
1078                    ));
1079                }
1080            }
1081            if let Some(c) = &command {
1082                let stmt = self.command(el, c, Scope::Screen, None)?;
1083                self.dispatch.push((
1084                    format!("::yog_kit::ViewEvent::TextSubmitted {{ slot: {tb}, text }}"),
1085                    format!("let _ = text; {stmt}"),
1086                ));
1087            }
1088        } else if command.is_some() || toggle_place.is_some() {
1089            let owner = ctx.owner;
1090            let slot = self.next_cmd(owner);
1091            push_raw(
1092                &mut out,
1093                format!(
1094                    "action(::yog_api::ui::Action {{ owner: {owner}, slot: {slot}, index: 0 }})"
1095                ),
1096            );
1097            let mut body = String::new();
1098            if let Some(t) = &toggle_place {
1099                if ctx.scope == Scope::Template {
1100                    return err(
1101                        el,
1102                        "Mode=TwoWay toggles in item templates aren't supported — use a command",
1103                    );
1104                }
1105                match (&t.bind_back, &t.expr) {
1106                    (Some(m), Some(e)) => {
1107                        let cur = e.emit(Scope::Screen, false)?;
1108                        let _ = write!(body, "let __v = !{cur}; vm.{m}(__v); ");
1109                    }
1110                    (None, Some(e)) if e.is_place() => {
1111                        let p = e.emit(Scope::Screen, false)?;
1112                        let _ = write!(body, "{p} = !{p}; ");
1113                    }
1114                    _ => {
1115                        return err(
1116                            el,
1117                            "checked Mode=TwoWay needs a bool field or BindBack=method",
1118                        );
1119                    }
1120                }
1121            }
1122            if let Some(c) = &command {
1123                body.push_str(&self.command(el, c, ctx.scope, items)?);
1124            }
1125            let pat = if owner == 0 {
1126                format!(
1127                    "::yog_kit::ViewEvent::Action(::yog_api::ui::Action {{ owner: 0, slot: {slot}, .. }})"
1128                )
1129            } else {
1130                format!(
1131                    "::yog_kit::ViewEvent::Action(::yog_api::ui::Action {{ owner: {owner}, slot: {slot}, index }})"
1132                )
1133            };
1134            self.dispatch.push((pat, body.trim_end().to_string()));
1135            if screen {
1136                let _ = writeln!(self.parts, "        parts.focusable({});", path_lit(path));
1137            }
1138        }
1139
1140        // Lists.
1141        if is_list {
1142            if !screen {
1143                return err(el, "lists inside item templates aren't supported");
1144            }
1145            self.list(ctx, el, &mut bindings, &list_attrs, path, scroller)?;
1146        }
1147
1148        // A component's bound properties: when any changes, the instance is
1149        // rebuilt with the new values (then its other bindings re-applied).
1150        let rebuild = if yui::is_custom_component(kind)
1151            && bindings.iter().any(|(k, _)| !yui::is_common_attr(k))
1152        {
1153            Some(self.component_props(ctx, el, &out, &mut bindings, path)?)
1154        } else {
1155            None
1156        };
1157        let slots_before = self.n_slots;
1158        if bindings.iter().any(|(k, _)| k == "source") {
1159            // A valid stand-in for the static checks; the binding sets it.
1160            match kind {
1161                "Image" => out.attrs.push(("source".into(), "item:air".into())),
1162                "Surface" => out.attrs.push(("source".into(), "yog:none".into())),
1163                _ => {}
1164            }
1165        }
1166        for (k, b) in &bindings {
1167            if matches!(k.as_str(), "items" | "content" | "key" | "selected") {
1168                continue;
1169            }
1170            self.bind_attr(ctx, el, kind, k, b, path, text_box, scroller)?;
1171        }
1172        if let Some(marker) = rebuild {
1173            let resets: String = (slots_before..self.n_slots)
1174                .map(|i| format!(" {}b{i}.reset();", ctx.fields))
1175                .collect();
1176            ctx.update = ctx.update.replace(&marker, &resets);
1177        }
1178
1179        if !is_list {
1180            let mut i = 0u16;
1181            for child in &el.children {
1182                if child.name.contains('.') {
1183                    if child.name == "Screen.Resources" && path.is_empty() {
1184                        continue;
1185                    }
1186                    return err(child, "isn't allowed here");
1187                }
1188                let mut p = path.to_vec();
1189                p.push(i);
1190                out.children.push(self.element(ctx, child, &p, items)?);
1191                i += 1;
1192            }
1193        }
1194        Ok(out)
1195    }
1196
1197    /// Binds the component properties among `bindings` (removing them):
1198    /// one text slot each, and an update block that rebuilds the instance
1199    /// at `path` from `out` (its static attributes) plus the slots' values.
1200    /// Returns the marker the block leaves for the resets of the element's
1201    /// other bindings.
1202    fn component_props(
1203        &mut self,
1204        ctx: &mut Ctx,
1205        el: &Element,
1206        out: &Element,
1207        bindings: &mut Vec<(String, Binding)>,
1208        path: &[u16],
1209    ) -> Result<String, String> {
1210        let mut inst = out.clone();
1211        let mut sets = String::new();
1212        let mut i = 0;
1213        while i < bindings.len() {
1214            if yui::is_common_attr(&bindings[i].0) {
1215                i += 1;
1216                continue;
1217            }
1218            let (key, b) = bindings.remove(i);
1219            if b.mode == Mode::TwoWay || b.bind_back.is_some() {
1220                return err(el, format!("{key}: component properties bind one way"));
1221            }
1222            let expr = b.rust(ctx.scope, el)?;
1223            let value = if b.expr.as_ref().is_some_and(Ex::has_opt) {
1224                let fallback = b.fallback.clone().unwrap_or_default();
1225                format!(
1226                    "(|| ::std::option::Option::Some(::yog_kit::bind::text(&({expr}))))().unwrap_or_else(|| ::std::string::String::from({fallback:?}))"
1227                )
1228            } else {
1229                format!("::yog_kit::bind::text(&({expr}))")
1230            };
1231            let slot = self.slot(ctx, "String");
1232            let f = format!("{}{slot}", ctx.fields);
1233            let _ = write!(
1234                sets,
1235                "        // @yui {}:{} {key}=\"{}\"\n        __props |= {f}.set({value});\n",
1236                self.file,
1237                el.line,
1238                b.raw.replace('\n', " ")
1239            );
1240            inst.attrs.push((key, format!("{RAW_VALUE}*{f}.get()")));
1241        }
1242        let (expr, _) = yui::static_widget(&inst, false, 2, self.mod_id)?;
1243        let marker = format!("\u{1}resets{}\u{1}", self.n_slots);
1244        let _ = write!(
1245            ctx.update,
1246            "        let mut __props = false;\n{sets}        if __props {{\n            #[allow(unused_imports)]\n            {UI_USE}\n            *{}.at_path_mut({}) = {expr};\n            u.relayout();{marker}\n        }}\n",
1247            ctx.tree,
1248            path_lit(path),
1249        );
1250        Ok(marker)
1251    }
1252
1253    /// The single element inside a template/empty property element.
1254    fn only_child(el: &Element) -> Result<&Element, String> {
1255        let mut c = el;
1256        if c.children.len() == 1 && c.children[0].name == "DataTemplate" {
1257            c = &c.children[0];
1258        }
1259        match c.children.as_slice() {
1260            [one] => Ok(one),
1261            _ => err(el, "needs exactly one child element"),
1262        }
1263    }
1264
1265    fn list(
1266        &mut self,
1267        ctx: &mut Ctx,
1268        el: &Element,
1269        bindings: &mut [(String, Binding)],
1270        attrs: &HashMap<String, String>,
1271        path: &[u16],
1272        scroller: Option<u16>,
1273    ) -> Result<(), String> {
1274        let name = el.name.as_str();
1275        let owner = {
1276            self.n_lists += 1;
1277            self.n_lists
1278        };
1279        let get = |k: &str| {
1280            bindings
1281                .iter()
1282                .find(|(bk, _)| bk == k)
1283                .map(|(_, b)| b.clone())
1284        };
1285        let source = if name == "ContentPresenter" {
1286            "content"
1287        } else {
1288            "items"
1289        };
1290        let Some(items_b) = get(source) else {
1291            return err(el, format!("needs {source}=\"{{x:Bind ...}}\""));
1292        };
1293        let items_ex = items_b.expr.clone().expect("parsed");
1294        let mut items = items_ex
1295            .emit(Scope::Screen, false)
1296            .map_err(|e| format!("line {}: {e}", el.line))?;
1297        if items_ex.is_place() {
1298            items = format!("&{items}");
1299        }
1300        let key = match get("key") {
1301            Some(b) => b
1302                .expr
1303                .expect("parsed")
1304                .emit(Scope::Template, false)
1305                .map_err(|e| format!("line {}: {e}", el.line))?,
1306            None => "index".to_string(),
1307        };
1308        let selected = get("selected");
1309        if selected.is_some() && name != "ListView" {
1310            return err(el, "selected is for ListView");
1311        }
1312        let item_height = match attrs.get("item_height") {
1313            Some(v) => Some(yui::number(el, "item_height", v)?),
1314            None => None,
1315        };
1316
1317        // Templates.
1318        let mut template = None;
1319        let mut empty = None;
1320        for c in &el.children {
1321            match c.name.strip_prefix(name).and_then(|n| n.strip_prefix('.')) {
1322                Some("ItemTemplate" | "ContentTemplate") => template = Some(Self::only_child(c)?),
1323                Some("Empty") => empty = Some(Self::only_child(c)?),
1324                _ if c.name == "DataTemplate" => template = Some(Self::only_child(c)?),
1325                _ => {
1326                    return err(
1327                        c,
1328                        format!(
1329                            "isn't allowed in <{name}> (expected <{name}.ItemTemplate> or <{name}.Empty>)"
1330                        ),
1331                    );
1332                }
1333            }
1334        }
1335        let Some(template) = template else {
1336            return err(
1337                el,
1338                format!("needs an item template (<{name}.ItemTemplate><DataTemplate>...)"),
1339            );
1340        };
1341
1342        let t = self.n_templates;
1343        self.n_templates += 1;
1344        let mut tctx = Ctx::new(Scope::Template, "inst.", "w", owner);
1345        let saved = std::mem::take(&mut self.n_slots);
1346        let tel = self.element(&mut tctx, template, &[], Some(&items))?;
1347        self.n_slots = saved;
1348        let (texpr, ids) = yui::static_widget(&tel, false, 1, self.mod_id)?;
1349        self.absorb(ids);
1350        let fields: String = tctx
1351            .slots
1352            .iter()
1353            .map(|(n, ty)| format!("    {n}: ::yog_kit::bind::Slot<{ty}>,\n"))
1354            .collect();
1355        let inits: String = tctx
1356            .slots
1357            .iter()
1358            .map(|(n, _)| format!("{n}: ::yog_kit::bind::Slot::new(), "))
1359            .collect();
1360        let _ = write!(
1361            self.templates,
1362            "/// Item template {t} ({}:{}).\n#[doc(hidden)]\n#[allow(non_camel_case_types)]\nstruct __T{t} {{\n{fields}}}\n\nimpl __T{t} {{\n    fn build() -> (Self, ::yog_api::ui::Widget) {{\n        #[allow(unused_imports)]\n        {UI_USE}\n        (Self {{ {inits}}}, {texpr})\n    }}\n}}\n\n",
1363            self.file, template.line
1364        );
1365
1366        // Empty state: built once, bound in view scope.
1367        let mut empty_update = String::new();
1368        let empty_fn = match empty {
1369            Some(e) => {
1370                let mut ectx = Ctx::new(Scope::Screen, "self.", "w", 0);
1371                let eel = self.element(&mut ectx, e, &[], None)?;
1372                let (eexpr, ids) = yui::static_widget(&eel, false, 1, self.mod_id)?;
1373                self.absorb(ids);
1374                empty_update = ectx.update;
1375                let _ = write!(
1376                    self.templates,
1377                    "#[doc(hidden)]\n#[allow(non_snake_case)]\nfn __E{t}() -> ::yog_api::ui::Widget {{\n    #[allow(unused_imports)]\n    {UI_USE}\n    {eexpr}\n}}\n\n"
1378                );
1379                format!("::std::option::Option::Some(__E{t})")
1380            }
1381            None => "::std::option::Option::None".to_string(),
1382        };
1383
1384        let ih = item_height.map_or("::std::option::Option::None".to_string(), |h| {
1385            format!("::std::option::Option::Some({h:?})")
1386        });
1387        let sc = scroller.map_or("::std::option::Option::None".to_string(), |s| {
1388            format!("::std::option::Option::Some({s})")
1389        });
1390        let _ = writeln!(
1391            self.parts,
1392            "        parts.list({owner}, {}, {sc}, {ih});",
1393            path_lit(path)
1394        );
1395        let field = format!("l{owner}");
1396        self.view_fields.push((
1397            field.clone(),
1398            format!("::yog_kit::items::ItemsHost<__T{t}>"),
1399            format!(
1400                "::yog_kit::items::ItemsHost::new({owner}, {}, {ih}, {sc}, {})",
1401                path_lit(path),
1402                selected.is_some()
1403            ),
1404        ));
1405
1406        // Update.
1407        let mut u = String::new();
1408        let _ = writeln!(
1409            u,
1410            "        // @yui {}:{} {source}=\"{}\"",
1411            self.file, el.line, items_b.raw
1412        );
1413        u.push_str("        {\n");
1414        let sel_expr = match &selected {
1415            Some(b) => {
1416                let e = b
1417                    .expr
1418                    .as_ref()
1419                    .expect("parsed")
1420                    .emit(Scope::Screen, false)?;
1421                let _ = writeln!(u, "            let __sel = {e};");
1422                format!("::yog_kit::bind::is_selected(&__sel, &({key}))")
1423            }
1424            None => "false".into(),
1425        };
1426        let _ = writeln!(u, "            let mut __it = self.{field}.begin(root, u);");
1427        let _ = writeln!(
1428            u,
1429            "            for (index, item) in ::std::iter::IntoIterator::into_iter({items}).enumerate() {{"
1430        );
1431        u.push_str("                let _ = (&index, &item);\n");
1432        if tctx.update.is_empty() {
1433            let _ = writeln!(
1434                u,
1435                "                let _ = __it.next(::yog_kit::bind::key(&({key})), {sel_expr}, __T{t}::build);"
1436            );
1437        } else {
1438            let _ = writeln!(
1439                u,
1440                "                let ::std::option::Option::Some(__row) = __it.next(::yog_kit::bind::key(&({key})), {sel_expr}, __T{t}::build) else {{ continue }};"
1441            );
1442            u.push_str("                let ::yog_kit::items::Item { inst, w, u } = __row;\n");
1443            for line in tctx.update.lines() {
1444                let _ = writeln!(u, "        {line}");
1445            }
1446        }
1447        u.push_str("            }\n");
1448        if empty_update.is_empty() {
1449            let _ = writeln!(u, "            __it.finish({empty_fn});");
1450        } else {
1451            let _ = writeln!(
1452                u,
1453                "            if let ::std::option::Option::Some((w, u)) = __it.finish({empty_fn}) {{"
1454            );
1455            for line in empty_update.lines() {
1456                let _ = writeln!(u, "        {line}");
1457            }
1458            u.push_str("            }\n");
1459        }
1460        u.push_str("        }\n");
1461        ctx.update.push_str(&u);
1462
1463        // Selection write-back.
1464        if let Some(b) = &selected {
1465            let write = match (&b.bind_back, b.mode, &b.expr) {
1466                (Some(m), _, _) => format!("vm.{m}(__k);"),
1467                (None, Mode::TwoWay, Some(e)) if e.is_place() => {
1468                    format!(
1469                        "{} = ::std::option::Option::Some(__k);",
1470                        e.emit(Scope::Screen, false)?
1471                    )
1472                }
1473                (None, Mode::TwoWay, _) => {
1474                    return err(el, "selected Mode=TwoWay needs a field or BindBack=method");
1475                }
1476                _ => String::new(),
1477            };
1478            if !write.is_empty() {
1479                self.dispatch.push((
1480                    format!(
1481                        "::yog_kit::ViewEvent::Action(::yog_api::ui::Action {{ owner: {owner}, slot: ::yog_kit::items::SELECT, index }})\n            | ::yog_kit::ViewEvent::Select {{ list: {owner}, index }}"
1482                    ),
1483                    format!(
1484                        "let __k = ::std::iter::IntoIterator::into_iter({items}).enumerate().nth(index as usize).map(|(index, item)| {{ let _ = (&index, &item); ::std::clone::Clone::clone(&({key})) }});\n                if let ::std::option::Option::Some(__k) = __k {{ {write} }}"
1485                    ),
1486                ));
1487            }
1488        }
1489        // A list's own bindings other than items/key/selected (bg, w, ...)
1490        // are applied by the caller.
1491        Ok(())
1492    }
1493
1494    fn absorb(&mut self, ids: Vec<String>) {
1495        for id in &ids {
1496            self.ids.push(id);
1497        }
1498    }
1499}
1500
1501/// Generates a view-model screen's `.g.rs` (see the module docs).
1502pub fn generate(
1503    root: &Element,
1504    name: &str,
1505    mod_id: Option<&str>,
1506) -> Result<(String, Vec<String>), String> {
1507    if root.name != "Screen" {
1508        return err(root, "a view-model screen's root must be <Screen>");
1509    }
1510    let id = root
1511        .attr("id")
1512        .filter(|s| !s.trim().is_empty())
1513        .ok_or_else(|| {
1514            format!(
1515                "line {}: <Screen> needs an id (the UI id, e.g. \"mymod:main\")",
1516                root.line
1517            )
1518        })?
1519        .to_string();
1520    let vm = root
1521        .attr("x:ViewModel")
1522        .unwrap_or_default()
1523        .trim()
1524        .to_string();
1525    if vm.is_empty() {
1526        return err(root, "x:ViewModel names the view-model type");
1527    }
1528    let create = root
1529        .attr("x:Create")
1530        .map(str::to_string)
1531        .unwrap_or_else(|| format!("<{vm} as ::std::default::Default>::default()"));
1532    let (width, height, anchor) = yui::screen_frame(root)?;
1533    let anchor = yui::pascal(anchor);
1534    let modal = root
1535        .attr("modal")
1536        .map(|v| yui::boolean(root, "modal", v))
1537        .transpose()?
1538        .unwrap_or(true);
1539    let pause = root
1540        .attr("pause")
1541        .map(|v| yui::boolean(root, "pause", v))
1542        .transpose()?
1543        .unwrap_or(false);
1544
1545    let mut g = VmGen {
1546        file: format!("{name}.yui"),
1547        mod_id,
1548        resources: HashMap::new(),
1549        styles: HashMap::new(),
1550        ids: yui::Names::default(),
1551        view_fields: Vec::new(),
1552        parts: String::new(),
1553        dispatch: Vec::new(),
1554        templates: String::new(),
1555        n_slots: 0,
1556        n_lists: 0,
1557        n_templates: 0,
1558        n_scrollers: 0,
1559        n_text_boxes: 0,
1560        cmd_slots: HashMap::new(),
1561    };
1562    for c in &root.children {
1563        if c.name == "Screen.Resources" {
1564            g.collect_resources(c)?;
1565        }
1566    }
1567    let mut content = root.clone();
1568    content.attrs.retain(|(k, _)| k != "id");
1569    let mut ctx = Ctx::new(Scope::Screen, "self.", "root", 0);
1570    let tree = g.element(&mut ctx, &content, &[], None)?;
1571    let (expr, ids) = yui::static_widget(&tree, false, 0, mod_id)?;
1572    g.absorb(ids);
1573
1574    let mut out = String::new();
1575    let _ = write!(
1576        out,
1577        r#"// <auto-generated>
1578//     Generated by yog from src/{name}.yui (view model {vm}, codegen {CODEGEN}) —
1579//     do not edit: changes are lost on the next `yog build` / `yog check` /
1580//     `yog ui gen`. Edit the .yui file instead.
1581// </auto-generated>
1582//
1583// Pulled into the code-behind module (which defines `{vm}`) with:
1584//
1585//     yog_api::ui_include!("{name}");
1586
1587const _: () = ::yog_kit::__codegen::require({CODEGEN});
1588
1589/// The UI id this screen registers under.
1590#[allow(dead_code)]
1591pub const ID: &str = {id:?};
1592/// Design-time size in GUI pixels.
1593#[allow(dead_code)]
1594pub const WIDTH: f32 = {width:?};
1595#[allow(dead_code)]
1596pub const HEIGHT: f32 = {height:?};
1597
1598/// Ids of this screen's named widgets.
1599#[allow(dead_code)]
1600pub mod ids {{
1601"#
1602    );
1603    out.push_str(&yui::str_consts(g.ids.as_slice()));
1604    out.push_str("}\n\n");
1605    out.push_str(&g.templates);
1606
1607    // View struct.
1608    out.push_str("/// The compiled view of this screen — hosted by `yog_kit::Screen`.\n/// Private like the view model it names; tests in the code-behind\n/// module drive it with `yog_kit::testing::TestHost<View>`.\nstruct View {\n");
1609    for (n, ty, _) in &g.view_fields {
1610        let _ = writeln!(out, "    {n}: {ty},");
1611    }
1612    out.push_str("}\n\n");
1613
1614    let _ = write!(
1615        out,
1616        r#"impl ::yog_kit::View for View {{
1617    type Vm = {vm};
1618    const META: ::yog_kit::ScreenMeta = ::yog_kit::ScreenMeta {{
1619        id: ID,
1620        w: WIDTH,
1621        h: HEIGHT,
1622        anchor: ::yog_kit::Anchor::{anchor},
1623        modal: {modal},
1624        pause: {pause},
1625    }};
1626
1627    fn build() -> (Self, ::yog_api::ui::Widget, ::yog_kit::Parts) {{
1628        #[allow(unused_imports)]
1629        {UI_USE}
1630        let root = {expr};
1631        #[allow(unused_mut)]
1632        let mut parts = ::yog_kit::Parts::new();
1633{parts}        let view = View {{
1634"#,
1635        parts = g.parts,
1636    );
1637    for (n, _, init) in &g.view_fields {
1638        let _ = writeln!(out, "            {n}: {init},");
1639    }
1640    let _ = write!(
1641        out,
1642        r#"        }};
1643        (view, root, parts)
1644    }}
1645
1646    #[allow(unused_variables)]
1647    fn update(&mut self, root: &mut ::yog_api::ui::Widget, vm: &{vm}, u: &mut ::yog_kit::Update) {{
1648{update}    }}
1649
1650    #[allow(unused_variables, clippy::let_unit_value, clippy::single_match, clippy::match_single_binding)]
1651    fn dispatch(&mut self, vm: &mut {vm}, cx: &mut ::yog_kit::Cx<'_, {vm}>, ev: ::yog_kit::ViewEvent) {{
1652        match ev {{
1653"#,
1654        update = ctx.update,
1655    );
1656    for (pat, body) in &g.dispatch {
1657        let _ = writeln!(
1658            out,
1659            "            {pat} => {{\n                {body}\n            }}"
1660        );
1661    }
1662    let _ = write!(
1663        out,
1664        r#"            _ => {{}}
1665        }}
1666    }}
1667}}
1668
1669static __HANDLE: ::std::sync::OnceLock<::yog_kit::ScreenHandle<{vm}>> = ::std::sync::OnceLock::new();
1670
1671/// Registers the screen (rendering + input) with a new view model
1672/// (`{create}`); returns its handle. Call once, from `Mod::register`.
1673#[allow(dead_code, private_interfaces)]
1674pub fn register(registry: &mut ::yog_api::Registry) -> ::yog_kit::ScreenHandle<{vm}> {{
1675    register_with(registry, {create})
1676}}
1677
1678/// [`register`] with a given view model.
1679#[allow(dead_code, private_interfaces)]
1680pub fn register_with(registry: &mut ::yog_api::Registry, vm: {vm}) -> ::yog_kit::ScreenHandle<{vm}> {{
1681    ::std::clone::Clone::clone(__HANDLE.get_or_init(|| ::yog_kit::Screen::<View>::register(registry, vm)))
1682}}
1683
1684/// The handle [`register`] returned (`None` before it).
1685#[allow(dead_code, private_interfaces)]
1686pub fn handle() -> ::std::option::Option<::yog_kit::ScreenHandle<{vm}>> {{
1687    __HANDLE.get().cloned()
1688}}
1689
1690/// Opens the screen (modal: {modal}, pauses the game: {pause}).
1691#[allow(dead_code)]
1692pub fn open() {{
1693    ::yog_api::open_ui(ID, {modal}, {pause});
1694}}
1695
1696/// Closes the screen if it's open.
1697#[allow(dead_code)]
1698pub fn close() {{
1699    ::yog_api::close_ui(ID);
1700}}
1701"#
1702    );
1703    Ok((out, Vec::new()))
1704}
1705
1706#[cfg(test)]
1707mod tests {
1708    use super::*;
1709
1710    fn codegen(body: &str) -> Result<String, String> {
1711        let src = format!(
1712            r#"<Screen id="t:s" width="200" height="100" x:ViewModel="Vm">{body}</Screen>"#
1713        );
1714        crate::yui::generate_for(&src, "s", None).map(|(c, _)| c)
1715    }
1716
1717    #[test]
1718    fn image_state_backgrounds() {
1719        let code = codegen(r#"<Button bg="sprite:button" hover:bg="sprite:button_hover" disabled:bg="sprite:button_disabled" command="{x:Bind go()}"/>"#).unwrap();
1720        assert!(code.contains(r#".bg_image("sprite:button")"#), "{code}");
1721        assert!(code.contains(r#"StateFlags::HOVER, ::yog_api::ui::StylePatch { bg_image: ::std::option::Option::Some(::std::string::String::from("sprite:button_hover"))"#), "{code}");
1722        assert!(code.contains(r#"bg_image: ::std::option::Option::Some(::std::string::String::from("sprite:button_disabled"))"#), "{code}");
1723    }
1724
1725    #[test]
1726    fn expressions() {
1727        let e = |s: &str, scope| parse_expr(s).unwrap().emit(scope, false).unwrap();
1728        assert_eq!(e("count", Scope::Screen), "vm.count");
1729        assert_eq!(e("count_text()", Scope::Screen), "vm.count_text()");
1730        assert_eq!(
1731            e("filter == Filter::All", Scope::Screen),
1732            "vm.filter == Filter::All"
1733        );
1734        assert_eq!(
1735            e("!has(Filter::Yog)", Scope::Screen),
1736            "!vm.has(Filter::Yog)"
1737        );
1738        assert_eq!(
1739            e("Strings::count(n, 'x')", Scope::Screen),
1740            "Strings::count(&vm.n, \"x\")"
1741        );
1742        assert_eq!(
1743            e("Strings::v(version)", Scope::Template),
1744            "Strings::v(&item.version)"
1745        );
1746        assert_eq!(e("selected()?.name", Scope::Screen), "vm.selected()?.name");
1747        assert_eq!(e("vm.x.len()", Scope::Template), "vm.x.len()");
1748        assert_eq!(e("item", Scope::Template), "item");
1749        assert_eq!(e("1.5", Scope::Screen), "1.5");
1750        assert!(parse_expr("a < b").is_err());
1751        assert!(
1752            parse_expr("cx.close()")
1753                .unwrap()
1754                .emit(Scope::Screen, false)
1755                .is_err()
1756        );
1757        assert!(
1758            parse_expr("index")
1759                .unwrap()
1760                .emit(Scope::Screen, false)
1761                .is_err()
1762        );
1763    }
1764
1765    #[test]
1766    fn yres_colors_everywhere() {
1767        let mut refs = crate::yres::Refs::default();
1768        refs.colors.insert("Colors.accent".into(), 0xFF11_2233);
1769        refs.colors.insert("Colors.hot".into(), 0xFF44_5566);
1770        refs.colors.insert("Colors.tint".into(), 0x8077_8899);
1771        crate::yui::set_resource_refs(&refs);
1772        let code = codegen(
1773            r##"
1774            <Screen.Resources>
1775                <Color x:Key="Accent" value="@Colors.accent"/>
1776                <Style x:Key="Btn" target="Button" bg="@Colors.accent" hover:bg="@Colors.hot"/>
1777            </Screen.Resources>
1778            <Column w="100%">
1779                <Label text="a" color="@Accent" selected:color="@Accent" disabled:bg="@Colors.hot"/>
1780                <Button style="@Btn" text="b"/>
1781                <Image source="item:air" tint="@Colors.tint"/>
1782            </Column>"##,
1783        );
1784        let missing = codegen(r#"<Label text="a" hover:bg="@Colors.nope"/>"#);
1785        crate::yui::set_resource_refs(&crate::yres::Refs::default());
1786        let code = code.unwrap();
1787        for want in [
1788            ".color(0xFF112233)",
1789            "StateFlags::SELECTED, ::yog_api::ui::StylePatch { color: ::std::option::Option::Some(0xFF112233)",
1790            "StateFlags::DISABLED, ::yog_api::ui::StylePatch { bg: ::std::option::Option::Some(0xFF445566)",
1791            ".bg(0xFF112233)",
1792            "StateFlags::HOVER, ::yog_api::ui::StylePatch { bg: ::std::option::Option::Some(0xFF445566)",
1793            ".tint(0x80778899)",
1794        ] {
1795            assert!(code.contains(want), "missing {want}:\n{code}");
1796        }
1797        assert!(missing.unwrap_err().contains("no color `Colors.nope`"));
1798    }
1799
1800    #[test]
1801    fn bindings_commands_and_parts() {
1802        let code = codegen(r##"
1803            <Screen.Resources>
1804                <Color x:Key="Accent" value="#FFD700"/>
1805                <Style x:Key="Btn" target="Button" w="40" h="14" bg="#FF333333" hover:bg="#FF444444"/>
1806                <Style x:Key="Toggle" based_on="@Btn" checked:bg="#FF555555"/>
1807            </Screen.Resources>
1808            <Column w="100%">
1809                <Label x:Name="count" text="{x:Bind count_text()}" color="@Accent"/>
1810                <Label text="@mymod.title"/>
1811                <Button style="@Btn" text="Close" command="{x:Bind cx.close()}"/>
1812                <ToggleButton style="@Toggle" text="Yog" checked="{x:Bind filter == Filter::Yog}"
1813                              enabled="{x:Bind has(Filter::Yog)}" command="{x:Bind set_filter(Filter::Yog)}"/>
1814                <TextBox w="100" h="14" text="{x:Bind search, Mode=TwoWay}" placeholder="@mymod.search"
1815                         command="{x:Bind submit()}"/>
1816                <ScrollView h="50" scroll_key="{x:Bind search}" visible="{x:Bind show}"/>
1817            </Column>"##)
1818        .unwrap();
1819        for want in [
1820            "const _: () = ::yog_kit::__codegen::require(1);",
1821            "type Vm = Vm;",
1822            ".color(0xFFFFD700)",
1823            r#".id("count")"#,
1824            "pub const COUNT: &str = \"count\";",
1825            "if self.b0.set(::yog_kit::bind::text(&(vm.count_text()))) { root.at_path_mut(&[0, 0]).set_text(",
1826            r#"::yog_kit::bind::text(&(::yog_api::tr("mymod.title")))"#,
1827            ".state_style(::yog_api::ui::StateFlags::HOVER, ::yog_api::ui::StylePatch { bg: ::std::option::Option::Some(0xFF444444), ..::std::default::Default::default() })",
1828            ".state_style(::yog_api::ui::StateFlags::CHECKED",
1829            ".action(::yog_api::ui::Action { owner: 0, slot: 0, index: 0 })",
1830            ".action(::yog_api::ui::Action { owner: 0, slot: 1, index: 0 })",
1831            "::yog_kit::bind::set_checked(root.at_path_mut(&[0, 3]), *self.",
1832            "::yog_kit::bind::flag(vm.filter == Filter::Yog)",
1833            "slot: 0, .. }) => {\n                cx.close();",
1834            "slot: 1, .. }) => {\n                vm.set_filter(Filter::Yog);",
1835            "parts.focusable(&[0, 2]);",
1836            "parts.text_box(&[0, 4]);",
1837            "parts.scroller(&[0, 5]);",
1838            "u.set_text_box(0, self.",
1839            "::yog_kit::ViewEvent::TextChanged { slot: 0, text } => {\n                vm.search = text;",
1840            "::yog_kit::ViewEvent::TextSubmitted { slot: 0, text } => {\n                let _ = text; vm.submit();",
1841            "u.reset_scroll(0);",
1842            ".visible = *self.",
1843            "::yog_kit::Screen::<View>::register(registry, vm)",
1844            "<Vm as ::std::default::Default>::default()",
1845        ] {
1846            assert!(code.contains(want), "missing {want}\n{code}");
1847        }
1848        assert!(
1849            !code.contains("text=") || code.contains("// @yui"),
1850            "{code}"
1851        );
1852    }
1853
1854    #[test]
1855    fn bound_sources() {
1856        let code = codegen(
1857            r##"
1858            <Column>
1859                <Surface w="10" h="10" source="{x:Bind grid_id()}"/>
1860                <Image w="10" h="10" source="{x:Bind icon}"/>
1861            </Column>"##,
1862        )
1863        .unwrap();
1864        for want in [
1865            r#"widget::surface("yog:none")"#,
1866            r#"widget::image("item:air")"#,
1867            "::yog_kit::bind::set_source(root.at_path_mut(&[0, 0]), ",
1868            "::yog_kit::bind::set_source(root.at_path_mut(&[0, 1]), ",
1869        ] {
1870            assert!(code.contains(want), "missing {want}\n{code}");
1871        }
1872    }
1873
1874    #[test]
1875    fn component_properties() {
1876        let code = codegen(r##"
1877            <Column>
1878                <StatBar id="hp" w="80" label="HP" value="{x:Bind hp}" fill="{x:Bind color()}" visible="{x:Bind alive}"/>
1879                <ListView h="40" items="{x:Bind rows}" key="{x:Bind id}">
1880                    <ListView.ItemTemplate>
1881                        <DataTemplate>
1882                            <Pill text="{x:Bind name}"/>
1883                        </DataTemplate>
1884                    </ListView.ItemTemplate>
1885                </ListView>
1886            </Column>"##)
1887        .unwrap();
1888        for want in [
1889            "__props |= self.b0.set(::yog_kit::bind::text(&(vm.hp)));",
1890            "__props |= self.b1.set(::yog_kit::bind::text(&(vm.color())));",
1891            r#"::yog_api::ui::component::build("StatBar", &[("label", "HP"), ("value", &**self.b0.get()), ("fill", &**self.b1.get())])"#,
1892            "u.relayout(); self.b2.reset();",
1893            r#"::yog_api::ui::component::build("Pill", &[("text", &**inst."#,
1894        ] {
1895            assert!(code.contains(want), "missing {want}\n{code}");
1896        }
1897        assert!(codegen(r#"<StatBar value="{x:Bind hp, Mode=TwoWay}"/>"#).is_err());
1898    }
1899
1900    #[test]
1901    fn lists() {
1902        let code = codegen(
1903            r##"
1904            <ListView w="100%" h="80" items="{x:Bind visible()}" key="{x:Bind id}"
1905                      selected="{x:Bind selected_id(), BindBack=select}" item_height="12">
1906                <ListView.ItemTemplate>
1907                    <DataTemplate x:DataType="Entry">
1908                        <Row w="100%" selected:bg="#FF333366">
1909                            <Label text="{x:Bind name}"/>
1910                            <Button text="x" command="{x:Bind vm.remove(id)}"/>
1911                        </Row>
1912                    </DataTemplate>
1913                </ListView.ItemTemplate>
1914                <ListView.Empty>
1915                    <Label text="{x:Bind empty_text()}"/>
1916                </ListView.Empty>
1917            </ListView>
1918            <ContentPresenter content="{x:Bind selected()}">
1919                <DataTemplate><Label text="{x:Bind Strings::v(version)}"/></DataTemplate>
1920            </ContentPresenter>"##,
1921        )
1922        .unwrap();
1923        for want in [
1924            "struct __T0 {",
1925            "fn __E0() -> ::yog_api::ui::Widget",
1926            "l1: ::yog_kit::items::ItemsHost<__T0>,",
1927            "::yog_kit::items::ItemsHost::new(1, &[0], ::std::option::Option::Some(12.0), ::std::option::Option::Some(0), true)",
1928            "parts.list(1, &[0], ::std::option::Option::Some(0), ::std::option::Option::Some(12.0));",
1929            "let __sel = vm.selected_id();",
1930            "for (index, item) in ::std::iter::IntoIterator::into_iter(vm.visible()).enumerate() {",
1931            "__it.next(::yog_kit::bind::key(&(item.id)), ::yog_kit::bind::is_selected(&__sel, &(item.id)), __T0::build)",
1932            "if inst.b0.set(::yog_kit::bind::text(&(item.name))) { w.at_path_mut(&[0]).set_text(",
1933            "if let ::std::option::Option::Some((w, u)) = __it.finish(::std::option::Option::Some(__E0)) {",
1934            "self.b0.set(::yog_kit::bind::text(&(vm.empty_text())))",
1935            ".action(::yog_api::ui::Action { owner: 1, slot: 0, index: 0 })",
1936            "::yog_kit::ViewEvent::Action(::yog_api::ui::Action { owner: 1, slot: 0, index }) => {",
1937            "::std::clone::Clone::clone(&(item.id))",
1938            "if let ::std::option::Option::Some((__a0,)) = __args { vm.remove(__a0); }",
1939            "| ::yog_kit::ViewEvent::Select { list: 1, index } => {",
1940            "vm.select(__k);",
1941            "::yog_kit::items::ItemsHost::new(2, &[1], ::std::option::Option::None, ::std::option::Option::None, false)",
1942            "into_iter(vm.selected()).enumerate()",
1943            "Strings::v(&item.version)",
1944            "__it.finish(::std::option::Option::None);",
1945        ] {
1946            assert!(code.contains(want), "missing {want}\n{code}");
1947        }
1948    }
1949
1950    #[test]
1951    fn errors() {
1952        let e = |b: &str| codegen(b).unwrap_err();
1953        assert!(e(r#"<Button on_click="x"/>"#).contains("command="),);
1954        assert!(e(r#"<Label w="{x:Bind a}" hover:w="3"/>"#).contains("paint attributes"));
1955        assert!(e(r#"<TextBox text="{x:Bind name(), Mode=TwoWay}"/>"#).contains("TwoWay"));
1956        assert!(e(r#"<Label text="{x:Bind a &lt; b}"/>"#).contains("unexpected"));
1957        assert!(e(r#"<Label color="@Nope"/>"#).contains("no resource"));
1958        assert!(e(r#"<ListView items="{x:Bind xs}"/>"#).contains("item template"));
1959        assert!(e(r#"<Label text="{x:Bind index}"/>"#).contains("item templates"));
1960    }
1961
1962    /// The yog-kit fixture's committed `.g.rs` matches the generator
1963    /// (`UPDATE_GOLDEN=1` rewrites it); yog-kit compiles and runs it.
1964    #[test]
1965    fn kit_fixture() {
1966        let dir =
1967            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../yog-kit/tests/fixtures");
1968        for name in ["list", "grid"] {
1969            let src = std::fs::read_to_string(dir.join(format!("{name}.yui"))).unwrap();
1970            let (code, warnings) = crate::yui::generate_for(&src, name, None).unwrap();
1971            assert!(warnings.is_empty(), "{warnings:?}");
1972            let out = dir.join(format!("{name}.g.rs"));
1973            if std::env::var_os("UPDATE_GOLDEN").is_some() {
1974                std::fs::write(&out, &code).unwrap();
1975            }
1976            let want = std::fs::read_to_string(&out).unwrap_or_default();
1977            assert!(
1978                want == code,
1979                "{} is stale; rerun with UPDATE_GOLDEN=1",
1980                out.display()
1981            );
1982        }
1983    }
1984
1985    #[test]
1986    fn legacy_screens_unchanged() {
1987        let src = r#"<Screen id="t:s"><Label text="@t.k" on_click="go"/></Screen>"#;
1988        let (code, _) = crate::yui::generate_for(src, "s", None).unwrap();
1989        assert!(code.contains("pub fn render(gfx"), "{code}");
1990        assert!(!code.contains("yog_kit"), "{code}");
1991    }
1992}