fernctl/domain/tokens/
spacing.rs

1//! # Scale-Based Spacing Tokens
2//!
3//! This module provides spacing tokens that follow a defined scale, preventing
4//! arbitrary pixel values and ensuring visual consistency.
5//!
6//! ## Design Rationale
7//!
8//! Arbitrary spacing values create visual inconsistency:
9//!
10//! ```rust,ignore
11//! // ❌ Bad: Arbitrary values
12//! button.padding = 7;   // Why 7? Looks off.
13//! card.margin = 13;     // Not on any scale.
14//! ```
15//!
16//! Scale-based spacing ensures everything aligns:
17//!
18//! ```rust,ignore
19//! // ✅ Good: Scale-based values
20//! button.padding = SpacingSm::pixels();   // 8px, on 4px scale
21//! card.margin = SpacingMd::pixels();      // 12px, on 4px scale
22//! ```
23//!
24//! ## The 4px Base Unit
25//!
26//! All spacing in Fern is based on a 4px unit. This creates a consistent
27//! rhythm and ensures elements align to a pixel grid.
28//!
29//! | Token | Multiplier | Pixels |
30//! |-------|------------|--------|
31//! | `SpacingXs` | 1× | 4px |
32//! | `SpacingSm` | 2× | 8px |
33//! | `SpacingMd` | 3× | 12px |
34//! | `SpacingLg` | 4× | 16px |
35//! | `SpacingXl` | 6× | 24px |
36//!
37//! ## Const Generics
38//!
39//! Spacing uses const generics to encode the multiplier in the type:
40//!
41//! ```rust
42//! use fernctl::domain::tokens::spacing::*;
43//!
44//! // The multiplier is part of the type, not a runtime value
45//! let _sm: Spacing<2> = Spacing::new();
46//! assert_eq!(Spacing::<2>::pixels(), 8);
47//!
48//! // Type aliases provide semantic names
49//! assert_eq!(SpacingSm::pixels(), 8);
50//! ```
51//!
52//! ## Compile-Time Validation
53//!
54//! The type system ensures spacing values are always on the scale:
55//!
56//! ```rust
57//! use fernctl::domain::tokens::spacing::*;
58//!
59//! // These are the only valid spacing values
60//! let xs = SpacingXs::pixels();  // 4
61//! let sm = SpacingSm::pixels();  // 8
62//! let md = SpacingMd::pixels();  // 12
63//! let lg = SpacingLg::pixels();  // 16
64//! let xl = SpacingXl::pixels();  // 24
65//!
66//! // There's no way to express "7px" — it's not a type!
67//! ```
68
69use serde::{Deserialize, Serialize};
70use std::fmt;
71use std::marker::PhantomData;
72
73/// The base unit for spacing in pixels.
74///
75/// All spacing values are multiples of this base unit, creating a consistent
76/// visual rhythm. The value 4 is chosen because:
77///
78/// - It's divisible by 2 (for half-spacing needs)
79/// - It aligns well with common screen densities
80/// - It's small enough for fine-grained control
81/// - It's large enough to be visually meaningful
82pub const SPACING_BASE: u16 = 4;
83
84/// A spacing value that is a multiple of the base unit.
85///
86/// The multiplier `N` is encoded in the type, ensuring spacing values are
87/// always on the scale. The actual pixel value is `N * SPACING_BASE`.
88///
89/// # Type Parameter
90///
91/// - `N` — The multiplier (e.g., 2 for 8px spacing)
92///
93/// # Memory Layout
94///
95/// `Spacing<N>` is a zero-sized type. It exists only at compile time to
96/// encode the spacing value in the type system.
97///
98/// ```rust
99/// use fernctl::domain::tokens::spacing::*;
100/// use std::mem::size_of;
101///
102/// assert_eq!(size_of::<Spacing<2>>(), 0);
103/// ```
104///
105/// # Example
106///
107/// ```rust
108/// use fernctl::domain::tokens::spacing::*;
109///
110/// // Using const generics directly
111/// let _spacing: Spacing<3> = Spacing::new();
112/// assert_eq!(Spacing::<3>::pixels(), 12);
113///
114/// // Using type aliases
115/// assert_eq!(SpacingMd::pixels(), 12);
116/// ```
117#[derive(Clone, Copy, PartialEq, Eq, Hash)]
118pub struct Spacing<const N: u8> {
119    _marker: PhantomData<()>,
120}
121
122impl<const N: u8> Spacing<N> {
123    /// Creates a new spacing value.
124    ///
125    /// Since `Spacing` is a zero-sized type, this is a no-op at runtime.
126    ///
127    /// # Example
128    ///
129    /// ```rust
130    /// use fernctl::domain::tokens::spacing::Spacing;
131    ///
132    /// let spacing: Spacing<2> = Spacing::new();
133    /// ```
134    #[must_use]
135    pub const fn new() -> Self {
136        Self {
137            _marker: PhantomData,
138        }
139    }
140
141    /// Returns the multiplier for this spacing value.
142    ///
143    /// # Example
144    ///
145    /// ```rust
146    /// use fernctl::domain::tokens::spacing::*;
147    ///
148    /// assert_eq!(SpacingSm::multiplier(), 2);
149    /// assert_eq!(SpacingLg::multiplier(), 4);
150    /// ```
151    #[must_use]
152    pub const fn multiplier() -> u8 {
153        N
154    }
155
156    /// Returns the spacing value in pixels.
157    ///
158    /// This is computed as `N * SPACING_BASE`.
159    ///
160    /// # Example
161    ///
162    /// ```rust
163    /// use fernctl::domain::tokens::spacing::*;
164    ///
165    /// assert_eq!(SpacingXs::pixels(), 4);   // 1 * 4
166    /// assert_eq!(SpacingSm::pixels(), 8);   // 2 * 4
167    /// assert_eq!(SpacingMd::pixels(), 12);  // 3 * 4
168    /// assert_eq!(SpacingLg::pixels(), 16);  // 4 * 4
169    /// assert_eq!(SpacingXl::pixels(), 24);  // 6 * 4
170    /// ```
171    #[must_use]
172    pub const fn pixels() -> u16 {
173        SPACING_BASE * N as u16
174    }
175
176    /// Returns the semantic name for this spacing level, if it has one.
177    ///
178    /// # Example
179    ///
180    /// ```rust
181    /// use fernctl::domain::tokens::spacing::*;
182    ///
183    /// assert_eq!(SpacingSm::name(), Some("sm"));
184    /// assert_eq!(Spacing::<7>::name(), None);  // Not a standard level
185    /// ```
186    #[must_use]
187    pub const fn name() -> Option<&'static str> {
188        match N {
189            1 => Some("xs"),
190            2 => Some("sm"),
191            3 => Some("md"),
192            4 => Some("lg"),
193            6 => Some("xl"),
194            _ => None,
195        }
196    }
197}
198
199impl<const N: u8> Default for Spacing<N> {
200    fn default() -> Self {
201        Self::new()
202    }
203}
204
205impl<const N: u8> fmt::Debug for Spacing<N> {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        match Self::name() {
208            Some(name) => write!(f, "Spacing::{} ({}px)", name, Self::pixels()),
209            None => write!(f, "Spacing<{}> ({}px)", N, Self::pixels()),
210        }
211    }
212}
213
214impl<const N: u8> fmt::Display for Spacing<N> {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        write!(f, "{}px", Self::pixels())
217    }
218}
219
220// Serialization: Spacing serializes to pixel value
221impl<const N: u8> Serialize for Spacing<N> {
222    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
223    where
224        S: serde::Serializer,
225    {
226        Self::pixels().serialize(serializer)
227    }
228}
229
230// Note: Deserialize is not implemented because spacing should be constructed
231// from known const values, not arbitrary runtime values.
232
233/// Extra-small spacing (4px).
234///
235/// Use for tight spaces where elements should feel closely related:
236/// - Icon padding
237/// - Inline element gaps
238/// - Dense list items
239///
240/// # Example
241///
242/// ```rust
243/// use fernctl::domain::tokens::spacing::SpacingXs;
244///
245/// assert_eq!(SpacingXs::pixels(), 4);
246/// ```
247pub type SpacingXs = Spacing<1>;
248
249/// Small spacing (8px).
250///
251/// Use for standard small gaps:
252/// - Button padding
253/// - Input padding
254/// - Small component margins
255///
256/// # Example
257///
258/// ```rust
259/// use fernctl::domain::tokens::spacing::SpacingSm;
260///
261/// assert_eq!(SpacingSm::pixels(), 8);
262/// ```
263pub type SpacingSm = Spacing<2>;
264
265/// Medium spacing (12px).
266///
267/// Use for standard component spacing:
268/// - Card padding
269/// - Section gaps
270/// - Form field spacing
271///
272/// # Example
273///
274/// ```rust
275/// use fernctl::domain::tokens::spacing::SpacingMd;
276///
277/// assert_eq!(SpacingMd::pixels(), 12);
278/// ```
279pub type SpacingMd = Spacing<3>;
280
281/// Large spacing (16px).
282///
283/// Use for larger gaps between distinct elements:
284/// - Panel margins
285/// - Major section breaks
286/// - Modal padding
287///
288/// # Example
289///
290/// ```rust
291/// use fernctl::domain::tokens::spacing::SpacingLg;
292///
293/// assert_eq!(SpacingLg::pixels(), 16);
294/// ```
295pub type SpacingLg = Spacing<4>;
296
297/// Extra-large spacing (24px).
298///
299/// Use for major layout spacing:
300/// - Page margins
301/// - Large section separations
302/// - Header/footer padding
303///
304/// # Example
305///
306/// ```rust
307/// use fernctl::domain::tokens::spacing::SpacingXl;
308///
309/// assert_eq!(SpacingXl::pixels(), 24);
310/// ```
311pub type SpacingXl = Spacing<6>;
312
313/// A runtime spacing value for when const generics aren't suitable.
314///
315/// While `Spacing<N>` is preferred for compile-time safety, `SpacingValue`
316/// is useful when the spacing level is determined at runtime (e.g., from
317/// configuration).
318///
319/// # Example
320///
321/// ```rust
322/// use fernctl::domain::tokens::spacing::SpacingValue;
323///
324/// let spacing = SpacingValue::from_name("md").unwrap();
325/// assert_eq!(spacing.pixels(), 12);
326/// ```
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
328#[serde(rename_all = "lowercase")]
329pub enum SpacingValue {
330    /// Extra-small (4px)
331    Xs,
332    /// Small (8px)
333    Sm,
334    /// Medium (12px)
335    Md,
336    /// Large (16px)
337    Lg,
338    /// Extra-large (24px)
339    Xl,
340}
341
342impl SpacingValue {
343    /// Creates a spacing value from its name.
344    ///
345    /// # Arguments
346    ///
347    /// * `name` — One of "xs", "sm", "md", "lg", "xl"
348    ///
349    /// # Returns
350    ///
351    /// `Some(SpacingValue)` if the name is valid, `None` otherwise.
352    ///
353    /// # Example
354    ///
355    /// ```rust
356    /// use fernctl::domain::tokens::spacing::SpacingValue;
357    ///
358    /// assert_eq!(SpacingValue::from_name("sm"), Some(SpacingValue::Sm));
359    /// assert_eq!(SpacingValue::from_name("invalid"), None);
360    /// ```
361    #[must_use]
362    pub fn from_name(name: &str) -> Option<Self> {
363        match name.to_lowercase().as_str() {
364            "xs" => Some(Self::Xs),
365            "sm" => Some(Self::Sm),
366            "md" => Some(Self::Md),
367            "lg" => Some(Self::Lg),
368            "xl" => Some(Self::Xl),
369            _ => None,
370        }
371    }
372
373    /// Returns the spacing value in pixels.
374    ///
375    /// # Example
376    ///
377    /// ```rust
378    /// use fernctl::domain::tokens::spacing::SpacingValue;
379    ///
380    /// assert_eq!(SpacingValue::Md.pixels(), 12);
381    /// ```
382    #[must_use]
383    pub const fn pixels(&self) -> u16 {
384        match self {
385            Self::Xs => SpacingXs::pixels(),
386            Self::Sm => SpacingSm::pixels(),
387            Self::Md => SpacingMd::pixels(),
388            Self::Lg => SpacingLg::pixels(),
389            Self::Xl => SpacingXl::pixels(),
390        }
391    }
392
393    /// Returns the name of this spacing level.
394    ///
395    /// # Example
396    ///
397    /// ```rust
398    /// use fernctl::domain::tokens::spacing::SpacingValue;
399    ///
400    /// assert_eq!(SpacingValue::Md.name(), "md");
401    /// ```
402    #[must_use]
403    pub const fn name(&self) -> &'static str {
404        match self {
405            Self::Xs => "xs",
406            Self::Sm => "sm",
407            Self::Md => "md",
408            Self::Lg => "lg",
409            Self::Xl => "xl",
410        }
411    }
412
413    /// Returns all spacing values in order from smallest to largest.
414    ///
415    /// # Example
416    ///
417    /// ```rust
418    /// use fernctl::domain::tokens::spacing::SpacingValue;
419    ///
420    /// for spacing in SpacingValue::all() {
421    ///     println!("{}: {}px", spacing.name(), spacing.pixels());
422    /// }
423    /// ```
424    #[must_use]
425    pub const fn all() -> &'static [SpacingValue] {
426        &[Self::Xs, Self::Sm, Self::Md, Self::Lg, Self::Xl]
427    }
428}
429
430impl Default for SpacingValue {
431    fn default() -> Self {
432        Self::Md
433    }
434}
435
436impl fmt::Display for SpacingValue {
437    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438        write!(f, "{}px", self.pixels())
439    }
440}
441
442#[cfg(test)]
443mod tests {
444    use super::*;
445
446    #[test]
447    fn spacing_is_zero_sized() {
448        assert_eq!(std::mem::size_of::<Spacing<2>>(), 0);
449        assert_eq!(std::mem::size_of::<SpacingMd>(), 0);
450    }
451
452    #[test]
453    fn spacing_values_correct() {
454        assert_eq!(SpacingXs::pixels(), 4);
455        assert_eq!(SpacingSm::pixels(), 8);
456        assert_eq!(SpacingMd::pixels(), 12);
457        assert_eq!(SpacingLg::pixels(), 16);
458        assert_eq!(SpacingXl::pixels(), 24);
459    }
460
461    #[test]
462    fn spacing_names() {
463        assert_eq!(SpacingXs::name(), Some("xs"));
464        assert_eq!(SpacingSm::name(), Some("sm"));
465        assert_eq!(SpacingMd::name(), Some("md"));
466        assert_eq!(SpacingLg::name(), Some("lg"));
467        assert_eq!(SpacingXl::name(), Some("xl"));
468        assert_eq!(Spacing::<7>::name(), None);
469    }
470
471    #[test]
472    fn spacing_value_from_name() {
473        assert_eq!(SpacingValue::from_name("xs"), Some(SpacingValue::Xs));
474        assert_eq!(SpacingValue::from_name("SM"), Some(SpacingValue::Sm)); // Case insensitive
475        assert_eq!(SpacingValue::from_name("invalid"), None);
476    }
477
478    #[test]
479    fn spacing_serialization() {
480        let sm = SpacingSm::new();
481        let json = serde_json::to_string(&sm).unwrap();
482        assert_eq!(json, "8");
483    }
484
485    #[test]
486    fn spacing_value_serialization_roundtrip() {
487        let original = SpacingValue::Md;
488        let json = serde_json::to_string(&original).unwrap();
489        let restored: SpacingValue = serde_json::from_str(&json).unwrap();
490        assert_eq!(original, restored);
491    }
492}