Skip to main content

yog_kit/
lib.rs

1//! yog-kit — MVVM screens for Yog mods.
2//!
3//! A screen is a `.yui` file with `x:ViewModel="MyVm"` plus a plain Rust
4//! view model. `yog build` compiles the markup into a [`View`] (widget tree,
5//! compiled `{x:Bind ...}` bindings, command dispatch) and this crate hosts
6//! it: it owns the view model, re-evaluates bindings after every change,
7//! routes input (clicks, hover, scrolling, text boxes, Tab focus, list
8//! keyboard selection, Esc) and draws the result.
9//!
10//! ```ignore
11//! // src/counter.rs, next to src/counter.yui
12//! yog_api::ui_include!("counter");
13//! use yog_kit::prelude::*;
14//!
15//! #[derive(Default)]
16//! pub struct CounterVm { count: u32 }
17//! impl ViewModel for CounterVm {}
18//! impl CounterVm {
19//!     pub fn increment(&mut self) { self.count += 1 }
20//! }
21//!
22//! // src/lib.rs: counter::register(registry); ... counter::open();
23//! ```
24//!
25//! The view model never touches widgets: the markup binds to its fields and
26//! methods, and commands call its methods. [`testing::TestHost`] drives a
27//! screen without the game.
28
29extern crate self as yog_kit;
30
31pub mod bind;
32mod host;
33pub mod items;
34mod screen;
35pub mod testing;
36
37pub use host::{Update, Viewport};
38pub use screen::{Cx, Screen, ScreenHandle, handle_of, inventory_of};
39pub use yog_api::ui::{Action, StateFlags, Widget};
40
41/// Everything a code-behind file needs.
42pub mod prelude {
43    pub use crate::{Cx, ScreenHandle, ViewModel};
44}
45
46/// A screen's state and logic. Implement it (often with no methods) for the
47/// type named by the `.yui` file's `x:ViewModel`.
48///
49/// All hooks run on the render thread with the screen locked; use
50/// [`Cx`] to close the screen, navigate, or get a [`ScreenHandle`] for
51/// updates from other threads.
52#[allow(unused_variables)]
53pub trait ViewModel: Send + 'static {
54    /// The screen was opened (every time).
55    fn on_open(&mut self, cx: &mut Cx<'_, Self>)
56    where
57        Self: Sized,
58    {
59    }
60    /// The screen was closed (by any path).
61    fn on_close(&mut self, cx: &mut Cx<'_, Self>)
62    where
63        Self: Sized,
64    {
65    }
66    /// Esc / back. Return `true` when handled; `false` (the default) goes
67    /// back to the screen this one was navigated from, else closes it.
68    fn on_back(&mut self, cx: &mut Cx<'_, Self>) -> bool
69    where
70        Self: Sized,
71    {
72        false
73    }
74    /// Escape hatch: imperative changes to the content tree after each
75    /// binding update. Rarely needed.
76    fn customize(&self, root: &mut Widget) {}
77}
78
79/// Where a screen's content sits in the GUI.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81pub enum Anchor {
82    #[default]
83    Center,
84    TopLeft,
85    Top,
86    TopRight,
87    Left,
88    Right,
89    BottomLeft,
90    Bottom,
91    BottomRight,
92    /// Stretched over the whole GUI.
93    Fill,
94}
95
96impl Anchor {
97    /// Top-left corner of a `w` × `h` box anchored in a `sw` × `sh` GUI.
98    pub fn place(self, sw: f32, sh: f32, w: f32, h: f32) -> (f32, f32) {
99        let cx = ((sw - w) / 2.0).floor();
100        let cy = ((sh - h) / 2.0).floor();
101        let (x, y) = match self {
102            Anchor::Center => (cx, cy),
103            Anchor::TopLeft | Anchor::Fill => (0.0, 0.0),
104            Anchor::Top => (cx, 0.0),
105            Anchor::TopRight => (sw - w, 0.0),
106            Anchor::Left => (0.0, cy),
107            Anchor::Right => (sw - w, cy),
108            Anchor::BottomLeft => (0.0, sh - h),
109            Anchor::Bottom => (cx, sh - h),
110            Anchor::BottomRight => (sw - w, sh - h),
111        };
112        (x.max(0.0), y.max(0.0))
113    }
114}
115
116/// Static facts about a screen, from its `<Screen>` attributes.
117#[derive(Debug, Clone, Copy, PartialEq)]
118pub struct ScreenMeta {
119    /// UI id (`register_ui`, `open_ui`).
120    pub id: &'static str,
121    /// Design size in GUI pixels.
122    pub w: f32,
123    pub h: f32,
124    pub anchor: Anchor,
125    pub modal: bool,
126    pub pause: bool,
127    /// Re-evaluates the bindings every frame (`<Screen live="true">`): for
128    /// a screen showing state that changes outside its own commands (a
129    /// server tick, a packet). Inventory screens always are.
130    pub live: bool,
131}
132
133/// Input for a view's [`View::dispatch`], produced by the host.
134#[derive(Debug, Clone, PartialEq)]
135pub enum ViewEvent {
136    /// A widget with this [`Action`] was clicked or activated (Enter/Space).
137    Action(Action),
138    /// Text box `slot` (index in [`Parts`]) was edited; `text` is its text.
139    TextChanged { slot: u16, text: String },
140    /// Enter in text box `slot`.
141    TextSubmitted { slot: u16, text: String },
142    /// Keyboard selection in list `list` (its owner id) moved to `index`.
143    Select { list: u16, index: u32 },
144}
145
146/// A compiled screen — implemented by `.yui` codegen only.
147///
148/// The host owns the content tree; paths are child-index paths from its
149/// root ([`Widget::at_path`]).
150pub trait View: Sized + Send + 'static {
151    type Vm: ViewModel;
152    const META: ScreenMeta;
153    /// The view's binding state, its content tree and its interactive parts.
154    fn build() -> (Self, Widget, Parts);
155    /// Re-evaluates the bindings against `vm`, patching `root`.
156    fn update(&mut self, root: &mut Widget, vm: &Self::Vm, u: &mut Update);
157    /// Runs the command (or write-back) for `ev`.
158    fn dispatch(&mut self, vm: &mut Self::Vm, cx: &mut Cx<'_, Self::Vm>, ev: ViewEvent);
159}
160
161/// One scrolling container of a view.
162#[derive(Debug, Clone)]
163pub struct ScrollerPart {
164    pub path: Vec<u16>,
165    pub state: yog_api::ui::ScrollState,
166}
167
168/// One text box of a view.
169#[derive(Debug, Clone)]
170pub struct TextBoxPart {
171    pub path: Vec<u16>,
172    pub state: yog_api::ui::TextBoxState,
173}
174
175/// One list (ListView / ItemsControl) of a view.
176#[derive(Debug, Clone)]
177pub struct ListPart {
178    /// The list's owner id (in its items' [`Action::owner`]).
179    pub owner: u16,
180    /// The items container.
181    pub path: Vec<u16>,
182    /// Its scroller (index in [`Parts`]), for ListView.
183    pub scroller: Option<u16>,
184    /// Fixed row height (virtualization, keyboard reveal).
185    pub item_height: Option<f32>,
186    /// Item count and selected index after the last update.
187    pub len: u32,
188    pub selected: Option<u32>,
189}
190
191/// The interactive parts of a view, created by [`View::build`]: scrollers,
192/// text boxes, lists, and the Tab focus order. Indices are the order they
193/// were added.
194#[derive(Debug, Clone, Default)]
195pub struct Parts {
196    pub scrollers: Vec<ScrollerPart>,
197    pub text_boxes: Vec<TextBoxPart>,
198    pub lists: Vec<ListPart>,
199    /// Tab order: buttons, text boxes and lists, in document order.
200    pub focusables: Vec<Vec<u16>>,
201}
202
203impl Parts {
204    pub fn new() -> Self {
205        Self::default()
206    }
207    /// Adds a scroll view at `path`; returns its index.
208    pub fn scroller(&mut self, path: &[u16]) -> u16 {
209        self.scrollers.push(ScrollerPart {
210            path: path.to_vec(),
211            state: Default::default(),
212        });
213        (self.scrollers.len() - 1) as u16
214    }
215    /// Adds a text box at `path` (also focusable); returns its slot.
216    pub fn text_box(&mut self, path: &[u16]) -> u16 {
217        self.text_boxes.push(TextBoxPart {
218            path: path.to_vec(),
219            state: Default::default(),
220        });
221        self.focusables.push(path.to_vec());
222        (self.text_boxes.len() - 1) as u16
223    }
224    /// Adds the list `owner` whose items container is at `path` (focusable
225    /// when it has a scroller, i.e. is a ListView).
226    pub fn list(
227        &mut self,
228        owner: u16,
229        path: &[u16],
230        scroller: Option<u16>,
231        item_height: Option<f32>,
232    ) {
233        self.lists.push(ListPart {
234            owner,
235            path: path.to_vec(),
236            scroller,
237            item_height,
238            len: 0,
239            selected: None,
240        });
241        if scroller.is_some() {
242            self.focusables.push(path.to_vec());
243        }
244    }
245    /// Adds a focusable widget (a button) to the Tab order.
246    pub fn focusable(&mut self, path: &[u16]) {
247        self.focusables.push(path.to_vec());
248    }
249}
250
251/// Used by generated code only.
252#[doc(hidden)]
253pub mod __codegen {
254    /// The codegen version this yog-kit understands.
255    pub const CODEGEN: u32 = 2;
256
257    /// Compile-time check that generated code matches this yog-kit.
258    pub const fn require(version: u32) {
259        if version > CODEGEN {
260            panic!(
261                "this .yui code was generated for a newer yog-kit; update the yog-kit dependency"
262            );
263        }
264        if version < CODEGEN {
265            panic!("this .yui code was generated by an old yog; regenerate it with `yog build`");
266        }
267    }
268}