gpuicn-cli 0.9.6

Install editable gpuicn Rust components without Node.js.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! The app's theme: a shadcn base color (or imported CSS) in `assets/theme.css`
//! and the generated `app_theme.rs` that turns it into a `UiTheme` pair.

use super::*;

/// shadcn 4.19.0's base colors, from `apps/v4/registry/themes.ts` at the pinned commit.
pub(super) const BASE_COLORS: [(&str, &str); 7] = [
    (
        "neutral",
        include_str!("../templates/base-colors/neutral.css"),
    ),
    ("stone", include_str!("../templates/base-colors/stone.css")),
    ("zinc", include_str!("../templates/base-colors/zinc.css")),
    ("mauve", include_str!("../templates/base-colors/mauve.css")),
    ("olive", include_str!("../templates/base-colors/olive.css")),
    ("mist", include_str!("../templates/base-colors/mist.css")),
    ("taupe", include_str!("../templates/base-colors/taupe.css")),
];
pub(super) const THEME_CSS: &str = "assets/theme.css";
const APP_THEME_HEADER: &str = "//! Generated by `gpuicn init` and `gpuicn theme`";

/// The `[theme]` table of gpuicn.toml.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct ThemeConfig {
    /// A shadcn base color, or none after `gpuicn theme import` (then
    /// `assets/theme.css` is the source of truth).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) base_color: Option<String>,
    /// Corner radius as CSS, such as `0.625rem`; the base color's when unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) radius: Option<String>,
    #[serde(default)]
    pub(super) appearance: AppearanceSetting,
}

impl Default for ThemeConfig {
    fn default() -> Self {
        Self {
            base_color: Some("neutral".into()),
            radius: None,
            appearance: AppearanceSetting::System,
        }
    }
}

/// Which theme of the pair the app opens with.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub(super) enum AppearanceSetting {
    Light,
    Dark,
    #[default]
    System,
}

impl AppearanceSetting {
    fn variant(self) -> &'static str {
        match self {
            Self::Light => "Light",
            Self::Dark => "Dark",
            Self::System => "System",
        }
    }
}

pub(super) fn base_color_css(name: &str) -> Result<&'static str> {
    BASE_COLORS
        .iter()
        .find(|(color, _)| *color == name)
        .map(|(_, css)| *css)
        .with_context(|| {
            format!(
                "unknown base color {name:?}; one of {}",
                BASE_COLORS
                    .iter()
                    .map(|(color, _)| *color)
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        })
}

/// `assets/` beside the installed `ui` module's parent, so `include_bytes!` and
/// `include_str!` paths in installed files are always `../../assets/…`.
pub(super) fn assets_dir(root: &Path, output: &Path) -> PathBuf {
    let output = root.join(output);
    output
        .parent()
        .and_then(Path::parent)
        .map_or_else(|| root.to_path_buf(), Path::to_path_buf)
        .join("assets")
}

/// Replaces (or adds) `--radius` in the `:root` block.
pub(super) fn with_radius(css: &str, radius: &str) -> Result<String> {
    ensure!(
        css_length_ok(radius),
        "radius must be a CSS length in rem or px, such as 0.625rem"
    );
    let root = css
        .find(":root")
        .context("theme.css has no `:root` block")?;
    let open = root + css[root..].find('{').context("theme.css `:root` block")?;
    let close = open + css[open..].find('}').context("theme.css `:root` block")?;
    let body = &css[open + 1..close];
    let new_body = if let Some(start) = body.find("--radius") {
        let end = start + body[start..].find(';').unwrap_or(body.len() - start);
        format!("{}--radius: {radius}{}", &body[..start], &body[end..])
    } else {
        format!("\n  --radius: {radius};{body}")
    };
    Ok(format!("{}{new_body}{}", &css[..=open], &css[close..]))
}

fn css_length_ok(value: &str) -> bool {
    let value = value.trim();
    let number = value
        .strip_suffix("rem")
        .or_else(|| value.strip_suffix("px"))
        .unwrap_or(value);
    number
        .trim()
        .parse::<f32>()
        .is_ok_and(|n| n.is_finite() && n >= 0.)
        && (value.ends_with("rem") || value.ends_with("px") || number.trim() == "0")
}

