yog-ui 0.40.6

Yog UI framework — flexbox and WPF-style grid layout + GPU rendering via yog-gfx
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Widget types and styling.

use crate::layout::{Align, FlexDir};

/// A single widget in the UI tree.
#[derive(Debug, Clone)]
pub struct Widget {
    pub kind: WidgetKind,
    pub id: Option<String>,
    pub style: Style,
    pub flex_dir: FlexDir,
    pub children: Vec<Widget>,
    pub on_click: Option<String>,
    pub enabled: bool,
    pub focused: bool,
    /// Typed click target set by generated code (yog-kit) — like
    /// [`Self::on_click`], but no string to parse. See [`Action`].
    pub action: Option<Action>,
    /// `false` = collapsed: takes no space, isn't drawn and can't be hit
    /// (its layout node is a zero rect without children).
    pub visible: bool,
    /// Interaction state (hover, pressed, selected, ...) the host sets each
    /// frame — picks the [`Self::states`] patches applied when drawing.
    pub state: StateFlags,
    /// Paint-only style overrides per state (`hover:bg="..."` in `.yui`).
    pub states: Option<Box<StateStyles>>,
    /// Text shown in a tooltip while the cursor rests on it (`\n` breaks
    /// lines) — see [`crate::UiRoot::tooltip_at`].
    pub tooltip: Option<String>,
}

/// A typed click target: `owner` 0 = the screen, `k` = items control `k`;
/// `slot` = the command (or [`Action::SELECT`]); `index` = the item index
/// inside an items control (0 elsewhere).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Action {
    pub owner: u16,
    pub slot: u16,
    pub index: u32,
}

impl Action {
    /// The `slot` of an items control's item container: clicking selects it.
    pub const SELECT: u16 = u16::MAX;

    /// A screen-level command `slot`.
    pub const fn new(slot: u16) -> Self {
        Self {
            owner: 0,
            slot,
            index: 0,
        }
    }
}

/// Interaction state bits of a widget — see [`Widget::state`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct StateFlags(pub u8);

impl StateFlags {
    pub const NONE: Self = Self(0);
    pub const HOVER: Self = Self(1);
    pub const PRESSED: Self = Self(2);
    pub const FOCUSED: Self = Self(4);
    pub const SELECTED: Self = Self(8);
    pub const CHECKED: Self = Self(16);
    pub const DISABLED: Self = Self(32);

    /// Every bit of `o` is set.
    pub const fn contains(self, o: Self) -> bool {
        self.0 & o.0 == o.0
    }
    pub fn insert(&mut self, o: Self) {
        self.0 |= o.0;
    }
    pub fn remove(&mut self, o: Self) {
        self.0 &= !o.0;
    }
    /// Sets or clears the bits of `o`.
    pub fn set(&mut self, o: Self, on: bool) {
        if on { self.insert(o) } else { self.remove(o) }
    }
    pub const fn union(self, o: Self) -> Self {
        Self(self.0 | o.0)
    }
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl std::ops::BitOr for StateFlags {
    type Output = Self;
    fn bitor(self, o: Self) -> Self {
        self.union(o)
    }
}

/// Paint-only style overrides — never affect layout.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StylePatch {
    pub bg: Option<u32>,
    pub bg_image: Option<String>,
    pub color: Option<u32>,
    pub shadow: Option<bool>,
    pub focus_color: Option<u32>,
}

impl StylePatch {
    /// `true` when it overrides nothing.
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    fn apply(&self, s: &mut Style) {
        if let Some(v) = self.bg {
            s.bg = v;
        }
        if let Some(v) = &self.bg_image {
            s.bg_image.clone_from(v);
        }
        if let Some(v) = self.color {
            s.color = v;
        }
        if let Some(v) = self.shadow {
            s.text_shadow = v;
        }
        if let Some(v) = self.focus_color {
            s.focus_color = v;
        }
    }
}

/// A widget's state patches: each applies when the widget's state contains
/// its flags; later rules win.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StateStyles {
    pub rules: Vec<(StateFlags, StylePatch)>,
}

