kitchen-ui 0.0.10

Shared UI for GPUI apps (gpui-kit): design tokens, light and dark themes with a contrast-checked accent, widgets, a parameter editor, icon bundling and its test
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
//! Icons: what an app ships ([`AppAssets`]: gpui-kit's component icons, the few Lucide icons the
//! app adds, and its own files), and the check that every icon its code names is shipped
//! ([`assert_icons_bundled`]): an icon missing from the assets draws nothing and logs an error.
//!
//! An app lists the icons it adds with gpui-kit's macro, so the binary carries those alone rather
//! than the whole catalog:
//!
//! ```ignore
//! gpui_kit::assets::icon_assets!(pub ExtraIcons, [AudioWaveform, Workflow, Microscope]);
//!
//! let assets = kitchen_ui::icons::AppAssets::new().icons(ExtraIcons).file(LOGO, LOGO_PNG);
//! gpui_kit::application().with_assets(assets).run(|cx| { /* … */ });
//!
//! #[test]
//! fn every_icon_used_is_bundled() {
//!     let assets = kitchen_ui::icons::AppAssets::new().icons(ExtraIcons);
//!     kitchen_ui::icons::assert_icons_bundled(&assets, &[concat!(env!("CARGO_MANIFEST_DIR"), "/src")]);
//! }
//! ```

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use gpui_kit::assets::IconName;
use gpui_kit::{AssetSource, SharedString};

/// The icons every app uses for the same thing (Design System, "The frame"): a view that does the
/// same job has the same icon in every app, and the shared workspaces have theirs. kitchen-ui
/// always ships them ([`FrameIcons`]), so naming one needs nothing in the app's icon set.
pub mod standard {
    use gpui_kit::assets::IconName;

    /// Explore: browse the data (a map).
    pub const EXPLORE: IconName = IconName::Map;
    /// Analysis: results in tables and figures (a table).
    pub const ANALYSIS: IconName = IconName::Table;
    /// Curation: go through items and accept or reject them (a checklist; not the home icon).
    pub const CURATION: IconName = IconName::ListChecks;
    /// Sorting: split a signal into its sources (spike sorting, cell separation).
    pub const SORTING: IconName = IconName::Split;
    /// The shared Pipeline workspace.
    pub const PIPELINE: IconName = IconName::Workflow;
    /// The shared Code workspace.
    pub const CODE: IconName = IconName::CodeXml;
    /// The Panels drawer of a narrow window (the side panes, folded away).
    pub const PANELS: IconName = IconName::PanelsTopLeft;
    /// The general menu (File, Edit, View, Help) of a narrow window.
    pub const MENU: IconName = IconName::Menu;
    /// File → Open… and the file picker's folders.
    pub const OPEN: IconName = IconName::FolderOpen;
    /// The theme switch.
    pub const THEME: IconName = IconName::SunMoon;
    /// File picker places: home, desktop, downloads, recent.
    pub const HOME: IconName = IconName::House;
    /// File picker place: the desktop.
    pub const DESKTOP: IconName = IconName::Monitor;
    /// File picker place: downloads.
    pub const DOWNLOADS: IconName = IconName::Download;
    /// File picker place: recent files.
    pub const RECENT: IconName = IconName::Clock;
    /// The file picker's "up one folder".
    pub const UP: IconName = IconName::FolderUp;
    /// A table file (CSV, Parquet) in the file picker.
    pub const FILE_TABLE: IconName = IconName::FileSpreadsheet;
    /// An image or video file in the file picker.
    pub const FILE_IMAGE: IconName = IconName::FileImage;
    /// A script in the file picker.
    pub const FILE_CODE: IconName = IconName::FileCode;
}

mod frame_icons {
    #![allow(missing_docs)]
    gpui_kit::assets::icon_assets!(
        pub FrameIcons,
        [Map, Table, ListChecks, Split, Workflow, CodeXml, PanelsTopLeft, SunMoon, House, Monitor, Download, Clock, FolderUp, FileSpreadsheet, FileImage, FileCode]
    );
}

/// The standard icons ([`standard`]) that gpui-kit's component set lacks; [`AppAssets`] always
/// serves them.
pub use frame_icons::FrameIcons;

