carloskiki / leptos-icons

An icon library for the leptos web framework
MIT License
84 stars 16 forks source link

Icon macro troubles #24

Closed SleeplessOne1917 closed 9 months ago

SleeplessOne1917 commented 9 months ago

I sort of figured out the issue I was having with the icon macro earlier. Suppose I am importing from this library like so:

use leptos_icons::{icon, ChIcon, Icon};

I try to use an icon like this:

<Icon icon=icon!(ChIcon::ChMenuHamburger)/>

When I run cargo leptos build, I get this compiler error:

error: proc macro panicked
  --> src/ui/components/common/nav.rs:12:24
   |
12 |             <Icon icon=icon!(ChIcon::ChMenuHamburger)/>
   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: message: Expected only one identifier, but received multiple tokens.

If I import like this:

use leptos_icons::{icon, ChIcon::ChMenuHamburger, Icon};

and use the icon like this:

<Icon icon=icon!(ChMenuHamburger)/>

I get a different compiler error along with an odd warning:

error[E0433]: failed to resolve: use of undeclared type `ChIcon`
  --> src/ui/components/common/nav.rs:12:24
   |
12 |             <Icon icon=icon!(ChMenuHamburger)/>
   |                        ^^^^^^^^^^^^^^^^^^^^^^ use of undeclared type `ChIcon`
   |
   = note: this error originates in the macro `icon` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider importing this enum
   |
1  + use leptos_icons::ChIcon;
   |

warning: unused import: `ChIcon::ChMenuHamburger`
 --> src/ui/components/common/nav.rs:2:26
  |
2 | use leptos_icons::{icon, ChIcon::ChMenuHamburger, Icon};

Unused import? I'm using it right there!

I managed to get it to compile by importing like this:

use leptos_icons::{
  icon,
  ChIcon::{self, ChMenuHamburger},
  Icon,
};

and writing the component like this:

<Icon icon=icon!(ChMenuHamburger)/>

Oddly enough, I still get the unused import warning for ChMenuHamburger.

I doubt this is the way the library is supposed to work, and it will definitely trip up consumers. It certainly confused me.

carloskiki commented 9 months ago

Here is what you need to do:

The icon! macro expands the argument, for example ChMenuHamburger into Icon::from(ChMenu::ChMenuHamburger.

So in your import statement, just import it like this:

use leptos_icons::{icon, ChIcon, Icon};

and in the macro pass this as an argument:

<Icon icon=icon!(ChMenuHamburger)/>

This should make the macro work. Note that you can take a look at the examples in the example directory.

carloskiki commented 9 months ago

FYI: This issue totally made me realize that this macro is useless if we export the Enum variants. Just like how we don't need to write Option::None, we would not need to write BsIcon::Bs{...}. When releasing 0.1, (when leptos 0.5) comes out, I will most likely get rid of the macro, and the notation Icon::from({your icon}) instead of having to qualify the enum variant.