#[derive(Debug, Clone)]
pub enum WidgetKind {
    /// Container — arranges children according to `flex_dir`.
    Panel(FlexDir),
    /// Container — WPF's `Grid`: rows and columns sized in pixels, to
    /// content (`Auto`) or as shares of the rest (`*`); each child sits in
    /// the cell(s) its [`Style::cell`] names — see [`grid`] and
    /// [`GridSpec`].
    Grid(Box<GridSpec>),
    /// Static or dynamic text label.
    Label(String),
    /// Clickable button with text.
    Button(String),
    /// Minecraft item icon (static, known at build time).
    ItemSlot(String),
    /// Inventory-slot decoration: an item icon plus a stack-count overlay,
    /// both supplied as plain data at tree-build time (like every other
    /// widget here) — this crate has no notion of "the currently open menu"
    /// or how to query it; that's the caller's job (see `yog-inventory`).
    /// Empty `item_id` draws an empty slot box.
    InvSlot { item_id: String, count: u32 },
    /// An image from a Yog image source (`item:apple`, `sprite:button`,
    /// `mymod:gui/logo`, ...) — see [`Image`] and [`image`].
    Image(Image),
    /// Invisible spacer.
    Spacer,
    /// Drawn by the code: the [`Surface`](crate::Surface) registered under
    /// this id (see [`crate::surface`] and [`surface`]).
    Surface(String),
    /// Single-line text input — see [`TextBox`] and
    /// [`TextBoxState`](crate::TextBoxState), which owns the text and drives it.
    TextBox(TextBox),
}

/// How a grid row or column is sized — WPF's `GridLength`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GridLength {
    /// Fits its content: the largest child in it (`Auto`).
    Auto,
    /// A fixed size in GUI pixels (`26`).
    Px(f32),
    /// A share of the space the other rows/columns leave (`*` = `Star(1.0)`,
    /// `2*` = `Star(2.0)`). Along an axis being measured for content (an
    /// auto-sized grid in a scroll view, ...) it acts as [`Self::Auto`].
    Star(f32),
}

impl GridLength {
    /// `*`.
    pub const STAR: Self = Self::Star(1.0);
}

/// One row or column of a [`GridSpec`]: its size and the limits on it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Track {
    pub size: GridLength,
    /// Never smaller than this (WPF's `MinHeight`/`MinWidth`).
    pub min: f32,
    /// Never larger than this (`f32::INFINITY` = no limit).
    pub max: f32,
}

impl Track {
    pub const fn new(size: GridLength) -> Self {
        Self {
            size,
            min: 0.0,
            max: f32::INFINITY,
        }
    }
    /// `Auto`.
    pub const fn auto() -> Self {
        Self::new(GridLength::Auto)
    }
    /// A fixed `px`.
    pub const fn px(px: f32) -> Self {
        Self::new(GridLength::Px(px))
    }
    /// `weight*`.
    pub const fn star(weight: f32) -> Self {
        Self::new(GridLength::Star(weight))
    }
    pub const fn min(mut self, v: f32) -> Self {
        self.min = v;
        self
    }
    pub const fn max(mut self, v: f32) -> Self {
        self.max = v;
        self
    }
}

impl From<GridLength> for Track {
    fn from(size: GridLength) -> Self {
        Self::new(size)
    }
}

/// A grid's rows, columns and the space between them. No rows (columns)
/// = one `*` row (column), like WPF.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GridSpec {
    pub rows: Vec<Track>,
    pub cols: Vec<Track>,
    /// Space between rows (WinUI's `RowSpacing`).
    pub row_spacing: f32,
    /// Space between columns (WinUI's `ColumnSpacing`).
    pub col_spacing: f32,
}

/// The grid cell(s) a widget occupies — WPF's `Grid.Row`, `Grid.Column`,
/// `Grid.RowSpan`, `Grid.ColumnSpan`. Only a [`grid`] reads it; out-of-range
/// values are clamped to the grid (like WPF).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cell {
    pub row: u16,
    pub col: u16,
    /// Rows spanned, at least 1.
    pub row_span: u16,
    /// Columns spanned, at least 1.
    pub col_span: u16,
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            row: 0,
            col: 0,
            row_span: 1,
            col_span: 1,
        }
    }
}

/// Where a widget sits horizontally in the space its parent gives it — WPF's
/// `HorizontalAlignment`. In a grid cell `None` means `Stretch`; in a
/// Column it overrides the parent's `align` for this child.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HAlign {
    Left,
    Center,
    Right,
    /// Fill the width (unless the widget has an explicit `w`).
    Stretch,
}

/// Where a widget sits vertically — WPF's `VerticalAlignment`; see [`HAlign`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VAlign {
    Top,
    Center,
    Bottom,
    /// Fill the height (unless the widget has an explicit `h`).
    Stretch,
}

/// An image widget's data — see [`image`].
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
    /// A Yog image source (see [`yog_gfx::image`]).
    pub source: String,
    /// How the image fills the widget (default [`Stretch::Uniform`]).
    pub stretch: Stretch,
    /// The part of the image drawn, `[u, v, w, h]` in the image's pixels
    /// (`None` = all of it). Textures only — items and sprites are whole.
    pub region: Option<[f32; 4]>,
    /// Color multiplier, `0xAARRGGBB` (`0xFFFFFFFF` = none; items ignore it).
    pub tint: u32,
}

