yog_ui/widget.rs
1//! Widget types and styling.
2
3use crate::layout::{Align, FlexDir};
4
5/// A single widget in the UI tree.
6#[derive(Debug, Clone)]
7pub struct Widget {
8 pub kind: WidgetKind,
9 pub id: Option<String>,
10 pub style: Style,
11 pub flex_dir: FlexDir,
12 pub children: Vec<Widget>,
13 pub on_click: Option<String>,
14 pub enabled: bool,
15 pub focused: bool,
16 /// Typed click target set by generated code (yog-kit) — like
17 /// [`Self::on_click`], but no string to parse. See [`Action`].
18 pub action: Option<Action>,
19 /// `false` = collapsed: takes no space, isn't drawn and can't be hit
20 /// (its layout node is a zero rect without children).
21 pub visible: bool,
22 /// Interaction state (hover, pressed, selected, ...) the host sets each
23 /// frame — picks the [`Self::states`] patches applied when drawing.
24 pub state: StateFlags,
25 /// Paint-only style overrides per state (`hover:bg="..."` in `.yui`).
26 pub states: Option<Box<StateStyles>>,
27}
28
29/// A typed click target: `owner` 0 = the screen, `k` = items control `k`;
30/// `slot` = the command (or [`Action::SELECT`]); `index` = the item index
31/// inside an items control (0 elsewhere).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub struct Action {
34 pub owner: u16,
35 pub slot: u16,
36 pub index: u32,
37}
38
39impl Action {
40 /// The `slot` of an items control's item container: clicking selects it.
41 pub const SELECT: u16 = u16::MAX;
42
43 /// A screen-level command `slot`.
44 pub const fn new(slot: u16) -> Self {
45 Self {
46 owner: 0,
47 slot,
48 index: 0,
49 }
50 }
51}
52
53/// Interaction state bits of a widget — see [`Widget::state`].
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
55pub struct StateFlags(pub u8);
56
57impl StateFlags {
58 pub const NONE: Self = Self(0);
59 pub const HOVER: Self = Self(1);
60 pub const PRESSED: Self = Self(2);
61 pub const FOCUSED: Self = Self(4);
62 pub const SELECTED: Self = Self(8);
63 pub const CHECKED: Self = Self(16);
64 pub const DISABLED: Self = Self(32);
65
66 /// Every bit of `o` is set.
67 pub const fn contains(self, o: Self) -> bool {
68 self.0 & o.0 == o.0
69 }
70 pub fn insert(&mut self, o: Self) {
71 self.0 |= o.0;
72 }
73 pub fn remove(&mut self, o: Self) {
74 self.0 &= !o.0;
75 }
76 /// Sets or clears the bits of `o`.
77 pub fn set(&mut self, o: Self, on: bool) {
78 if on { self.insert(o) } else { self.remove(o) }
79 }
80 pub const fn union(self, o: Self) -> Self {
81 Self(self.0 | o.0)
82 }
83 pub const fn is_empty(self) -> bool {
84 self.0 == 0
85 }
86}
87
88impl std::ops::BitOr for StateFlags {
89 type Output = Self;
90 fn bitor(self, o: Self) -> Self {
91 self.union(o)
92 }
93}
94
95/// Paint-only style overrides — never affect layout.
96#[derive(Debug, Clone, Default, PartialEq)]
97pub struct StylePatch {
98 pub bg: Option<u32>,
99 pub bg_image: Option<String>,
100 pub color: Option<u32>,
101 pub shadow: Option<bool>,
102 pub focus_color: Option<u32>,
103}
104
105impl StylePatch {
106 /// `true` when it overrides nothing.
107 pub fn is_empty(&self) -> bool {
108 *self == Self::default()
109 }
110
111 fn apply(&self, s: &mut Style) {
112 if let Some(v) = self.bg {
113 s.bg = v;
114 }
115 if let Some(v) = &self.bg_image {
116 s.bg_image.clone_from(v);
117 }
118 if let Some(v) = self.color {
119 s.color = v;
120 }
121 if let Some(v) = self.shadow {
122 s.text_shadow = v;
123 }
124 if let Some(v) = self.focus_color {
125 s.focus_color = v;
126 }
127 }
128}
129
130/// A widget's state patches: each applies when the widget's state contains
131/// its flags; later rules win.
132#[derive(Debug, Clone, Default, PartialEq)]
133pub struct StateStyles {
134 pub rules: Vec<(StateFlags, StylePatch)>,
135}
136
137#[derive(Debug, Clone)]
138pub enum WidgetKind {
139 /// Container — arranges children according to `flex_dir`.
140 Panel(FlexDir),
141 /// Container — WPF's `Grid`: rows and columns sized in pixels, to
142 /// content (`Auto`) or as shares of the rest (`*`); each child sits in
143 /// the cell(s) its [`Style::cell`] names — see [`grid`] and
144 /// [`GridSpec`].
145 Grid(Box<GridSpec>),
146 /// Static or dynamic text label.
147 Label(String),
148 /// Clickable button with text.
149 Button(String),
150 /// Minecraft item icon (static, known at build time).
151 ItemSlot(String),
152 /// Inventory-slot decoration: an item icon plus a stack-count overlay,
153 /// both supplied as plain data at tree-build time (like every other
154 /// widget here) — this crate has no notion of "the currently open menu"
155 /// or how to query it; that's the caller's job (see `yog-inventory`).
156 /// Empty `item_id` draws an empty slot box.
157 InvSlot { item_id: String, count: u32 },
158 /// An image from a Yog image source (`item:apple`, `sprite:button`,
159 /// `mymod:gui/logo`, ...) — see [`Image`] and [`image`].
160 Image(Image),
161 /// Invisible spacer.
162 Spacer,
163 /// Drawn by the code: the [`Surface`](crate::Surface) registered under
164 /// this id (see [`crate::surface`] and [`surface`]).
165 Surface(String),
166 /// Single-line text input — see [`TextBox`] and
167 /// [`TextBoxState`](crate::TextBoxState), which owns the text and drives it.
168 TextBox(TextBox),
169}
170
171/// How a grid row or column is sized — WPF's `GridLength`.
172#[derive(Debug, Clone, Copy, PartialEq)]
173pub enum GridLength {
174 /// Fits its content: the largest child in it (`Auto`).
175 Auto,
176 /// A fixed size in GUI pixels (`26`).
177 Px(f32),
178 /// A share of the space the other rows/columns leave (`*` = `Star(1.0)`,
179 /// `2*` = `Star(2.0)`). Along an axis being measured for content (an
180 /// auto-sized grid in a scroll view, ...) it acts as [`Self::Auto`].
181 Star(f32),
182}
183
184impl GridLength {
185 /// `*`.
186 pub const STAR: Self = Self::Star(1.0);
187}
188
189/// One row or column of a [`GridSpec`]: its size and the limits on it.
190#[derive(Debug, Clone, Copy, PartialEq)]
191pub struct Track {
192 pub size: GridLength,
193 /// Never smaller than this (WPF's `MinHeight`/`MinWidth`).
194 pub min: f32,
195 /// Never larger than this (`f32::INFINITY` = no limit).
196 pub max: f32,
197}
198
199impl Track {
200 pub const fn new(size: GridLength) -> Self {
201 Self {
202 size,
203 min: 0.0,
204 max: f32::INFINITY,
205 }
206 }
207 /// `Auto`.
208 pub const fn auto() -> Self {
209 Self::new(GridLength::Auto)
210 }
211 /// A fixed `px`.
212 pub const fn px(px: f32) -> Self {
213 Self::new(GridLength::Px(px))
214 }
215 /// `weight*`.
216 pub const fn star(weight: f32) -> Self {
217 Self::new(GridLength::Star(weight))
218 }
219 pub const fn min(mut self, v: f32) -> Self {
220 self.min = v;
221 self
222 }
223 pub const fn max(mut self, v: f32) -> Self {
224 self.max = v;
225 self
226 }
227}
228
229impl From<GridLength> for Track {
230 fn from(size: GridLength) -> Self {
231 Self::new(size)
232 }
233}
234
235/// A grid's rows, columns and the space between them. No rows (columns)
236/// = one `*` row (column), like WPF.
237#[derive(Debug, Clone, Default, PartialEq)]
238pub struct GridSpec {
239 pub rows: Vec<Track>,
240 pub cols: Vec<Track>,
241 /// Space between rows (WinUI's `RowSpacing`).
242 pub row_spacing: f32,
243 /// Space between columns (WinUI's `ColumnSpacing`).
244 pub col_spacing: f32,
245}
246
247/// The grid cell(s) a widget occupies — WPF's `Grid.Row`, `Grid.Column`,
248/// `Grid.RowSpan`, `Grid.ColumnSpan`. Only a [`grid`] reads it; out-of-range
249/// values are clamped to the grid (like WPF).
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub struct Cell {
252 pub row: u16,
253 pub col: u16,
254 /// Rows spanned, at least 1.
255 pub row_span: u16,
256 /// Columns spanned, at least 1.
257 pub col_span: u16,
258}
259
260impl Default for Cell {
261 fn default() -> Self {
262 Self {
263 row: 0,
264 col: 0,
265 row_span: 1,
266 col_span: 1,
267 }
268 }
269}
270
271/// Where a widget sits horizontally in the space its parent gives it — WPF's
272/// `HorizontalAlignment`. In a grid cell `None` means `Stretch`; in a
273/// Column it overrides the parent's `align` for this child.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub enum HAlign {
276 Left,
277 Center,
278 Right,
279 /// Fill the width (unless the widget has an explicit `w`).
280 Stretch,
281}
282
283/// Where a widget sits vertically — WPF's `VerticalAlignment`; see [`HAlign`].
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub enum VAlign {
286 Top,
287 Center,
288 Bottom,
289 /// Fill the height (unless the widget has an explicit `h`).
290 Stretch,
291}
292
293/// An image widget's data — see [`image`].
294#[derive(Debug, Clone, PartialEq)]
295pub struct Image {
296 /// A Yog image source (see [`yog_gfx::image`]).
297 pub source: String,
298 /// How the image fills the widget (default [`Stretch::Uniform`]).
299 pub stretch: Stretch,
300 /// The part of the image drawn, `[u, v, w, h]` in the image's pixels
301 /// (`None` = all of it). Textures only — items and sprites are whole.
302 pub region: Option<[f32; 4]>,
303 /// Color multiplier, `0xAARRGGBB` (`0xFFFFFFFF` = none; items ignore it).
304 pub tint: u32,
305}
306
307pub use yog_gfx::image::Stretch;
308
309/// A text box's content and editing state, as drawn this frame. Built by
310/// [`text_box`] (text, placeholder, max length, event names); the caret,
311/// selection and horizontal scroll are filled in each frame by
312/// [`TextBoxState::apply`](crate::TextBoxState::apply).
313#[derive(Debug, Clone, Default, PartialEq)]
314pub struct TextBox {
315 pub text: String,
316 /// Shown greyed while the text is empty.
317 pub placeholder: String,
318 /// Longest text allowed, in characters; 0 = unlimited.
319 pub max_length: usize,
320 /// Event name for text changes (see `TextBoxState::event_name`).
321 pub on_change: Option<String>,
322 /// Event name for Enter (see `TextBoxState::event_name`).
323 pub on_submit: Option<String>,
324 /// Caret position in characters — `Some` while the box has focus.
325 pub caret: Option<usize>,
326 /// Draw the caret this frame (it blinks).
327 pub caret_visible: bool,
328 /// Selected characters `start..end` (empty = none).
329 pub selection: (usize, usize),
330 /// First visible character (horizontal scroll).
331 pub first: usize,
332}
333
334/// Side of an item / inventory slot box in GUI pixels (vanilla's 18).
335pub const SLOT_SIZE: f32 = 18.0;
336/// Focus indicator color when `focus_color` is 0 (amber).
337pub const DEFAULT_FOCUS_COLOR: u32 = 0xFF_FFE040;
338
339/// A text box's default left/right padding.
340pub(crate) const TEXT_BOX_PAD_X: f32 = 4.0;
341/// Placeholder text color of a text box.
342pub const PLACEHOLDER_COLOR: u32 = 0xFF_707070;
343/// Border of an unfocused text box (vanilla `EditBox`).
344pub const TEXT_BOX_BORDER: u32 = 0xFF_A0A0A0;
345/// Border of a focused text box unless `focus_color` is set.
346pub const TEXT_BOX_FOCUS_BORDER: u32 = 0xFF_FFFFFF;
347/// Selection highlight behind selected text.
348pub const SELECTION_COLOR: u32 = 0xFF_2850A0;
349
350/// WinForms-style dock — which edge(s) the widget attaches to inside its parent.
351///
352/// - `None` — normal flex positioning (default)
353/// - `Fill` — stretch to fill all remaining space (both axes)
354/// - `Left` — full height, natural width, hugs left edge; other children flow right
355/// - `Right` — full height, natural width, hugs right edge
356/// - `Top` — full width, natural height, hugs top edge; other children flow down
357/// - `Bottom` — full width, natural height, hugs bottom edge
358#[derive(Debug, Clone, Copy, PartialEq, Default)]
359pub enum Dock {
360 #[default]
361 None,
362 Fill,
363 Left,
364 Right,
365 Top,
366 Bottom,
367}
368
369/// How a focused widget shows its focus indicator.
370#[derive(Debug, Clone, Copy, PartialEq, Default)]
371pub enum FocusStyle {
372 /// 1px outline using `focus_color` (default, amber).
373 #[default]
374 Outline,
375 /// Solid background fill using `focus_color`.
376 Fill,
377 /// No visual indicator.
378 None,
379}
380
381/// A size value — either a fixed pixel amount, a CSS-style percentage of the
382/// parent's own resolved content size (0.0–100.0), or `Auto` (size to
383/// content/available space, this crate's original behaviour).
384#[derive(Debug, Clone, Copy, PartialEq, Default)]
385pub enum Units {
386 #[default]
387 Auto,
388 Px(f32),
389 /// Percent of the parent's resolved content size along the same axis.
390 Percent(f32),
391}
392
393impl From<f32> for Units {
394 /// `0.0` maps to `Auto` (matches this crate's original `0.0 = auto` convention,
395 /// so every existing `.w(18.0)`/`.h(0.0)` call keeps meaning exactly what it did).
396 fn from(v: f32) -> Self {
397 if v <= 0.0 { Units::Auto } else { Units::Px(v) }
398 }
399}
400
401impl Units {
402 /// Resolve against `avail` (the parent's resolved content size on this
403 /// axis). `None` for `Auto` — caller falls back to its own auto-sizing.
404 pub fn resolve(self, avail: f32) -> Option<f32> {
405 match self {
406 Units::Auto => None,
407 Units::Px(v) => Some(v),
408 Units::Percent(p) => Some(avail * p / 100.0),
409 }
410 }
411
412 pub fn is_auto(self) -> bool {
413 matches!(self, Units::Auto)
414 }
415}
416
417/// Visual and layout style for a widget.
418#[derive(Debug, Clone)]
419pub struct Style {
420 pub w: Units, // explicit width; Auto = size to content/available space
421 pub h: Units, // explicit height; Auto = size to content/available space
422 pub min_w: f32,
423 pub min_h: f32,
424 pub flex: f32, // grow factor inside flex container (main axis)
425 pub dock: Dock, // WinForms-style edge attachment
426 pub gap: f32, // spacing between children
427 pub pad: [f32; 4], // top, right, bottom, left — space INSIDE the border
428 pub margin: [f32; 4], // top, right, bottom, left — space OUTSIDE the border
429 /// The grid cell(s) it occupies inside a [`grid`] — see [`Cell`].
430 pub cell: Cell,
431 /// Horizontal placement in its slot (grid cell, or a Column's width) —
432 /// see [`HAlign`]. `None` = the parent's default.
433 pub halign: Option<HAlign>,
434 /// Vertical placement in its slot (grid cell, or a Row's height) — see
435 /// [`VAlign`]. `None` = the parent's default.
436 pub valign: Option<VAlign>,
437 pub bg: u32, // background colour 0xAARRGGBB; 0 = transparent
438 /// Background image, drawn over `bg` and stretched to the box — a Yog
439 /// image source (`sprite:button`, `sprite:panel`, `mymod:gui/frame`);
440 /// sprites are nine-sliced, so frames keep their edges. Empty = none.
441 pub bg_image: String,
442 pub color: u32, // text colour
443 pub align: Align,
444 pub font_scale: f32,
445 pub text_shadow: bool, // MC drop-shadow behind text (HUD default; books disable it)
446 pub focus_style: FocusStyle,
447 pub focus_color: u32, // 0 = DEFAULT_FOCUS_COLOR
448 /// Labels/buttons: never word-wrap, even if narrower than the text.
449 /// For single-line titles/headers that must stay on one line — matches
450 /// Patchouli, where such text overflows its box horizontally rather than
451 /// wrapping onto a second line.
452 pub no_wrap: bool,
453 /// Absolute position `(x, y)` inside the parent's content box (inside its
454 /// padding) — WPF `Canvas` / WinForms `Location` style. A positioned
455 /// widget is taken out of the parent's flex flow: it takes no main-axis
456 /// space, ignores `flex`/`dock`, and is drawn in tree order (later
457 /// siblings on top). `None` (default) = normal flex positioning.
458 pub pos: Option<(f32, f32)>,
459 /// Labels/buttons: a single line (implies `no_wrap`) cut with `...` when
460 /// wider than the box, instead of overflowing it.
461 pub ellipsis: bool,
462 /// Containers: children are drawn (and hit) only inside this widget's
463 /// rect — anything scrolled or overflowing past it is cut off.
464 pub clip: bool,
465 /// Containers: vertical scroll offset of the children in GUI pixels
466 /// (0 = top). Layout clamps it to the content — the effective value is
467 /// [`LayoutNode::scroll_y`](crate::LayoutNode::scroll_y).
468 pub scroll_y: f32,
469 /// Containers: reserve a strip on the right edge and draw a vertical
470 /// scrollbar there whenever the content overflows (see
471 /// [`ScrollState`](crate::ScrollState) for driving it).
472 pub scrollbar: bool,
473 /// Font id for text — empty (default) = Minecraft's default font
474 /// (`minecraft:default`); also `minecraft:uniform`, `minecraft:alt`,
475 /// `minecraft:illageralt` or a resource-pack font such as `mymod:fancy`.
476 /// See [`crate::text`] for how non-default fonts are measured.
477 pub font: String,
478}
479
480impl Default for Style {
481 fn default() -> Self {
482 Self {
483 w: Units::Auto,
484 h: Units::Auto,
485 min_w: 4.0,
486 min_h: 4.0,
487 flex: 0.0,
488 dock: Dock::None,
489 gap: 2.0,
490 pad: [0.0; 4],
491 margin: [0.0; 4],
492 cell: Cell::default(),
493 halign: None,
494 valign: None,
495 bg: 0,
496 bg_image: String::new(),
497 color: 0xFF_CCCCAA,
498 align: Align::Start,
499 font_scale: 1.0,
500 text_shadow: true,
501 focus_style: FocusStyle::default(),
502 focus_color: 0,
503 no_wrap: false,
504 pos: None,
505 ellipsis: false,
506 clip: false,
507 scroll_y: 0.0,
508 scrollbar: false,
509 font: String::new(),
510 }
511 }
512}
513
514// ── Builder API ───────────────────────────────────────────────────────────────
515
516impl Widget {
517 fn new(kind: WidgetKind) -> Self {
518 let flex_dir = if let WidgetKind::Panel(dir) = &kind {
519 *dir
520 } else {
521 FlexDir::Column
522 };
523 Self {
524 kind,
525 id: None,
526 style: Style::default(),
527 flex_dir,
528 children: Vec::new(),
529 on_click: None,
530 enabled: true,
531 focused: false,
532 action: None,
533 visible: true,
534 state: StateFlags::NONE,
535 states: None,
536 }
537 }
538
539 /// Typed click target — see [`Action`].
540 pub fn action(mut self, a: Action) -> Self {
541 self.action = Some(a);
542 self
543 }
544 /// `false` = collapsed — see [`Widget::visible`].
545 pub fn visible(mut self, v: bool) -> Self {
546 self.visible = v;
547 self
548 }
549 /// Adds a paint-only override applied while the state contains `when`
550 /// (later calls win over earlier ones).
551 pub fn state_style(mut self, when: StateFlags, patch: StylePatch) -> Self {
552 self.states
553 .get_or_insert_with(Default::default)
554 .rules
555 .push((when, patch));
556 self
557 }
558
559 /// The descendant at child-index `path` (`&[]` = self); `None` past the
560 /// tree.
561 pub fn get_path(&self, path: &[u16]) -> Option<&Widget> {
562 let mut w = self;
563 for &i in path {
564 w = w.children.get(i as usize)?;
565 }
566 Some(w)
567 }
568 /// [`Self::get_path`], mutably.
569 pub fn get_path_mut(&mut self, path: &[u16]) -> Option<&mut Widget> {
570 let mut w = self;
571 for &i in path {
572 w = w.children.get_mut(i as usize)?;
573 }
574 Some(w)
575 }
576 /// The descendant at `path`. Panics on a bad path — for generated code,
577 /// whose paths are fixed when it's generated.
578 pub fn at_path(&self, path: &[u16]) -> &Widget {
579 self.get_path(path)
580 .unwrap_or_else(|| panic!("yog-ui: no widget at path {path:?}"))
581 }
582 /// [`Self::at_path`], mutably.
583 pub fn at_path_mut(&mut self, path: &[u16]) -> &mut Widget {
584 self.get_path_mut(path)
585 .unwrap_or_else(|| panic!("yog-ui: no widget at path {path:?}"))
586 }
587
588 /// Whether clicking it does something (an [`Action`] or `on_click`).
589 pub fn is_interactive(&self) -> bool {
590 self.action.is_some() || self.on_click.is_some()
591 }
592
593 /// Sets (or clears) `mask` on this widget and its descendants, stopping
594 /// at descendants that are interactive themselves (a button in a row
595 /// keeps its own hover) — so a row's labels follow the row's state.
596 pub fn set_state_inherited(&mut self, mask: StateFlags, on: bool) {
597 self.state.set(mask, on);
598 for c in &mut self.children {
599 if !c.is_interactive() {
600 c.set_state_inherited(mask, on);
601 }
602 }
603 }
604
605 /// Clears `mask` on the whole subtree (interactive descendants too).
606 pub fn clear_state_deep(&mut self, mask: StateFlags) {
607 self.state.remove(mask);
608 for c in &mut self.children {
609 c.clear_state_deep(mask);
610 }
611 }
612
613 /// The style drawn: [`Self::style`] plus the [`Self::states`] patches
614 /// matching [`Self::state`] (with DISABLED while `enabled` is false).
615 pub fn effective_style(&self) -> std::borrow::Cow<'_, Style> {
616 let mut state = self.state;
617 if !self.enabled {
618 state.insert(StateFlags::DISABLED);
619 }
620 self.effective_style_in(state)
621 }
622
623 /// [`Self::effective_style`] for an explicit `state`.
624 pub fn effective_style_in(&self, state: StateFlags) -> std::borrow::Cow<'_, Style> {
625 let Some(states) = &self.states else {
626 return std::borrow::Cow::Borrowed(&self.style);
627 };
628 let mut matching = states
629 .rules
630 .iter()
631 .filter(|(when, _)| !when.is_empty() && state.contains(*when))
632 .peekable();
633 if matching.peek().is_none() {
634 return std::borrow::Cow::Borrowed(&self.style);
635 }
636 let mut s = self.style.clone();
637 for (_, patch) in matching {
638 patch.apply(&mut s);
639 }
640 std::borrow::Cow::Owned(s)
641 }
642
643 pub fn id(mut self, id: impl Into<String>) -> Self {
644 self.id = Some(id.into());
645 self
646 }
647 pub fn on_click(mut self, ev: impl Into<String>) -> Self {
648 self.on_click = Some(ev.into());
649 self
650 }
651 pub fn child(mut self, w: Widget) -> Self {
652 self.children.push(w);
653 self
654 }
655
656 /// Accepts a plain px value (`0.0` = auto) or a [`Units`] directly —
657 /// e.g. `.w(18.0)` or `.w(Units::Percent(60.0))`.
658 pub fn w(mut self, w: impl Into<Units>) -> Self {
659 self.style.w = w.into();
660 self
661 }
662 pub fn h(mut self, h: impl Into<Units>) -> Self {
663 self.style.h = h.into();
664 self
665 }
666 pub fn min_w(mut self, v: f32) -> Self {
667 self.style.min_w = v;
668 self
669 }
670 pub fn min_h(mut self, v: f32) -> Self {
671 self.style.min_h = v;
672 self
673 }
674 pub fn flex(mut self, v: f32) -> Self {
675 self.style.flex = v;
676 self
677 }
678 pub fn flex_dir(mut self, v: FlexDir) -> Self {
679 self.flex_dir = v;
680 self
681 }
682 pub fn gap(mut self, v: f32) -> Self {
683 self.style.gap = v;
684 self
685 }
686 pub fn bg(mut self, v: u32) -> Self {
687 self.style.bg = v;
688 self
689 }
690 /// See [`Style::bg_image`].
691 pub fn bg_image(mut self, source: impl Into<String>) -> Self {
692 self.style.bg_image = source.into();
693 self
694 }
695 pub fn color(mut self, v: u32) -> Self {
696 self.style.color = v;
697 self
698 }
699 pub fn align(mut self, v: Align) -> Self {
700 self.style.align = v;
701 self
702 }
703 pub fn font_scale(mut self, v: f32) -> Self {
704 self.style.font_scale = v;
705 self
706 }
707 pub fn shadow(mut self, v: bool) -> Self {
708 self.style.text_shadow = v;
709 self
710 }
711 pub fn no_wrap(mut self) -> Self {
712 self.style.no_wrap = true;
713 self
714 }
715 pub fn focus_style(mut self, v: FocusStyle) -> Self {
716 self.style.focus_style = v;
717 self
718 }
719 pub fn focus_color(mut self, v: u32) -> Self {
720 self.style.focus_color = v;
721 self
722 }
723 pub fn dock(mut self, v: Dock) -> Self {
724 self.style.dock = v;
725 self
726 }
727 pub fn enabled(mut self, v: bool) -> Self {
728 self.enabled = v;
729 self
730 }
731 pub fn focused(mut self, v: bool) -> Self {
732 self.focused = v;
733 self
734 }
735 /// Position absolutely at `(x, y)` inside the parent's content box — see [`Style::pos`].
736 pub fn at(mut self, x: f32, y: f32) -> Self {
737 self.style.pos = Some((x, y));
738 self
739 }
740 /// Single line, cut with `...` when too wide — see [`Style::ellipsis`].
741 pub fn ellipsis(mut self) -> Self {
742 self.style.no_wrap = true;
743 self.style.ellipsis = true;
744 self
745 }
746 /// Clip children to this widget's rect — see [`Style::clip`].
747 pub fn clip(mut self, v: bool) -> Self {
748 self.style.clip = v;
749 self
750 }
751 /// Vertical scroll offset of the children — see [`Style::scroll_y`].
752 pub fn scroll_y(mut self, v: f32) -> Self {
753 self.style.scroll_y = v;
754 self
755 }
756 /// Draw a vertical scrollbar on overflow — see [`Style::scrollbar`].
757 pub fn scrollbar(mut self, v: bool) -> Self {
758 self.style.scrollbar = v;
759 self
760 }
761 /// Font for this widget's text — see [`Style::font`].
762 pub fn font(mut self, font: impl Into<String>) -> Self {
763 self.style.font = font.into();
764 self
765 }
766 /// Text box: greyed text shown while it's empty.
767 pub fn placeholder(mut self, text: impl Into<String>) -> Self {
768 if let WidgetKind::TextBox(t) = &mut self.kind {
769 t.placeholder = text.into();
770 }
771 self
772 }
773 /// Text box: longest text allowed, in characters (0 = unlimited).
774 pub fn max_length(mut self, n: usize) -> Self {
775 if let WidgetKind::TextBox(t) = &mut self.kind {
776 t.max_length = n;
777 }
778 self
779 }
780 /// Text box: event name raised when the text changes.
781 pub fn on_change(mut self, ev: impl Into<String>) -> Self {
782 if let WidgetKind::TextBox(t) = &mut self.kind {
783 t.on_change = Some(ev.into());
784 }
785 self
786 }
787 /// Text box: event name raised by Enter.
788 pub fn on_submit(mut self, ev: impl Into<String>) -> Self {
789 if let WidgetKind::TextBox(t) = &mut self.kind {
790 t.on_submit = Some(ev.into());
791 }
792 self
793 }
794 /// Image: how it fills the widget (WPF's `Stretch`).
795 pub fn stretch(mut self, stretch: Stretch) -> Self {
796 if let WidgetKind::Image(i) = &mut self.kind {
797 i.stretch = stretch;
798 }
799 self
800 }
801 /// Image: draw only `[u, v, w, h]` of it (texture pixels).
802 pub fn region(mut self, region: [f32; 4]) -> Self {
803 if let WidgetKind::Image(i) = &mut self.kind {
804 i.region = Some(region);
805 }
806 self
807 }
808 /// Image: multiply its colors by `tint` (`0xAARRGGBB`).
809 pub fn tint(mut self, tint: u32) -> Self {
810 if let WidgetKind::Image(i) = &mut self.kind {
811 i.tint = tint;
812 }
813 self
814 }
815 /// Adds every widget in `children`, in order.
816 pub fn children(mut self, children: impl IntoIterator<Item = Widget>) -> Self {
817 self.children.extend(children);
818 self
819 }
820
821 /// The first widget in this subtree (depth-first, self included) whose
822 /// [`Widget::id`] is `id` — for changing a built tree before laying it
823 /// out (dynamic text, enabled state, ...).
824 pub fn find_mut(&mut self, id: &str) -> Option<&mut Widget> {
825 if self.id.as_deref() == Some(id) {
826 return Some(self);
827 }
828 self.children.iter_mut().find_map(|c| c.find_mut(id))
829 }
830
831 /// Replaces the text of a label, button or text box; `false` for any
832 /// other kind.
833 pub fn set_text(&mut self, text: impl Into<String>) -> bool {
834 match &mut self.kind {
835 WidgetKind::Label(t) | WidgetKind::Button(t) => {
836 *t = text.into();
837 true
838 }
839 WidgetKind::TextBox(t) => {
840 t.text = text.into();
841 true
842 }
843 _ => false,
844 }
845 }
846
847 /// [`set_text`](Self::set_text) as a builder call.
848 pub fn with_text(mut self, text: impl Into<String>) -> Self {
849 self.set_text(text);
850 self
851 }
852
853 /// Replaces an image's source or a slot's item id (other kinds: no-op).
854 pub fn with_source(mut self, source: impl Into<String>) -> Self {
855 match &mut self.kind {
856 WidgetKind::Image(i) => i.source = source.into(),
857 WidgetKind::Surface(id) => *id = source.into(),
858 WidgetKind::ItemSlot(id) | WidgetKind::InvSlot { item_id: id, .. } => {
859 *id = source.into()
860 }
861 _ => {}
862 }
863 self
864 }
865
866 /// Replaces an inventory slot's stack count (other kinds: no-op).
867 pub fn with_count(mut self, n: u32) -> Self {
868 if let WidgetKind::InvSlot { count, .. } = &mut self.kind {
869 *count = n;
870 }
871 self
872 }
873
874 pub fn padding(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
875 self.style.pad = [top, right, bottom, left];
876 self
877 }
878 pub fn margin(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
879 self.style.margin = [top, right, bottom, left];
880 self
881 }
882
883 /// Puts it in grid cell `(row, col)` (spanning one row and column) —
884 /// WPF's `Grid.Row` / `Grid.Column`. See [`Self::span`].
885 pub fn cell(mut self, row: u16, col: u16) -> Self {
886 self.style.cell.row = row;
887 self.style.cell.col = col;
888 self
889 }
890 /// Spans `rows` × `cols` grid cells from its [`Self::cell`] — WPF's
891 /// `Grid.RowSpan` / `Grid.ColumnSpan` (0 counts as 1).
892 pub fn span(mut self, rows: u16, cols: u16) -> Self {
893 self.style.cell.row_span = rows.max(1);
894 self.style.cell.col_span = cols.max(1);
895 self
896 }
897 /// Horizontal placement in its slot — see [`HAlign`].
898 pub fn halign(mut self, v: HAlign) -> Self {
899 self.style.halign = Some(v);
900 self
901 }
902 /// Vertical placement in its slot — see [`VAlign`].
903 pub fn valign(mut self, v: VAlign) -> Self {
904 self.style.valign = Some(v);
905 self
906 }
907
908 /// Grid: its rows (no rows = one `*` row).
909 pub fn rows(mut self, rows: impl IntoIterator<Item = impl Into<Track>>) -> Self {
910 if let WidgetKind::Grid(g) = &mut self.kind {
911 g.rows = rows.into_iter().map(Into::into).collect();
912 }
913 self
914 }
915 /// Grid: its columns (no columns = one `*` column).
916 pub fn cols(mut self, cols: impl IntoIterator<Item = impl Into<Track>>) -> Self {
917 if let WidgetKind::Grid(g) = &mut self.kind {
918 g.cols = cols.into_iter().map(Into::into).collect();
919 }
920 self
921 }
922 /// Grid: space between rows.
923 pub fn row_spacing(mut self, v: f32) -> Self {
924 if let WidgetKind::Grid(g) = &mut self.kind {
925 g.row_spacing = v;
926 }
927 self
928 }
929 /// Grid: space between columns.
930 pub fn col_spacing(mut self, v: f32) -> Self {
931 if let WidgetKind::Grid(g) = &mut self.kind {
932 g.col_spacing = v;
933 }
934 self
935 }
936}
937
938// ── Widget constructors ───────────────────────────────────────────────────────
939
940pub fn panel(dir: FlexDir) -> Widget {
941 Widget::new(WidgetKind::Panel(dir))
942}
943/// WPF's `Grid`: a container of rows and columns — give it [`Widget::rows`]
944/// and [`Widget::cols`] ([`Track`]s: pixels, `Auto` or `*` shares) and put
945/// each child in a cell with [`Widget::cell`] / [`Widget::span`]. A child
946/// fills its cell unless it has [`Widget::halign`] / [`Widget::valign`] (or
947/// an explicit size); [`Widget::margin`] insets it.
948///
949/// ```
950/// use yog_ui::widget::{self, GridLength, Track};
951/// let ui = widget::grid()
952/// .rows([Track::auto(), Track::star(1.0), Track::px(20.0)])
953/// .cols([GridLength::Px(80.0), GridLength::STAR])
954/// .child(widget::label("Title").cell(0, 0).span(1, 2))
955/// .child(widget::scroll_view().cell(1, 0))
956/// .child(widget::label("Details").cell(1, 1))
957/// .child(widget::button("OK").cell(2, 1));
958/// ```
959pub fn grid() -> Widget {
960 Widget::new(WidgetKind::Grid(Box::default()))
961}
962/// A vertically scrolling column: clips its children, scrolls them by
963/// [`Widget::scroll_y`] and draws a scrollbar when they overflow — WPF's
964/// `ScrollViewer` around a `StackPanel`. Give it a fixed (or flex) height.
965pub fn scroll_view() -> Widget {
966 panel(FlexDir::Column).clip(true).scrollbar(true)
967}
968pub fn label(text: impl Into<String>) -> Widget {
969 Widget::new(WidgetKind::Label(text.into()))
970}
971pub fn button(text: impl Into<String>) -> Widget {
972 Widget::new(WidgetKind::Button(text.into()))
973}
974pub fn item_slot(item_id: impl Into<String>) -> Widget {
975 Widget::new(WidgetKind::ItemSlot(item_id.into()))
976}
977/// An inventory-slot decoration (icon + stack-count overlay) for `item_id`
978/// (empty string = empty slot) with `count` items. Purely decorative — real
979/// drag-and-drop still goes through the vanilla `Slot` this overlays.
980pub fn inv_slot(item_id: impl Into<String>, count: u32) -> Widget {
981 Widget::new(WidgetKind::InvSlot {
982 item_id: item_id.into(),
983 count,
984 })
985 .w(SLOT_SIZE)
986 .h(SLOT_SIZE)
987}
988/// Id prefix of a [`slot`]: `yog:slot:<index>`, and `=<accepts>` (`|`-joined)
989/// for a [`slot_accepting`].
990pub const SLOT_ID_PREFIX: &str = "yog:slot:";
991/// Id of a [`player_inventory`].
992pub const PLAYER_INVENTORY_ID: &str = "yog:player_inventory";
993/// Gap between the player's main inventory and their hotbar (vanilla).
994pub const HOTBAR_GAP: f32 = 4.0;
995
996/// Slot `index` of an inventory screen's container: the frame its real
997/// slot sits in — the game draws the item, the hover and the drag over it.
998/// Where it lands in the layout is where the slot is.
999pub fn slot(index: usize) -> Widget {
1000 inv_slot("", 0).id(format!("{SLOT_ID_PREFIX}{index}"))
1001}
1002/// A [`slot`] that only takes `accepts`: item ids (`minecraft:redstone`)
1003/// and item tags (`#c:dusts`).
1004pub fn slot_accepting(index: usize, accepts: &[&str]) -> Widget {
1005 if accepts.is_empty() {
1006 return slot(index);
1007 }
1008 inv_slot("", 0).id(format!("{SLOT_ID_PREFIX}{index}={}", accepts.join("|")))
1009}
1010/// The player's inventory on an inventory screen: 3 rows of 9, then the
1011/// hotbar [`HOTBAR_GAP`] below — frames for the real slots, like [`slot`].
1012pub fn player_inventory() -> Widget {
1013 let row = || (0..9).fold(panel(FlexDir::Row).gap(0.0), |r, _| r.child(inv_slot("", 0)));
1014 panel(FlexDir::Column)
1015 .id(PLAYER_INVENTORY_ID)
1016 .gap(0.0)
1017 .child(row())
1018 .child(row())
1019 .child(row())
1020 .child(row().margin(HOTBAR_GAP, 0.0, 0.0, 0.0))
1021}
1022/// An image from a Yog image source — `"item:apple"`, `"block:stone"`,
1023/// `"sprite:button"`, `"mymod:gui/logo"` (see [`yog_gfx::image`]) — the
1024/// host resolves it for its Minecraft version. Sized to the image's natural
1025/// size (16×16 until the host told it) unless given `w`/`h`; scaled into the
1026/// widget per [`Widget::stretch`] (default `Uniform`), nearest-neighbour.
1027pub fn image(source: impl Into<String>) -> Widget {
1028 Widget::new(WidgetKind::Image(Image {
1029 source: source.into(),
1030 stretch: Stretch::Uniform,
1031 region: None,
1032 tint: 0xFFFF_FFFF,
1033 }))
1034}
1035pub fn spacer() -> Widget {
1036 Widget::new(WidgetKind::Spacer)
1037}
1038/// A box drawn by the code — the [`Surface`](crate::Surface) registered
1039/// under `id` with [`crate::surface::register`]. No natural size: give it
1040/// `w`/`h` (or let a parent stretch it).
1041pub fn surface(id: impl Into<String>) -> Widget {
1042 Widget::new(WidgetKind::Surface(id.into()))
1043}
1044/// A single-line text input holding `text` — black box, grey border (white
1045/// while focused), like vanilla's `EditBox`. Its text, caret and focus live
1046/// in a [`TextBoxState`](crate::TextBoxState) that the code-behind keeps and
1047/// applies to it each frame.
1048pub fn text_box(text: impl Into<String>) -> Widget {
1049 Widget::new(WidgetKind::TextBox(TextBox {
1050 text: text.into(),
1051 ..TextBox::default()
1052 }))
1053 .bg(0xFF_000000)
1054 .color(0xFF_E0E0E0)
1055 .padding(0.0, TEXT_BOX_PAD_X, 0.0, TEXT_BOX_PAD_X)
1056}