ferravex_render/ui/
kit.rs

1//! Modern UI kit: cards, buttons, meters, toasts, key caps and screen
2//! transitions drawn with [`crate::shapes`] and the modern text face.
3//!
4//! The kit is **visual only**. Input, focus, hit testing and activation stay in
5//! [`super::Ui`]: submit buttons there with [`INVISIBLE_BUTTON`] (or your own
6//! style), then paint them here with [`ui_button_state`] and [`ui_rect`].
7//! Everything draws in screen units (the default 2D camera), writes straight to
8//! the frame's vertex stream and allocates nothing.
9//!
10//! Recommended style (see `docs/UI.md`, "Modern UI kit"):
11//!
12//! | token        | values                                          |
13//! |--------------|-------------------------------------------------|
14//! | spacing      | [`SPACE`] = 4, 8, 12, 16, 24, 32                |
15//! | radii        | [`RADIUS_SMALL`] 6 (chips), [`RADIUS`] 10 (buttons), [`RADIUS_LARGE`] 16 (cards) |
16//! | type (modern)| [`TYPE_CAPTION`] 8, [`TYPE_BODY`] 16, [`TYPE_TITLE`] 24, [`TYPE_DISPLAY`] 32 |
17//!
18//! Type sizes are multiples of 8 so every font pixel lands on whole screen
19//! pixels. Pair the modern face for copy with the classic face for big
20//! retro numerals or titles when a game wants more attitude.
21//!
22//! ```
23//! use ferravex_render::{Rect, ui::kit::{self, ButtonKind, ButtonMotion, ButtonState, KitTheme}};
24//! use ferravex_play::tween::Motion;
25//! let theme = KitTheme::default();
26//! let content = kit::card(Rect::new(40., 40., 320., 200.), Some("Settings"), &theme);
27//! let mut motion = ButtonMotion::default();
28//! let state = ButtonState { hovered: true, ..ButtonState::default() };
29//! motion.update(state, 1. / 60., Motion::Full);
30//! let button = Rect::new(content.x, content.y, 140., 36.);
31//! kit::button(button, "Resume", ButtonKind::Primary, &motion, &theme);
32//! kit::meter(Rect::new(content.x, content.y + 52., 200., 12.), 0.7, Some(0.85), theme.success, &theme);
33//! ```
34use super::{Ui, UiRect, Viewport, WidgetId};
35use crate::shapes::{self, Fill, Shadow, mix};
36use crate::text::{TextAlign, TextStyle, draw_text_styled, text_width};
37use crate::{Color, Rect, Vec2, vec2};
38use ferravex_play::tween::{Appearance, Motion, Spring, TransitionKind};
39use ferravex_play::ui::theme::{ColorRole, UiTheme};
40
41/// Spacing scale in screen units.
42pub const SPACE: [f32; 6] = [4., 8., 12., 16., 24., 32.];
43/// Corner radius for chips, key caps and small tags.
44pub const RADIUS_SMALL: f32 = 6.;
45/// Corner radius for buttons, fields and toasts.
46pub const RADIUS: f32 = 10.;
47/// Corner radius for cards and dialogs.
48pub const RADIUS_LARGE: f32 = 16.;
49/// Modern-face sizes (multiples of 8 stay pixel-crisp).
50pub const TYPE_CAPTION: f32 = 8.;
51pub const TYPE_BODY: f32 = 16.;
52pub const TYPE_TITLE: f32 = 24.;
53pub const TYPE_DISPLAY: f32 = 32.;
54
55/// Colors and sizes for kit widgets. `alpha` multiplies everything, which is
56/// how fades from [`Appearance`] are applied ([`KitTheme::faded`]).
57///
58/// ```
59/// use ferravex_play::ui::theme::{ThemeMode, UiTheme};
60/// use ferravex_render::ui::kit::KitTheme;
61/// let theme = KitTheme::from_ui_theme(UiTheme::preset(ThemeMode::HighContrast));
62/// assert_eq!(theme.faded(0.5).alpha, 0.5);
63/// ```
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub struct KitTheme {
66    pub backdrop: Color,
67    pub surface: Color,
68    pub raised: Color,
69    pub header: Color,
70    pub ink: Color,
71    pub muted: Color,
72    pub disabled: Color,
73    pub accent: Color,
74    /// Text on an accent fill.
75    pub accent_ink: Color,
76    pub success: Color,
77    pub warning: Color,
78    pub danger: Color,
79    pub focus: Color,
80    pub line: Color,
81    pub shadow: Color,
82    pub radius: f32,
83    /// Modern text size for labels and body copy.
84    pub body: f32,
85    /// Modern text size for titles.
86    pub title: f32,
87    pub alpha: f32,
88}
89
90const fn hex(rgb: u32) -> Color {
91    Color::from_hex(rgb)
92}
93
94impl Default for KitTheme {
95    fn default() -> Self {
96        Self {
97            backdrop: Color::new(0.02, 0.03, 0.06, 0.6),
98            surface: hex(0x1d2436),
99            raised: hex(0x2b3550),
100            header: hex(0x343f5c),
101            ink: hex(0xf2ede3),
102            muted: hex(0x9aa7b8),
103            disabled: hex(0x5d6678),
104            accent: hex(0xf7b553),
105            accent_ink: hex(0x24170a),
106            success: hex(0x7fdc8f),
107            warning: hex(0xffd166),
108            danger: hex(0xff6b6b),
109            focus: hex(0x8fd8ff),
110            line: Color::new(1., 1., 1., 0.09),
111            shadow: Color::new(0., 0., 0., 0.5),
112            radius: RADIUS,
113            body: TYPE_BODY,
114            title: TYPE_TITLE,
115            alpha: 1.,
116        }
117    }
118}
119
120impl KitTheme {
121    /// Maps an accessibility-checked [`UiTheme`] palette onto kit roles.
122    pub fn from_ui_theme(theme: UiTheme) -> Self {
123        let c = |role| theme.color(role);
124        let surface = c(ColorRole::Surface);
125        let lift = |amount| mix(surface, Color::new(1., 1., 1., surface.a), amount);
126        Self {
127            backdrop: Color::new(0., 0., 0., 0.6),
128            surface,
129            raised: lift(0.08),
130            header: lift(0.14),
131            ink: c(ColorRole::Text),
132            muted: c(ColorRole::MutedText),
133            disabled: c(ColorRole::DisabledText),
134            accent: c(ColorRole::Accent),
135            accent_ink: c(ColorRole::Canvas),
136            success: c(ColorRole::Success),
137            warning: c(ColorRole::Warning),
138            danger: c(ColorRole::Danger),
139            focus: c(ColorRole::Focus),
140            line: c(ColorRole::Border),
141            ..Self::default()
142        }
143    }
144    /// Copy with every color's alpha multiplied by `alpha`.
145    pub fn faded(mut self, alpha: f32) -> Self {
146        self.alpha = (self.alpha * alpha).clamp(0., 1.);
147        self
148    }
149    fn c(&self, color: Color) -> Color {
150        Color::new(color.r, color.g, color.b, color.a * self.alpha)
151    }
152    fn text(&self, size: f32, color: Color) -> TextStyle {
153        TextStyle::modern(size, self.c(color))
154    }
155}
156
157/// Screen rectangle of a [`Ui`] layout rectangle.
158///
159/// ```
160/// use ferravex_render::ui::{UiRect, Viewport, kit::ui_rect};
161/// let viewport = Viewport::fit([1280., 720.], [640., 360.], [0.; 4]).unwrap();
162/// let r = ui_rect(viewport, UiRect { min: [10., 20.], size: [100., 30.] });
163/// assert_eq!((r.x, r.y, r.w, r.h), (20., 40., 200., 60.));
164/// ```
165pub fn ui_rect(viewport: Viewport, rect: UiRect) -> Rect {
166    let p = viewport.pixels();
167    let s = viewport.scale();
168    Rect::new(
169        p.min[0] + rect.min[0] * s,
170        p.min[1] + rect.min[1] * s,
171        rect.size[0] * s,
172        rect.size[1] * s,
173    )
174}
175
176/// Moves and scales `rect` about its center per an [`Appearance`].
177///
178/// ```
179/// use ferravex_play::tween::Appearance;
180/// use ferravex_render::{Rect, ui::kit::appear};
181/// let r = appear(Rect::new(0., 0., 100., 50.), Appearance { alpha: 1., offset: [0., 10.], scale: 0.5 });
182/// assert_eq!((r.x, r.y, r.w, r.h), (25., 22.5, 50., 25.));
183/// ```
184pub fn appear(rect: Rect, look: Appearance) -> Rect {
185    let c = rect.center() + vec2(look.offset[0], look.offset[1]);
186    let size = vec2(rect.w, rect.h) * look.scale;
187    Rect::new(c.x - size.x * 0.5, c.y - size.y * 0.5, size.x, size.y)
188}
189
190/// Raised surface: soft shadow, subtle top-lit gradient and a hairline edge.
191///
192/// ```
193/// use ferravex_render::{Rect, ui::kit::{self, KitTheme}};
194/// kit::panel(Rect::new(20., 20., 200., 120.), &KitTheme::default());
195/// ```
196pub fn panel(rect: Rect, theme: &KitTheme) {
197    panel_with_radius(rect, RADIUS_LARGE.max(theme.radius), theme);
198}
199
200fn panel_with_radius(rect: Rect, radius: f32, theme: &KitTheme) {
201    shapes::drop_shadow(
202        rect,
203        radius,
204        Shadow::soft(theme.c(theme.shadow))
205            .offset(vec2(0., 6.))
206            .blur(24.),
207    );
208    let top = mix(theme.surface, theme.raised, 0.6);
209    shapes::fill_rounded_rect(
210        rect,
211        radius,
212        Fill::vertical(rect, theme.c(top), theme.c(theme.surface)),
213    );
214    shapes::stroke_rounded_rect(rect, radius, 1., theme.c(theme.line));
215}
216
217/// [`panel`] with an optional header band and title; returns the content area
218/// inset by the spacing scale.
219///
220/// ```
221/// use ferravex_render::{Rect, ui::kit::{self, KitTheme}};
222/// let inner = kit::card(Rect::new(0., 0., 300., 200.), Some("Loadout"), &KitTheme::default());
223/// assert!(inner.y > 40. && inner.x == 16.);
224/// ```
225pub fn card(rect: Rect, title: Option<&str>, theme: &KitTheme) -> Rect {
226    let radius = RADIUS_LARGE.max(theme.radius);
227    panel_with_radius(rect, radius, theme);
228    let pad = SPACE[3];
229    let Some(title) = title else {
230        return Rect::new(
231            rect.x + pad,
232            rect.y + pad,
233            rect.w - 2. * pad,
234            rect.h - 2. * pad,
235        );
236    };
237    let band = (theme.title * 0.5 + SPACE[4]).min(rect.h);
238    let header = theme.c(theme.header);
239    // Round only the top corners: a rounded band squared off below.
240    let r = radius.min(band);
241    shapes::fill_rounded_rect(Rect::new(rect.x, rect.y, rect.w, band), r, header);
242    shapes::fill_rounded_rect(Rect::new(rect.x, rect.y + band - r, rect.w, r), 0., header);
243    shapes::fill_rounded_rect(
244        Rect::new(rect.x, rect.y + band, rect.w, 1.),
245        0.,
246        theme.c(theme.line),
247    );
248    let style = theme.text(theme.body, theme.ink);
249    draw_text_styled(
250        title,
251        rect.x + pad,
252        style.centered_baseline(rect.y + band * 0.5),
253        style.with_shadow(theme.c(Color::new(0., 0., 0., 0.35))),
254    );
255    let top = rect.y + band + pad;
256    Rect::new(
257        rect.x + pad,
258        top,
259        rect.w - 2. * pad,
260        (rect.y + rect.h - pad - top).max(0.),
261    )
262}
263
264/// Pointer/focus state of a button for one frame.
265#[derive(Clone, Copy, Debug, PartialEq, Eq)]
266pub struct ButtonState {
267    pub hovered: bool,
268    pub pressed: bool,
269    pub focused: bool,
270    pub enabled: bool,
271}
272
273impl Default for ButtonState {
274    fn default() -> Self {
275        Self {
276            hovered: false,
277            pressed: false,
278            focused: false,
279            enabled: true,
280        }
281    }
282}
283
284/// State of a [`Ui`] button `id` after [`Ui::finish`] (hover, pointer capture
285/// and keyboard/gamepad focus), for painting it with the kit.
286///
287/// ```
288/// use ferravex_render::ui::{Ui, kit::ui_button_state};
289/// let ui = Ui::new();
290/// assert!(!ui_button_state(&ui, 7, true).hovered);
291/// ```
292pub fn ui_button_state(ui: &Ui, id: WidgetId, enabled: bool) -> ButtonState {
293    ButtonState {
294        hovered: enabled && ui.hovered() == Some(id),
295        pressed: enabled && ui.interaction().pointer_capture == Some(id),
296        focused: enabled && ui.focused() == Some(id),
297        enabled,
298    }
299}
300
301/// A [`super::ButtonStyle`] whose own paint is fully transparent, for buttons
302/// that keep [`Ui`] input/focus but are drawn by the kit.
303pub const INVISIBLE_BUTTON: super::ButtonStyle = super::ButtonStyle {
304    fill: Color::new(0., 0., 0., 0.),
305    ink: Color::new(0., 0., 0., 0.),
306    focus: Color::new(0., 0., 0., 0.),
307    disabled: Color::new(0., 0., 0., 0.),
308    size: 18.,
309};
310
311/// Eased hover/press/focus amounts for one button (critically damped springs,
312/// so state changes glide without overshoot). Keep one per button.
313///
314/// ```
315/// use ferravex_play::tween::Motion;
316/// use ferravex_render::ui::kit::{ButtonMotion, ButtonState};
317/// let mut m = ButtonMotion::default();
318/// let hover = ButtonState { hovered: true, ..ButtonState::default() };
319/// m.update(hover, 1. / 60., Motion::Full);
320/// assert!(m.hover() > 0. && m.hover() < 1.);
321/// m.update(hover, 1. / 60., Motion::Reduced);
322/// assert_eq!(m.hover(), 1.);
323/// ```
324#[derive(Clone, Copy, Debug, PartialEq)]
325pub struct ButtonMotion {
326    hover: Spring,
327    press: Spring,
328    focus: Spring,
329    enabled: bool,
330}
331
332impl Default for ButtonMotion {
333    fn default() -> Self {
334        Self {
335            hover: Spring::critical(0., 7.),
336            press: Spring::critical(0., 14.),
337            focus: Spring::critical(0., 6.),
338            enabled: true,
339        }
340    }
341}
342
343impl ButtonMotion {
344    pub fn update(&mut self, state: ButtonState, dt: f32, motion: Motion) {
345        let on = |b: bool| if b { 1. } else { 0. };
346        self.enabled = state.enabled;
347        self.hover.set_target(on(state.enabled && state.hovered));
348        self.press.set_target(on(state.enabled && state.pressed));
349        self.focus.set_target(on(state.enabled && state.focused));
350        for spring in [&mut self.hover, &mut self.press, &mut self.focus] {
351            spring.advance(dt, motion);
352        }
353    }
354    /// Snaps all amounts to `state` (e.g. when a menu opens).
355    pub fn snap(&mut self, state: ButtonState) {
356        self.update(state, 0., Motion::Reduced);
357    }
358    pub fn hover(&self) -> f32 {
359        self.hover.value.clamp(0., 1.)
360    }
361    pub fn press(&self) -> f32 {
362        self.press.value.clamp(0., 1.)
363    }
364    pub fn focus(&self) -> f32 {
365        self.focus.value.clamp(0., 1.)
366    }
367}
368
369/// Button emphasis.
370#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
371pub enum ButtonKind {
372    /// Accent fill for the main action.
373    #[default]
374    Primary,
375    /// Raised neutral fill.
376    Secondary,
377    /// Text-only until hovered.
378    Ghost,
379    /// Destructive action.
380    Danger,
381}
382
383/// Paints a button: rounded fill that brightens on hover, sinks and darkens
384/// on press, and an eased focus ring outside the edge. Disabled buttons are
385/// flat and muted. The label is centered in the modern face.
386///
387/// ```
388/// use ferravex_render::{Rect, ui::kit::{self, ButtonKind, ButtonMotion, KitTheme}};
389/// kit::button(Rect::new(20., 20., 160., 40.), "New game", ButtonKind::Primary,
390///     &ButtonMotion::default(), &KitTheme::default());
391/// ```
392pub fn button(rect: Rect, label: &str, kind: ButtonKind, motion: &ButtonMotion, theme: &KitTheme) {
393    button_with(rect, None, label, kind, motion, theme);
394}
395
396/// [`button`] with a pictogram before its label (or alone when `label` is
397/// empty): `[▶ Play]`, `[↻ Retry]`, `[⚙]`. The icon takes the label's ink.
398///
399/// ```
400/// use ferravex_render::{Rect, icons::Icon, ui::kit::{self, ButtonKind, ButtonMotion, KitTheme}};
401/// let theme = KitTheme::default();
402/// kit::button_icon(Rect::new(20., 20., 160., 40.), Icon::Play, "Resume",
403///     ButtonKind::Primary, &ButtonMotion::default(), &theme);
404/// ```
405pub fn button_icon(
406    rect: Rect,
407    icon: crate::icons::Icon,
408    label: &str,
409    kind: ButtonKind,
410    motion: &ButtonMotion,
411    theme: &KitTheme,
412) {
413    button_with(rect, Some(icon), label, kind, motion, theme);
414}
415
416/// The label (and optional icon) centered on `c` in `style`.
417fn button_label(c: Vec2, icon: Option<crate::icons::Icon>, label: &str, style: TextStyle) {
418    let Some(icon) = icon else {
419        draw_text_styled(label, c.x, style.centered_baseline(c.y), style);
420        return;
421    };
422    let size = style.size * 1.1;
423    let gap = if label.is_empty() { 0. } else { SPACE[1] };
424    let left = style.with_align(TextAlign::Left);
425    let w = size
426        + gap
427        + if label.is_empty() {
428            0.
429        } else {
430            text_width(label, left)
431        };
432    let x = c.x - w * 0.5;
433    crate::icons::draw(icon, vec2(x + size * 0.5, c.y), size, style.color);
434    if !label.is_empty() {
435        draw_text_styled(label, x + size + gap, left.centered_baseline(c.y), left);
436    }
437}
438
439fn button_with(
440    rect: Rect,
441    icon: Option<crate::icons::Icon>,
442    label: &str,
443    kind: ButtonKind,
444    motion: &ButtonMotion,
445    theme: &KitTheme,
446) {
447    let (hover, press, focus) = (motion.hover(), motion.press(), motion.focus());
448    let radius = theme.radius.min(rect.h * 0.5);
449    let sink = 2. * press;
450    let r = Rect::new(rect.x, rect.y + sink, rect.w, rect.h);
451    let (base, ink) = match kind {
452        ButtonKind::Primary => (theme.accent, theme.accent_ink),
453        ButtonKind::Secondary => (theme.raised, theme.ink),
454        ButtonKind::Ghost => (
455            Color::new(theme.raised.r, theme.raised.g, theme.raised.b, 0.),
456            theme.ink,
457        ),
458        ButtonKind::Danger => (theme.danger, theme.accent_ink),
459    };
460    if !motion.enabled {
461        shapes::fill_rounded_rect(r, radius, theme.c(mix(theme.surface, theme.raised, 0.5)));
462        shapes::stroke_rounded_rect(r, radius, 1., theme.c(theme.line));
463        let style = theme
464            .text(theme.body, theme.disabled)
465            .with_align(TextAlign::Center);
466        button_label(r.center(), icon, label, style);
467        return;
468    }
469    if kind != ButtonKind::Ghost {
470        shapes::drop_shadow(
471            r,
472            radius,
473            Shadow::soft(theme.c(Color::new(0., 0., 0., 0.35 * (1. - press))))
474                .offset(vec2(0., 3. - sink))
475                .blur(10.),
476        );
477    }
478    let white = Color::new(1., 1., 1., 1.);
479    let lit = |c: Color, k: f32| {
480        let m = mix(c, white, k);
481        Color::new(m.r, m.g, m.b, c.a)
482    };
483    let mut fill = lit(base, 0.12 * hover);
484    if kind == ButtonKind::Ghost {
485        fill.a = 0.9 * hover.max(press);
486    }
487    fill = mix(fill, Color::new(0., 0., 0., fill.a), 0.18 * press);
488    let top = lit(fill, 0.08);
489    shapes::fill_rounded_rect(r, radius, Fill::vertical(r, theme.c(top), theme.c(fill)));
490    shapes::stroke_rounded_rect(
491        r,
492        radius,
493        1.,
494        theme.c(Color::new(1., 1., 1., 0.10 + 0.12 * hover)),
495    );
496    if focus > 0.01 {
497        let grow = 3. + 1. * (1. - focus);
498        let ring = Rect::new(r.x - grow, r.y - grow, r.w + 2. * grow, r.h + 2. * grow);
499        let f = theme.focus;
500        shapes::stroke_rounded_rect(
501            ring,
502            radius + grow,
503            2.,
504            theme.c(Color::new(f.r, f.g, f.b, f.a * focus)),
505        );
506    }
507    let mut style = theme.text(theme.body, ink).with_align(TextAlign::Center);
508    if matches!(kind, ButtonKind::Secondary | ButtonKind::Ghost) {
509        // Light ink on a dark fill reads crisper with a 1 px shadow.
510        style = style.with_shadow(theme.c(Color::new(0., 0., 0., 0.35)));
511    }
512    button_label(r.center(), icon, label, style);
513}
514
515/// Horizontal meter (health, XP, loading): an inset rounded track, a gradient
516/// fill with a top highlight and an optional lighter `ghost` value trailing
517/// behind (show the pre-damage value and tween it down for a "chip" effect).
518/// Values are clamped to `[0, 1]`.
519///
520/// ```
521/// use ferravex_render::{Rect, ui::kit::{self, KitTheme}};
522/// let theme = KitTheme::default();
523/// kit::meter(Rect::new(20., 20., 180., 12.), 0.4, Some(0.65), theme.danger, &theme);
524/// ```
525pub fn meter(rect: Rect, value: f32, ghost: Option<f32>, color: Color, theme: &KitTheme) {
526    let clamp = |v: f32| if v.is_finite() { v.clamp(0., 1.) } else { 0. };
527    let radius = rect.h * 0.5;
528    shapes::fill_rounded_rect(rect, radius, theme.c(Color::new(0., 0., 0., 0.45)));
529    shapes::stroke_rounded_rect(rect, radius, 1., theme.c(Color::new(1., 1., 1., 0.06)));
530    let span = |v: f32| Rect::new(rect.x, rect.y, (rect.w * v).max(rect.h.min(rect.w)), rect.h);
531    if let Some(g) = ghost.map(clamp).filter(|&g| g > clamp(value)) {
532        let r = span(g);
533        shapes::fill_rounded_rect(r, radius, theme.c(Color::new(1., 0.95, 0.85, 0.55)));
534    }
535    let v = clamp(value);
536    if v <= 0. {
537        return;
538    }
539    let r = span(v);
540    let white = Color::new(1., 1., 1., color.a);
541    shapes::fill_rounded_rect(
542        r,
543        radius,
544        Fill::vertical(r, theme.c(mix(color, white, 0.25)), theme.c(color)),
545    );
546    if r.h >= 6. {
547        let gloss = Rect::new(
548            r.x + radius * 0.5,
549            r.y + r.h * 0.2,
550            (r.w - radius).max(0.),
551            r.h * 0.22,
552        );
553        shapes::fill_rounded_rect(gloss, gloss.h * 0.5, theme.c(Color::new(1., 1., 1., 0.22)));
554    }
555}
556
557/// Notification tone for [`toast`].
558#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
559pub enum Tone {
560    #[default]
561    Info,
562    Success,
563    Warning,
564    Danger,
565}
566
567/// A toast centered horizontally on `center_x` with its top at `top`. Pass the
568/// [`Appearance`] from a [`ferravex_play::tween::Entrance`] to slide/fade it.
569/// `icon` is drawn in the tone's color before the text. Returns its rectangle.
570///
571/// ```
572/// use ferravex_play::tween::Appearance;
573/// use ferravex_render::ui::kit::{self, KitTheme, Tone};
574/// let r = kit::toast(640., 24., Some('★'), "Achievement unlocked", Tone::Success,
575///     Appearance::SHOWN, &KitTheme::default());
576/// assert!(r.w > 100.);
577/// ```
578pub fn toast(
579    center_x: f32,
580    top: f32,
581    icon: Option<char>,
582    text: &str,
583    tone: Tone,
584    look: Appearance,
585    theme: &KitTheme,
586) -> Rect {
587    let theme = theme.faded(look.alpha);
588    let tint = match tone {
589        Tone::Info => theme.focus,
590        Tone::Success => theme.success,
591        Tone::Warning => theme.warning,
592        Tone::Danger => theme.danger,
593    };
594    let style = theme.text(theme.body, theme.ink);
595    let mut buffer = [0_u8; 4];
596    let icon_text = icon.map(|c| &*c.encode_utf8(&mut buffer));
597    let icon_w = icon_text.map_or(0., |i| text_width(i, style) + SPACE[1]);
598    let w = icon_w + text_width(text, style) + SPACE[3] * 2. + SPACE[0];
599    let h = theme.body * 1.25 + SPACE[2];
600    let rect = appear(Rect::new(center_x - w * 0.5, top, w, h), look);
601    let radius = rect.h * 0.5;
602    shapes::drop_shadow(
603        rect,
604        radius,
605        Shadow::soft(theme.c(theme.shadow))
606            .offset(vec2(0., 6.))
607            .blur(20.),
608    );
609    shapes::fill_rounded_rect(
610        rect,
611        radius,
612        Fill::vertical(rect, theme.c(theme.raised), theme.c(theme.surface)),
613    );
614    shapes::stroke_rounded_rect(
615        rect,
616        radius,
617        1.,
618        theme.c(Color::new(tint.r, tint.g, tint.b, 0.35)),
619    );
620    let s = rect.w / w.max(1e-3);
621    let style = style.with_size(theme.body * s);
622    let baseline = style.centered_baseline(rect.y + rect.h * 0.5);
623    let mut x = rect.x + (SPACE[3] + SPACE[0]) * s;
624    if let Some(icon) = icon_text {
625        let icon_style = style.with_color(theme.c(tint));
626        draw_text_styled(icon, x, baseline, icon_style);
627        x += icon_w * s;
628    }
629    draw_text_styled(text, x, baseline, style.with_pixel_snap(look.scale == 1.));
630    rect
631}
632
633/// [`toast`] led by a pictogram in the tone's color instead of a font glyph.
634///
635/// ```
636/// use ferravex_play::tween::Appearance;
637/// use ferravex_render::{icons::Icon, ui::kit::{self, KitTheme, Tone}};
638/// let theme = KitTheme::default();
639/// let r = kit::toast_icon(320., 40., Icon::Trophy, "Course record", Tone::Success,
640///     Appearance::SHOWN, &theme);
641/// assert!(r.w > 100.);
642/// ```
643pub fn toast_icon(
644    center_x: f32,
645    top: f32,
646    icon: crate::icons::Icon,
647    text: &str,
648    tone: Tone,
649    look: Appearance,
650    theme: &KitTheme,
651) -> Rect {
652    let theme = theme.faded(look.alpha);
653    let tint = match tone {
654        Tone::Info => theme.focus,
655        Tone::Success => theme.success,
656        Tone::Warning => theme.warning,
657        Tone::Danger => theme.danger,
658    };
659    let style = theme.text(theme.body, theme.ink);
660    let icon_w = theme.body * 1.15 + SPACE[1];
661    let w = icon_w + text_width(text, style) + SPACE[3] * 2. + SPACE[0];
662    let h = theme.body * 1.25 + SPACE[2];
663    let rect = appear(Rect::new(center_x - w * 0.5, top, w, h), look);
664    let radius = rect.h * 0.5;
665    shapes::drop_shadow(
666        rect,
667        radius,
668        Shadow::soft(theme.c(theme.shadow))
669            .offset(vec2(0., 6.))
670            .blur(20.),
671    );
672    shapes::fill_rounded_rect(
673        rect,
674        radius,
675        Fill::vertical(rect, theme.c(theme.raised), theme.c(theme.surface)),
676    );
677    shapes::stroke_rounded_rect(
678        rect,
679        radius,
680        1.,
681        theme.c(Color::new(tint.r, tint.g, tint.b, 0.35)),
682    );
683    let s = rect.w / w.max(1e-3);
684    let style = style.with_size(theme.body * s);
685    let cy = rect.y + rect.h * 0.5;
686    let x = rect.x + (SPACE[3] + SPACE[0]) * s;
687    let size = theme.body * 1.15 * s;
688    crate::icons::draw(icon, vec2(x + size * 0.5, cy), size, theme.c(tint));
689    draw_text_styled(
690        text,
691        x + icon_w * s,
692        style.centered_baseline(cy),
693        style.with_pixel_snap(look.scale == 1.),
694    );
695    rect
696}
697
698/// A keyboard/gamepad key cap (e.g. `"Space"`, `"E"`, `"A"`) with a raised
699/// lip, its top-left at (`x`, `y`). Returns its rectangle so prompts can flow.
700///
701/// ```
702/// use ferravex_render::ui::kit::{self, KitTheme};
703/// let theme = KitTheme::default();
704/// let cap = kit::keycap(20., 20., "E", &theme);
705/// assert!(cap.w >= cap.h - 3.); // single letters stay square-ish
706/// ```
707pub fn keycap(x: f32, y: f32, label: &str, theme: &KitTheme) -> Rect {
708    let style = theme.text(theme.body, theme.ink);
709    let h = theme.body * 1.5 + 2.;
710    let w = (text_width(label, style) + SPACE[2] * 2.).max(h - 3.);
711    let rect = Rect::new(x, y, w, h - 3.);
712    let lip = Rect::new(x, y + 3., w, h - 3.);
713    shapes::fill_rounded_rect(
714        lip,
715        RADIUS_SMALL,
716        theme.c(mix(theme.surface, Color::new(0., 0., 0., 1.), 0.35)),
717    );
718    shapes::fill_rounded_rect(
719        rect,
720        RADIUS_SMALL,
721        Fill::vertical(
722            rect,
723            theme.c(mix(theme.raised, theme.header, 0.7)),
724            theme.c(theme.raised),
725        ),
726    );
727    shapes::stroke_rounded_rect(
728        rect,
729        RADIUS_SMALL,
730        1.,
731        theme.c(Color::new(1., 1., 1., 0.14)),
732    );
733    let c = rect.center();
734    let style = style.with_align(TextAlign::Center);
735    draw_text_styled(label, c.x, style.centered_baseline(c.y), style);
736    Rect::new(x, y, w, h)
737}
738
739/// Key caps followed by an action label, e.g. `[E] Open`. Returns the total width.
740///
741/// ```
742/// use ferravex_render::ui::kit::{self, KitTheme};
743/// let w = kit::key_prompt(20., 20., &["Shift", "Space"], "Dash", &KitTheme::default());
744/// assert!(w > 100.);
745/// ```
746pub fn key_prompt(x: f32, y: f32, keys: &[&str], action: &str, theme: &KitTheme) -> f32 {
747    let mut cursor = x;
748    let mut height: f32 = 0.;
749    for key in keys {
750        let cap = keycap(cursor, y, key, theme);
751        cursor += cap.w + SPACE[0];
752        height = height.max(cap.h);
753    }
754    let style = theme.text(theme.body, theme.muted);
755    let baseline = style.centered_baseline(y + (height - 3.) * 0.5);
756    let w = draw_text_styled(action, cursor + SPACE[0], baseline, style).width;
757    cursor + SPACE[0] + w - x
758}
759
760/// The standard HUD stat: `icon` then `value`, vertically centered on `cy`
761/// and starting at `x` (for example a heart and `12`). `size` is the icon's
762/// box; the value uses the theme's body size scaled to match. Returns the width.
763///
764/// ```
765/// use ferravex_render::{Color, icons::Icon, ui::kit::{self, KitTheme}};
766/// let theme = KitTheme::default();
767/// let w = kit::icon_value(20., 40., Icon::Coin, "158", 20., Color::from_hex(0xf7b553), &theme);
768/// assert!(w > 20.);
769/// ```
770pub fn icon_value(
771    x: f32,
772    cy: f32,
773    icon: crate::icons::Icon,
774    value: &str,
775    size: f32,
776    color: Color,
777    theme: &KitTheme,
778) -> f32 {
779    crate::icons::draw_styled(
780        icon,
781        vec2(x + size * 0.5, cy),
782        size,
783        crate::icons::IconStyle::new(theme.c(color)).shadow(theme.c(theme.shadow)),
784    );
785    if value.is_empty() {
786        return size;
787    }
788    let style = theme
789        .text(size.max(theme.body * 0.75), theme.ink)
790        .with_shadow(theme.c(theme.shadow));
791    let gap = SPACE[1] * size / 20.;
792    let w = draw_text_styled(value, x + size + gap, style.centered_baseline(cy), style).width;
793    size + gap + w
794}
795
796/// A row of progress pips centered on `cy`: pips before `current` (one-based)
797/// are filled, `current` is enlarged with a glow, later ones are hollow.
798/// Totals above 16 draw a compact meter instead. Returns the width.
799///
800/// ```
801/// use ferravex_render::{Color, ui::kit::{self, KitTheme}};
802/// let w = kit::pips(20., 40., 3, 6, Color::from_hex(0x8fd16a), &KitTheme::default());
803/// assert!(w > 50.);
804/// ```
805pub fn pips(x: f32, cy: f32, current: u32, total: u32, color: Color, theme: &KitTheme) -> f32 {
806    if total == 0 {
807        return 0.;
808    }
809    if total > 16 {
810        let w = 96.;
811        let f = current.min(total) as f32 / total as f32;
812        meter(Rect::new(x, cy - 3., w, 6.), f, None, color, theme);
813        return w;
814    }
815    let gap = 13.;
816    for i in 0..total {
817        let at = vec2(x + 5. + i as f32 * gap, cy);
818        let index = i + 1;
819        if index < current {
820            shapes::fill_circle(at, 4., theme.c(color));
821        } else if index == current {
822            shapes::glow_disc(
823                at,
824                11.,
825                theme.c(Color::new(color.r, color.g, color.b, 0.35)),
826            );
827            shapes::fill_circle(
828                at,
829                5.,
830                theme.c(mix(color, Color::new(1., 1., 1., 1.), 0.25)),
831            );
832        } else {
833            shapes::stroke_circle(
834                at,
835                3.5,
836                1.5,
837                theme.c(Color::new(color.r, color.g, color.b, 0.45)),
838            );
839        }
840    }
841    10. + (total - 1) as f32 * gap
842}
843
844/// Circular progress: a faint track and a bright arc clockwise from 12
845/// o'clock covering `fraction` (timers, cooldowns, charge).
846///
847/// ```
848/// use ferravex_render::{Color, vec2, ui::kit::{self, KitTheme}};
849/// kit::ring_meter(vec2(40., 40.), 14., 4., 0.65, Color::from_hex(0x5bd5d8), &KitTheme::default());
850/// ```
851pub fn ring_meter(
852    center: Vec2,
853    radius: f32,
854    width: f32,
855    fraction: f32,
856    color: Color,
857    theme: &KitTheme,
858) {
859    let f = if fraction.is_finite() {
860        fraction.clamp(0., 1.)
861    } else {
862        0.
863    };
864    shapes::stroke_circle(center, radius, width, theme.c(theme.line));
865    if f > 0. {
866        shapes::stroke_arc(
867            center,
868            radius,
869            -std::f32::consts::FRAC_PI_2,
870            f * std::f32::consts::TAU,
871            shapes::Stroke::new(width, theme.c(color)).cap(shapes::Cap::Round),
872        );
873    }
874}
875
876/// Width of [`keycap`] for `label` without drawing it, for laying out rows.
877///
878/// ```
879/// use ferravex_render::ui::kit::{self, KitTheme};
880/// let theme = KitTheme::default();
881/// assert!(kit::keycap_width("Space", &theme) > kit::keycap_width("E", &theme));
882/// ```
883pub fn keycap_width(label: &str, theme: &KitTheme) -> f32 {
884    let style = theme.text(theme.body, theme.ink);
885    let h = theme.body * 1.5 + 2.;
886    (text_width(label, style) + SPACE[2] * 2.).max(h - 3.)
887}
888
889/// One piece of a [`row`]: the vocabulary of an icon-first HUD line.
890#[derive(Clone, Copy, Debug, PartialEq)]
891pub enum RowItem<'a> {
892    /// A pictogram in a `size` box.
893    Icon(crate::icons::Icon, f32, Color),
894    /// Modern-face text at `size`.
895    Text(&'a str, f32, Color),
896    /// A key cap such as `E` or `Space`.
897    Key(&'a str),
898    /// Progress pips: `(current, total, color)`, see [`pips`].
899    Pips(u32, u32, Color),
900    /// Extra horizontal space.
901    Gap(f32),
902}
903
904impl RowItem<'_> {
905    fn width(&self, theme: &KitTheme) -> f32 {
906        match *self {
907            RowItem::Icon(_, size, _) => size,
908            RowItem::Text(text, size, color) => text_width(text, theme.text(size, color)),
909            RowItem::Key(label) => keycap_width(label, theme),
910            RowItem::Pips(_, total, _) if total > 16 => 96.,
911            RowItem::Pips(_, 0, _) => 0.,
912            RowItem::Pips(_, total, _) => 10. + (total - 1) as f32 * 13.,
913            RowItem::Gap(w) => w,
914        }
915    }
916}
917
918/// Width of [`row`] for `items` without drawing, for centering and fitting.
919pub fn row_width(items: &[RowItem], theme: &KitTheme) -> f32 {
920    let gaps = items.len().saturating_sub(1) as f32 * SPACE[1];
921    items.iter().map(|item| item.width(theme)).sum::<f32>() + gaps
922}
923
924/// Lay out `items` left to right from `x`, vertically centered on `cy`, with
925/// an 8-unit gap between pieces; returns the width. This is the standard
926/// icon-first HUD line (`[E] gem 3/6 ●●○`), shared so games don't each
927/// rebuild it.
928///
929/// ```
930/// use ferravex_render::{Color, icons::Icon, ui::kit::{self, KitTheme, RowItem}};
931/// let theme = KitTheme::default();
932/// let gold = Color::from_hex(0xf7b553);
933/// let items = [RowItem::Key("E"), RowItem::Icon(Icon::Gem, 18., gold),
934///     RowItem::Text("3", 16., gold), RowItem::Pips(3, 6, gold)];
935/// let w = kit::row(40., 40., &items, &theme);
936/// assert!((w - kit::row_width(&items, &theme)).abs() < 0.5);
937/// ```
938pub fn row(x: f32, cy: f32, items: &[RowItem], theme: &KitTheme) -> f32 {
939    let mut cursor = x;
940    for (i, item) in items.iter().enumerate() {
941        if i > 0 {
942            cursor += SPACE[1];
943        }
944        let w = item.width(theme);
945        match *item {
946            RowItem::Icon(icon, size, color) => {
947                crate::icons::draw(icon, vec2(cursor + size * 0.5, cy), size, theme.c(color));
948            }
949            RowItem::Text(text, size, color) => {
950                let style = theme.text(size, color);
951                draw_text_styled(text, cursor, style.centered_baseline(cy), style);
952            }
953            RowItem::Key(label) => {
954                let h = theme.body * 1.5 + 2.;
955                keycap(cursor, cy - (h - 3.) * 0.5, label, theme);
956            }
957            RowItem::Pips(current, total, color) => {
958                pips(cursor, cy, current, total, color, theme);
959            }
960            RowItem::Gap(_) => {}
961        }
962        cursor += w;
963    }
964    cursor - x
965}
966
967/// Draws a full-screen scene transition at `coverage` (0 clear … 1 covered)
968/// in `color`. Wipes have a soft leading edge; the iris closes on `focus`
969/// (screen units). Use `ScreenTransition::kind(motion)` so reduced motion fades.
970///
971/// ```
972/// use ferravex_play::tween::TransitionKind;
973/// use ferravex_render::{Color, vec2, ui::kit};
974/// kit::draw_screen_transition(TransitionKind::Iris, 0.5, Color::new(0., 0., 0., 1.), vec2(640., 360.));
975/// ```
976pub fn draw_screen_transition(kind: TransitionKind, coverage: f32, color: Color, focus: Vec2) {
977    let t = if coverage.is_finite() {
978        coverage.clamp(0., 1.)
979    } else {
980        0.
981    };
982    if t <= 0. {
983        return;
984    }
985    let (w, h) = (crate::screen_width(), crate::screen_height());
986    let screen = Rect::new(0., 0., w, h);
987    match kind {
988        TransitionKind::Fade => {
989            shapes::fill_rounded_rect(
990                screen,
991                0.,
992                Color::new(color.r, color.g, color.b, color.a * t),
993            );
994        }
995        _ if t >= 1. => shapes::fill_rounded_rect(screen, 0., color),
996        TransitionKind::Wipe { direction } => {
997            let d = vec2(direction.cos(), direction.sin());
998            let d = if d.is_finite() { d } else { Vec2::X };
999            let center = vec2(w, h) * 0.5;
1000            let half = (w * w + h * h).sqrt() * 0.5 + 2.;
1001            let soft = 0.12 * half;
1002            // Leading edge travels from -half to half + soft.
1003            let edge = -half + t * (2. * half + soft);
1004            crate::edit(|s| {
1005                let mut sink = shapes::Sink::new(s);
1006                let p = d.perp() * half;
1007                let at = |a: f32| center + d * a;
1008                let clear = Color::new(color.r, color.g, color.b, 0.);
1009                let solid_end = (edge - soft).max(-half);
1010                if solid_end > -half {
1011                    let (a, b) = (at(-half), at(solid_end));
1012                    sink.tri(a - p, color, b - p, color, a + p, color);
1013                    sink.tri(a + p, color, b - p, color, b + p, color);
1014                }
1015                let (a, b) = (at(solid_end), at(edge));
1016                sink.tri(a - p, color, b - p, clear, a + p, color);
1017                sink.tri(a + p, color, b - p, clear, b + p, clear);
1018            });
1019        }
1020        TransitionKind::Iris => {
1021            let reach = [vec2(0., 0.), vec2(w, 0.), vec2(0., h), vec2(w, h)]
1022                .iter()
1023                .map(|c| (*c - focus).length())
1024                .fold(0., f32::max)
1025                + 2.;
1026            let inner = reach * (1. - t);
1027            let outer = reach + 4.;
1028            if inner < 0.5 {
1029                return shapes::fill_rounded_rect(screen, 0., color);
1030            }
1031            // The ring's outer radius reaches past the farthest screen corner.
1032            shapes::stroke_circle(focus, (inner + outer) * 0.5, outer - inner, color);
1033        }
1034    }
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039    use super::*;
1040    use crate::shapes::tests::capture;
1041    use ferravex_play::tween::Entrance;
1042
1043    #[test]
1044    fn kit_widgets_draw_bounded_finite_geometry() {
1045        let theme = KitTheme::default();
1046        let v = capture(1280, 720, || {
1047            let inner = card(Rect::new(40., 40., 400., 300.), Some("Settings"), &theme);
1048            assert!(inner.w > 0. && inner.h > 0.);
1049            let mut m = ButtonMotion::default();
1050            m.update(
1051                ButtonState {
1052                    hovered: true,
1053                    focused: true,
1054                    ..Default::default()
1055                },
1056                0.1,
1057                Motion::Full,
1058            );
1059            for kind in [
1060                ButtonKind::Primary,
1061                ButtonKind::Secondary,
1062                ButtonKind::Ghost,
1063                ButtonKind::Danger,
1064            ] {
1065                button(Rect::new(60., 100., 160., 40.), "Play", kind, &m, &theme);
1066            }
1067            m.update(
1068                ButtonState {
1069                    enabled: false,
1070                    ..Default::default()
1071                },
1072                0.1,
1073                Motion::Full,
1074            );
1075            button(
1076                Rect::new(60., 160., 160., 40.),
1077                "Locked",
1078                ButtonKind::Primary,
1079                &m,
1080                &theme,
1081            );
1082            meter(
1083                Rect::new(60., 220., 200., 12.),
1084                0.3,
1085                Some(0.6),
1086                theme.success,
1087                &theme,
1088            );
1089            meter(
1090                Rect::new(60., 240., 200., 12.),
1091                f32::NAN,
1092                None,
1093                theme.success,
1094                &theme,
1095            );
1096            toast(
1097                640.,
1098                20.,
1099                Some('★'),
1100                "Saved",
1101                Tone::Success,
1102                Entrance::fade_up(10.).sample(0.05, 0, Motion::Full),
1103                &theme,
1104            );
1105            key_prompt(60., 300., &["E"], "Open", &theme);
1106        });
1107        assert!(!v.is_empty());
1108        assert!(v.iter().flatten().all(|x| x.is_finite()));
1109        assert!(v.len() < 40_000, "{}", v.len());
1110    }
1111
1112    #[test]
1113    fn transitions_cover_the_screen_monotonically() {
1114        use crate::specimen::rasterize;
1115        for kind in [
1116            TransitionKind::Fade,
1117            TransitionKind::Wipe { direction: 0.3 },
1118            TransitionKind::Iris,
1119        ] {
1120            let mut previous = -1.;
1121            for step in 0..=4 {
1122                let t = step as f32 / 4.;
1123                capture(64, 48, || {
1124                    draw_screen_transition(kind, t, Color::new(1., 1., 1., 1.), vec2(20., 20.))
1125                });
1126                let image = rasterize(64, 48, [0.; 3]);
1127                let covered: f32 = image.iter().map(|p| p[0]).sum::<f32>() / image.len() as f32;
1128                assert!(
1129                    covered >= previous - 1e-3,
1130                    "{kind:?} at {t}: {covered} < {previous}"
1131                );
1132                if step == 0 {
1133                    assert_eq!(covered, 0.);
1134                }
1135                if step == 4 {
1136                    assert!(covered > 0.999, "{kind:?} fully covers: {covered}");
1137                }
1138                previous = covered;
1139            }
1140        }
1141    }
1142
1143    #[test]
1144    fn ui_rect_and_button_state_follow_the_shared_ui() {
1145        let viewport = Viewport::fit([800., 600.], [400., 300.], [0.; 4]).unwrap();
1146        let r = ui_rect(
1147            viewport,
1148            UiRect {
1149                min: [0., 0.],
1150                size: [400., 300.],
1151            },
1152        );
1153        assert_eq!((r.w, r.h), (800., 600.));
1154        let ui = Ui::new();
1155        assert_eq!(
1156            ui_button_state(&ui, 1, false),
1157            ButtonState {
1158                enabled: false,
1159                ..Default::default()
1160            }
1161        );
1162    }
1163}