fernctl/domain/tokens/
radius.rs

1//! # Semantic Border Radius Tokens
2//!
3//! This module provides border radius tokens with semantic names and
4//! component-specific validity constraints.
5//!
6//! ## Design Rationale
7//!
8//! Border radius affects the visual character of UI elements. Rather than
9//! allowing arbitrary pixel values, we define semantic names that can be
10//! customized while maintaining consistent meaning.
11//!
12//! ```rust,ignore
13//! // ❌ Bad: Magic numbers
14//! button.radius = 4;
15//! card.radius = 8;
16//! pill.radius = 9999;
17//!
18//! // ✅ Good: Semantic names
19//! button.radius = RadiusSm;   // "Small" - for compact elements
20//! card.radius = RadiusMd;     // "Medium" - for cards/modules
21//! pill.radius = RadiusFull;   // "Full" - for pill shapes
22//! ```
23//!
24//! ## Component Constraints
25//!
26//! Not all radii make sense for all components. A button with `RadiusFull`
27//! looks like a pill — probably not intended. The type system prevents this:
28//!
29//! ```rust,ignore
30//! // ButtonSpec requires R: ButtonRadius
31//! struct ButtonSpec<R: ButtonRadius> { ... }
32//!
33//! // RadiusSm implements ButtonRadius
34//! ButtonSpec::<RadiusSm>::new()  // ✓ Compiles
35//!
36//! // RadiusFull does NOT implement ButtonRadius
37//! ButtonSpec::<RadiusFull>::new()  // ✗ Error!
38//! ```
39//!
40//! ## Customizable Values
41//!
42//! While the semantic names are fixed, the actual pixel values can be
43//! customized via configuration:
44//!
45//! ```toml
46//! [appearance.radius]
47//! sm = 4   # Could be changed to 2 for sharper corners
48//! md = 8   # Could be changed to 12 for rounder corners
49//! ```
50
51use serde::{Deserialize, Serialize};
52use std::fmt;
53
54// ============================================================================
55// Sealed Trait Pattern
56// ============================================================================
57
58mod private {
59    pub trait Sealed {}
60}
61
62// ============================================================================
63// Radius Semantic Traits
64// ============================================================================
65
66/// Marker trait for all radius semantics.
67///
68/// This is the base trait that all radius types implement. It is sealed,
69/// meaning only types in this crate can implement it.
70pub trait RadiusSemantic: private::Sealed + fmt::Debug + Clone + Copy + 'static {
71    /// The default pixel value for this radius.
72    const DEFAULT_PIXELS: u16;
73
74    /// Returns the semantic name of this radius.
75    fn name() -> &'static str;
76}
77
78/// Marker trait for radii valid on buttons.
79///
80/// Buttons should have subtle rounding — not too sharp, not pill-shaped.
81/// This trait marks which radius semantics are appropriate for buttons.
82///
83/// # Implementors
84///
85/// - [`RadiusNone`] — Sharp corners (allowed but not recommended)
86/// - [`RadiusSm`] — Small rounding (recommended)
87/// - [`RadiusMd`] — Medium rounding (allowed)
88///
89/// [`RadiusLg`] and [`RadiusFull`] are NOT valid for buttons.
90pub trait ButtonRadius: RadiusSemantic {}
91
92/// Marker trait for radii valid on modules/cards.
93///
94/// Modules and cards benefit from more rounding than buttons.
95///
96/// # Implementors
97///
98/// - [`RadiusSm`] — Small (for dense layouts)
99/// - [`RadiusMd`] — Medium (recommended)
100/// - [`RadiusLg`] — Large (for softer appearance)
101///
102/// [`RadiusNone`] and [`RadiusFull`] are NOT valid for modules.
103pub trait ModuleRadius: RadiusSemantic {}
104
105/// Marker trait for radii valid on inputs.
106///
107/// Input fields should have consistent, subtle rounding.
108///
109/// # Implementors
110///
111/// - [`RadiusNone`] — Sharp (allowed)
112/// - [`RadiusSm`] — Small (recommended)
113/// - [`RadiusMd`] — Medium (allowed)
114pub trait InputRadius: RadiusSemantic {}
115
116// ============================================================================
117// Radius Marker Types
118// ============================================================================
119
120/// No border radius (sharp corners).
121///
122/// Use when you need completely square corners. This is valid for most
123/// components but rarely recommended — even 2px of rounding softens the UI.
124///
125/// # Default Value
126///
127/// Always 0px (cannot be customized).
128///
129/// # Example
130///
131/// ```rust
132/// use fernctl::domain::tokens::radius::*;
133///
134/// assert_eq!(RadiusNone::DEFAULT_PIXELS, 0);
135/// ```
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
137pub struct RadiusNone;
138
139impl private::Sealed for RadiusNone {}
140impl RadiusSemantic for RadiusNone {
141    const DEFAULT_PIXELS: u16 = 0;
142    fn name() -> &'static str {
143        "none"
144    }
145}
146impl ButtonRadius for RadiusNone {}
147impl InputRadius for RadiusNone {}
148
149/// Small border radius.
150///
151/// Use for compact elements that need subtle rounding:
152/// - Buttons
153/// - Input fields
154/// - Small badges
155/// - Inline elements
156///
157/// # Default Value
158///
159/// 4px (customizable via configuration).
160///
161/// # Example
162///
163/// ```rust
164/// use fernctl::domain::tokens::radius::*;
165///
166/// assert_eq!(RadiusSm::DEFAULT_PIXELS, 4);
167/// ```
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
169pub struct RadiusSm;
170
171impl private::Sealed for RadiusSm {}
172impl RadiusSemantic for RadiusSm {
173    const DEFAULT_PIXELS: u16 = 4;
174    fn name() -> &'static str {
175        "sm"
176    }
177}
178impl ButtonRadius for RadiusSm {}
179impl ModuleRadius for RadiusSm {}
180impl InputRadius for RadiusSm {}
181
182/// Medium border radius.
183///
184/// Use for standard components:
185/// - Cards
186/// - Modals
187/// - Dropdown menus
188/// - Tooltips
189///
190/// # Default Value
191///
192/// 8px (customizable via configuration).
193///
194/// # Example
195///
196/// ```rust
197/// use fernctl::domain::tokens::radius::*;
198///
199/// assert_eq!(RadiusMd::DEFAULT_PIXELS, 8);
200/// ```
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
202pub struct RadiusMd;
203
204impl private::Sealed for RadiusMd {}
205impl RadiusSemantic for RadiusMd {
206    const DEFAULT_PIXELS: u16 = 8;
207    fn name() -> &'static str {
208        "md"
209    }
210}
211impl ButtonRadius for RadiusMd {}
212impl ModuleRadius for RadiusMd {}
213impl InputRadius for RadiusMd {}
214
215/// Large border radius.
216///
217/// Use for prominent, standalone elements:
218/// - Large cards
219/// - Featured content
220/// - Hero sections
221///
222/// # Default Value
223///
224/// 12px (customizable via configuration).
225///
226/// # Example
227///
228/// ```rust
229/// use fernctl::domain::tokens::radius::*;
230///
231/// assert_eq!(RadiusLg::DEFAULT_PIXELS, 12);
232/// ```
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
234pub struct RadiusLg;
235
236impl private::Sealed for RadiusLg {}
237impl RadiusSemantic for RadiusLg {
238    const DEFAULT_PIXELS: u16 = 12;
239    fn name() -> &'static str {
240        "lg"
241    }
242}
243impl ModuleRadius for RadiusLg {}
244
245/// Full border radius (pill shape).
246///
247/// Use when you want completely rounded ends:
248/// - Pill badges
249/// - Toggle switches
250/// - Circular avatars (on square elements)
251///
252/// # Default Value
253///
254/// 9999px — A large value that ensures full rounding regardless of element size.
255///
256/// # Note
257///
258/// This radius is NOT valid for buttons, modules, or inputs because it creates
259/// a pill shape that's usually unintended.
260///
261/// # Example
262///
263/// ```rust
264/// use fernctl::domain::tokens::radius::*;
265///
266/// assert_eq!(RadiusFull::DEFAULT_PIXELS, 9999);
267/// ```
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
269pub struct RadiusFull;
270
271impl private::Sealed for RadiusFull {}
272impl RadiusSemantic for RadiusFull {
273    const DEFAULT_PIXELS: u16 = 9999;
274    fn name() -> &'static str {
275        "full"
276    }
277}
278
279// ============================================================================
280// Runtime Radius Scale
281// ============================================================================
282
283/// A complete radius scale with customizable pixel values.
284///
285/// While the radius marker types ([`RadiusSm`], [`RadiusMd`], etc.) provide
286/// compile-time type safety, `RadiusScale` provides runtime-configurable
287/// values for the actual pixels.
288///
289/// # Default Values
290///
291/// ```rust
292/// use fernctl::domain::tokens::radius::RadiusScale;
293///
294/// let scale = RadiusScale::default();
295/// assert_eq!(scale.none, 0);
296/// assert_eq!(scale.sm, 4);
297/// assert_eq!(scale.md, 8);
298/// assert_eq!(scale.lg, 12);
299/// assert_eq!(scale.full, 9999);
300/// ```
301///
302/// # Customization
303///
304/// Users can customize the pixel values via configuration:
305///
306/// ```toml
307/// [appearance.radius]
308/// sm = 2    # Sharper corners
309/// md = 6
310/// lg = 10
311/// ```
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
313pub struct RadiusScale {
314    /// No radius (always 0).
315    #[serde(default)]
316    pub none: u16,
317    /// Small radius (default 4px).
318    #[serde(default = "default_sm")]
319    pub sm: u16,
320    /// Medium radius (default 8px).
321    #[serde(default = "default_md")]
322    pub md: u16,
323    /// Large radius (default 12px).
324    #[serde(default = "default_lg")]
325    pub lg: u16,
326    /// Full radius (always 9999).
327    #[serde(default = "default_full")]
328    pub full: u16,
329}
330
331fn default_sm() -> u16 {
332    RadiusSm::DEFAULT_PIXELS
333}
334fn default_md() -> u16 {
335    RadiusMd::DEFAULT_PIXELS
336}
337fn default_lg() -> u16 {
338    RadiusLg::DEFAULT_PIXELS
339}
340fn default_full() -> u16 {
341    RadiusFull::DEFAULT_PIXELS
342}
343
344impl RadiusScale {
345    /// Creates a new radius scale with default values.
346    #[must_use]
347    pub const fn new() -> Self {
348        Self {
349            none: RadiusNone::DEFAULT_PIXELS,
350            sm: RadiusSm::DEFAULT_PIXELS,
351            md: RadiusMd::DEFAULT_PIXELS,
352            lg: RadiusLg::DEFAULT_PIXELS,
353            full: RadiusFull::DEFAULT_PIXELS,
354        }
355    }
356
357    /// Returns the pixel value for a given semantic radius.
358    ///
359    /// # Example
360    ///
361    /// ```rust
362    /// use fernctl::domain::tokens::radius::*;
363    ///
364    /// let scale = RadiusScale::default();
365    /// assert_eq!(scale.get::<RadiusMd>(), 8);
366    /// ```
367    #[must_use]
368    pub fn get<R: RadiusSemantic>(&self) -> u16 {
369        match R::name() {
370            "none" => self.none,
371            "sm" => self.sm,
372            "md" => self.md,
373            "lg" => self.lg,
374            "full" => self.full,
375            _ => R::DEFAULT_PIXELS,
376        }
377    }
378
379    /// Returns the pixel value for a button radius.
380    ///
381    /// This is a convenience method that defaults to [`RadiusSm`].
382    #[must_use]
383    pub const fn button(&self) -> u16 {
384        self.sm
385    }
386
387    /// Returns the pixel value for a module/card radius.
388    ///
389    /// This is a convenience method that defaults to [`RadiusMd`].
390    #[must_use]
391    pub const fn module(&self) -> u16 {
392        self.md
393    }
394
395    /// Returns the pixel value for an input radius.
396    ///
397    /// This is a convenience method that defaults to [`RadiusSm`].
398    #[must_use]
399    pub const fn input(&self) -> u16 {
400        self.sm
401    }
402}
403
404impl Default for RadiusScale {
405    fn default() -> Self {
406        Self::new()
407    }
408}
409
410/// A runtime radius value for when const generics aren't suitable.
411///
412/// Use when the radius level is determined at runtime.
413#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
414#[serde(rename_all = "lowercase")]
415pub enum RadiusValue {
416    /// No radius
417    None,
418    /// Small radius
419    Sm,
420    /// Medium radius
421    Md,
422    /// Large radius
423    Lg,
424    /// Full radius
425    Full,
426}
427
428impl RadiusValue {
429    /// Creates a radius value from its name.
430    #[must_use]
431    pub fn from_name(name: &str) -> Option<Self> {
432        match name.to_lowercase().as_str() {
433            "none" => Some(Self::None),
434            "sm" => Some(Self::Sm),
435            "md" => Some(Self::Md),
436            "lg" => Some(Self::Lg),
437            "full" => Some(Self::Full),
438            _ => None,
439        }
440    }
441
442    /// Returns the default pixel value for this radius.
443    #[must_use]
444    pub const fn default_pixels(&self) -> u16 {
445        match self {
446            Self::None => RadiusNone::DEFAULT_PIXELS,
447            Self::Sm => RadiusSm::DEFAULT_PIXELS,
448            Self::Md => RadiusMd::DEFAULT_PIXELS,
449            Self::Lg => RadiusLg::DEFAULT_PIXELS,
450            Self::Full => RadiusFull::DEFAULT_PIXELS,
451        }
452    }
453
454    /// Returns the name of this radius level.
455    #[must_use]
456    pub const fn name(&self) -> &'static str {
457        match self {
458            Self::None => "none",
459            Self::Sm => "sm",
460            Self::Md => "md",
461            Self::Lg => "lg",
462            Self::Full => "full",
463        }
464    }
465
466    /// Returns all radius values.
467    #[must_use]
468    pub const fn all() -> &'static [RadiusValue] {
469        &[Self::None, Self::Sm, Self::Md, Self::Lg, Self::Full]
470    }
471}
472
473impl Default for RadiusValue {
474    fn default() -> Self {
475        Self::Md
476    }
477}
478
479impl fmt::Display for RadiusValue {
480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481        write!(f, "{}", self.name())
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    #[test]
490    fn radius_defaults() {
491        assert_eq!(RadiusNone::DEFAULT_PIXELS, 0);
492        assert_eq!(RadiusSm::DEFAULT_PIXELS, 4);
493        assert_eq!(RadiusMd::DEFAULT_PIXELS, 8);
494        assert_eq!(RadiusLg::DEFAULT_PIXELS, 12);
495        assert_eq!(RadiusFull::DEFAULT_PIXELS, 9999);
496    }
497
498    #[test]
499    fn radius_scale_get() {
500        let scale = RadiusScale::default();
501        assert_eq!(scale.get::<RadiusSm>(), 4);
502        assert_eq!(scale.get::<RadiusMd>(), 8);
503    }
504
505    #[test]
506    fn radius_scale_serialization() {
507        let scale = RadiusScale::default();
508        let json = serde_json::to_string(&scale).unwrap();
509        let restored: RadiusScale = serde_json::from_str(&json).unwrap();
510        assert_eq!(scale, restored);
511    }
512
513    #[test]
514    fn radius_value_from_name() {
515        assert_eq!(RadiusValue::from_name("sm"), Some(RadiusValue::Sm));
516        assert_eq!(RadiusValue::from_name("MD"), Some(RadiusValue::Md));
517        assert_eq!(RadiusValue::from_name("invalid"), None);
518    }
519
520    // Compile-time test: These should compile
521    fn _button_radius_sm(_: impl ButtonRadius) {}
522    fn _module_radius_md(_: impl ModuleRadius) {}
523
524    #[test]
525    fn trait_implementations() {
526        // ButtonRadius: None, Sm, Md
527        _button_radius_sm(RadiusNone);
528        _button_radius_sm(RadiusSm);
529        _button_radius_sm(RadiusMd);
530
531        // ModuleRadius: Sm, Md, Lg
532        _module_radius_md(RadiusSm);
533        _module_radius_md(RadiusMd);
534        _module_radius_md(RadiusLg);
535    }
536
537    // These would NOT compile (which is the point):
538    // _button_radius_sm(RadiusLg);   // RadiusLg doesn't implement ButtonRadius
539    // _button_radius_sm(RadiusFull); // RadiusFull doesn't implement ButtonRadius
540    // _module_radius_md(RadiusNone); // RadiusNone doesn't implement ModuleRadius
541}