pub use yog_gfx::image::Stretch;

/// A text box's content and editing state, as drawn this frame. Built by
/// [`text_box`] (text, placeholder, max length, event names); the caret,
/// selection and horizontal scroll are filled in each frame by
/// [`TextBoxState::apply`](crate::TextBoxState::apply).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TextBox {
    pub text: String,
    /// Shown greyed while the text is empty.
    pub placeholder: String,
    /// Longest text allowed, in characters; 0 = unlimited.
    pub max_length: usize,
    /// Event name for text changes (see `TextBoxState::event_name`).
    pub on_change: Option<String>,
    /// Event name for Enter (see `TextBoxState::event_name`).
    pub on_submit: Option<String>,
    /// Caret position in characters — `Some` while the box has focus.
    pub caret: Option<usize>,
    /// Draw the caret this frame (it blinks).
    pub caret_visible: bool,
    /// Selected characters `start..end` (empty = none).
    pub selection: (usize, usize),
    /// First visible character (horizontal scroll).
    pub first: usize,
}

/// Side of an item / inventory slot box in GUI pixels (vanilla's 18).
pub const SLOT_SIZE: f32 = 18.0;
/// Focus indicator color when `focus_color` is 0 (amber).
pub const DEFAULT_FOCUS_COLOR: u32 = 0xFF_FFE040;

/// A text box's default left/right padding.
pub(crate) const TEXT_BOX_PAD_X: f32 = 4.0;
/// Placeholder text color of a text box.
pub const PLACEHOLDER_COLOR: u32 = 0xFF_707070;
/// Border of an unfocused text box (vanilla `EditBox`).
pub const TEXT_BOX_BORDER: u32 = 0xFF_A0A0A0;
/// Border of a focused text box unless `focus_color` is set.
pub const TEXT_BOX_FOCUS_BORDER: u32 = 0xFF_FFFFFF;
/// Selection highlight behind selected text.
pub const SELECTION_COLOR: u32 = 0xFF_2850A0;

/// WinForms-style dock — which edge(s) the widget attaches to inside its parent.
///
/// - `None`   — normal flex positioning (default)
/// - `Fill`   — stretch to fill all remaining space (both axes)
/// - `Left`   — full height, natural width, hugs left edge; other children flow right
/// - `Right`  — full height, natural width, hugs right edge
/// - `Top`    — full width, natural height, hugs top edge; other children flow down
/// - `Bottom` — full width, natural height, hugs bottom edge
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Dock {
    #[default]
    None,
    Fill,
    Left,
    Right,
    Top,
    Bottom,
}

/// How a focused widget shows its focus indicator.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FocusStyle {
    /// 1px outline using `focus_color` (default, amber).
    #[default]
    Outline,
    /// Solid background fill using `focus_color`.
    Fill,
    /// No visual indicator.
    None,
}

/// A size value — either a fixed pixel amount, a CSS-style percentage of the
/// parent's own resolved content size (0.0–100.0), or `Auto` (size to
/// content/available space, this crate's original behaviour).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Units {
    #[default]
    Auto,
    Px(f32),
    /// Percent of the parent's resolved content size along the same axis.
    Percent(f32),
}

impl From<f32> for Units {
    /// `0.0` maps to `Auto` (matches this crate's original `0.0 = auto` convention,
    /// so every existing `.w(18.0)`/`.h(0.0)` call keeps meaning exactly what it did).
    fn from(v: f32) -> Self {
        if v <= 0.0 { Units::Auto } else { Units::Px(v) }
    }
}

impl Units {
    /// Resolve against `avail` (the parent's resolved content size on this
    /// axis). `None` for `Auto` — caller falls back to its own auto-sizing.
    pub fn resolve(self, avail: f32) -> Option<f32> {
        match self {
            Units::Auto => None,
            Units::Px(v) => Some(v),
            Units::Percent(p) => Some(avail * p / 100.0),
        }
    }

    pub fn is_auto(self) -> bool {
        matches!(self, Units::Auto)
    }
}

