Skip to main content

gpui_component_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::parse::{Parse, ParseStream};
4
5mod derive_into_plot;
6
7/// Input for icon_name! macro: EnumName, "path", [optional derives]
8struct IconNameInput {
9    enum_name: syn::Ident,
10    _comma: syn::Token![,],
11    path: syn::LitStr,
12    derives: Option<(
13        syn::Token![,],
14        syn::punctuated::Punctuated<syn::Path, syn::Token![,]>,
15    )>,
16}
17
18impl Parse for IconNameInput {
19    fn parse(input: ParseStream) -> syn::Result<Self> {
20        let enum_name = input.parse()?;
21        let _comma = input.parse()?;
22        let path = input.parse()?;
23
24        // Check if there's an optional derives list
25        let derives = if input.peek(syn::Token![,]) {
26            let comma = input.parse()?;
27            let content;
28            syn::bracketed!(content in input);
29            let derives = content.parse_terminated(syn::Path::parse, syn::Token![,])?;
30            Some((comma, derives))
31        } else {
32            None
33        };
34
35        Ok(IconNameInput {
36            enum_name,
37            _comma,
38            path,
39            derives,
40        })
41    }
42}
43
44#[proc_macro_derive(IntoPlot)]
45pub fn derive_into_plot(input: TokenStream) -> TokenStream {
46    derive_into_plot::derive_into_plot(input)
47}
48
49/// Convert an SVG filename to PascalCase identifier.
50///
51/// Strips `.svg` extension, splits on separators (`-`, `_`, `.`),
52/// and capitalizes each word following Rust naming conventions.
53///
54/// # Examples
55///
56/// ```ignore
57/// assert_eq!(pascal_case("arrow-right.svg"), "ArrowRight");
58/// assert_eq!(pascal_case("some_icon_name.svg"), "SomeIconName");
59/// assert_eq!(pascal_case("icon-123.svg"), "Icon123");
60/// ```
61fn pascal_case(filename: &str) -> String {
62    filename
63        .strip_suffix(".svg")
64        .unwrap_or(filename)
65        .split(|c: char| c == '-' || c == '_' || c == '.')
66        .filter(|part| !part.is_empty())
67        .map(|word| {
68            let mut chars = word.chars();
69            match chars.next() {
70                None => String::new(),
71                Some(first) if first.is_ascii_digit() => word.to_string(),
72                Some(first) => {
73                    let mut result = String::with_capacity(word.len());
74                    result.extend(first.to_uppercase());
75                    result.push_str(&chars.as_str().to_lowercase());
76                    result
77                }
78            }
79        })
80        .collect()
81}
82
83/// Generate a custom icon enum and its `IconNamed` impl by scanning a directory of SVG files.
84///
85/// Accepts an enum name, a path, and optionally a list of additional derive traits.
86/// Each `.svg` file becomes an enum variant using PascalCase conversion.
87///
88/// The path may be either:
89///
90/// - **A literal path** (the common case), resolved relative to the calling crate's
91///   `CARGO_MANIFEST_DIR`. Use this when the icons live inside your own package.
92/// - **An env-var reference** of the form `"$NAME"`, where `NAME` names a build-time
93///   environment variable whose value is the absolute path to the icons directory.
94///   Use this when the icons live in *another* crate and the path is plumbed
95///   through cargo's `links` / `DEP_<X>_<KEY>` propagation mechanism. The default
96///   `IconName` enum in `gpui-component` uses this pattern to consume icons from
97///   `gpui-component-assets` without a sibling-crate reference, which would
98///   otherwise break `cargo vendor` and `cargo publish`.
99///
100/// # Example
101///
102/// ```ignore
103/// // Literal path (relative to the calling crate's CARGO_MANIFEST_DIR)
104/// icon_named!(IconName, "icons");
105///
106/// // Env-var reference (resolved at macro expansion time)
107/// icon_named!(IconName, "$GPUI_COMPONENT_DEFAULT_ICONS_DIR");
108///
109/// // With custom derives
110/// icon_named!(IconName, "icons", [Debug, Copy, PartialEq, Eq]);
111/// ```
112#[proc_macro]
113pub fn icon_named(input: TokenStream) -> TokenStream {
114    let IconNameInput {
115        enum_name,
116        path,
117        derives,
118        ..
119    } = syn::parse_macro_input!(input as IconNameInput);
120
121    let raw_path = path.value();
122
123    // Resolve the path. A leading `$` switches us into env-var mode: the
124    // remainder of the string is an env var name whose value (set by the
125    // caller's `build.rs` via `cargo:rustc-env=`) is the absolute path of
126    // the icons directory. Otherwise treat the string as a path relative
127    // to the calling crate's `CARGO_MANIFEST_DIR`, the original behavior.
128    let icons_dir = if let Some(env_name) = raw_path.strip_prefix('$') {
129        let env_value = std::env::var(env_name).unwrap_or_else(|_| {
130            panic!(
131                "icon_named!: env var `{env_name}` is not set at expansion time. \
132                 Ensure the calling crate's build.rs propagates it via \
133                 `cargo:rustc-env={env_name}=<absolute path>`."
134            )
135        });
136        std::path::PathBuf::from(env_value)
137    } else {
138        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
139        std::path::Path::new(&manifest_dir).join(&raw_path)
140    };
141
142    let mut entries: Vec<(String, String)> = Vec::new();
143
144    let dir = std::fs::read_dir(&icons_dir).unwrap_or_else(|e| {
145        panic!(
146            "generate_icon_enum: failed to read '{}': {}",
147            icons_dir.display(),
148            e
149        )
150    });
151
152    for entry in dir {
153        let entry = entry.expect("failed to read directory entry");
154        let filename = entry.file_name().to_string_lossy().to_string();
155        if filename.ends_with(".svg") {
156            let variant_name = pascal_case(&filename);
157            let path = format!("icons/{}", filename);
158            entries.push((variant_name, path));
159        }
160    }
161
162    entries.sort_by(|a, b| a.0.cmp(&b.0));
163
164    let variants: Vec<proc_macro2::Ident> = entries
165        .iter()
166        .map(|(name, _)| proc_macro2::Ident::new(name, proc_macro2::Span::call_site()))
167        .collect();
168    let paths: Vec<&str> = entries.iter().map(|(_, p)| p.as_str()).collect();
169
170    // Build derive list: always include IntoElement and Clone, then add custom derives
171    let derive_attrs = if let Some((_, custom_derives)) = derives {
172        let derives_vec: Vec<_> = custom_derives.iter().collect();
173        quote! {
174            #[derive(IntoElement, Clone, #(#derives_vec),*)]
175        }
176    } else {
177        quote! {
178            #[derive(IntoElement, Clone)]
179        }
180    };
181
182    let expanded = quote! {
183        #derive_attrs
184
185        pub enum #enum_name {
186            #(#variants,)*
187        }
188
189        impl IconNamed for #enum_name {
190            fn path(self) -> SharedString {
191                match self {
192                    #(Self::#variants => #paths,)*
193                }
194                .into()
195            }
196        }
197    };
198
199    TokenStream::from(expanded)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn test_pascal_case_basic() {
208        assert_eq!(pascal_case("arrow-right.svg"), "ArrowRight");
209        assert_eq!(pascal_case("home.svg"), "Home");
210        assert_eq!(pascal_case("x-circle.svg"), "XCircle");
211
212        assert_eq!(pascal_case("some_icon_name.svg"), "SomeIconName");
213        assert_eq!(pascal_case("arrow_up_down.svg"), "ArrowUpDown");
214
215        assert_eq!(pascal_case("kebab-case_mixed.svg"), "KebabCaseMixed");
216        assert_eq!(pascal_case("icon-with_under.svg"), "IconWithUnder");
217
218        assert_eq!(pascal_case("icon-123.svg"), "Icon123");
219        assert_eq!(pascal_case("arrow-2x.svg"), "Arrow2x");
220        assert_eq!(pascal_case("24-hour.svg"), "24Hour");
221
222        assert_eq!(pascal_case("arrow--right.svg"), "ArrowRight");
223        assert_eq!(pascal_case("icon__name.svg"), "IconName");
224        assert_eq!(pascal_case("multiple---dash.svg"), "MultipleDash");
225
226        assert_eq!(pascal_case("a.svg"), "A");
227        assert_eq!(pascal_case("-leading.svg"), "Leading");
228        assert_eq!(pascal_case("trailing-.svg"), "Trailing");
229        assert_eq!(pascal_case("-.svg"), "");
230
231        assert_eq!(pascal_case("arrow-right"), "ArrowRight");
232        assert_eq!(pascal_case("home"), "Home");
233
234        assert_eq!(pascal_case("hello.svg"), "Hello");
235        assert_eq!(pascal_case("WORLD.svg"), "World");
236        assert_eq!(pascal_case("iOS-icon.svg"), "IosIcon");
237        assert_eq!(pascal_case("API-key.svg"), "ApiKey");
238    }
239}