fernctl/domain/
user_config.rs

1//! # User Configuration Format
2//!
3//! This module defines the user-facing configuration format that matches the
4//! TOML structure users write. It provides a bridge between the user's config
5//! file and the internal [`Theme`] representation.
6//!
7//! ## Design Rationale
8//!
9//! Users write configuration in a hierarchical, intuitive format:
10//!
11//! ```toml
12//! [appearance]
13//! theme = "dark"
14//! accent = "#ff6b6b"
15//! font_family = "Inter"
16//!
17//! [bar]
18//! height = 40
19//! position = "top"
20//! ```
21//!
22//! But the internal [`Theme`] struct has a different structure optimized for
23//! the domain model. This module handles the transformation.
24//!
25//! ## Transformation Flow
26//!
27//! ```text
28//! TOML file
29//!     ↓
30//! [parse to UserConfig]
31//!     ↓
32//! UserConfig::into_theme()
33//!     ↓
34//! Theme (validated, ready for use)
35//! ```
36
37use crate::domain::theme::{BarConfig, BarPosition, ColorPalette, Theme, ThemeVariant};
38use crate::domain::tokens::color::{Accent, ColorToken};
39use crate::domain::tokens::radius::RadiusScale;
40use crate::domain::tokens::typography::{FontFamily, FontSizeScale, Typography};
41use crate::error::{ConfigError, FernError, Result};
42use serde::Deserialize;
43
44// ============================================================================
45// UserConfig — Top-level configuration
46// ============================================================================
47
48/// User-facing configuration format matching the TOML structure.
49///
50/// This struct deserializes directly from the user's TOML file and provides
51/// transformation to the internal [`Theme`] representation.
52///
53/// # Example
54///
55/// ```rust,ignore
56/// let toml_content = r#"
57///     [appearance]
58///     theme = "dark"
59///     accent = "#ff6b6b"
60///
61///     [bar]
62///     height = 32
63/// "#;
64///
65/// let user_config: UserConfig = toml::from_str(toml_content)?;
66/// let theme = user_config.into_theme()?;
67/// ```
68#[derive(Debug, Clone, Default, Deserialize)]
69pub struct UserConfig {
70    /// Appearance settings (colors, fonts, etc.)
71    #[serde(default)]
72    pub appearance: AppearanceConfig,
73
74    /// Bar/panel configuration
75    #[serde(default)]
76    pub bar: UserBarConfig,
77
78    /// Module-specific settings (passed through to QuickShell, not validated)
79    #[serde(default)]
80    pub modules: serde_json::Value,
81}
82
83impl UserConfig {
84    /// Transforms the user configuration into a validated [`Theme`].
85    ///
86    /// This method:
87    /// 1. Determines the base theme variant (dark/light)
88    /// 2. Applies any color overrides (e.g., accent)
89    /// 3. Applies typography overrides
90    /// 4. Applies radius overrides
91    /// 5. Builds the bar configuration
92    ///
93    /// # Errors
94    ///
95    /// Returns an error if:
96    /// - An invalid color value is provided (e.g., "#gg0000")
97    /// - An invalid theme variant is specified
98    ///
99    /// # Example
100    ///
101    /// ```rust,ignore
102    /// let user_config = UserConfig::default();
103    /// let theme = user_config.into_theme()?;
104    /// assert_eq!(theme.variant, ThemeVariant::Dark);
105    /// ```
106    pub fn into_theme(self) -> Result<Theme> {
107        // Determine base theme variant
108        let variant = ThemeVariant::from_name(&self.appearance.theme).unwrap_or(ThemeVariant::Dark);
109
110        // Start with default colors for the variant
111        let mut colors = match variant {
112            ThemeVariant::Dark => ColorPalette::dark(),
113            ThemeVariant::Light => ColorPalette::light(),
114            ThemeVariant::Auto => ColorPalette::dark(), // Default to dark for auto
115        };
116
117        // Apply accent color override if provided
118        if let Some(ref accent) = self.appearance.accent {
119            colors.accent = ColorToken::<Accent>::from_hex(accent).map_err(|_| {
120                FernError::Config(ConfigError::InvalidColor {
121                    value: accent.clone(),
122                    span: None,
123                    source_code: None,
124                })
125            })?;
126        }
127
128        // Build typography with overrides
129        let typography = Typography {
130            family: self
131                .appearance
132                .font_family
133                .map(FontFamily::new)
134                .unwrap_or_else(FontFamily::default_primary),
135            mono: self
136                .appearance
137                .font_mono
138                .map(FontFamily::new)
139                .unwrap_or_else(FontFamily::default_mono),
140            icon: self
141                .appearance
142                .font_icon
143                .map(FontFamily::new)
144                .unwrap_or_else(FontFamily::default_icon),
145            size: FontSizeScale::default(),
146        };
147
148        // Build radius scale with overrides
149        let radius = self
150            .appearance
151            .radius
152            .map(UserRadiusConfig::into_scale)
153            .unwrap_or_default();
154
155        // Build bar configuration
156        let bar = BarConfig {
157            height: self.bar.height,
158            position: BarPosition::from_name(&self.bar.position).unwrap_or_default(),
159            margin: self.bar.margin,
160        };
161
162        Ok(Theme {
163            variant,
164            colors,
165            typography,
166            radius,
167            bar,
168        })
169    }
170}
171
172// ============================================================================
173// AppearanceConfig — Visual styling options
174// ============================================================================
175
176/// Appearance configuration section.
177///
178/// Contains all visual styling options: theme variant, colors, fonts, and radii.
179#[derive(Debug, Clone, Deserialize)]
180pub struct AppearanceConfig {
181    /// Theme variant: "dark", "light", or "auto"
182    #[serde(default = "default_theme")]
183    pub theme: String,
184
185    /// Accent color override (hex format, e.g., "#ff6b6b")
186    #[serde(default)]
187    pub accent: Option<String>,
188
189    /// Primary font family name
190    #[serde(default)]
191    pub font_family: Option<String>,
192
193    /// Monospace font family name
194    #[serde(default)]
195    pub font_mono: Option<String>,
196
197    /// Icon font family name
198    #[serde(default)]
199    pub font_icon: Option<String>,
200
201    /// Border radius overrides
202    #[serde(default)]
203    pub radius: Option<UserRadiusConfig>,
204}
205
206fn default_theme() -> String {
207    "dark".to_string()
208}
209
210impl Default for AppearanceConfig {
211    fn default() -> Self {
212        Self {
213            theme: default_theme(),
214            accent: None,
215            font_family: None,
216            font_mono: None,
217            font_icon: None,
218            radius: None,
219        }
220    }
221}
222
223// ============================================================================
224// UserBarConfig — Bar/panel settings
225// ============================================================================
226
227/// Bar/panel configuration section.
228///
229/// Note: `modules_left`, `modules_center`, and `modules_right` are parsed
230/// but not included in the Theme — they're passed through to QuickShell.
231#[derive(Debug, Clone, Deserialize)]
232pub struct UserBarConfig {
233    /// Bar height in pixels
234    #[serde(default = "default_bar_height")]
235    pub height: u16,
236
237    /// Bar position: "top" or "bottom"
238    #[serde(default = "default_bar_position")]
239    pub position: String,
240
241    /// Margin from screen edge
242    #[serde(default)]
243    pub margin: u16,
244
245    /// Modules on the left (passed through to QuickShell)
246    #[serde(default)]
247    pub modules_left: Vec<String>,
248
249    /// Modules in the center (passed through to QuickShell)
250    #[serde(default)]
251    pub modules_center: Vec<String>,
252
253    /// Modules on the right (passed through to QuickShell)
254    #[serde(default)]
255    pub modules_right: Vec<String>,
256}
257
258fn default_bar_height() -> u16 {
259    40
260}
261
262fn default_bar_position() -> String {
263    "top".to_string()
264}
265
266impl Default for UserBarConfig {
267    fn default() -> Self {
268        Self {
269            height: default_bar_height(),
270            position: default_bar_position(),
271            margin: 0,
272            modules_left: vec!["workspaces".to_string()],
273            modules_center: vec!["clock".to_string()],
274            modules_right: vec!["tray".to_string()],
275        }
276    }
277}
278
279// ============================================================================
280// UserRadiusConfig — Radius overrides
281// ============================================================================
282
283/// Border radius configuration section.
284///
285/// Allows users to customize the radius scale values.
286#[derive(Debug, Clone, Deserialize)]
287pub struct UserRadiusConfig {
288    /// No radius (typically 0)
289    #[serde(default)]
290    pub none: Option<u16>,
291
292    /// Small radius (default 4px)
293    #[serde(default)]
294    pub sm: Option<u16>,
295
296    /// Medium radius (default 8px)
297    #[serde(default)]
298    pub md: Option<u16>,
299
300    /// Large radius (default 12px)
301    #[serde(default)]
302    pub lg: Option<u16>,
303
304    /// Full radius (default 9999px)
305    #[serde(default)]
306    pub full: Option<u16>,
307}
308
309impl UserRadiusConfig {
310    /// Converts user radius config into a [`RadiusScale`].
311    fn into_scale(self) -> RadiusScale {
312        let default = RadiusScale::default();
313        RadiusScale {
314            none: self.none.unwrap_or(default.none),
315            sm: self.sm.unwrap_or(default.sm),
316            md: self.md.unwrap_or(default.md),
317            lg: self.lg.unwrap_or(default.lg),
318            full: self.full.unwrap_or(default.full),
319        }
320    }
321}
322
323impl Default for UserRadiusConfig {
324    fn default() -> Self {
325        Self {
326            none: None,
327            sm: None,
328            md: None,
329            lg: None,
330            full: None,
331        }
332    }
333}
334
335// ============================================================================
336// BarPosition helper
337// ============================================================================
338
339impl BarPosition {
340    /// Creates a bar position from its string name.
341    #[must_use]
342    pub fn from_name(name: &str) -> Option<Self> {
343        match name.to_lowercase().as_str() {
344            "top" => Some(Self::Top),
345            "bottom" => Some(Self::Bottom),
346            _ => None,
347        }
348    }
349}
350
351// ============================================================================
352// Tests
353// ============================================================================
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358
359    #[test]
360    fn default_user_config() {
361        let config = UserConfig::default();
362        assert_eq!(config.appearance.theme, "dark");
363        assert_eq!(config.bar.height, 40);
364    }
365
366    #[test]
367    fn user_config_into_theme_defaults() {
368        let config = UserConfig::default();
369        let theme = config.into_theme().unwrap();
370
371        assert_eq!(theme.variant, ThemeVariant::Dark);
372        assert_eq!(theme.bar.height, 40);
373        assert_eq!(theme.bar.position, BarPosition::Top);
374    }
375
376    #[test]
377    fn user_config_accent_override() {
378        let config = UserConfig {
379            appearance: AppearanceConfig {
380                theme: "dark".to_string(),
381                accent: Some("#ff6b6b".to_string()),
382                ..Default::default()
383            },
384            ..Default::default()
385        };
386
387        let theme = config.into_theme().unwrap();
388        assert_eq!(theme.colors.accent.to_hex(), "#ff6b6b");
389    }
390
391    #[test]
392    fn user_config_invalid_accent() {
393        let config = UserConfig {
394            appearance: AppearanceConfig {
395                accent: Some("#gg0000".to_string()),
396                ..Default::default()
397            },
398            ..Default::default()
399        };
400
401        let result = config.into_theme();
402        assert!(result.is_err());
403    }
404
405    #[test]
406    fn user_config_light_theme() {
407        let config = UserConfig {
408            appearance: AppearanceConfig {
409                theme: "light".to_string(),
410                ..Default::default()
411            },
412            ..Default::default()
413        };
414
415        let theme = config.into_theme().unwrap();
416        assert_eq!(theme.variant, ThemeVariant::Light);
417    }
418
419    #[test]
420    fn user_config_font_override() {
421        let config = UserConfig {
422            appearance: AppearanceConfig {
423                font_family: Some("Fira Sans".to_string()),
424                font_mono: Some("Fira Code".to_string()),
425                ..Default::default()
426            },
427            ..Default::default()
428        };
429
430        let theme = config.into_theme().unwrap();
431        assert_eq!(theme.typography.family.name(), "Fira Sans");
432        assert_eq!(theme.typography.mono.name(), "Fira Code");
433    }
434
435    #[test]
436    fn user_config_radius_override() {
437        let config = UserConfig {
438            appearance: AppearanceConfig {
439                radius: Some(UserRadiusConfig {
440                    sm: Some(2),
441                    md: Some(6),
442                    ..Default::default()
443                }),
444                ..Default::default()
445            },
446            ..Default::default()
447        };
448
449        let theme = config.into_theme().unwrap();
450        assert_eq!(theme.radius.sm, 2);
451        assert_eq!(theme.radius.md, 6);
452        assert_eq!(theme.radius.lg, 12); // Default unchanged
453    }
454
455    #[test]
456    fn user_config_bar_position() {
457        let config = UserConfig {
458            bar: UserBarConfig {
459                position: "bottom".to_string(),
460                ..Default::default()
461            },
462            ..Default::default()
463        };
464
465        let theme = config.into_theme().unwrap();
466        assert_eq!(theme.bar.position, BarPosition::Bottom);
467    }
468
469    #[test]
470    fn bar_position_from_name() {
471        assert_eq!(BarPosition::from_name("top"), Some(BarPosition::Top));
472        assert_eq!(BarPosition::from_name("BOTTOM"), Some(BarPosition::Bottom));
473        assert_eq!(BarPosition::from_name("invalid"), None);
474    }
475
476    #[test]
477    fn deserialize_from_toml() {
478        let toml_content = r##"
479[appearance]
480theme = "dark"
481accent = "#89b4fa"
482font_family = "Inter"
483
484[bar]
485height = 32
486position = "top"
487"##;
488
489        let config: UserConfig = toml::from_str(toml_content).unwrap();
490        assert_eq!(config.appearance.theme, "dark");
491        assert_eq!(config.appearance.accent, Some("#89b4fa".to_string()));
492        assert_eq!(config.bar.height, 32);
493
494        let theme = config.into_theme().unwrap();
495        assert_eq!(theme.colors.accent.to_hex(), "#89b4fa");
496        assert_eq!(theme.bar.height, 32);
497    }
498}