1use std::collections::HashMap;
9use std::fmt::Write as _;
10
11use crate::yui::{self, Element, RAW_CALL, RAW_VALUE, UI_USE, err};
12
13const 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#[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#[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 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#[derive(Debug, Clone)]
373struct Binding {
374 raw: String,
376 expr: Option<Ex>,
377 rust: Option<String>,
379 mode: Mode,
380 bind_back: Option<String>,
381 fallback: Option<String>,
382}
383
384impl Binding {
385 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
397fn 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
460pub(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#[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
518struct Ctx {
520 scope: Scope,
521 fields: &'static str,
523 tree: &'static str,
525 owner: u16,
527 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: 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 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 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 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 #[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 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 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 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" | "color" | "focus_color" => {
926 let c = yui::color_attr(el, k, v)?;
927 format!("{attr}: ::std::option::Option::Some(0x{c:08X})")
928 }
929 "shadow" => format!(
930 "shadow: ::std::option::Option::Some({})",
931 yui::boolean(el, k, v)?
932 ),
933 _ => {
934 return err(
935 el,
936 format!(
937 "{k}: only paint attributes (bg, color, shadow, focus_color) take a state prefix"
938 ),
939 );
940 }
941 };
942 match patches.iter_mut().find(|(f, _)| f == flag) {
943 Some((_, fs)) => fs.push(field),
944 None => patches.push((flag, vec![field])),
945 }
946 continue;
947 }
948 if let Some(b) = parse_binding(v) {
949 let b = b.map_err(|e| format!("line {}: {e}", el.line))?;
950 if k == "command" {
951 command = Some(b);
952 } else if matches!(k, "items" | "content" | "key" | "selected") {
953 if !is_list {
954 return err(
955 el,
956 format!("{k} is for ListView, ItemsControl and ContentPresenter"),
957 );
958 }
959 bindings.push((k.to_string(), b));
960 } else {
961 bindings.push((k.to_string(), b));
962 }
963 continue;
964 }
965 match k {
966 "command" => return err(el, "command needs {x:Bind method(...)}"),
967 "items" | "content" | "key" | "selected" => {
968 return err(el, format!("{k} needs a binding: {k}=\"{{x:Bind ...}}\""));
969 }
970 "item_height" | "orientation" if is_list => {
971 list_attrs.insert(k.into(), v.clone());
972 }
973 "visible" => {
974 let b = yui::boolean(el, k, v)?;
975 push_raw(&mut out, format!("visible({b})"));
976 }
977 "checked" if kind == "Button" => {
978 let b = yui::boolean(el, k, v)?;
979 bindings.push((
980 k.into(),
981 Binding {
982 raw: v.clone(),
983 expr: Some(Ex::Post(Head::Lit(b.to_string()), Vec::new())),
984 rust: None,
985 mode: Mode::OneWay,
986 bind_back: None,
987 fallback: None,
988 },
989 ));
990 }
991 "text" | "placeholder"
992 if v.starts_with('@') && !v.starts_with("@@") && v.len() > 1 =>
993 {
994 bindings.push((
996 k.into(),
997 Binding {
998 raw: v.clone(),
999 expr: None,
1000 rust: Some(yui::text_expr(v)),
1001 mode: Mode::OneWay,
1002 bind_back: None,
1003 fallback: None,
1004 },
1005 ));
1006 }
1007 _ => out.attrs.push((k.to_string(), v.clone())),
1008 }
1009 }
1010 for (flag, fields) in patches {
1011 push_raw(
1012 &mut out,
1013 format!(
1014 "state_style(::yog_api::ui::StateFlags::{flag}, ::yog_api::ui::StylePatch {{ {}, ..::std::default::Default::default() }})",
1015 fields.join(", ")
1016 ),
1017 );
1018 }
1019 if let Some(id) = out.attr("id") {
1020 self.ids.push(id);
1021 }
1022
1023 let text_box = if kind == "TextBox" && screen {
1025 let n = self.n_text_boxes;
1026 self.n_text_boxes += 1;
1027 let _ = writeln!(self.parts, " parts.text_box({});", path_lit(path));
1028 Some(n)
1029 } else {
1030 None
1031 };
1032 let scroller = if kind == "ScrollView" {
1033 if !screen {
1034 return err(el, "scroll views inside item templates aren't supported");
1035 }
1036 let n = self.n_scrollers;
1037 self.n_scrollers += 1;
1038 let _ = writeln!(self.parts, " parts.scroller({});", path_lit(path));
1039 Some(n)
1040 } else {
1041 None
1042 };
1043
1044 let toggle_place = bindings
1046 .iter()
1047 .find(|(k, b)| k == "checked" && b.mode == Mode::TwoWay)
1048 .map(|(_, b)| b.clone());
1049 if kind == "TextBox" {
1050 let tb = text_box.ok_or_else(|| {
1051 format!(
1052 "line {}: text boxes in item templates aren't supported",
1053 el.line
1054 )
1055 })?;
1056 if let Some((_, b)) = bindings.iter().find(|(k, _)| k == "text") {
1057 let write = match (&b.bind_back, b.mode, &b.expr) {
1058 (Some(m), _, _) => Some(format!("vm.{m}(text);")),
1059 (None, Mode::TwoWay, Some(e)) if e.is_place() => {
1060 Some(format!("{} = text;", e.emit(Scope::Screen, false)?))
1061 }
1062 (None, Mode::TwoWay, _) => {
1063 return err(
1064 el,
1065 "Mode=TwoWay needs a field (text=\"{x:Bind search, Mode=TwoWay}\") or BindBack=method",
1066 );
1067 }
1068 _ => None,
1069 };
1070 if let Some(write) = write {
1071 self.dispatch.push((
1072 format!("::yog_kit::ViewEvent::TextChanged {{ slot: {tb}, text }}"),
1073 write,
1074 ));
1075 }
1076 }
1077 if let Some(c) = &command {
1078 let stmt = self.command(el, c, Scope::Screen, None)?;
1079 self.dispatch.push((
1080 format!("::yog_kit::ViewEvent::TextSubmitted {{ slot: {tb}, text }}"),
1081 format!("let _ = text; {stmt}"),
1082 ));
1083 }
1084 } else if command.is_some() || toggle_place.is_some() {
1085 let owner = ctx.owner;
1086 let slot = self.next_cmd(owner);
1087 push_raw(
1088 &mut out,
1089 format!(
1090 "action(::yog_api::ui::Action {{ owner: {owner}, slot: {slot}, index: 0 }})"
1091 ),
1092 );
1093 let mut body = String::new();
1094 if let Some(t) = &toggle_place {
1095 if ctx.scope == Scope::Template {
1096 return err(
1097 el,
1098 "Mode=TwoWay toggles in item templates aren't supported — use a command",
1099 );
1100 }
1101 match (&t.bind_back, &t.expr) {
1102 (Some(m), Some(e)) => {
1103 let cur = e.emit(Scope::Screen, false)?;
1104 let _ = write!(body, "let __v = !{cur}; vm.{m}(__v); ");
1105 }
1106 (None, Some(e)) if e.is_place() => {
1107 let p = e.emit(Scope::Screen, false)?;
1108 let _ = write!(body, "{p} = !{p}; ");
1109 }
1110 _ => {
1111 return err(
1112 el,
1113 "checked Mode=TwoWay needs a bool field or BindBack=method",
1114 );
1115 }
1116 }
1117 }
1118 if let Some(c) = &command {
1119 body.push_str(&self.command(el, c, ctx.scope, items)?);
1120 }
1121 let pat = if owner == 0 {
1122 format!(
1123 "::yog_kit::ViewEvent::Action(::yog_api::ui::Action {{ owner: 0, slot: {slot}, .. }})"
1124 )
1125 } else {
1126 format!(
1127 "::yog_kit::ViewEvent::Action(::yog_api::ui::Action {{ owner: {owner}, slot: {slot}, index }})"
1128 )
1129 };
1130 self.dispatch.push((pat, body.trim_end().to_string()));
1131 if screen {
1132 let _ = writeln!(self.parts, " parts.focusable({});", path_lit(path));
1133 }
1134 }
1135
1136 if is_list {
1138 if !screen {
1139 return err(el, "lists inside item templates aren't supported");
1140 }
1141 self.list(ctx, el, &mut bindings, &list_attrs, path, scroller)?;
1142 }
1143
1144 let rebuild = if yui::is_custom_component(kind)
1147 && bindings.iter().any(|(k, _)| !yui::is_common_attr(k))
1148 {
1149 Some(self.component_props(ctx, el, &out, &mut bindings, path)?)
1150 } else {
1151 None
1152 };
1153 let slots_before = self.n_slots;
1154 if bindings.iter().any(|(k, _)| k == "source") {
1155 match kind {
1157 "Image" => out.attrs.push(("source".into(), "item:air".into())),
1158 "Surface" => out.attrs.push(("source".into(), "yog:none".into())),
1159 _ => {}
1160 }
1161 }
1162 for (k, b) in &bindings {
1163 if matches!(k.as_str(), "items" | "content" | "key" | "selected") {
1164 continue;
1165 }
1166 self.bind_attr(ctx, el, kind, k, b, path, text_box, scroller)?;
1167 }
1168 if let Some(marker) = rebuild {
1169 let resets: String = (slots_before..self.n_slots)
1170 .map(|i| format!(" {}b{i}.reset();", ctx.fields))
1171 .collect();
1172 ctx.update = ctx.update.replace(&marker, &resets);
1173 }
1174
1175 if !is_list {
1176 let mut i = 0u16;
1177 for child in &el.children {
1178 if child.name.contains('.') {
1179 if child.name == "Screen.Resources" && path.is_empty() {
1180 continue;
1181 }
1182 return err(child, "isn't allowed here");
1183 }
1184 let mut p = path.to_vec();
1185 p.push(i);
1186 out.children.push(self.element(ctx, child, &p, items)?);
1187 i += 1;
1188 }
1189 }
1190 Ok(out)
1191 }
1192
1193 fn component_props(
1199 &mut self,
1200 ctx: &mut Ctx,
1201 el: &Element,
1202 out: &Element,
1203 bindings: &mut Vec<(String, Binding)>,
1204 path: &[u16],
1205 ) -> Result<String, String> {
1206 let mut inst = out.clone();
1207 let mut sets = String::new();
1208 let mut i = 0;
1209 while i < bindings.len() {
1210 if yui::is_common_attr(&bindings[i].0) {
1211 i += 1;
1212 continue;
1213 }
1214 let (key, b) = bindings.remove(i);
1215 if b.mode == Mode::TwoWay || b.bind_back.is_some() {
1216 return err(el, format!("{key}: component properties bind one way"));
1217 }
1218 let expr = b.rust(ctx.scope, el)?;
1219 let value = if b.expr.as_ref().is_some_and(Ex::has_opt) {
1220 let fallback = b.fallback.clone().unwrap_or_default();
1221 format!(
1222 "(|| ::std::option::Option::Some(::yog_kit::bind::text(&({expr}))))().unwrap_or_else(|| ::std::string::String::from({fallback:?}))"
1223 )
1224 } else {
1225 format!("::yog_kit::bind::text(&({expr}))")
1226 };
1227 let slot = self.slot(ctx, "String");
1228 let f = format!("{}{slot}", ctx.fields);
1229 let _ = write!(
1230 sets,
1231 " // @yui {}:{} {key}=\"{}\"\n __props |= {f}.set({value});\n",
1232 self.file,
1233 el.line,
1234 b.raw.replace('\n', " ")
1235 );
1236 inst.attrs.push((key, format!("{RAW_VALUE}*{f}.get()")));
1237 }
1238 let (expr, _) = yui::static_widget(&inst, false, 2, self.mod_id)?;
1239 let marker = format!("\u{1}resets{}\u{1}", self.n_slots);
1240 let _ = write!(
1241 ctx.update,
1242 " 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",
1243 ctx.tree,
1244 path_lit(path),
1245 );
1246 Ok(marker)
1247 }
1248
1249 fn only_child(el: &Element) -> Result<&Element, String> {
1251 let mut c = el;
1252 if c.children.len() == 1 && c.children[0].name == "DataTemplate" {
1253 c = &c.children[0];
1254 }
1255 match c.children.as_slice() {
1256 [one] => Ok(one),
1257 _ => err(el, "needs exactly one child element"),
1258 }
1259 }
1260
1261 fn list(
1262 &mut self,
1263 ctx: &mut Ctx,
1264 el: &Element,
1265 bindings: &mut [(String, Binding)],
1266 attrs: &HashMap<String, String>,
1267 path: &[u16],
1268 scroller: Option<u16>,
1269 ) -> Result<(), String> {
1270 let name = el.name.as_str();
1271 let owner = {
1272 self.n_lists += 1;
1273 self.n_lists
1274 };
1275 let get = |k: &str| {
1276 bindings
1277 .iter()
1278 .find(|(bk, _)| bk == k)
1279 .map(|(_, b)| b.clone())
1280 };
1281 let source = if name == "ContentPresenter" {
1282 "content"
1283 } else {
1284 "items"
1285 };
1286 let Some(items_b) = get(source) else {
1287 return err(el, format!("needs {source}=\"{{x:Bind ...}}\""));
1288 };
1289 let items_ex = items_b.expr.clone().expect("parsed");
1290 let mut items = items_ex
1291 .emit(Scope::Screen, false)
1292 .map_err(|e| format!("line {}: {e}", el.line))?;
1293 if items_ex.is_place() {
1294 items = format!("&{items}");
1295 }
1296 let key = match get("key") {
1297 Some(b) => b
1298 .expr
1299 .expect("parsed")
1300 .emit(Scope::Template, false)
1301 .map_err(|e| format!("line {}: {e}", el.line))?,
1302 None => "index".to_string(),
1303 };
1304 let selected = get("selected");
1305 if selected.is_some() && name != "ListView" {
1306 return err(el, "selected is for ListView");
1307 }
1308 let item_height = match attrs.get("item_height") {
1309 Some(v) => Some(yui::number(el, "item_height", v)?),
1310 None => None,
1311 };
1312
1313 let mut template = None;
1315 let mut empty = None;
1316 for c in &el.children {
1317 match c.name.strip_prefix(name).and_then(|n| n.strip_prefix('.')) {
1318 Some("ItemTemplate" | "ContentTemplate") => template = Some(Self::only_child(c)?),
1319 Some("Empty") => empty = Some(Self::only_child(c)?),
1320 _ if c.name == "DataTemplate" => template = Some(Self::only_child(c)?),
1321 _ => {
1322 return err(
1323 c,
1324 format!(
1325 "isn't allowed in <{name}> (expected <{name}.ItemTemplate> or <{name}.Empty>)"
1326 ),
1327 );
1328 }
1329 }
1330 }
1331 let Some(template) = template else {
1332 return err(
1333 el,
1334 format!("needs an item template (<{name}.ItemTemplate><DataTemplate>...)"),
1335 );
1336 };
1337
1338 let t = self.n_templates;
1339 self.n_templates += 1;
1340 let mut tctx = Ctx::new(Scope::Template, "inst.", "w", owner);
1341 let saved = std::mem::take(&mut self.n_slots);
1342 let tel = self.element(&mut tctx, template, &[], Some(&items))?;
1343 self.n_slots = saved;
1344 let (texpr, ids) = yui::static_widget(&tel, false, 1, self.mod_id)?;
1345 self.absorb(ids);
1346 let fields: String = tctx
1347 .slots
1348 .iter()
1349 .map(|(n, ty)| format!(" {n}: ::yog_kit::bind::Slot<{ty}>,\n"))
1350 .collect();
1351 let inits: String = tctx
1352 .slots
1353 .iter()
1354 .map(|(n, _)| format!("{n}: ::yog_kit::bind::Slot::new(), "))
1355 .collect();
1356 let _ = write!(
1357 self.templates,
1358 "/// 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",
1359 self.file, template.line
1360 );
1361
1362 let mut empty_update = String::new();
1364 let empty_fn = match empty {
1365 Some(e) => {
1366 let mut ectx = Ctx::new(Scope::Screen, "self.", "w", 0);
1367 let eel = self.element(&mut ectx, e, &[], None)?;
1368 let (eexpr, ids) = yui::static_widget(&eel, false, 1, self.mod_id)?;
1369 self.absorb(ids);
1370 empty_update = ectx.update;
1371 let _ = write!(
1372 self.templates,
1373 "#[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"
1374 );
1375 format!("::std::option::Option::Some(__E{t})")
1376 }
1377 None => "::std::option::Option::None".to_string(),
1378 };
1379
1380 let ih = item_height.map_or("::std::option::Option::None".to_string(), |h| {
1381 format!("::std::option::Option::Some({h:?})")
1382 });
1383 let sc = scroller.map_or("::std::option::Option::None".to_string(), |s| {
1384 format!("::std::option::Option::Some({s})")
1385 });
1386 let _ = writeln!(
1387 self.parts,
1388 " parts.list({owner}, {}, {sc}, {ih});",
1389 path_lit(path)
1390 );
1391 let field = format!("l{owner}");
1392 self.view_fields.push((
1393 field.clone(),
1394 format!("::yog_kit::items::ItemsHost<__T{t}>"),
1395 format!(
1396 "::yog_kit::items::ItemsHost::new({owner}, {}, {ih}, {sc}, {})",
1397 path_lit(path),
1398 selected.is_some()
1399 ),
1400 ));
1401
1402 let mut u = String::new();
1404 let _ = writeln!(
1405 u,
1406 " // @yui {}:{} {source}=\"{}\"",
1407 self.file, el.line, items_b.raw
1408 );
1409 u.push_str(" {\n");
1410 let sel_expr = match &selected {
1411 Some(b) => {
1412 let e = b
1413 .expr
1414 .as_ref()
1415 .expect("parsed")
1416 .emit(Scope::Screen, false)?;
1417 let _ = writeln!(u, " let __sel = {e};");
1418 format!("::yog_kit::bind::is_selected(&__sel, &({key}))")
1419 }
1420 None => "false".into(),
1421 };
1422 let _ = writeln!(u, " let mut __it = self.{field}.begin(root, u);");
1423 let _ = writeln!(
1424 u,
1425 " for (index, item) in ::std::iter::IntoIterator::into_iter({items}).enumerate() {{"
1426 );
1427 u.push_str(" let _ = (&index, &item);\n");
1428 if tctx.update.is_empty() {
1429 let _ = writeln!(
1430 u,
1431 " let _ = __it.next(::yog_kit::bind::key(&({key})), {sel_expr}, __T{t}::build);"
1432 );
1433 } else {
1434 let _ = writeln!(
1435 u,
1436 " let ::std::option::Option::Some(__row) = __it.next(::yog_kit::bind::key(&({key})), {sel_expr}, __T{t}::build) else {{ continue }};"
1437 );
1438 u.push_str(" let ::yog_kit::items::Item { inst, w, u } = __row;\n");
1439 for line in tctx.update.lines() {
1440 let _ = writeln!(u, " {line}");
1441 }
1442 }
1443 u.push_str(" }\n");
1444 if empty_update.is_empty() {
1445 let _ = writeln!(u, " __it.finish({empty_fn});");
1446 } else {
1447 let _ = writeln!(
1448 u,
1449 " if let ::std::option::Option::Some((w, u)) = __it.finish({empty_fn}) {{"
1450 );
1451 for line in empty_update.lines() {
1452 let _ = writeln!(u, " {line}");
1453 }
1454 u.push_str(" }\n");
1455 }
1456 u.push_str(" }\n");
1457 ctx.update.push_str(&u);
1458
1459 if let Some(b) = &selected {
1461 let write = match (&b.bind_back, b.mode, &b.expr) {
1462 (Some(m), _, _) => format!("vm.{m}(__k);"),
1463 (None, Mode::TwoWay, Some(e)) if e.is_place() => {
1464 format!(
1465 "{} = ::std::option::Option::Some(__k);",
1466 e.emit(Scope::Screen, false)?
1467 )
1468 }
1469 (None, Mode::TwoWay, _) => {
1470 return err(el, "selected Mode=TwoWay needs a field or BindBack=method");
1471 }
1472 _ => String::new(),
1473 };
1474 if !write.is_empty() {
1475 self.dispatch.push((
1476 format!(
1477 "::yog_kit::ViewEvent::Action(::yog_api::ui::Action {{ owner: {owner}, slot: ::yog_kit::items::SELECT, index }})\n | ::yog_kit::ViewEvent::Select {{ list: {owner}, index }}"
1478 ),
1479 format!(
1480 "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} }}"
1481 ),
1482 ));
1483 }
1484 }
1485 Ok(())
1488 }
1489
1490 fn absorb(&mut self, ids: Vec<String>) {
1491 for id in &ids {
1492 self.ids.push(id);
1493 }
1494 }
1495}
1496
1497pub fn generate(
1499 root: &Element,
1500 name: &str,
1501 mod_id: Option<&str>,
1502) -> Result<(String, Vec<String>), String> {
1503 if root.name != "Screen" {
1504 return err(root, "a view-model screen's root must be <Screen>");
1505 }
1506 let id = root
1507 .attr("id")
1508 .filter(|s| !s.trim().is_empty())
1509 .ok_or_else(|| {
1510 format!(
1511 "line {}: <Screen> needs an id (the UI id, e.g. \"mymod:main\")",
1512 root.line
1513 )
1514 })?
1515 .to_string();
1516 let vm = root
1517 .attr("x:ViewModel")
1518 .unwrap_or_default()
1519 .trim()
1520 .to_string();
1521 if vm.is_empty() {
1522 return err(root, "x:ViewModel names the view-model type");
1523 }
1524 let create = root
1525 .attr("x:Create")
1526 .map(str::to_string)
1527 .unwrap_or_else(|| format!("<{vm} as ::std::default::Default>::default()"));
1528 let (width, height, anchor) = yui::screen_frame(root)?;
1529 let anchor = yui::pascal(anchor);
1530 let modal = root
1531 .attr("modal")
1532 .map(|v| yui::boolean(root, "modal", v))
1533 .transpose()?
1534 .unwrap_or(true);
1535 let pause = root
1536 .attr("pause")
1537 .map(|v| yui::boolean(root, "pause", v))
1538 .transpose()?
1539 .unwrap_or(false);
1540
1541 let mut g = VmGen {
1542 file: format!("{name}.yui"),
1543 mod_id,
1544 resources: HashMap::new(),
1545 styles: HashMap::new(),
1546 ids: yui::Names::default(),
1547 view_fields: Vec::new(),
1548 parts: String::new(),
1549 dispatch: Vec::new(),
1550 templates: String::new(),
1551 n_slots: 0,
1552 n_lists: 0,
1553 n_templates: 0,
1554 n_scrollers: 0,
1555 n_text_boxes: 0,
1556 cmd_slots: HashMap::new(),
1557 };
1558 for c in &root.children {
1559 if c.name == "Screen.Resources" {
1560 g.collect_resources(c)?;
1561 }
1562 }
1563 let mut content = root.clone();
1564 content.attrs.retain(|(k, _)| k != "id");
1565 let mut ctx = Ctx::new(Scope::Screen, "self.", "root", 0);
1566 let tree = g.element(&mut ctx, &content, &[], None)?;
1567 let (expr, ids) = yui::static_widget(&tree, false, 0, mod_id)?;
1568 g.absorb(ids);
1569
1570 let mut out = String::new();
1571 let _ = write!(
1572 out,
1573 r#"// <auto-generated>
1574// Generated by yog from src/{name}.yui (view model {vm}, codegen {CODEGEN}) —
1575// do not edit: changes are lost on the next `yog build` / `yog check` /
1576// `yog ui gen`. Edit the .yui file instead.
1577// </auto-generated>
1578//
1579// Pulled into the code-behind module (which defines `{vm}`) with:
1580//
1581// yog_api::ui_include!("{name}");
1582
1583const _: () = ::yog_kit::__codegen::require({CODEGEN});
1584
1585/// The UI id this screen registers under.
1586#[allow(dead_code)]
1587pub const ID: &str = {id:?};
1588/// Design-time size in GUI pixels.
1589#[allow(dead_code)]
1590pub const WIDTH: f32 = {width:?};
1591#[allow(dead_code)]
1592pub const HEIGHT: f32 = {height:?};
1593
1594/// Ids of this screen's named widgets.
1595#[allow(dead_code)]
1596pub mod ids {{
1597"#
1598 );
1599 out.push_str(&yui::str_consts(g.ids.as_slice()));
1600 out.push_str("}\n\n");
1601 out.push_str(&g.templates);
1602
1603 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");
1605 for (n, ty, _) in &g.view_fields {
1606 let _ = writeln!(out, " {n}: {ty},");
1607 }
1608 out.push_str("}\n\n");
1609
1610 let _ = write!(
1611 out,
1612 r#"impl ::yog_kit::View for View {{
1613 type Vm = {vm};
1614 const META: ::yog_kit::ScreenMeta = ::yog_kit::ScreenMeta {{
1615 id: ID,
1616 w: WIDTH,
1617 h: HEIGHT,
1618 anchor: ::yog_kit::Anchor::{anchor},
1619 modal: {modal},
1620 pause: {pause},
1621 }};
1622
1623 fn build() -> (Self, ::yog_api::ui::Widget, ::yog_kit::Parts) {{
1624 #[allow(unused_imports)]
1625 {UI_USE}
1626 let root = {expr};
1627 #[allow(unused_mut)]
1628 let mut parts = ::yog_kit::Parts::new();
1629{parts} let view = View {{
1630"#,
1631 parts = g.parts,
1632 );
1633 for (n, _, init) in &g.view_fields {
1634 let _ = writeln!(out, " {n}: {init},");
1635 }
1636 let _ = write!(
1637 out,
1638 r#" }};
1639 (view, root, parts)
1640 }}
1641
1642 #[allow(unused_variables)]
1643 fn update(&mut self, root: &mut ::yog_api::ui::Widget, vm: &{vm}, u: &mut ::yog_kit::Update) {{
1644{update} }}
1645
1646 #[allow(unused_variables, clippy::let_unit_value, clippy::single_match, clippy::match_single_binding)]
1647 fn dispatch(&mut self, vm: &mut {vm}, cx: &mut ::yog_kit::Cx<'_, {vm}>, ev: ::yog_kit::ViewEvent) {{
1648 match ev {{
1649"#,
1650 update = ctx.update,
1651 );
1652 for (pat, body) in &g.dispatch {
1653 let _ = writeln!(
1654 out,
1655 " {pat} => {{\n {body}\n }}"
1656 );
1657 }
1658 let _ = write!(
1659 out,
1660 r#" _ => {{}}
1661 }}
1662 }}
1663}}
1664
1665static __HANDLE: ::std::sync::OnceLock<::yog_kit::ScreenHandle<{vm}>> = ::std::sync::OnceLock::new();
1666
1667/// Registers the screen (rendering + input) with a new view model
1668/// (`{create}`); returns its handle. Call once, from `Mod::register`.
1669#[allow(dead_code, private_interfaces)]
1670pub fn register(registry: &mut ::yog_api::Registry) -> ::yog_kit::ScreenHandle<{vm}> {{
1671 register_with(registry, {create})
1672}}
1673
1674/// [`register`] with a given view model.
1675#[allow(dead_code, private_interfaces)]
1676pub fn register_with(registry: &mut ::yog_api::Registry, vm: {vm}) -> ::yog_kit::ScreenHandle<{vm}> {{
1677 ::std::clone::Clone::clone(__HANDLE.get_or_init(|| ::yog_kit::Screen::<View>::register(registry, vm)))
1678}}
1679
1680/// The handle [`register`] returned (`None` before it).
1681#[allow(dead_code, private_interfaces)]
1682pub fn handle() -> ::std::option::Option<::yog_kit::ScreenHandle<{vm}>> {{
1683 __HANDLE.get().cloned()
1684}}
1685
1686/// Opens the screen (modal: {modal}, pauses the game: {pause}).
1687#[allow(dead_code)]
1688pub fn open() {{
1689 ::yog_api::open_ui(ID, {modal}, {pause});
1690}}
1691
1692/// Closes the screen if it's open.
1693#[allow(dead_code)]
1694pub fn close() {{
1695 ::yog_api::close_ui(ID);
1696}}
1697"#
1698 );
1699 Ok((out, Vec::new()))
1700}
1701
1702#[cfg(test)]
1703mod tests {
1704 use super::*;
1705
1706 fn codegen(body: &str) -> Result<String, String> {
1707 let src = format!(
1708 r#"<Screen id="t:s" width="200" height="100" x:ViewModel="Vm">{body}</Screen>"#
1709 );
1710 crate::yui::generate_for(&src, "s", None).map(|(c, _)| c)
1711 }
1712
1713 #[test]
1714 fn expressions() {
1715 let e = |s: &str, scope| parse_expr(s).unwrap().emit(scope, false).unwrap();
1716 assert_eq!(e("count", Scope::Screen), "vm.count");
1717 assert_eq!(e("count_text()", Scope::Screen), "vm.count_text()");
1718 assert_eq!(
1719 e("filter == Filter::All", Scope::Screen),
1720 "vm.filter == Filter::All"
1721 );
1722 assert_eq!(
1723 e("!has(Filter::Yog)", Scope::Screen),
1724 "!vm.has(Filter::Yog)"
1725 );
1726 assert_eq!(
1727 e("Strings::count(n, 'x')", Scope::Screen),
1728 "Strings::count(&vm.n, \"x\")"
1729 );
1730 assert_eq!(
1731 e("Strings::v(version)", Scope::Template),
1732 "Strings::v(&item.version)"
1733 );
1734 assert_eq!(e("selected()?.name", Scope::Screen), "vm.selected()?.name");
1735 assert_eq!(e("vm.x.len()", Scope::Template), "vm.x.len()");
1736 assert_eq!(e("item", Scope::Template), "item");
1737 assert_eq!(e("1.5", Scope::Screen), "1.5");
1738 assert!(parse_expr("a < b").is_err());
1739 assert!(
1740 parse_expr("cx.close()")
1741 .unwrap()
1742 .emit(Scope::Screen, false)
1743 .is_err()
1744 );
1745 assert!(
1746 parse_expr("index")
1747 .unwrap()
1748 .emit(Scope::Screen, false)
1749 .is_err()
1750 );
1751 }
1752
1753 #[test]
1754 fn yres_colors_everywhere() {
1755 let mut refs = crate::yres::Refs::default();
1756 refs.colors.insert("Colors.accent".into(), 0xFF11_2233);
1757 refs.colors.insert("Colors.hot".into(), 0xFF44_5566);
1758 refs.colors.insert("Colors.tint".into(), 0x8077_8899);
1759 crate::yui::set_resource_refs(&refs);
1760 let code = codegen(
1761 r##"
1762 <Screen.Resources>
1763 <Color x:Key="Accent" value="@Colors.accent"/>
1764 <Style x:Key="Btn" target="Button" bg="@Colors.accent" hover:bg="@Colors.hot"/>
1765 </Screen.Resources>
1766 <Column w="100%">
1767 <Label text="a" color="@Accent" selected:color="@Accent" disabled:bg="@Colors.hot"/>
1768 <Button style="@Btn" text="b"/>
1769 <Image source="item:air" tint="@Colors.tint"/>
1770 </Column>"##,
1771 );
1772 let missing = codegen(r#"<Label text="a" hover:bg="@Colors.nope"/>"#);
1773 crate::yui::set_resource_refs(&crate::yres::Refs::default());
1774 let code = code.unwrap();
1775 for want in [
1776 ".color(0xFF112233)",
1777 "StateFlags::SELECTED, ::yog_api::ui::StylePatch { color: ::std::option::Option::Some(0xFF112233)",
1778 "StateFlags::DISABLED, ::yog_api::ui::StylePatch { bg: ::std::option::Option::Some(0xFF445566)",
1779 ".bg(0xFF112233)",
1780 "StateFlags::HOVER, ::yog_api::ui::StylePatch { bg: ::std::option::Option::Some(0xFF445566)",
1781 ".tint(0x80778899)",
1782 ] {
1783 assert!(code.contains(want), "missing {want}:\n{code}");
1784 }
1785 assert!(missing.unwrap_err().contains("no color `Colors.nope`"));
1786 }
1787
1788 #[test]
1789 fn bindings_commands_and_parts() {
1790 let code = codegen(r##"
1791 <Screen.Resources>
1792 <Color x:Key="Accent" value="#FFD700"/>
1793 <Style x:Key="Btn" target="Button" w="40" h="14" bg="#FF333333" hover:bg="#FF444444"/>
1794 <Style x:Key="Toggle" based_on="@Btn" checked:bg="#FF555555"/>
1795 </Screen.Resources>
1796 <Column w="100%">
1797 <Label x:Name="count" text="{x:Bind count_text()}" color="@Accent"/>
1798 <Label text="@mymod.title"/>
1799 <Button style="@Btn" text="Close" command="{x:Bind cx.close()}"/>
1800 <ToggleButton style="@Toggle" text="Yog" checked="{x:Bind filter == Filter::Yog}"
1801 enabled="{x:Bind has(Filter::Yog)}" command="{x:Bind set_filter(Filter::Yog)}"/>
1802 <TextBox w="100" h="14" text="{x:Bind search, Mode=TwoWay}" placeholder="@mymod.search"
1803 command="{x:Bind submit()}"/>
1804 <ScrollView h="50" scroll_key="{x:Bind search}" visible="{x:Bind show}"/>
1805 </Column>"##)
1806 .unwrap();
1807 for want in [
1808 "const _: () = ::yog_kit::__codegen::require(1);",
1809 "type Vm = Vm;",
1810 ".color(0xFFFFD700)",
1811 r#".id("count")"#,
1812 "pub const COUNT: &str = \"count\";",
1813 "if self.b0.set(::yog_kit::bind::text(&(vm.count_text()))) { root.at_path_mut(&[0, 0]).set_text(",
1814 r#"::yog_kit::bind::text(&(::yog_api::tr("mymod.title")))"#,
1815 ".state_style(::yog_api::ui::StateFlags::HOVER, ::yog_api::ui::StylePatch { bg: ::std::option::Option::Some(0xFF444444), ..::std::default::Default::default() })",
1816 ".state_style(::yog_api::ui::StateFlags::CHECKED",
1817 ".action(::yog_api::ui::Action { owner: 0, slot: 0, index: 0 })",
1818 ".action(::yog_api::ui::Action { owner: 0, slot: 1, index: 0 })",
1819 "::yog_kit::bind::set_checked(root.at_path_mut(&[0, 3]), *self.",
1820 "::yog_kit::bind::flag(vm.filter == Filter::Yog)",
1821 "slot: 0, .. }) => {\n cx.close();",
1822 "slot: 1, .. }) => {\n vm.set_filter(Filter::Yog);",
1823 "parts.focusable(&[0, 2]);",
1824 "parts.text_box(&[0, 4]);",
1825 "parts.scroller(&[0, 5]);",
1826 "u.set_text_box(0, self.",
1827 "::yog_kit::ViewEvent::TextChanged { slot: 0, text } => {\n vm.search = text;",
1828 "::yog_kit::ViewEvent::TextSubmitted { slot: 0, text } => {\n let _ = text; vm.submit();",
1829 "u.reset_scroll(0);",
1830 ".visible = *self.",
1831 "::yog_kit::Screen::<View>::register(registry, vm)",
1832 "<Vm as ::std::default::Default>::default()",
1833 ] {
1834 assert!(code.contains(want), "missing {want}\n{code}");
1835 }
1836 assert!(
1837 !code.contains("text=") || code.contains("// @yui"),
1838 "{code}"
1839 );
1840 }
1841
1842 #[test]
1843 fn bound_sources() {
1844 let code = codegen(
1845 r##"
1846 <Column>
1847 <Surface w="10" h="10" source="{x:Bind grid_id()}"/>
1848 <Image w="10" h="10" source="{x:Bind icon}"/>
1849 </Column>"##,
1850 )
1851 .unwrap();
1852 for want in [
1853 r#"widget::surface("yog:none")"#,
1854 r#"widget::image("item:air")"#,
1855 "::yog_kit::bind::set_source(root.at_path_mut(&[0, 0]), ",
1856 "::yog_kit::bind::set_source(root.at_path_mut(&[0, 1]), ",
1857 ] {
1858 assert!(code.contains(want), "missing {want}\n{code}");
1859 }
1860 }
1861
1862 #[test]
1863 fn component_properties() {
1864 let code = codegen(r##"
1865 <Column>
1866 <StatBar id="hp" w="80" label="HP" value="{x:Bind hp}" fill="{x:Bind color()}" visible="{x:Bind alive}"/>
1867 <ListView h="40" items="{x:Bind rows}" key="{x:Bind id}">
1868 <ListView.ItemTemplate>
1869 <DataTemplate>
1870 <Pill text="{x:Bind name}"/>
1871 </DataTemplate>
1872 </ListView.ItemTemplate>
1873 </ListView>
1874 </Column>"##)
1875 .unwrap();
1876 for want in [
1877 "__props |= self.b0.set(::yog_kit::bind::text(&(vm.hp)));",
1878 "__props |= self.b1.set(::yog_kit::bind::text(&(vm.color())));",
1879 r#"::yog_api::ui::component::build("StatBar", &[("label", "HP"), ("value", &**self.b0.get()), ("fill", &**self.b1.get())])"#,
1880 "u.relayout(); self.b2.reset();",
1881 r#"::yog_api::ui::component::build("Pill", &[("text", &**inst."#,
1882 ] {
1883 assert!(code.contains(want), "missing {want}\n{code}");
1884 }
1885 assert!(codegen(r#"<StatBar value="{x:Bind hp, Mode=TwoWay}"/>"#).is_err());
1886 }
1887
1888 #[test]
1889 fn lists() {
1890 let code = codegen(
1891 r##"
1892 <ListView w="100%" h="80" items="{x:Bind visible()}" key="{x:Bind id}"
1893 selected="{x:Bind selected_id(), BindBack=select}" item_height="12">
1894 <ListView.ItemTemplate>
1895 <DataTemplate x:DataType="Entry">
1896 <Row w="100%" selected:bg="#FF333366">
1897 <Label text="{x:Bind name}"/>
1898 <Button text="x" command="{x:Bind vm.remove(id)}"/>
1899 </Row>
1900 </DataTemplate>
1901 </ListView.ItemTemplate>
1902 <ListView.Empty>
1903 <Label text="{x:Bind empty_text()}"/>
1904 </ListView.Empty>
1905 </ListView>
1906 <ContentPresenter content="{x:Bind selected()}">
1907 <DataTemplate><Label text="{x:Bind Strings::v(version)}"/></DataTemplate>
1908 </ContentPresenter>"##,
1909 )
1910 .unwrap();
1911 for want in [
1912 "struct __T0 {",
1913 "fn __E0() -> ::yog_api::ui::Widget",
1914 "l1: ::yog_kit::items::ItemsHost<__T0>,",
1915 "::yog_kit::items::ItemsHost::new(1, &[0], ::std::option::Option::Some(12.0), ::std::option::Option::Some(0), true)",
1916 "parts.list(1, &[0], ::std::option::Option::Some(0), ::std::option::Option::Some(12.0));",
1917 "let __sel = vm.selected_id();",
1918 "for (index, item) in ::std::iter::IntoIterator::into_iter(vm.visible()).enumerate() {",
1919 "__it.next(::yog_kit::bind::key(&(item.id)), ::yog_kit::bind::is_selected(&__sel, &(item.id)), __T0::build)",
1920 "if inst.b0.set(::yog_kit::bind::text(&(item.name))) { w.at_path_mut(&[0]).set_text(",
1921 "if let ::std::option::Option::Some((w, u)) = __it.finish(::std::option::Option::Some(__E0)) {",
1922 "self.b0.set(::yog_kit::bind::text(&(vm.empty_text())))",
1923 ".action(::yog_api::ui::Action { owner: 1, slot: 0, index: 0 })",
1924 "::yog_kit::ViewEvent::Action(::yog_api::ui::Action { owner: 1, slot: 0, index }) => {",
1925 "::std::clone::Clone::clone(&(item.id))",
1926 "if let ::std::option::Option::Some((__a0,)) = __args { vm.remove(__a0); }",
1927 "| ::yog_kit::ViewEvent::Select { list: 1, index } => {",
1928 "vm.select(__k);",
1929 "::yog_kit::items::ItemsHost::new(2, &[1], ::std::option::Option::None, ::std::option::Option::None, false)",
1930 "into_iter(vm.selected()).enumerate()",
1931 "Strings::v(&item.version)",
1932 "__it.finish(::std::option::Option::None);",
1933 ] {
1934 assert!(code.contains(want), "missing {want}\n{code}");
1935 }
1936 }
1937
1938 #[test]
1939 fn errors() {
1940 let e = |b: &str| codegen(b).unwrap_err();
1941 assert!(e(r#"<Button on_click="x"/>"#).contains("command="),);
1942 assert!(e(r#"<Label w="{x:Bind a}" hover:w="3"/>"#).contains("paint attributes"));
1943 assert!(e(r#"<TextBox text="{x:Bind name(), Mode=TwoWay}"/>"#).contains("TwoWay"));
1944 assert!(e(r#"<Label text="{x:Bind a < b}"/>"#).contains("unexpected"));
1945 assert!(e(r#"<Label color="@Nope"/>"#).contains("no resource"));
1946 assert!(e(r#"<ListView items="{x:Bind xs}"/>"#).contains("item template"));
1947 assert!(e(r#"<Label text="{x:Bind index}"/>"#).contains("item templates"));
1948 }
1949
1950 #[test]
1953 fn kit_fixture() {
1954 let dir =
1955 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../yog-kit/tests/fixtures");
1956 for name in ["list", "grid"] {
1957 let src = std::fs::read_to_string(dir.join(format!("{name}.yui"))).unwrap();
1958 let (code, warnings) = crate::yui::generate_for(&src, name, None).unwrap();
1959 assert!(warnings.is_empty(), "{warnings:?}");
1960 let out = dir.join(format!("{name}.g.rs"));
1961 if std::env::var_os("UPDATE_GOLDEN").is_some() {
1962 std::fs::write(&out, &code).unwrap();
1963 }
1964 let want = std::fs::read_to_string(&out).unwrap_or_default();
1965 assert!(
1966 want == code,
1967 "{} is stale; rerun with UPDATE_GOLDEN=1",
1968 out.display()
1969 );
1970 }
1971 }
1972
1973 #[test]
1974 fn legacy_screens_unchanged() {
1975 let src = r#"<Screen id="t:s"><Label text="@t.k" on_click="go"/></Screen>"#;
1976 let (code, _) = crate::yui::generate_for(src, "s", None).unwrap();
1977 assert!(code.contains("pub fn render(gfx"), "{code}");
1978 assert!(!code.contains("yog_kit"), "{code}");
1979 }
1980}