/// The assets an app ships: its own files (a logo), then the icon sets it adds, then gpui-kit's
/// component icons (or the whole Lucide catalog, [`AppAssets::all_icons`]).
#[derive(Default)]
pub struct AppAssets {
    files: Vec<(&'static str, &'static [u8])>,
    extra: Vec<Box<dyn AssetSource>>,
    all_icons: bool,
}

impl AppAssets {
    /// gpui-kit's component icons alone.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a set of icons (one made with `gpui_kit::assets::icon_assets!`), or any other source.
    pub fn icons(mut self, source: impl AssetSource) -> Self {
        self.extra.push(Box::new(source));
        self
    }

    /// Adds a file served at `path` (for `img(path)`: a logo, a picture in the about dialog).
    pub fn file(mut self, path: &'static str, bytes: &'static [u8]) -> Self {
        self.files.push((path, bytes));
        self
    }

    /// Ships the whole Lucide catalog instead of the component icons (a larger binary; for an app
    /// that has not listed its icons yet).
    pub fn all_icons(mut self) -> Self {
        self.all_icons = true;
        self
    }

    #[cfg(not(target_family = "wasm"))]
    fn base(&self) -> &dyn AssetSource {
        if self.all_icons { &gpui_kit::assets::AllAssets } else { &gpui_kit::assets::Assets }
    }

    /// In a browser gpui-kit's own source downloads each icon when it is first asked for and
    /// reports an error until it arrives (every frame, for every icon); here the component icons
    /// are embedded instead ([`ComponentIcons`]), as on the desktop. The whole catalog is not
    /// offered there: list the icons the app adds.
    #[cfg(target_family = "wasm")]
    fn base(&self) -> &dyn AssetSource {
        let _ = self.all_icons;
        &ComponentIcons
    }
}

// gpui-kit's component icons (its `default-icons.txt`, 0.9.1), embedded for the browser build.
#[cfg(target_family = "wasm")]
gpui_kit::assets::icon_assets!(
    ComponentIcons,
    [
        ALargeSmall,
        ArrowDown,
        ArrowLeft,
        ArrowRight,
        ArrowUp,
        Asterisk,
        Ban,
        BatteryCharging,
        BatteryFull,
        BatteryLow,
        BatteryMedium,
        BatteryWarning,
        Battery,
        Bell,
        BookOpen,
        Bot,
        Building2,
        Calendar,
        CaseSensitive,
        ChartPie,
        Check,
        ChevronDown,
        ChevronLeft,
        ChevronRight,
        ChevronUp,
        ChevronsUpDown,
        CircleAlert,
        CircleCheck,
        CircleUser,
        CircleX,
        Close,
        Copy,
        Cpu,
        Dash,
        Delete,
        EllipsisVertical,
        Ellipsis,
        ExternalLink,
        EyeOff,
        Eye,
        FileText,
        File,
        FolderClosed,
        FolderOpen,
        Folder,
        Frame,
        GalleryVerticalEnd,
        Github,
        Globe,
        HardDrive,
        HeartOff,
        Heart,
        Inbox,
        Info,
        Inspector,
        LayoutDashboard,
        LoaderCircle,
        Loader,
        Map,
        Maximize,
        MemoryStick,
        Menu,
        Mic,
        Minimize,
        Minus,
        Moon,
        Network,
        Palette,
        PanelBottomOpen,
        PanelBottom,
        PanelLeftClose,
        PanelLeftOpen,
        PanelLeft,
        PanelRightClose,
        PanelRightOpen,
        PanelRight,
        Pause,
        Play,
        Plus,
        Redo2,
        Redo,
        RefreshCw,
        Replace,
        ResizeCorner,
        RotateCw,
        Search,
        Settings2,
        Settings,
        SortAscending,
        SortDescending,
        SquareTerminal,
        Square,
        StarFill,
        StarOff,
        Star,
        Sun,
        ThumbsDown,
        ThumbsUp,
        TriangleAlert,
        Undo2,
        Undo,
        User,
        WindowClose,
        WindowMaximize,
        WindowMinimize,
        WindowRestore
    ]
);

