diff --git a/bench.rb b/bench.rb index 75f4908..35333c8 100644 --- a/bench.rb +++ b/bench.rb @@ -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, } ) @@ -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 diff --git a/lib/class_variants/instance.rb b/lib/class_variants/instance.rb index 0c5e1da..c60d25e 100644 --- a/lib/class_variants/instance.rb +++ b/lib/class_variants/instance.rb @@ -5,7 +5,7 @@ class ClassVariants::Instance def initialize(classes = "", variants: {}, defaults: {}) @classes = classes - @variants = variants + @variants = expand_boolean_variants(variants) @defaults = defaults end @@ -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 diff --git a/readme.md b/readme.md index ac6cadd..f2f3ae9 100644 --- a/readme.md +++ b/readme.md @@ -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