/// Visual and layout style for a widget.
#[derive(Debug, Clone)]
pub struct Style {
    pub w: Units, // explicit width; Auto = size to content/available space
    pub h: Units, // explicit height; Auto = size to content/available space
    pub min_w: f32,
    pub min_h: f32,
    pub flex: f32,        // grow factor inside flex container (main axis)
    pub dock: Dock,       // WinForms-style edge attachment
    pub gap: f32,         // spacing between children
    pub pad: [f32; 4],    // top, right, bottom, left — space INSIDE the border
    pub margin: [f32; 4], // top, right, bottom, left — space OUTSIDE the border
    /// The grid cell(s) it occupies inside a [`grid`] — see [`Cell`].
    pub cell: Cell,
    /// Horizontal placement in its slot (grid cell, or a Column's width) —
    /// see [`HAlign`]. `None` = the parent's default.
    pub halign: Option<HAlign>,
    /// Vertical placement in its slot (grid cell, or a Row's height) — see
    /// [`VAlign`]. `None` = the parent's default.
    pub valign: Option<VAlign>,
    pub bg: u32,    // background colour 0xAARRGGBB; 0 = transparent
    /// Background image, drawn over `bg` and stretched to the box — a Yog
    /// image source (`sprite:button`, `sprite:panel`, `mymod:gui/frame`);
    /// sprites are nine-sliced, so frames keep their edges. Empty = none.
    pub bg_image: String,
    pub color: u32, // text colour
    pub align: Align,
    pub font_scale: f32,
    pub text_shadow: bool, // MC drop-shadow behind text (HUD default; books disable it)
    pub focus_style: FocusStyle,
    pub focus_color: u32, // 0 = DEFAULT_FOCUS_COLOR
    /// Labels/buttons: never word-wrap, even if narrower than the text.
    /// For single-line titles/headers that must stay on one line — matches
    /// Patchouli, where such text overflows its box horizontally rather than
    /// wrapping onto a second line.
    pub no_wrap: bool,
    /// Absolute position `(x, y)` inside the parent's content box (inside its
    /// padding) — WPF `Canvas` / WinForms `Location` style. A positioned
    /// widget is taken out of the parent's flex flow: it takes no main-axis
    /// space, ignores `flex`/`dock`, and is drawn in tree order (later
    /// siblings on top). `None` (default) = normal flex positioning.
    pub pos: Option<(f32, f32)>,
    /// Labels/buttons: a single line (implies `no_wrap`) cut with `...` when
    /// wider than the box, instead of overflowing it.
    pub ellipsis: bool,
    /// Containers: children are drawn (and hit) only inside this widget's
    /// rect — anything scrolled or overflowing past it is cut off.
    pub clip: bool,
    /// Containers: vertical scroll offset of the children in GUI pixels
    /// (0 = top). Layout clamps it to the content — the effective value is
    /// [`LayoutNode::scroll_y`](crate::LayoutNode::scroll_y).
    pub scroll_y: f32,
    /// Containers: reserve a strip on the right edge and draw a vertical
    /// scrollbar there whenever the content overflows (see
    /// [`ScrollState`](crate::ScrollState) for driving it).
    pub scrollbar: bool,
    /// Font id for text — empty (default) = Minecraft's default font
    /// (`minecraft:default`); also `minecraft:uniform`, `minecraft:alt`,
    /// `minecraft:illageralt` or a resource-pack font such as `mymod:fancy`.
    /// See [`crate::text`] for how non-default fonts are measured.
    pub font: String,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            w: Units::Auto,
            h: Units::Auto,
            min_w: 4.0,
            min_h: 4.0,
            flex: 0.0,
            dock: Dock::None,
            gap: 2.0,
            pad: [0.0; 4],
            margin: [0.0; 4],
            cell: Cell::default(),
            halign: None,
            valign: None,
            bg: 0,
            bg_image: String::new(),
            color: 0xFF_CCCCAA,
            align: Align::Start,
            font_scale: 1.0,
            text_shadow: true,
            focus_style: FocusStyle::default(),
            focus_color: 0,
            no_wrap: false,
            pos: None,
            ellipsis: false,
            clip: false,
            scroll_y: 0.0,
            scrollbar: false,
            font: String::new(),
        }
    }
}

// ── Builder API ───────────────────────────────────────────────────────────────

impl Widget {
    fn new(kind: WidgetKind) -> Self {
        let flex_dir = if let WidgetKind::Panel(dir) = &kind {
            *dir
        } else {
            FlexDir::Column
        };
        Self {
            kind,
            id: None,
            style: Style::default(),
            flex_dir,
            children: Vec::new(),
            on_click: None,
            enabled: true,
            focused: false,
            action: None,
            visible: true,
            state: StateFlags::NONE,
            states: None,
            tooltip: None,
        }
    }

    /// See [`Self::tooltip`]; empty = none.
    pub fn tooltip(mut self, text: impl Into<String>) -> Self {
        self.set_tooltip(text);
        self
    }
    /// Sets (empty: clears) [`Self::tooltip`].
    pub fn set_tooltip(&mut self, text: impl Into<String>) {
        let t = text.into();
        self.tooltip = (!t.is_empty()).then_some(t);
    }