impl AssetSource for AppAssets {
    fn load(&self, path: &str) -> gpui_kit::Result<Option<Cow<'static, [u8]>>> {
        if let Some((_, bytes)) = self.files.iter().find(|(p, _)| *p == path) {
            return Ok(Some(Cow::Borrowed(bytes)));
        }
        for source in &self.extra {
            if let Some(bytes) = source.load(path)? {
                return Ok(Some(bytes));
            }
        }
        if let Some(bytes) = FrameIcons.load(path)? {
            return Ok(Some(bytes));
        }
        self.base().load(path)
    }

    fn list(&self, path: &str) -> gpui_kit::Result<Vec<SharedString>> {
        let mut paths = self.base().list(path)?;
        paths.extend(FrameIcons.list(path)?);
        for source in &self.extra {
            paths.extend(source.list(path)?);
        }
        paths.extend(self.files.iter().filter(|(p, _)| p.starts_with(path)).map(|(p, _)| SharedString::from(*p)));
        paths.sort();
        paths.dedup();
        Ok(paths)
    }
}

/// The names of the icons the Rust sources under `roots` name: `IconName::Server`, and the same
/// through an alias (`use gpui_kit::assets::IconName as I;` then `I::Server`, or
/// `type Icons = IconName;`). Aliases are collected from every file first, so an alias declared
/// in one module and used in another is found too. Only real icon names are kept, so another
/// type behind the same alias adds nothing. A glob import (`use IconName::*`) is not seen.
pub fn icon_names_used(roots: &[impl AsRef<Path>]) -> BTreeSet<String> {
    let texts: Vec<String> = rust_files(roots).iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect();
    let mut markers: BTreeSet<String> = BTreeSet::from(["IconName".to_string()]);
    for text in &texts {
        markers.extend(aliases_in(text));
    }
    let known: BTreeSet<String> = IconName::ALL.iter().map(|i| format!("{i:?}")).collect();
    let mut used = BTreeSet::new();
    for text in &texts {
        used.extend(names_after(text, &markers).into_iter().filter(|n| known.contains(n)));
    }
    used
}

/// The icons named in `used` that `assets` cannot load.
pub fn missing_icons(assets: &dyn AssetSource, used: &BTreeSet<String>) -> Vec<String> {
    let mut missing = Vec::new();
    for name in used {
        let Some(icon) = IconName::ALL.iter().find(|i| format!("{i:?}") == *name) else { continue };
        if assets.load(&icon.path()).ok().flatten().is_none() {
            missing.push(name.clone());
        }
    }
    missing
}

/// Panics unless every icon the sources under `roots` name is in `assets` (and at least one icon
/// is found, so a wrong root fails instead of passing empty). For an app's test.
pub fn assert_icons_bundled(assets: &dyn AssetSource, roots: &[impl AsRef<Path>]) {
    let used = icon_names_used(roots);
    assert!(
        !used.is_empty(),
        "no icons found in the sources: are the roots right? {:?}",
        roots.iter().map(|r| r.as_ref().display().to_string()).collect::<Vec<_>>()
    );
    let missing = missing_icons(assets, &used);
    assert!(missing.is_empty(), "icons used but not bundled (add them to the app's icon set): {missing:?}");
}

/// Every `.rs` file under `roots` (roots that do not exist are skipped).
fn rust_files(roots: &[impl AsRef<Path>]) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack: Vec<PathBuf> = roots.iter().map(|r| r.as_ref().to_path_buf()).collect();
    while let Some(path) = stack.pop() {
        if path.is_dir() {
            let Ok(entries) = std::fs::read_dir(&path) else { continue };
            stack.extend(entries.flatten().map(|e| e.path()));
        } else if path.extension().is_some_and(|x| x == "rs") {
            out.push(path);
        }
    }
    out.sort();
    out
}

/// Names `IconName` goes by in `text`: `IconName as I` (in a `use`, grouped or not) and
/// `type I = …IconName;`.
fn aliases_in(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    for (at, _) in text.match_indices("IconName") {
        let rest = text[at + "IconName".len()..].trim_start();
        if let Some(after) = rest.strip_prefix("as") {
            if after.starts_with(char::is_whitespace) {
                let name = ident_at(after.trim_start());
                if !name.is_empty() && name != "_" {
                    out.push(name);
                }
            }
        }
    }
    for (at, _) in text.match_indices("type ") {
        if at > 0 && is_ident_char(text[..at].chars().next_back().unwrap_or(' ')) {
            continue;
        }
        let rest = &text[at + 5..];
        let name = ident_at(rest.trim_start());
        let Some(eq) = rest.find('=') else { continue };
        let Some(end) = rest[eq..].find(';') else { continue };
        let target = rest[eq + 1..eq + end].trim();
        if !name.is_empty() && (target == "IconName" || target.ends_with("::IconName")) {
            out.push(name);
        }
    }
    out
}

