fluidattacks-designs 0.12.0

Fluid Attacks design system, GPUI variant: desktop widgets over the shared tokens
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
//! Runtime asset resolution: icons at `icons/<style>/<name>.svg`, illustrations
//! at `images/<public-id>.png`.
//!
//! Everything resolves from one place — the `Resources` directory beside the
//! running executable — so the app carries no asset knowledge at all: no
//! directory to configure, no table to bake in, no variable to export, and no
//! second path that behaves differently. Putting the files there is the
//! packaging step's job, which is where this component's `assets` directory is
//! pointed.
//!
//! That layout is macOS's own: a bundle runs `Contents/MacOS/<bin>` and reads
//! `Contents/Resources`. A `cargo run` puts the binary in `target/debug`, so the
//! dev shell materializes `target/Resources` and the same single lookup holds.
//!
//! Apps register [`Assets`] with `Application::with_assets`.

use std::borrow::Cow;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;

use fluidattacks_designs_domain::color::GRADIENT_01;
use gpui::{AssetSource, Result, SharedString};

/// The design system's assets, resolved beside the executable.
#[derive(Default, Clone, Copy)]
#[non_exhaustive]
pub struct Assets;

impl Assets {
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

/// Where a `Resources` directory may sit for an executable at `exe`: nearest
/// first, walking up.
///
/// One rule covers every way these binaries run. A bundle executes
/// `Contents/MacOS/<bin>` and answers on the first step. A `cargo run` leaves
/// the binary in `target/debug` and an example one level under that, so the
/// same `target/Resources` answers on the first step or the second.
fn candidates(exe: &Path) -> Vec<PathBuf> {
    exe.ancestors()
        .skip(2)
        .take(3)
        .map(|dir| dir.join("Resources"))
        .collect()
}

/// The `Resources` this design system put its assets in.
///
/// Resolved once: every glyph a frame paints would otherwise re-derive it, and
/// the answer cannot change while the process runs.
fn resources() -> Result<PathBuf> {
    static ROOT: OnceLock<Option<PathBuf>> = OnceLock::new();
    let found = ROOT.get_or_init(|| {
        let exe = std::env::current_exe().ok()?;
        // The glyph directory is the marker. Walking up for a bare `Resources`
        // would otherwise accept an unrelated one beside the bundle — a
        // download directory holding both is enough — and its contents reach a
        // renderer and the text system.
        candidates(&exe)
            .into_iter()
            .find(|path| path.join("icons").is_dir())
    });
    found.clone().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "no Resources holding the design system's assets at or above this \
             executable, so the packaging step did not land them",
        )
        .into()
    })
}

/// Whether `path` is one of ours and stays inside `Resources`.
///
/// Returns a verdict rather than the path: it sanitizes nothing, and handing
/// the input back would read as though it had.
fn is_ours(path: &str) -> bool {
    if !(path.starts_with("icons/") || path.starts_with("images/")) {
        return false;
    }
    // by component, so a glyph named `v1..2` is served rather than refused
    !Path::new(path)
        .components()
        .any(|part| matches!(part, Component::ParentDir | Component::RootDir))
}

/// Gradient glyphs derive from the solid set: the web's `fa-gradient` fill
/// (`gradients.svg` gradient-01, -45deg) injected into the svg, so the color
/// tracks the tokens. The intrinsic 24px size bounds the raster (gpui renders
/// images at size x2, and the raw viewbox would downscale ~40:1).
fn gradient_svg(solid: &str) -> String {
    let (from, to) = GRADIENT_01;
    let defs = format!(
        "<defs><linearGradient id=\"designs-gradient\" \
         gradientTransform=\"rotate(-45)\"><stop stop-color=\"#{from:06x}\"/>\
         <stop offset=\"1\" stop-color=\"#{to:06x}\"/></linearGradient></defs>"
    );
    solid
        .replacen("<svg ", "<svg width=\"24\" height=\"24\" ", 1)
        .replacen('>', &format!(">{defs}"), 1)
        .replace("<path ", "<path fill=\"url(#designs-gradient)\" ")
}