    /// Typed click target — see [`Action`].
    pub fn action(mut self, a: Action) -> Self {
        self.action = Some(a);
        self
    }
    /// `false` = collapsed — see [`Widget::visible`].
    pub fn visible(mut self, v: bool) -> Self {
        self.visible = v;
        self
    }
    /// Adds a paint-only override applied while the state contains `when`
    /// (later calls win over earlier ones).
    pub fn state_style(mut self, when: StateFlags, patch: StylePatch) -> Self {
        self.states
            .get_or_insert_with(Default::default)
            .rules
            .push((when, patch));
        self
    }

    /// The descendant at child-index `path` (`&[]` = self); `None` past the
    /// tree.
    pub fn get_path(&self, path: &[u16]) -> Option<&Widget> {
        let mut w = self;
        for &i in path {
            w = w.children.get(i as usize)?;
        }
        Some(w)
    }
    /// [`Self::get_path`], mutably.
    pub fn get_path_mut(&mut self, path: &[u16]) -> Option<&mut Widget> {
        let mut w = self;
        for &i in path {
            w = w.children.get_mut(i as usize)?;
        }
        Some(w)
    }
    /// The descendant at `path`. Panics on a bad path — for generated code,
    /// whose paths are fixed when it's generated.
    pub fn at_path(&self, path: &[u16]) -> &Widget {
        self.get_path(path)
            .unwrap_or_else(|| panic!("yog-ui: no widget at path {path:?}"))
    }
    /// [`Self::at_path`], mutably.
    pub fn at_path_mut(&mut self, path: &[u16]) -> &mut Widget {
        self.get_path_mut(path)
            .unwrap_or_else(|| panic!("yog-ui: no widget at path {path:?}"))
    }

    /// Whether clicking it does something (an [`Action`] or `on_click`).
    pub fn is_interactive(&self) -> bool {
        self.action.is_some() || self.on_click.is_some()
    }

    /// Sets (or clears) `mask` on this widget and its descendants, stopping
    /// at descendants that are interactive themselves (a button in a row
    /// keeps its own hover) — so a row's labels follow the row's state.
    pub fn set_state_inherited(&mut self, mask: StateFlags, on: bool) {
        self.state.set(mask, on);
        for c in &mut self.children {
            if !c.is_interactive() {
                c.set_state_inherited(mask, on);
            }
        }
    }

    /// Clears `mask` on the whole subtree (interactive descendants too).
    pub fn clear_state_deep(&mut self, mask: StateFlags) {
        self.state.remove(mask);
        for c in &mut self.children {
            c.clear_state_deep(mask);
        }
    }

