ferravex_play/ui/theme.rs
1//! Opt-in, caller-owned UI tokens in logical screen pixels, before viewport/DPR
2//! projection. No game palette, renderer default, global state, input, motion or
3//! flash preference is changed. Rebuild measured layout and share its rectangles
4//! with paint/hits after changing tokens; wrap, scroll or report overflow rather
5//! than reducing essential text. A fitted viewport can still scale these units;
6//! use a responsive viewport when readable pixel-sized UI is intended.
7//!
8//! Palette RGB is **unpremultiplied, normalized sRGB encoded** and opaque. These
9//! are foreground roles on Canvas/Surface, not arbitrary fills behind text.
10//! Measurements decode via `ferravex_math::Color::try_srgb_to_linear`, then use
11//! linear-light relative luminance. They describe an ideal sRGB color pair,
12//! not physical-display accessibility, glyph legibility or renderer blending.
13//! Transparency is rejected by tokens/opaque measurements. [`contrast_on`]
14//! explicitly composites in linear light over a supplied opaque backdrop; a
15//! renderer blending encoded channels can produce a different result.
16//!
17//! ```
18//! use ferravex_math::Color;
19//! use ferravex_play::ui::theme::*;
20//! let mut theme = UiTheme::preset(ThemeMode::Normal); // Explicit adoption.
21//! theme.set_colors(&[(ColorRole::Accent, Color::from_hex(0xffdb80))])?;
22//! assert_eq!(theme.text(TextRole::Body).size, 18.);
23//! assert!(theme.role_contrast(ColorRole::Accent, ColorRole::Surface)? >= 4.5);
24//! // Enlarge by author/user choice, never by available layout width.
25//! let types = theme.types().try_scaled(1.5)?;
26//! let spacing = Spacing { control_height: 56., ..theme.spacing() };
27//! theme.set_metrics(types, spacing)?;
28//! assert_eq!(theme.text(TextRole::Body).size, 27.);
29//! assert_eq!(theme.state(ThemeState::Warning).cue.label, "WARNING");
30//! theme = UiTheme::preset(ThemeMode::HighContrast); // Explicit reset/replacement.
31//! assert_eq!(theme.types().body, 18.);
32//! # Ok::<(), ThemeError>(())
33//! ```
34//!
35//! Renderer mapping (the executed task290 receipt recipe supplies full code):
36//! map [`TextTokens`] into `TextStyle` size/color; `StatRowsStyle` accepts those
37//! styles and spacing gaps. For ordinary retained `ButtonStyle`, use Surface for
38//! both fill/disabled fill, Text for ink, Focus for the outline, and body size.
39//! Supply an explicit unavailable label/shape; the renderer does not draw token
40//! cues automatically. A meter can compose Surface track, semantic foreground
41//! fill, and a separate Text value plus labeled tick/shape cues, sharing pure
42//! rectangles with custom software hosts. Text ON a semantic fill needs a
43//! separate pair check, since roles are validated on Canvas/Surface only.
44//!
45//! Current task277 `CardLayout::new(bounds, content)` has no style argument:
46//! title 24/body/stat/action 18, padding 16/gap 12/action gap 8/height 44, PANEL,
47//! default TextStyle and ButtonStyle remain fixed. Passing tokens to that API
48//! does not theme it. Compose panels/wrapped text/stats/buttons via `Ui::compose`
49//! for explicit themed cards/inspectors; parent may later add an additive card
50//! style seam. Button padding/focus stroke are also renderer-fixed.
51
52use ferravex_math::Color;
53
54/// RGB units for measurement, never inferred from [`Color`]. Alpha is linear
55/// coverage in either encoding. All RGBA channels must be in `0..=1`.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum RgbEncoding {
58 Srgb,
59 LinearSrgb,
60}
61
62/// Opt-in presets/contrast policies. Neither changes existing UI defaults.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum ThemeMode {
65 Normal,
66 HighContrast,
67}
68
69/// Order for [`Palette::try_new_srgb`]. All roles except Canvas/Surface are
70/// foregrounds on BOTH backgrounds. Focus/Border are non-text marks; all other
71/// foreground roles must satisfy the small-text threshold.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73#[repr(usize)]
74pub enum ColorRole {
75 Canvas,
76 Surface,
77 Text,
78 MutedText,
79 Accent,
80 Success,
81 Warning,
82 Danger,
83 Focus,
84 Border,
85 DisabledText,
86}
87
88/// Fixed palette capacity; no growing registry or heap storage.
89pub const COLOR_ROLE_COUNT: usize = 11;
90
91impl ColorRole {
92 pub const ALL: [Self; COLOR_ROLE_COUNT] = [
93 Self::Canvas,
94 Self::Surface,
95 Self::Text,
96 Self::MutedText,
97 Self::Accent,
98 Self::Success,
99 Self::Warning,
100 Self::Danger,
101 Self::Focus,
102 Self::Border,
103 Self::DisabledText,
104 ];
105}
106
107/// Rejection before theme mutation. Contrast reports the first failed pair in
108/// role order. Ratios are unitless; colors are never silently clipped/repaired.
109#[derive(Clone, Copy, Debug, PartialEq)]
110pub enum ThemeError {
111 InvalidTypeScale,
112 InvalidSpacing,
113 NonFiniteColor,
114 ColorOutOfRange,
115 AlphaRequiresBackdrop,
116 Capacity,
117 DuplicateRole,
118 Contrast {
119 foreground: ColorRole,
120 background: ColorRole,
121 measured: f64,
122 required: f64,
123 },
124}
125impl std::fmt::Display for ThemeError {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 write!(f, "UI theme: {self:?}")
128 }
129}
130impl std::error::Error for ThemeError {}
131
132fn linear(color: Color, encoding: RgbEncoding) -> Result<Color, ThemeError> {
133 if !color.is_finite() {
134 return Err(ThemeError::NonFiniteColor);
135 }
136 if !color
137 .to_array()
138 .into_iter()
139 .all(|v| (0. ..=1.).contains(&v))
140 {
141 return Err(ThemeError::ColorOutOfRange);
142 }
143 match encoding {
144 RgbEncoding::Srgb => color
145 .try_srgb_to_linear()
146 .map_err(|_| ThemeError::NonFiniteColor),
147 RgbEncoding::LinearSrgb => Ok(color),
148 }
149}
150fn opaque(color: Color) -> Result<(), ThemeError> {
151 if color.a != 1. {
152 return Err(ThemeError::AlphaRequiresBackdrop);
153 }
154 Ok(())
155}
156fn luminance(color: Color) -> f64 {
157 0.2126 * f64::from(color.r) + 0.7152 * f64::from(color.g) + 0.0722 * f64::from(color.b)
158}
159fn ratio(a: Color, b: Color) -> f64 {
160 let a = luminance(a);
161 let b = luminance(b);
162 (a.max(b) + 0.05) / (a.min(b) + 0.05)
163}
164
165/// Relative luminance `0..=1` of opaque normalized RGB in the stated units.
166/// Linear input is not decoded a second time.
167///
168/// ```
169/// use ferravex_math::Color;
170/// use ferravex_play::ui::theme::{relative_luminance, RgbEncoding};
171/// let gray = Color::from_hex(0x808080);
172/// let a = relative_luminance(gray, RgbEncoding::Srgb)?;
173/// let b = relative_luminance(gray.try_srgb_to_linear()?, RgbEncoding::LinearSrgb)?;
174/// assert!((a - 0.21586).abs() < 0.00001);
175/// assert_eq!(a, b);
176/// # Ok::<(), Box<dyn std::error::Error>>(())
177/// ```
178pub fn relative_luminance(color: Color, encoding: RgbEncoding) -> Result<f64, ThemeError> {
179 let color = linear(color, encoding)?;
180 opaque(color)?;
181 Ok(luminance(color))
182}
183
184/// Symmetric ratio `1..=21` for two opaque colors in the same stated units.
185/// Transparent inputs require [`contrast_on`], not an assumed black backdrop.
186///
187/// ```
188/// use ferravex_math::Color;
189/// use ferravex_play::ui::theme::{contrast_ratio, RgbEncoding};
190/// assert_eq!(contrast_ratio(Color::from_hex(0), Color::from_hex(0xffffff),
191/// RgbEncoding::Srgb)?, 21.);
192/// # Ok::<(), ferravex_play::ui::theme::ThemeError>(())
193/// ```
194pub fn contrast_ratio(a: Color, b: Color, encoding: RgbEncoding) -> Result<f64, ThemeError> {
195 let a = linear(a, encoding)?;
196 let b = linear(b, encoding)?;
197 opaque(a)?;
198 opaque(b)?;
199 Ok(ratio(a, b))
200}
201
202/// Decode all colors in the stated units; source-over background onto opaque
203/// backdrop, then foreground onto that result, **in linear light**. Return
204/// foreground-result versus background-result contrast. No premultiplied/HDR,
205/// encoded-channel blending, unknown-backdrop or physical-display claim.
206///
207/// ```
208/// use ferravex_math::Color;
209/// use ferravex_play::ui::theme::{contrast_on, RgbEncoding};
210/// let black = Color::from_hex(0);
211/// assert!((contrast_on(Color::new(1., 1., 1., 0.5), black, black,
212/// RgbEncoding::Srgb)? - 11.).abs() < 1e-6);
213/// # Ok::<(), ferravex_play::ui::theme::ThemeError>(())
214/// ```
215pub fn contrast_on(
216 foreground: Color,
217 background: Color,
218 backdrop: Color,
219 encoding: RgbEncoding,
220) -> Result<f64, ThemeError> {
221 let fg = linear(foreground, encoding)?;
222 let bg = linear(background, encoding)?;
223 let backdrop = linear(backdrop, encoding)?;
224 opaque(backdrop)?;
225 fn over(a: Color, b: Color) -> Color {
226 let blend = |a_rgb: f32, b_rgb: f32| {
227 (f64::from(a_rgb) * f64::from(a.a) + f64::from(b_rgb) * (1. - f64::from(a.a))) as f32
228 };
229 Color::new(blend(a.r, b.r), blend(a.g, b.g), blend(a.b, b.b), 1.)
230 }
231 let bg = over(bg, backdrop);
232 Ok(ratio(over(fg, bg), bg))
233}
234
235/// Essential label/body/heading sizes in logical pixels, each `16..=256`, with
236/// `label <= body <= heading`. Raw authoring value; checked on theme adoption.
237#[derive(Clone, Copy, Debug, PartialEq)]
238pub struct TypeScale {
239 pub label: f32,
240 pub body: f32,
241 pub heading: f32,
242}
243impl TypeScale {
244 fn validate(self) -> Result<(), ThemeError> {
245 if ![self.label, self.body, self.heading]
246 .into_iter()
247 .all(|v| v.is_finite() && (16. ..=256.).contains(&v))
248 || self.label > self.body
249 || self.body > self.heading
250 {
251 return Err(ThemeError::InvalidTypeScale);
252 }
253 Ok(())
254 }
255 /// Explicit enlargement by finite factor >= 1. Reject overflow/size cap;
256 /// never clamp or shrink to fit. See the module's executable theme recipe.
257 pub fn try_scaled(self, factor: f32) -> Result<Self, ThemeError> {
258 self.validate()?;
259 if !factor.is_finite() || factor < 1. {
260 return Err(ThemeError::InvalidTypeScale);
261 }
262 let scaled = Self {
263 label: self.label * factor,
264 body: self.body * factor,
265 heading: self.heading * factor,
266 };
267 scaled.validate()?;
268 Ok(scaled)
269 }
270}
271
272/// Raw logical metrics. Gaps/inset `0..=4096`, stroke `1..=64`, control height
273/// `44..=4096` and at least body + 2 * compact_gap. A minimum layout request,
274/// not a text measurement/fit guarantee. Reflow/overflow remains consumer-owned.
275#[derive(Clone, Copy, Debug, PartialEq)]
276pub struct Spacing {
277 pub inset: f32,
278 pub gap: f32,
279 pub compact_gap: f32,
280 pub control_height: f32,
281 pub stroke: f32,
282}
283impl Spacing {
284 fn validate(self, types: TypeScale) -> Result<(), ThemeError> {
285 if ![self.inset, self.gap, self.compact_gap]
286 .into_iter()
287 .all(|v| v.is_finite() && (0. ..=4096.).contains(&v))
288 || !self.stroke.is_finite()
289 || !(1. ..=64.).contains(&self.stroke)
290 || !self.control_height.is_finite()
291 || !(44. ..=4096.).contains(&self.control_height)
292 || self.control_height < types.body + 2. * self.compact_gap
293 {
294 return Err(ThemeError::InvalidSpacing);
295 }
296 Ok(())
297 }
298}
299
300/// Opaque normalized sRGB in [`ColorRole::ALL`] order. Private storage preserves
301/// channel/alpha validation. A palette alone has no contrast policy;
302/// [`UiTheme::try_new`] checks required pairs before adoption.
303#[derive(Clone, Copy, Debug, PartialEq)]
304pub struct Palette {
305 colors: [Color; COLOR_ROLE_COUNT],
306}
307impl Palette {
308 /// Author a full palette without silently converting/clipping channels.
309 ///
310 /// ```
311 /// use ferravex_play::ui::theme::*;
312 /// let base = UiTheme::preset(ThemeMode::Normal);
313 /// let colors = ColorRole::ALL.map(|r| base.color(r));
314 /// let palette = Palette::try_new_srgb(colors)?;
315 /// let custom = UiTheme::try_new(base.mode(), base.types(), base.spacing(), palette)?;
316 /// assert_eq!(custom, base);
317 /// # Ok::<(), ThemeError>(())
318 /// ```
319 pub fn try_new_srgb(colors: [Color; COLOR_ROLE_COUNT]) -> Result<Self, ThemeError> {
320 for color in colors {
321 linear(color, RgbEncoding::Srgb)?;
322 opaque(color)?;
323 }
324 Ok(Self { colors })
325 }
326 pub fn color(self, role: ColorRole) -> Color {
327 self.colors[role as usize]
328 }
329}
330
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub enum TextRole {
333 Label,
334 Body,
335 Heading,
336}
337
338/// Renderer-independent text inputs, on Canvas/Surface.
339#[derive(Clone, Copy, Debug, PartialEq)]
340pub struct TextTokens {
341 pub size: f32,
342 pub color: Color,
343}
344
345/// Supplemental shape guidance; consumers draw it, not this pure module.
346#[derive(Clone, Copy, Debug, PartialEq, Eq)]
347pub enum CueShape {
348 None,
349 Check,
350 Outline,
351 Cross,
352 Triangle,
353 Octagon,
354}
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
356pub enum CuePattern {
357 Solid,
358 DoubleOutline,
359 Hatch,
360 Dots,
361}
362#[derive(Clone, Copy, Debug, PartialEq, Eq)]
363pub enum ThemeState {
364 Neutral,
365 Selected,
366 Focused,
367 Disabled,
368 Success,
369 Warning,
370 Error,
371}
372
373/// Render a descriptive localizable label (replace this English fallback when
374/// needed) AND a visible shape/pattern; never convey a state only by hue. Static
375/// cues require no flash/motion and have no input/remapping semantics.
376#[derive(Clone, Copy, Debug, PartialEq, Eq)]
377pub struct StateCue {
378 pub label: &'static str,
379 pub shape: CueShape,
380 pub pattern: CuePattern,
381}
382#[derive(Clone, Copy, Debug, PartialEq)]
383pub struct StateTokens {
384 pub foreground: Color,
385 pub cue: StateCue,
386}
387
388/// Validated metrics/palette with checked atomic edits. Fixed value storage;
389/// create/copy/reset per consumer, with no retained history or heap allocation.
390#[derive(Clone, Copy, Debug, PartialEq)]
391pub struct UiTheme {
392 mode: ThemeMode,
393 types: TypeScale,
394 spacing: Spacing,
395 palette: Palette,
396}
397impl UiTheme {
398 /// Explicit authored presets: label 16/body 18/heading 24, inset 16/gap 12/
399 /// compact gap 8/control height 44/stroke 2 in BOTH modes. Normal text roles
400 /// require 4.5:1, high-contrast text roles 7:1; Focus/Border require 3:1 and
401 /// 4.5:1 respectively on Canvas and Surface independently. These thresholds
402 /// are token policy, not whole-renderer conformance/physical readability.
403 pub fn preset(mode: ThemeMode) -> Self {
404 let hex = match mode {
405 ThemeMode::Normal => [
406 0x101820, 0x182430, 0xf4f7fa, 0xbfc9d2, 0xffdb80, 0x94e0ac, 0xffdb80, 0xffa6b2,
407 0x80ddff, 0x92a4b5, 0xbfc9d2,
408 ],
409 ThemeMode::HighContrast => [
410 0x000000, 0x000000, 0xffffff, 0xe0e0e0, 0xffff00, 0x80ff80, 0xffff00, 0xffa6b2,
411 0x00ffff, 0xffffff, 0xe0e0e0,
412 ],
413 };
414 Self {
415 mode,
416 types: TypeScale {
417 label: 16.,
418 body: 18.,
419 heading: 24.,
420 },
421 spacing: Spacing {
422 inset: 16.,
423 gap: 12.,
424 compact_gap: 8.,
425 control_height: 44.,
426 stroke: 2.,
427 },
428 palette: Palette {
429 colors: hex.map(Color::from_hex),
430 },
431 }
432 }
433 /// Validate a complete authored choice; see [`Palette`]'s executable example.
434 pub fn try_new(
435 mode: ThemeMode,
436 types: TypeScale,
437 spacing: Spacing,
438 palette: Palette,
439 ) -> Result<Self, ThemeError> {
440 types.validate()?;
441 spacing.validate(types)?;
442 let theme = Self {
443 mode,
444 types,
445 spacing,
446 palette,
447 };
448 theme.validate_contrast()?;
449 Ok(theme)
450 }
451 pub fn mode(self) -> ThemeMode {
452 self.mode
453 }
454 pub fn types(self) -> TypeScale {
455 self.types
456 }
457 pub fn spacing(self) -> Spacing {
458 self.spacing
459 }
460 pub fn palette(self) -> Palette {
461 self.palette
462 }
463 pub fn color(self, role: ColorRole) -> Color {
464 self.palette.color(role)
465 }
466
467 /// Inspect any actual token pair, including pairs outside required roles.
468 /// This measures, rather than makes the pair pass policy.
469 pub fn role_contrast(self, a: ColorRole, b: ColorRole) -> Result<f64, ThemeError> {
470 contrast_ratio(self.color(a), self.color(b), RgbEncoding::Srgb)
471 }
472 fn validate_contrast(self) -> Result<(), ThemeError> {
473 for foreground in ColorRole::ALL.into_iter().skip(2) {
474 let required = match (self.mode, foreground) {
475 (ThemeMode::Normal, ColorRole::Focus | ColorRole::Border) => 3.,
476 (ThemeMode::Normal, _) => 4.5,
477 (ThemeMode::HighContrast, ColorRole::Focus | ColorRole::Border) => 4.5,
478 (ThemeMode::HighContrast, _) => 7.,
479 };
480 for background in [ColorRole::Canvas, ColorRole::Surface] {
481 let measured = self.role_contrast(foreground, background)?;
482 if measured < required {
483 return Err(ThemeError::Contrast {
484 foreground,
485 background,
486 measured,
487 required,
488 });
489 }
490 }
491 }
492 Ok(())
493 }
494 /// Override at most [`COLOR_ROLE_COUNT`] distinct roles. Related background/
495 /// foreground edits may be adopted together. Duplicate/capacity/color/pair
496 /// failure leaves self intact; empty edits succeed unchanged. See module recipe.
497 pub fn set_colors(&mut self, edits: &[(ColorRole, Color)]) -> Result<(), ThemeError> {
498 if edits.len() > COLOR_ROLE_COUNT {
499 return Err(ThemeError::Capacity);
500 }
501 let mut candidate = *self;
502 let mut seen = [false; COLOR_ROLE_COUNT];
503 for &(role, color) in edits {
504 if seen[role as usize] {
505 return Err(ThemeError::DuplicateRole);
506 }
507 seen[role as usize] = true;
508 linear(color, RgbEncoding::Srgb)?;
509 opaque(color)?;
510 candidate.palette.colors[role as usize] = color;
511 }
512 candidate.validate_contrast()?;
513 *self = candidate;
514 Ok(())
515 }
516 /// Adopt type/spacing together before layout/paint/hit rebuild. Invalid
517 /// metrics leave both unchanged. No fitting/scaling occurs here.
518 pub fn set_metrics(&mut self, types: TypeScale, spacing: Spacing) -> Result<(), ThemeError> {
519 types.validate()?;
520 spacing.validate(types)?;
521 self.types = types;
522 self.spacing = spacing;
523 Ok(())
524 }
525 pub fn text(self, role: TextRole) -> TextTokens {
526 TextTokens {
527 size: match role {
528 TextRole::Label => self.types.label,
529 TextRole::Body => self.types.body,
530 TextRole::Heading => self.types.heading,
531 },
532 color: self.color(if role == TextRole::Label {
533 ColorRole::MutedText
534 } else {
535 ColorRole::Text
536 }),
537 }
538 }
539 /// State foregrounds plus non-color guidance for cards/meters/inspectors.
540 /// Focus color is for non-text outlines; accompanying labels stay in Text.
541 /// Nothing automatically draws cues or changes authoritative game state.
542 pub fn state(self, state: ThemeState) -> StateTokens {
543 use CuePattern::{Dots, DoubleOutline, Hatch, Solid};
544 use CueShape::{Check, Cross, None, Octagon, Outline, Triangle};
545 let (role, label, shape, pattern) = match state {
546 ThemeState::Neutral => (ColorRole::Text, "", None, Solid),
547 ThemeState::Selected => (ColorRole::Accent, "SELECTED", Check, DoubleOutline),
548 ThemeState::Focused => (ColorRole::Focus, "FOCUSED", Outline, DoubleOutline),
549 ThemeState::Disabled => (ColorRole::DisabledText, "UNAVAILABLE", Cross, Hatch),
550 ThemeState::Success => (ColorRole::Success, "SUCCESS", Check, Solid),
551 ThemeState::Warning => (ColorRole::Warning, "WARNING", Triangle, Dots),
552 ThemeState::Error => (ColorRole::Danger, "ERROR", Octagon, Hatch),
553 };
554 StateTokens {
555 foreground: self.color(role),
556 cue: StateCue {
557 label,
558 shape,
559 pattern,
560 },
561 }
562 }
563}