/// A gradient request reads the solid glyph: the fill is injected, not stored.
/// Rewrites the directory form too (`icons/gradient` alone), so [`Assets::list`]
/// looks where [`Assets::load`] reads instead of at a `gradient/` that no kit
/// carries.
fn solid_source(path: &str) -> (Cow<'_, str>, bool) {
    match path.strip_prefix("icons/gradient") {
        // guard the separator, or `icons/gradientfoo` would rewrite as well
        Some(rest) if rest.is_empty() || rest.starts_with('/') => {
            (Cow::Owned(format!("icons/solid{rest}")), true)
        }
        _ => (Cow::Borrowed(path), false),
    }
}

/// Every face the design system's type is set in, for [`crate::Theme::init`].
///
/// Read rather than baked in, from the same `Resources` the glyphs come from,
/// so an app carries no font knowledge and the licences travel beside the
/// faces they cover.
///
/// # Errors
///
/// Fails when the directory is absent or holds no face — the widgets name
/// `Roboto` by family, and a fallback typeface is not what anyone chose.
pub fn faces() -> Result<Vec<Cow<'static, [u8]>>> {
    faces_in(&resources()?)
}

fn faces_in(root: &Path) -> Result<Vec<Cow<'static, [u8]>>> {
    let dir = root.join("fonts");
    let mut files: Vec<PathBuf> = fs::read_dir(&dir)
        .into_iter()
        .flatten()
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.extension().is_some_and(|kind| kind == "ttf"))
        .collect();
    // read_dir yields in filesystem order, so sort: one machine registers the
    // faces exactly as another does
    files.sort();
    if files.is_empty() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!(
                "no .ttf under {}, so the type would be the platform's",
                dir.display()
            ),
        )
        .into());
    }
    files
        .iter()
        .map(|file| fs::read(file).map(Cow::Owned).map_err(Into::into))
        .collect()
}

fn load_from(root: &Path, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
    if !is_ours(path) {
        return Ok(None);
    }
    let (source, gradient) = solid_source(path);
    let Ok(bytes) = fs::read(root.join(source.as_ref())) else {
        // Loudly: a miss means the packaging step did not land the assets, and a
        // silent `None` is how that stays invisible until someone squints at an
        // empty square.
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("no design system asset {path} under {}", root.display()),
        )
        .into());
    };
    if !gradient {
        return Ok(Some(Cow::Owned(bytes)));
    }
    // the only branch that has to reshape: the fill is injected into the text
    let Ok(svg) = String::from_utf8(bytes) else {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("{path} is not utf-8, so no gradient can be injected"),
        )
        .into());
    };
    Ok(Some(Cow::Owned(gradient_svg(&svg).into_bytes())))
}

fn list_from(root: &Path, path: &str) -> Vec<SharedString> {
    // resolve through the same rewrite `load` uses, or a gradient listing
    // reports nothing for a namespace `load` happily serves
    let (source, _) = solid_source(path);
    if !is_ours(&source) {
        return Vec::new();
    }
    let mut names: Vec<SharedString> = fs::read_dir(root.join(source.as_ref()))
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|entry| entry.file_name().into_string().ok())
        .map(SharedString::from)
        .collect();
    names.sort_unstable();
    names.dedup();
    names
}

impl AssetSource for Assets {
    fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
        load_from(&resources()?, path)
    }

    fn list(&self, path: &str) -> Result<Vec<SharedString>> {
        Ok(list_from(&resources()?, path))
    }
}

#[cfg(test)]
mod tests {
    use super::{candidates, gradient_svg, list_from, load_from};
    use fluidattacks_designs_domain::icon::REQUIRED_ICONS;
    use std::path::{Path, PathBuf};

    const SOLID: &str = "<svg xmlns=\"x\" viewBox=\"0 0 512 512\"><path d=\"M0\"/></svg>";

    /// A `Resources` tree holding one glyph and one illustration.
    fn resources(case: &str) -> PathBuf {
        let root = std::env::temp_dir().join("designs-assets-tests").join(case);
        let _ = std::fs::remove_dir_all(&root);
        write(&root.join("icons/solid/gear.svg"), SOLID.as_bytes());
        write(
            &root.join("images/integrates/empty/addRoot.png"),
            b"\x89PNG stub",
        );
        root
    }