    /// The style drawn: [`Self::style`] plus the [`Self::states`] patches
    /// matching [`Self::state`] (with DISABLED while `enabled` is false).
    pub fn effective_style(&self) -> std::borrow::Cow<'_, Style> {
        let mut state = self.state;
        if !self.enabled {
            state.insert(StateFlags::DISABLED);
        }
        self.effective_style_in(state)
    }

    /// [`Self::effective_style`] for an explicit `state`.
    pub fn effective_style_in(&self, state: StateFlags) -> std::borrow::Cow<'_, Style> {
        let Some(states) = &self.states else {
            return std::borrow::Cow::Borrowed(&self.style);
        };
        let mut matching = states
            .rules
            .iter()
            .filter(|(when, _)| !when.is_empty() && state.contains(*when))
            .peekable();
        if matching.peek().is_none() {
            return std::borrow::Cow::Borrowed(&self.style);
        }
        let mut s = self.style.clone();
        for (_, patch) in matching {
            patch.apply(&mut s);
        }
        std::borrow::Cow::Owned(s)
    }

    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }
    pub fn on_click(mut self, ev: impl Into<String>) -> Self {
        self.on_click = Some(ev.into());
        self
    }
    pub fn child(mut self, w: Widget) -> Self {
        self.children.push(w);
        self
    }

    /// Accepts a plain px value (`0.0` = auto) or a [`Units`] directly —
    /// e.g. `.w(18.0)` or `.w(Units::Percent(60.0))`.
    pub fn w(mut self, w: impl Into<Units>) -> Self {
        self.style.w = w.into();
        self
    }
    pub fn h(mut self, h: impl Into<Units>) -> Self {
        self.style.h = h.into();
        self
    }
    pub fn min_w(mut self, v: f32) -> Self {
        self.style.min_w = v;
        self
    }
    pub fn min_h(mut self, v: f32) -> Self {
        self.style.min_h = v;
        self
    }
    pub fn flex(mut self, v: f32) -> Self {
        self.style.flex = v;
        self
    }
    pub fn flex_dir(mut self, v: FlexDir) -> Self {
        self.flex_dir = v;
        self
    }
    pub fn gap(mut self, v: f32) -> Self {
        self.style.gap = v;
        self
    }
    pub fn bg(mut self, v: u32) -> Self {
        self.style.bg = v;
        self
    }
    /// See [`Style::bg_image`].
    pub fn bg_image(mut self, source: impl Into<String>) -> Self {
        self.style.bg_image = source.into();
        self
    }
    pub fn color(mut self, v: u32) -> Self {
        self.style.color = v;
        self
    }
    pub fn align(mut self, v: Align) -> Self {
        self.style.align = v;
        self
    }
    pub fn font_scale(mut self, v: f32) -> Self {
        self.style.font_scale = v;
        self
    }
    pub fn shadow(mut self, v: bool) -> Self {
        self.style.text_shadow = v;
        self
    }
    pub fn no_wrap(mut self) -> Self {
        self.style.no_wrap = true;
        self
    }
    pub fn focus_style(mut self, v: FocusStyle) -> Self {
        self.style.focus_style = v;
        self
    }
    pub fn focus_color(mut self, v: u32) -> Self {
        self.style.focus_color = v;
        self
    }
    pub fn dock(mut self, v: Dock) -> Self {
        self.style.dock = v;
        self
    }
    pub fn enabled(mut self, v: bool) -> Self {
        self.enabled = v;
        self
    }
    pub fn focused(mut self, v: bool) -> Self {
        self.focused = v;
        self
    }
    /// Position absolutely at `(x, y)` inside the parent's content box — see [`Style::pos`].
    pub fn at(mut self, x: f32, y: f32) -> Self {
        self.style.pos = Some((x, y));
        self
    }
    /// Single line, cut with `...` when too wide — see [`Style::ellipsis`].
    pub fn ellipsis(mut self) -> Self {
        self.style.no_wrap = true;
        self.style.ellipsis = true;
        self
    }
    /// Clip children to this widget's rect — see [`Style::clip`].
    pub fn clip(mut self, v: bool) -> Self {
        self.style.clip = v;
        self
    }
    /// Vertical scroll offset of the children — see [`Style::scroll_y`].
    pub fn scroll_y(mut self, v: f32) -> Self {
        self.style.scroll_y = v;
        self
    }
    /// Draw a vertical scrollbar on overflow — see [`Style::scrollbar`].
    pub fn scrollbar(mut self, v: bool) -> Self {
        self.style.scrollbar = v;
        self
    }
    /// Font for this widget's text — see [`Style::font`].
    pub fn font(mut self, font: impl Into<String>) -> Self {
        self.style.font = font.into();
        self
    }
    /// Text box: greyed text shown while it's empty.
    pub fn placeholder(mut self, text: impl Into<String>) -> Self {
        if let WidgetKind::TextBox(t) = &mut self.kind {
            t.placeholder = text.into();
        }
        self
    }
    /// Text box: longest text allowed, in characters (0 = unlimited).
    pub fn max_length(mut self, n: usize) -> Self {
        if let WidgetKind::TextBox(t) = &mut self.kind {
            t.max_length = n;
        }
        self
    }
    /// Text box: event name raised when the text changes.
    pub fn on_change(mut self, ev: impl Into<String>) -> Self {
        if let WidgetKind::TextBox(t) = &mut self.kind {
            t.on_change = Some(ev.into());
        }
        self
    }
    /// Text box: event name raised by Enter.
    pub fn on_submit(mut self, ev: impl Into<String>) -> Self {
        if let WidgetKind::TextBox(t) = &mut self.kind {
            t.on_submit = Some(ev.into());
        }
        self
    }
    /// Image: how it fills the widget (WPF's `Stretch`).
    pub fn stretch(mut self, stretch: Stretch) -> Self {
        if let WidgetKind::Image(i) = &mut self.kind {
            i.stretch = stretch;
        }
        self
    }
    /// Image: draw only `[u, v, w, h]` of it (texture pixels).
    pub fn region(mut self, region: [f32; 4]) -> Self {
        if let WidgetKind::Image(i) = &mut self.kind {
            i.region = Some(region);
        }
        self
    }
    /// Image: multiply its colors by `tint` (`0xAARRGGBB`).
    pub fn tint(mut self, tint: u32) -> Self {
        if let WidgetKind::Image(i) = &mut self.kind {
            i.tint = tint;
        }
        self
    }
    /// Adds every widget in `children`, in order.
    pub fn children(mut self, children: impl IntoIterator<Item = Widget>) -> Self {
        self.children.extend(children);
        self
    }

    /// The first widget in this subtree (depth-first, self included) whose
    /// [`Widget::id`] is `id` — for changing a built tree before laying it
    /// out (dynamic text, enabled state, ...).
    pub fn find_mut(&mut self, id: &str) -> Option<&mut Widget> {
        if self.id.as_deref() == Some(id) {
            return Some(self);
        }
        self.children.iter_mut().find_map(|c| c.find_mut(id))
    }

    /// Replaces the text of a label, button or text box; `false` for any
    /// other kind.
    pub fn set_text(&mut self, text: impl Into<String>) -> bool {
        match &mut self.kind {
            WidgetKind::Label(t) | WidgetKind::Button(t) => {
                *t = text.into();
                true
            }
            WidgetKind::TextBox(t) => {
                t.text = text.into();
                true
            }
            _ => false,
        }
    }

    /// [`set_text`](Self::set_text) as a builder call.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.set_text(text);
        self
    }

    /// Replaces an image's source or a slot's item id (other kinds: no-op).
    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        match &mut self.kind {
            WidgetKind::Image(i) => i.source = source.into(),
            WidgetKind::Surface(id) => *id = source.into(),
            WidgetKind::ItemSlot(id) | WidgetKind::InvSlot { item_id: id, .. } => {
                *id = source.into()
            }
            _ => {}
        }
        self
    }

    /// Replaces an inventory slot's stack count (other kinds: no-op).
    pub fn with_count(mut self, n: u32) -> Self {
        if let WidgetKind::InvSlot { count, .. } = &mut self.kind {
            *count = n;
        }
        self
    }

    pub fn padding(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
        self.style.pad = [top, right, bottom, left];
        self
    }
    pub fn margin(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
        self.style.margin = [top, right, bottom, left];
        self
    }

    /// Puts it in grid cell `(row, col)` (spanning one row and column) —
    /// WPF's `Grid.Row` / `Grid.Column`. See [`Self::span`].
    pub fn cell(mut self, row: u16, col: u16) -> Self {
        self.style.cell.row = row;
        self.style.cell.col = col;
        self
    }
    /// Spans `rows` × `cols` grid cells from its [`Self::cell`] — WPF's
    /// `Grid.RowSpan` / `Grid.ColumnSpan` (0 counts as 1).
    pub fn span(mut self, rows: u16, cols: u16) -> Self {
        self.style.cell.row_span = rows.max(1);
        self.style.cell.col_span = cols.max(1);
        self
    }
    /// Horizontal placement in its slot — see [`HAlign`].
    pub fn halign(mut self, v: HAlign) -> Self {
        self.style.halign = Some(v);
        self
    }
    /// Vertical placement in its slot — see [`VAlign`].
    pub fn valign(mut self, v: VAlign) -> Self {
        self.style.valign = Some(v);
        self
    }

    /// Grid: its rows (no rows = one `*` row).
    pub fn rows(mut self, rows: impl IntoIterator<Item = impl Into<Track>>) -> Self {
        if let WidgetKind::Grid(g) = &mut self.kind {
            g.rows = rows.into_iter().map(Into::into).collect();
        }
        self
    }
    /// Grid: its columns (no columns = one `*` column).
    pub fn cols(mut self, cols: impl IntoIterator<Item = impl Into<Track>>) -> Self {
        if let WidgetKind::Grid(g) = &mut self.kind {
            g.cols = cols.into_iter().map(Into::into).collect();
        }
        self
    }
    /// Grid: space between rows.
    pub fn row_spacing(mut self, v: f32) -> Self {
        if let WidgetKind::Grid(g) = &mut self.kind {
            g.row_spacing = v;
        }
        self
    }
    /// Grid: space between columns.
    pub fn col_spacing(mut self, v: f32) -> Self {
        if let WidgetKind::Grid(g) = &mut self.kind {
            g.col_spacing = v;
        }
        self
    }
}

