Skip to content

Commit

Permalink
add support for boolean variants
Browse files Browse the repository at this point in the history
  • Loading branch information
benvp committed Dec 6, 2022
1 parent fd57acc commit 23ad959
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
4 changes: 4 additions & 0 deletions lib/cva.ex
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ defmodule CVA do
p -> p
end || default_variant_prop

# In case we receive nil, convert it to false to properly support
# boolean variants. E.g. `disabled: [true: "i-am-disabled"]`
variant_key = if variant_key, do: variant_key, else: false

config[:variants][variant][variant_key]
end
end)
Expand Down
26 changes: 19 additions & 7 deletions lib/cva/component.ex
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ defmodule CVA.Component do
* `name` - an atom defining the name of the attribute. Note that attributes cannot define the
same name as any other attributes or slots or attributes declared for the same component.
* `variants` - a keyword list of variants.
* `variants` - a keyword list of variants. Supported variant values are strings and a list of strings.
* `opts` - a keyword list of options. Defaults to `[]`.
Expand Down Expand Up @@ -198,18 +198,30 @@ defmodule CVA.Component do
values =
variants
|> Keyword.keys()
|> Enum.map(&Atom.to_string/1)
|> Enum.map(fn
v when is_boolean(v) -> v
v -> Atom.to_string(v)
end)

cva_opts = [values: values]
cva_opts = [values: values ++ [nil]]

cva_opts =
if opts[:default] != nil,
do: Keyword.put(cva_opts, :default, Atom.to_string(opts[:default])),
else: Keyword.put(cva_opts, :required, true)
cond do
is_boolean(opts[:default]) -> Keyword.put(cva_opts, :default, opts[:default])
opts[:default] != nil -> Keyword.put(cva_opts, :default, Atom.to_string(opts[:default]))
true -> cva_opts
end

opts = Keyword.merge(opts, cva_opts)

[name, :string, opts]
type =
cond do
Enum.all?(values, &is_boolean/1) -> :boolean
Enum.all?(values, &is_binary/1) -> :string
true -> :any
end

[name, type, opts]
end

def __on_definition__(env, kind, name, _args, _guards, _body) do
Expand Down

0 comments on commit 23ad959

Please sign in to comment.