Skip to main content

yog_kit/
bind.rs

1//! Binding helpers used by generated `.yui` code: a [`Slot`] remembers a
2//! binding's last value so widgets are only patched when it changes, and
3//! the conversion functions turn view-model values into widget values with
4//! readable compile errors.
5
6use std::fmt::Display;
7use std::hash::{Hash, Hasher};
8
9use yog_api::ui::{Color, StateFlags, Units, Widget};
10
11/// The last value of one binding.
12#[derive(Debug, Clone, Default)]
13pub struct Slot<T>(Option<T>);
14
15impl<T: PartialEq> Slot<T> {
16    pub const fn new() -> Self {
17        Slot(None)
18    }
19    /// Stores `v`; `true` when it differs from the previous value (or is
20    /// the first).
21    pub fn set(&mut self, v: T) -> bool {
22        if self.0.as_ref() == Some(&v) {
23            return false;
24        }
25        self.0 = Some(v);
26        true
27    }
28    /// The current value. Panics before the first [`Self::set`].
29    pub fn get(&self) -> &T {
30        self.0
31            .as_ref()
32            .expect("yog-kit: binding read before it was set")
33    }
34    /// Forgets the value, so the next `set` reports a change.
35    pub fn reset(&mut self) {
36        self.0 = None;
37    }
38}
39
40/// A value shown as text by a `.yui` binding.
41#[diagnostic::on_unimplemented(
42    message = "`{Self}` can't be shown as text in a .yui binding",
43    note = "bind a value that implements Display, or call a view-model method returning String"
44)]
45pub trait BindText {
46    fn bind_text(&self) -> String;
47}
48
49impl<T: Display + ?Sized> BindText for T {
50    fn bind_text(&self) -> String {
51        self.to_string()
52    }
53}
54
55/// A value used as a color by a `.yui` binding.
56#[diagnostic::on_unimplemented(
57    message = "`{Self}` can't be used as a color in a .yui binding",
58    note = "colors are `Color` or u32 values 0xAARRGGBB (a .yres color, or a view-model method returning one)"
59)]
60pub trait BindColor {
61    fn bind_color(&self) -> Color;
62}
63
64impl BindColor for Color {
65    fn bind_color(&self) -> Color {
66        *self
67    }
68}
69
70impl BindColor for u32 {
71    fn bind_color(&self) -> Color {
72        Color(*self)
73    }
74}
75
76impl<T: BindColor + ?Sized> BindColor for &T {
77    fn bind_color(&self) -> Color {
78        (**self).bind_color()
79    }
80}
81
82/// Text of a bound value.
83pub fn text<T: BindText + ?Sized>(v: &T) -> String {
84    v.bind_text()
85}
86
87/// Color of a bound value.
88pub fn color<T: BindColor>(v: T) -> Color {
89    v.bind_color()
90}
91
92/// A bound flag (`enabled`, `visible`, `checked`).
93pub fn flag(v: impl Into<bool>) -> bool {
94    v.into()
95}
96
97/// A bound size (`w`, `h`).
98pub fn units(v: impl Into<Units>) -> Units {
99    v.into()
100}
101
102/// A bound number (`gap`, `font_scale`, ...).
103pub fn number(v: impl Into<f64>) -> f32 {
104    v.into() as f32
105}
106
107/// A bound count (`count`); out-of-range values become 0.
108pub fn count<T: TryInto<u32>>(v: T) -> u32 {
109    v.try_into().unwrap_or(0)
110}
111
112/// Hash of a bound key (`key`, `scroll_key`) — stable within a process.
113pub fn key<K: Hash + ?Sized>(k: &K) -> u64 {
114    let mut h = std::collections::hash_map::DefaultHasher::new();
115    k.hash(&mut h);
116    h.finish()
117}
118
119/// Whether the item with `key` is the selected one.
120pub fn is_selected<S: PartialEq<K>, K: ?Sized>(selected: &Option<S>, key: &K) -> bool {
121    selected.as_ref().is_some_and(|s| s == key)
122}
123
124/// Sets the placeholder of a text box; `false` for other kinds.
125pub fn set_placeholder(w: &mut Widget, text: &str) -> bool {
126    match &mut w.kind {
127        yog_api::ui::widget::WidgetKind::TextBox(tb) => {
128            tb.placeholder = text.to_owned();
129            true
130        }
131        _ => false,
132    }
133}
134
135/// Sets the item of an item slot / inventory slot; `false` for other kinds.
136pub fn set_item(w: &mut Widget, item: &str) -> bool {
137    use yog_api::ui::widget::WidgetKind;
138    match &mut w.kind {
139        WidgetKind::ItemSlot(id) | WidgetKind::InvSlot { item_id: id, .. } => {
140            *id = item.to_owned();
141            true
142        }
143        _ => false,
144    }
145}
146
147/// Sets the stack count of an inventory slot; `false` for other kinds.
148pub fn set_count(w: &mut Widget, n: u32) -> bool {
149    match &mut w.kind {
150        yog_api::ui::widget::WidgetKind::InvSlot { count, .. } => {
151            *count = n;
152            true
153        }
154        _ => false,
155    }
156}
157
158/// Sets the image source of an image or the id of a surface; `false` for
159/// other kinds.
160pub fn set_source(w: &mut Widget, source: &str) -> bool {
161    use yog_api::ui::widget::WidgetKind;
162    match &mut w.kind {
163        WidgetKind::Image(img) => {
164            img.source = source.to_owned();
165            true
166        }
167        WidgetKind::Surface(id) => {
168            *id = source.to_owned();
169            true
170        }
171        _ => false,
172    }
173}
174
175/// Sets or clears the CHECKED state (inherited by non-interactive children).
176pub fn set_checked(w: &mut Widget, on: bool) {
177    w.set_state_inherited(StateFlags::CHECKED, on);
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn slot_reports_changes_only() {
186        let mut s = Slot::new();
187        assert!(s.set(1));
188        assert!(!s.set(1));
189        assert!(s.set(2));
190        assert_eq!(*s.get(), 2);
191        s.reset();
192        assert!(s.set(2));
193    }
194
195    #[test]
196    fn conversions() {
197        assert_eq!(text(&5), "5");
198        assert_eq!(text("x"), "x");
199        assert_eq!(color(0xFF00FF00u32), Color(0xFF00FF00));
200        let seven: &u32 = &7;
201        assert_eq!(color(seven), Color(7));
202        assert_eq!(count(-1i32), 0);
203        assert_eq!(count(3usize), 3);
204        assert_eq!(key("a"), key(&"a".to_string()));
205        let sel: Option<&str> = Some("b");
206        assert!(is_selected(&sel, &"b".to_string()));
207        assert!(!is_selected(&None::<&str>, &"b".to_string()));
208    }
209}