/// The `--name: value` declarations of one selector's blocks, comments removed.
pub(super) fn css_variables(css: &str, selector: &str) -> BTreeMap<String, String> {
    let mut text = String::with_capacity(css.len());
    let mut rest = css;
    while let Some(start) = rest.find("/*") {
        text.push_str(&rest[..start]);
        rest = rest[start + 2..]
            .split_once("*/")
            .map_or("", |(_, after)| after);
    }
    text.push_str(rest);
    let mut variables = BTreeMap::new();
    let mut selector_start = 0;
    let mut open: Option<(String, usize)> = None;
    for (index, character) in text.char_indices() {
        match character {
            '{' => {
                open = Some((text[selector_start..index].trim().to_owned(), index + 1));
                selector_start = index + 1;
            }
            '}' => {
                if let Some((name, body)) = open.take()
                    && name.split(',').any(|part| part.trim() == selector)
                {
                    for declaration in text[body..index].split(';') {
                        if let Some((key, value)) = declaration.split_once(':')
                            && let Some(key) = key.trim().strip_prefix("--")
                        {
                            variables.insert(key.to_owned(), value.trim().to_owned());
                        }
                    }
                }
                selector_start = index + 1;
            }
            ';' if open.is_none() => selector_start = index + 1,
            _ => {}
        }
    }
    variables
}

/// The variables every theme needs: the neutral base color's `.dark` set.
fn required_variables() -> BTreeSet<String> {
    css_variables(BASE_COLORS[0].1, ".dark")
        .into_keys()
        .collect()
}

/// Checks that CSS has `:root` and `.dark` blocks naming every shadcn token.
pub(super) fn check_theme_css(css: &str) -> Result<()> {
    let required = required_variables();
    for selector in [":root", ".dark"] {
        let found = css_variables(css, selector);
        ensure!(!found.is_empty(), "no `{selector}` block with variables");
        let missing: Vec<_> = required
            .iter()
            .filter(|name| !found.contains_key(*name))
            .map(String::as_str)
            .collect();
        ensure!(
            missing.is_empty(),
            "`{selector}` is missing --{}",
            missing.join(", --")
        );
        let radius = found.get("radius");
        ensure!(
            selector == ".dark" || radius.is_some_and(|r| css_length_ok(r)),
            "`:root` needs `--radius` as a length in rem or px"
        );
    }
    Ok(())
}

/// The CSS the config describes: the base color with the radius applied, or the
/// imported CSS (`existing`) with the radius applied.
pub(super) fn theme_css(config: &ThemeConfig, existing: Option<&str>) -> Result<String> {
    let css = match &config.base_color {
        Some(name) => base_color_css(name)?.to_owned(),
        None => existing
            .context(format!(
                "{THEME_CSS} is missing; run `gpuicn theme set --base-color neutral` or `gpuicn theme import <css>`"
            ))?
            .to_owned(),
    };
    match &config.radius {
        Some(radius) => with_radius(&css, radius),
        None => Ok(css),
    }
}

/// `src/ui/app_theme.rs`: the theme pair and appearance for `ui::app::run`.
pub(super) fn app_theme_source(appearance: AppearanceSetting) -> String {
    format!(
        "{APP_THEME_HEADER}; change the theme with `gpuicn theme set` or\n\
         //! `gpuicn theme import`, or edit `{THEME_CSS}` and keep this file.\n\
         \n\
         use super::theme::{{Appearance, ThemeMode, UiTheme}};\n\
         \n\
         /// The app's shadcn theme CSS (`:root` is light, `.dark` is dark).\n\
         pub const CSS: &str = include_str!(\"../../{THEME_CSS}\");\n\
         /// The appearance gpuicn.toml selects; `System` follows the OS.\n\
         pub const APPEARANCE: Appearance = Appearance::{};\n\
         \n\
         /// The light theme from `{THEME_CSS}`.\n\
         pub fn light() -> UiTheme {{\n\
         \x20   UiTheme::from_shadcn_css(CSS, ThemeMode::Light).expect(\"{THEME_CSS} parses\")\n\
         }}\n\
         \n\
         /// The dark theme from `{THEME_CSS}`.\n\
         pub fn dark() -> UiTheme {{\n\
         \x20   UiTheme::from_shadcn_css(CSS, ThemeMode::Dark).expect(\"{THEME_CSS} parses\")\n\
         }}\n",
        appearance.variant()
    )
}