    fn write(file: &Path, body: &[u8]) {
        if let Some(parent) = file.parent() {
            std::fs::create_dir_all(parent).expect("create the fixture directory");
        }
        std::fs::write(file, body).expect("write the fixture");
    }

    fn glyph_constants() -> Vec<(String, String)> {
        let tokens = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("domain")
            .join("src");
        let sources = crate_sources(tokens);
        sources
            .iter()
            .flat_map(|source| source.lines().filter_map(declared_glyph))
            .collect()
    }

    fn declared_glyph(line: &str) -> Option<(String, String)> {
        let rest = line.trim().strip_prefix("pub const ")?;
        let (name, tail) = rest.split_once(": &str = \"")?;
        let (glyph, _) = tail.split_once('"')?;
        Some((name.to_owned(), glyph.to_owned()))
    }

    fn resolve(argument: &str, declared: &[(String, String)]) -> Option<String> {
        if let Some(quoted) = argument.strip_prefix('"') {
            return quoted.split_once('"').map(|(glyph, _)| glyph.to_owned());
        }
        declared
            .iter()
            .find(|(name, _)| name == argument)
            .map(|(_, glyph)| glyph.clone())
    }

    fn named_glyphs(source: &str, declared: &[(String, String)]) -> Vec<String> {
        // assembled rather than written, so the scan does not match itself
        let call = concat!("Icon", "::new(");
        source
            .split(call)
            .skip(1)
            .filter_map(|rest| rest.split_once(')').map(|(argument, _)| argument.trim()))
            .filter_map(|argument| resolve(argument, declared))
            .collect()
    }

