ratatui_toolkit/services/theme/app_theme/constructors/from_json.rs
1//! JSON constructor for [`AppTheme`].
2
3use std::path::Path;
4
5use crate::services::theme::app_theme::AppTheme;
6use crate::services::theme::loader::{load_theme_file, load_theme_str};
7use crate::services::theme::ThemeVariant;
8
9impl AppTheme {
10 /// Creates an [`AppTheme`] from a JSON string in opencode format.
11 ///
12 /// This parses the JSON, resolves all color references from the `defs`
13 /// section, and constructs a complete theme.
14 ///
15 /// # Arguments
16 ///
17 /// * `json` - The JSON string in opencode theme format
18 /// * `variant` - Which theme variant (dark/light) to use
19 ///
20 /// # Returns
21 ///
22 /// `Ok(AppTheme)` if parsing succeeds, `Err` with a description otherwise.
23 ///
24 /// # Errors
25 ///
26 /// Returns an error if:
27 /// - The JSON is malformed
28 /// - Color values cannot be resolved
29 ///
30 /// # Example
31 ///
32 /// ```rust
33 /// use ratatui_toolkit::services::theme::{AppTheme, ThemeVariant};
34 ///
35 /// let json = r#"{
36 /// "defs": { "myBlue": "#0066ff" },
37 /// "theme": { "primary": { "dark": "myBlue", "light": "myBlue" } }
38 /// }"#;
39 ///
40 /// let theme = AppTheme::from_json(json, ThemeVariant::Dark)
41 /// .expect("Failed to parse theme");
42 /// ```
43 pub fn from_json(json: &str, variant: ThemeVariant) -> Result<Self, String> {
44 load_theme_str(json, variant)
45 }
46
47 /// Creates an [`AppTheme`] from a JSON file path.
48 ///
49 /// Reads the file and parses it as an opencode theme.
50 ///
51 /// # Arguments
52 ///
53 /// * `path` - Path to the JSON theme file
54 /// * `variant` - Which theme variant (dark/light) to use
55 ///
56 /// # Returns
57 ///
58 /// `Ok(AppTheme)` if the file can be read and parsed,
59 /// `Err` with a description otherwise.
60 ///
61 /// # Errors
62 ///
63 /// Returns an error if:
64 /// - The file cannot be read
65 /// - The JSON is malformed
66 /// - Color values cannot be resolved
67 ///
68 /// # Example
69 ///
70 /// ```rust,no_run
71 /// use ratatui_toolkit::services::theme::{AppTheme, ThemeVariant};
72 ///
73 /// let theme = AppTheme::from_json_file("themes/gruvbox.json", ThemeVariant::Dark)
74 /// .expect("Failed to load theme");
75 /// ```
76 pub fn from_json_file<P: AsRef<Path>>(path: P, variant: ThemeVariant) -> Result<Self, String> {
77 load_theme_file(path, variant)
78 }
79}