/// Writes `assets/theme.css` (kept when it exists and `replace` is false) and
/// regenerates `app_theme.rs` with its `pub mod` declaration.
pub(super) fn write_theme_files(root: &Path, config: &Config, replace: bool) -> Result<()> {
    let css_path = assets_dir(root, &config.output).join("theme.css");
    let existing = current_file(&css_path)?
        .map(|bytes| String::from_utf8(bytes).context("theme.css is not UTF-8"))
        .transpose()?;
    let css = theme_css(&config.theme, existing.as_deref())?;
    check_theme_css(&css).context("theme.css")?;
    match &existing {
        None => write_new(&css_path, css.as_bytes())?,
        Some(current) if *current == css => {}
        Some(_) if replace => {
            fs::write(&css_path, &css)?;
            println!("Write {}", css_path.display());
        }
        Some(_) => println!(
            "Keep {} (edited; `gpuicn theme set` regenerates it)",
            css_path.display()
        ),
    }
    let output = root.join(&config.output);
    let source = app_theme_source(config.theme.appearance);
    let path = output.join("app_theme.rs");
    let current = current_file(&path)?;
    if current.as_deref() != Some(source.as_bytes()) {
        if current
            .as_deref()
            .is_some_and(|text| !text.starts_with(APP_THEME_HEADER.as_bytes()))
        {
            println!("Keep {} (not generated by gpuicn)", path.display());
        } else {
            fs::create_dir_all(&output)?;
            fs::write(&path, &source)?;
            println!("Write {}", path.display());
        }
    }
    let mod_path = output.join("mod.rs");
    let existing_mod = String::from_utf8(current_file(&mod_path)?.unwrap_or_default())?;
    let updated_mod = declarations(&existing_mod, ["app_theme".to_owned()].into_iter())?;
    if updated_mod != existing_mod {
        fs::write(&mod_path, &updated_mod)?;
        println!("Write {}", mod_path.display());
    }
    Ok(())
}

/// Reads CSS from a path or URL, such as the shadcn theme editor's export.
pub(super) fn read_css(location: &str, root: &Path) -> Result<String> {
    let bytes = if location.starts_with("https://") || location.starts_with("http://") {
        download(&http_client()?, location, MAX_ITEM_BYTES)
            .with_context(|| format!("fetch {location}"))?
    } else {
        fs::read(root.join(location)).with_context(|| format!("read {location}"))?
    };
    String::from_utf8(bytes).context("theme CSS is not UTF-8")
}

/// `gpuicn theme import`: the CSS replaces the base color.
pub(super) fn import(
    root: &Path,
    config_path: &Path,
    mut config: Config,
    source: &str,
) -> Result<()> {
    let css = read_css(source, root)?;
    check_theme_css(&css).with_context(|| format!("{source} is not a complete shadcn theme"))?;
    let css_path = assets_dir(root, &config.output).join("theme.css");
    fs::create_dir_all(css_path.parent().context("assets directory")?)?;
    fs::write(&css_path, &css)?;
    println!("Write {} (from {source})", css_path.display());
    config.theme.base_color = None;
    config.theme.radius = None;
    write_config(config_path, &config)?;
    write_theme_files(root, &config, true)?;
    println!("\nThe app now uses the imported theme. `gpuicn theme preview` prints its tokens.");
    Ok(())
}

/// `gpuicn theme set`.
pub(super) fn set(
    root: &Path,
    config_path: &Path,
    mut config: Config,
    base_color: Option<String>,
    radius: Option<String>,
    appearance: Option<AppearanceSetting>,
) -> Result<()> {
    ensure!(
        base_color.is_some() || radius.is_some() || appearance.is_some(),
        "pass --base-color, --radius or --appearance"
    );
    if let Some(name) = base_color {
        base_color_css(&name)?;
        config.theme.base_color = Some(name);
    }
    if let Some(radius) = radius {
        ensure!(
            css_length_ok(&radius),
            "radius must be a CSS length in rem or px, such as 0.625rem"
        );
        config.theme.radius = Some(radius);
    }
    if let Some(appearance) = appearance {
        config.theme.appearance = appearance;
    }
    write_config(config_path, &config)?;
    write_theme_files(root, &config, true)
}

/// `gpuicn theme preview`: every token in both modes.
pub(super) fn preview(root: &Path, config: &Config) -> Result<()> {
    let css_path = assets_dir(root, &config.output).join("theme.css");
    let css = match current_file(&css_path)? {
        Some(bytes) => String::from_utf8(bytes)?,
        None => theme_css(&config.theme, None)?,
    };
    let light = css_variables(&css, ":root");
    let dark = css_variables(&css, ".dark");
    println!(
        "{} · appearance {}\n",
        config.theme.base_color.as_deref().map_or_else(
            || format!("imported ({})", css_path.display()),
            |c| format!("base color {c}")
        ),
        toml::Value::try_from(config.theme.appearance)?
            .as_str()
            .unwrap_or("system")
    );
    let width = light.keys().map(String::len).max().unwrap_or(0);
    println!("{:width$}  {:<28}  dark", "token", "light");
    for (name, value) in &light {
        println!(
            "{name:width$}  {value:<28}  {}",
            dark.get(name).map_or("(light)", String::as_str)
        );
    }
    Ok(())
}