    fn crate_sources(dir: PathBuf) -> Vec<String> {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return Vec::new();
        };
        let mut sources = Vec::new();
        for path in entries.flatten().map(|entry| entry.path()) {
            if path.is_dir() {
                sources.extend(crate_sources(path));
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                sources.extend(std::fs::read_to_string(path));
            }
        }
        sources
    }

    #[test]
    fn required_icons_covers_every_glyph_the_widgets_name() {
        let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let sources = crate_sources(dir);
        assert!(
            sources.len() > 1,
            "the scan found no sources, so it is not reading the crate"
        );
        let declared = glyph_constants();
        assert!(
            !declared.is_empty(),
            "no token constants were read, so glyphs named through one go unchecked"
        );
        let missing: Vec<String> = sources
            .iter()
            .flat_map(|source| named_glyphs(source, &declared))
            .filter(|glyph| {
                !REQUIRED_ICONS
                    .iter()
                    .any(|&(_, listed)| listed == glyph.as_str())
            })
            .collect();
        assert!(
            missing.is_empty(),
            "add these to REQUIRED_ICONS: {missing:?}"
        );
    }

    /// Every layout the one rule has to serve, nearest first.
    #[test]
    fn resources_resolves_for_a_bundle_a_binary_and_an_example() {
        assert_eq!(
            candidates(Path::new("/A/mrq.app/Contents/MacOS/mrq")).first(),
            Some(&PathBuf::from("/A/mrq.app/Contents/Resources"))
        );
        for exe in [
            "/repo/target/debug/mrq",
            "/repo/target/debug/examples/gallery",
        ] {
            assert!(
                candidates(Path::new(exe)).contains(&PathBuf::from("/repo/target/Resources")),
                "{exe} never looks in target/Resources"
            );
        }
    }

    #[test]
    fn both_namespaces_resolve_from_resources() {
        let root = resources("namespaces");
        for path in [
            "icons/solid/gear.svg",
            "images/integrates/empty/addRoot.png",
        ] {
            assert!(load_from(&root, path).expect("ok").is_some(), "{path}");
        }
    }

    /// A miss means the packaging step failed, which must not read as an empty
    /// square.
    #[test]
    fn a_missing_asset_is_an_error_naming_where_it_looked() {
        let root = resources("missing");
        let error = load_from(&root, "icons/solid/nonesuch.svg").expect_err("a miss must fail");
        assert!(error.to_string().contains("icons/solid/nonesuch.svg"));
        assert!(error.to_string().contains(&root.display().to_string()));
    }

    #[test]
    fn a_foreign_namespace_is_absent_rather_than_broken() {
        let root = resources("foreign");
        assert!(load_from(&root, "elsewhere/thing.png")
            .expect("ok")
            .is_none());
    }

    /// The guard is what keeps an asset path from reading the rest of the disk.
    #[test]
    fn a_path_climbing_out_of_resources_is_refused() {
        let root = resources("escape");
        for path in ["icons/../../etc/passwd", "icons/gradient/../../../secret"] {
            assert!(load_from(&root, path).expect("ok").is_none(), "{path}");
        }
    }

    /// Refusing by component rather than by substring: a glyph may legitimately
    /// carry dots, and refusing one paints nothing and says nothing.
    #[test]
    fn a_glyph_whose_name_contains_dots_is_served() {
        let root = resources("dots");
        write(&root.join("icons/solid/v1..2.svg"), SOLID.as_bytes());
        assert!(load_from(&root, "icons/solid/v1..2.svg")
            .expect("ok")
            .is_some());
    }

    #[test]
    fn every_face_in_resources_is_read_in_a_stable_order() {
        let root = resources("faces");
        write(&root.join("fonts/Zeta-Bold.ttf"), b"ttf");
        write(&root.join("fonts/Alpha-Regular.ttf"), b"ttf");
        write(&root.join("fonts/notes.txt"), b"not a face");
        let faces = super::faces_in(&root).expect("faces");
        assert_eq!(faces.len(), 2, "only the faces, and both of them");
    }

    /// A fallback typeface is not what anyone chose, so an empty directory has
    /// to say so rather than render in whatever the platform offers.
    #[test]
    fn a_resources_directory_without_a_face_fails() {
        let root = resources("no-faces");
        let error = super::faces_in(&root).expect_err("an empty directory must fail");
        assert!(error.to_string().contains("no .ttf"));
    }

    #[test]
    fn listing_walks_the_resources_directory() {
        let root = resources("listing");
        assert!(list_from(&root, "icons/solid").contains(&"gear.svg".into()));
        assert!(list_from(&root, "images/integrates").contains(&"empty".into()));
    }

    #[test]
    fn listing_gradients_reports_the_solid_set() {
        let root = resources("gradient-list");
        for path in ["icons/gradient", "icons/gradient/"] {
            assert!(
                list_from(&root, path).contains(&"gear.svg".into()),
                "{path} listed nothing"
            );
        }
    }

    #[test]
    fn gradient_derives_from_the_solid_glyph() {
        let root = resources("gradient");
        let bytes = load_from(&root, "icons/gradient/gear.svg")
            .expect("ok")
            .expect("some");
        let svg = String::from_utf8(bytes.to_vec()).expect("utf-8");
        assert!(svg.contains("url(#designs-gradient)"));
    }

    #[test]
    fn a_namespace_that_merely_starts_with_gradient_is_left_alone() {
        let (source, gradient) = super::solid_source("icons/gradientfoo/x.svg");
        assert_eq!(source, "icons/gradientfoo/x.svg");
        assert!(!gradient);
    }

    #[test]
    fn gradient_bounds_the_raster_and_fills_every_path() {
        let svg = gradient_svg(SOLID);
        assert!(svg.starts_with("<svg width=\"24\" height=\"24\" "));
        assert!(svg.contains("<path fill=\"url(#designs-gradient)\" d="));
    }

    #[test]
    fn gradient_defs_land_inside_the_svg_element() {
        assert!(gradient_svg(SOLID).contains("512\"><defs><linearGradient"));
    }

    #[test]
    fn gradient_fill_tracks_the_palette() {
        let svg = gradient_svg(SOLID);
        assert!(svg.contains("stop-color=\"#f32637\""));
        assert!(svg.contains("stop-color=\"#b8075d\""));
    }
}