// ── Widget constructors ───────────────────────────────────────────────────────

pub fn panel(dir: FlexDir) -> Widget {
    Widget::new(WidgetKind::Panel(dir))
}
/// WPF's `Grid`: a container of rows and columns — give it [`Widget::rows`]
/// and [`Widget::cols`] ([`Track`]s: pixels, `Auto` or `*` shares) and put
/// each child in a cell with [`Widget::cell`] / [`Widget::span`]. A child
/// fills its cell unless it has [`Widget::halign`] / [`Widget::valign`] (or
/// an explicit size); [`Widget::margin`] insets it.
///
/// ```
/// use yog_ui::widget::{self, GridLength, Track};
/// let ui = widget::grid()
///     .rows([Track::auto(), Track::star(1.0), Track::px(20.0)])
///     .cols([GridLength::Px(80.0), GridLength::STAR])
///     .child(widget::label("Title").cell(0, 0).span(1, 2))
///     .child(widget::scroll_view().cell(1, 0))
///     .child(widget::label("Details").cell(1, 1))
///     .child(widget::button("OK").cell(2, 1));
/// ```
pub fn grid() -> Widget {
    Widget::new(WidgetKind::Grid(Box::default()))
}
/// A vertically scrolling column: clips its children, scrolls them by
/// [`Widget::scroll_y`] and draws a scrollbar when they overflow — WPF's
/// `ScrollViewer` around a `StackPanel`. Give it a fixed (or flex) height.
pub fn scroll_view() -> Widget {
    panel(FlexDir::Column).clip(true).scrollbar(true)
}
pub fn label(text: impl Into<String>) -> Widget {
    Widget::new(WidgetKind::Label(text.into()))
}
pub fn button(text: impl Into<String>) -> Widget {
    Widget::new(WidgetKind::Button(text.into()))
}
pub fn item_slot(item_id: impl Into<String>) -> Widget {
    Widget::new(WidgetKind::ItemSlot(item_id.into()))
}
/// An inventory-slot decoration (icon + stack-count overlay) for `item_id`
/// (empty string = empty slot) with `count` items. Purely decorative — real
/// drag-and-drop still goes through the vanilla `Slot` this overlays.
pub fn inv_slot(item_id: impl Into<String>, count: u32) -> Widget {
    Widget::new(WidgetKind::InvSlot {
        item_id: item_id.into(),
        count,
    })
    .w(SLOT_SIZE)
    .h(SLOT_SIZE)
}
/// Id prefix of a [`slot`]: `yog:slot:<index>`, and `=<accepts>` (`|`-joined)
/// for a [`slot_accepting`].
pub const SLOT_ID_PREFIX: &str = "yog:slot:";
/// Id of a [`player_inventory`].
pub const PLAYER_INVENTORY_ID: &str = "yog:player_inventory";
/// Gap between the player's main inventory and their hotbar (vanilla).
pub const HOTBAR_GAP: f32 = 4.0;

