Skip to content

Commit

Permalink
Merge pull request #3 from willcosgrove/boolean-variants
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianthedev authored Dec 21, 2022
2 parents a8681df + 55fc9a8 commit 899a9b1
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
5 changes: 4 additions & 1 deletion bench.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ module ClassVariants
blue: "text-white bg-blue-500 border-blue-700 hover:bg-blue-600",
red: "text-white bg-red-500 border-red-700 hover:bg-red-600",
},
block: "justify-center w-full",
"!block": "justify-between",
},
defaults: {
size: :base,
color: :white,
block: false,
}
)

Expand All @@ -33,6 +36,6 @@ module ClassVariants
end

x.report("rendering with overrides") do
button_classes.render(size: :sm, color: :red)
button_classes.render(size: :sm, color: :red, block: true)
end
end
18 changes: 17 additions & 1 deletion lib/class_variants/instance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class ClassVariants::Instance

def initialize(classes = "", variants: {}, defaults: {})
@classes = classes
@variants = variants
@variants = expand_boolean_variants(variants)
@defaults = defaults
end

Expand All @@ -26,4 +26,20 @@ def render(**overrides)
# Return the final token list
result.join " "
end

private

def expand_boolean_variants(variants)
variants.each.map { |key, value|
case value
when String
s_key = key.to_s
{ s_key.delete_prefix("!").to_sym => { !s_key.start_with?("!") => value } }
else
{ key => value }
end
}.reduce do |variants, more_variants|
variants.merge!(more_variants) { |_key, v1, v2| v1.merge!(v2) }
end
end
end
9 changes: 8 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,24 @@ button_classes = ClassVariants.build(
red: "bg-red-600 hover:bg-red-700 focus:ring-red-500",
blue: "bg-blue-600 hover:bg-blue-700 focus:ring-blue-500",
},
# A variant whose value is a string will be expanded into a hash that looks
# like { true => "classes" }
block: "w-full justify-center",
# Unless the key starts with !, in which case it will expand into
# { false => "classes" }
"!block": "w-auto",
},
defaults: {
size: :md,
color: :indigo,
icon: false
}
)

# Call it with our desired variants
button_classes.render(color: :blue, size: :sm)
button_classes.render
button_classes.render(color: :red, size: :xl)
button_classes.render(color: :red, size: :xl, icon: true)
```

## Use with Rails
Expand Down

0 comments on commit 899a9b1

Please sign in to comment.