/// The capitalised names after `marker::` for each marker, where the marker is a whole word.
fn names_after(text: &str, markers: &BTreeSet<String>) -> Vec<String> {
    let mut out = Vec::new();
    for m in markers {
        let pat = format!("{m}::");
        for (at, _) in text.match_indices(&pat) {
            if text[..at].chars().next_back().is_some_and(is_ident_char) {
                continue;
            }
            let name = ident_at(&text[at + pat.len()..]);
            if name.starts_with(|c: char| c.is_ascii_uppercase()) {
                out.push(name);
            }
        }
    }
    out
}

fn ident_at(s: &str) -> String {
    s.chars().take_while(|c| is_ident_char(*c)).collect()
}

fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

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

    fn markers(text: &str) -> BTreeSet<String> {
        let mut m = BTreeSet::from(["IconName".to_string()]);
        m.extend(aliases_in(text));
        m
    }

    #[test]
    fn finds_names_and_aliases() {
        let text = r#"
            use gpui_kit::assets::IconName as I;
            use gpui_kit::{assets::{IconName as Lucide, Assets}, px};
            type Icons = gpui_kit::assets::IconName;
            fn f() { (IconName::Plus, I::Server, Lucide::Columns2, Icons::Flame, UI::Nope, I::new()) }
        "#;
        let m = markers(text);
        assert_eq!(m, BTreeSet::from(["IconName", "I", "Lucide", "Icons"].map(String::from)));
        let mut names = names_after(text, &m);
        names.sort();
        // `UI::Nope` is not `I::Nope`; `I::new` is not a name
        assert_eq!(names, ["Columns2", "Flame", "Plus", "Server"]);
    }

    #[test]
    fn an_alias_named_like_a_type_is_filtered_by_real_names() {
        // dsp-kitchen aliases the enum as `Assets` while `Assets` is also gpui-kit's asset source
        let text = "use gpui_kit::assets::IconName as Assets; let _ = (Assets::AppWindow, Assets::load);";
        let names = names_after(text, &markers(text));
        assert_eq!(names, ["AppWindow"]);
    }

    /// kitchen-ui's widgets name only icons gpui-kit's component set ships: the check run here as
    /// an app runs it (over the widget sources; this file's test texts name icons on purpose).
    #[test]
    fn every_icon_used_is_bundled() {
        let root = env!("CARGO_MANIFEST_DIR");
        assert_icons_bundled(
            &AppAssets::new(),
            &[format!("{root}/src/widgets"), format!("{root}/src/param_editor.rs")],
        );
    }

    #[test]
    fn a_missing_icon_is_reported() {
        let used = BTreeSet::from(["Microscope".to_string(), "Plus".to_string()]);
        assert_eq!(missing_icons(&AppAssets::new(), &used), ["Microscope"]);
        gpui_kit::assets::icon_assets!(Extra, [Microscope]);
        assert!(missing_icons(&AppAssets::new().icons(Extra), &used).is_empty());
    }

    /// The standard icons come with kitchen-ui: an app names them without adding them.
    #[test]
    fn the_standard_icons_are_always_shipped() {
        let root = env!("CARGO_MANIFEST_DIR");
        let used = icon_names_used(&[format!("{root}/src/icons.rs")]);
        let standard: BTreeSet<String> = [
            "Map",
            "Table",
            "ListChecks",
            "Split",
            "Workflow",
            "CodeXml",
            "PanelsTopLeft",
            "Menu",
            "FolderOpen",
            "SunMoon",
            "House",
            "Monitor",
            "Download",
            "Clock",
            "FolderUp",
            "FileSpreadsheet",
            "FileImage",
            "FileCode",
        ]
        .map(String::from)
        .into();
        for name in &standard {
            assert!(used.contains(name), "{name} is named in `standard`");
        }
        // (this file's own test texts name icons on purpose; only the standard ones are checked)
        assert_eq!(missing_icons(&AppAssets::new(), &standard), Vec::<String>::new());
    }
}