/// Slot `index` of an inventory screen's container: the frame its real
/// slot sits in — the game draws the item, the hover and the drag over it.
/// Where it lands in the layout is where the slot is.
pub fn slot(index: usize) -> Widget {
    inv_slot("", 0).id(format!("{SLOT_ID_PREFIX}{index}"))
}
/// A [`slot`] that only takes `accepts`: item ids (`minecraft:redstone`)
/// and item tags (`#c:dusts`).
pub fn slot_accepting(index: usize, accepts: &[&str]) -> Widget {
    if accepts.is_empty() {
        return slot(index);
    }
    inv_slot("", 0).id(format!("{SLOT_ID_PREFIX}{index}={}", accepts.join("|")))
}
/// The player's inventory on an inventory screen: 3 rows of 9, then the
/// hotbar [`HOTBAR_GAP`] below — frames for the real slots, like [`slot`].
pub fn player_inventory() -> Widget {
    let row = || (0..9).fold(panel(FlexDir::Row).gap(0.0), |r, _| r.child(inv_slot("", 0)));
    panel(FlexDir::Column)
        .id(PLAYER_INVENTORY_ID)
        .gap(0.0)
        .child(row())
        .child(row())
        .child(row())
        .child(row().margin(HOTBAR_GAP, 0.0, 0.0, 0.0))
}
/// An image from a Yog image source — `"item:apple"`, `"block:stone"`,
/// `"sprite:button"`, `"mymod:gui/logo"` (see [`yog_gfx::image`]) — the
/// host resolves it for its Minecraft version. Sized to the image's natural
/// size (16×16 until the host told it) unless given `w`/`h`; scaled into the
/// widget per [`Widget::stretch`] (default `Uniform`), nearest-neighbour.
pub fn image(source: impl Into<String>) -> Widget {
    Widget::new(WidgetKind::Image(Image {
        source: source.into(),
        stretch: Stretch::Uniform,
        region: None,
        tint: 0xFFFF_FFFF,
    }))
}
pub fn spacer() -> Widget {
    Widget::new(WidgetKind::Spacer)
}
/// A box drawn by the code — the [`Surface`](crate::Surface) registered
/// under `id` with [`crate::surface::register`]. No natural size: give it
/// `w`/`h` (or let a parent stretch it).
pub fn surface(id: impl Into<String>) -> Widget {
    Widget::new(WidgetKind::Surface(id.into()))
}
/// A single-line text input holding `text` — black box, grey border (white
/// while focused), like vanilla's `EditBox`. Its text, caret and focus live
/// in a [`TextBoxState`](crate::TextBoxState) that the code-behind keeps and
/// applies to it each frame.
pub fn text_box(text: impl Into<String>) -> Widget {
    Widget::new(WidgetKind::TextBox(TextBox {
        text: text.into(),
        ..TextBox::default()
    }))
    .bg(0xFF_000000)
    .color(0xFF_E0E0E0)
    .padding(0.0, TEXT_BOX_PAD_X, 0.0, TEXT_BOX_PAD_X)
}