pub(super) fn write_config(path: &Path, config: &Config) -> Result<()> {
    let mut config = config.clone();
    config.version = 2;
    let text = toml::to_string_pretty(&config)?;
    if current_file(path)?.as_deref() != Some(text.as_bytes()) {
        fs::write(path, text)?;
        println!("Write {}", path.display());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn base_colors_are_complete_and_radius_is_replaced() -> Result<()> {
        for (name, css) in BASE_COLORS {
            check_theme_css(css).with_context(|| name.to_owned())?;
            let rounded = with_radius(css, "0.5rem")?;
            assert_eq!(
                css_variables(&rounded, ":root")["radius"],
                "0.5rem",
                "{name}"
            );
            assert_eq!(
                css_variables(&rounded, ":root").len(),
                css_variables(css, ":root").len()
            );
        }
        assert!(with_radius(BASE_COLORS[0].1, "big").is_err());
        let no_radius =
            ":root {\n  --background: oklch(1 0 0);\n}\n.dark { --background: oklch(0 0 0); }";
        assert_eq!(
            css_variables(&with_radius(no_radius, "4px")?, ":root")["radius"],
            "4px"
        );
        assert!(check_theme_css(no_radius).is_err());
        Ok(())
    }

    #[test]
    fn theme_files_follow_the_config_and_keep_edits() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let root = temp.path();
        let config = Config {
            version: 2,
            registry: "r".into(),
            output: "src/ui".into(),
            mode: Mode::Source,
            theme: ThemeConfig {
                base_color: Some("zinc".into()),
                radius: Some("0.5rem".into()),
                appearance: AppearanceSetting::Dark,
            },
        };
        write_theme_files(root, &config, false)?;
        let css = fs::read_to_string(root.join("assets/theme.css"))?;
        assert_eq!(css, with_radius(base_color_css("zinc")?, "0.5rem")?);
        let generated = fs::read_to_string(root.join("src/ui/app_theme.rs"))?;
        assert!(generated.contains("include_str!(\"../../assets/theme.css\")"));
        assert!(generated.contains("Appearance::Dark"));
        assert_eq!(
            fs::read_to_string(root.join("src/ui/mod.rs"))?,
            "pub mod app_theme;\n"
        );
        syn::parse_file(&generated)?;

        fs::write(
            root.join("assets/theme.css"),
            "/* mine */\n".to_owned() + &css,
        )?;
        write_theme_files(root, &config, false)?;
        assert!(fs::read_to_string(root.join("assets/theme.css"))?.starts_with("/* mine */"));
        write_theme_files(root, &config, true)?;
        assert_eq!(fs::read_to_string(root.join("assets/theme.css"))?, css);

        let deep = Config {
            output: "src/components/ui".into(),
            ..config.clone()
        };
        assert_eq!(assets_dir(root, &deep.output), root.join("src/assets"));

        let imported = base_color_css("stone")?.replace("0.625rem", "1rem");
        fs::write(root.join("import.css"), &imported)?;
        import(
            root,
            &root.join("gpuicn.toml"),
            config.clone(),
            "import.css",
        )?;
        assert_eq!(fs::read_to_string(root.join("assets/theme.css"))?, imported);
        let saved: Config = toml::from_str(&fs::read_to_string(root.join("gpuicn.toml"))?)?;
        assert_eq!(saved.version, 2);
        assert_eq!(saved.theme.base_color, None);
        assert_eq!(saved.theme.radius, None);
        assert_eq!(saved.theme.appearance, AppearanceSetting::Dark);
        set(
            root,
            &root.join("gpuicn.toml"),
            saved,
            None,
            Some("2px".into()),
            Some(AppearanceSetting::Light),
        )?;
        assert_eq!(
            css_variables(&fs::read_to_string(root.join("assets/theme.css"))?, ":root")["radius"],
            "2px"
        );
        assert!(
            fs::read_to_string(root.join("src/ui/app_theme.rs"))?.contains("Appearance::Light")
        );
        assert!(fs::write(root.join("bad.css"), ":root { --a: b; }").is_ok());
        assert!(import(root, &root.join("gpuicn.toml"), config, "bad.css").is_err());
        Ok(())
    }
}