cva_rails 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 340542305df7017584d5b8f4a44248108469d9fb01a71374caf5d875420adc77
4
+ data.tar.gz: 7996e799b372442959a8ffe91403a1368aa43de261bc1f31498e0009ed5431d6
5
+ SHA512:
6
+ metadata.gz: 85a6b919b6f6a4d9158f1b3f80291169eecb134bfd78778a574fc3854262e127a754b56020da9c9357352ae189faeb5ba2fc217d2b67657607714ba530a1e437
7
+ data.tar.gz: 65a8b684ea4f181234a7e34afa7e638f5427cce23cd148c1468a1ce6145245800528f5a2dc02a2344d90197b01497687e3fcedca1790e43410e024985bbcb0ad
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and to [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).
6
+
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 TODO: Write your name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # cva_rails [![codecov](https://codecov.io/gh/defvova/cva_rails/branch/main/graph/badge.svg?token=SUOCE7FAYF)](https://codecov.io/gh/defvova/cva_rails) [![CI](https://github.com/defvova/cva_rails/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/defvova/cva_rails/actions?query=workflow%3ACI) [![GitHub License](https://img.shields.io/github/license/defvova/cva_rails)](LICENSE.txt)
2
+
3
+ > A tiny and simple gem for variant-based styling logic.
4
+
5
+ This gem offers a lightweight and straightforward solution for managing dynamic class names and
6
+ style variants in Ruby on Rails applications. It draws inspiration from the popular
7
+ [<strong>C</strong>lass <strong>V</strong>ariance <strong>A</strong>uthority (CVA)](https://github.com/joe-bell/cva) package from the JavaScript ecosystem.
8
+
9
+ By defining a collection of named style rules, the gem helps developers easily handle conditional styling based on schemas and runtime parameters. It’s particularly useful when working with complex UI states requiring dynamic styling.
10
+
11
+ ## Supported Ruby and Rails versions
12
+
13
+ Ruby 3.1+ and Rails 7.0+ are supported.
14
+
15
+ <strong>Dependency: [clsx-rails](https://github.com/svyatov/clsx-rails)</strong>
16
+
17
+ ## Installation
18
+
19
+ Install the gem and add to the application's Gemfile by executing:
20
+
21
+ ```bash
22
+ bundle add cva_rails
23
+ ```
24
+
25
+ Or add it manually to the Gemfile:
26
+
27
+ ```ruby
28
+ gem 'cva_rails', '~> 1.0'
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ The cva method allows you to define and manage class variants for your components efficiently.
34
+
35
+ Syntax
36
+ ```ruby
37
+ cva(base_classes, variants)
38
+ ```
39
+
40
+ 1. base_classes (String or Array)
41
+ A set of base CSS classes applied to the component by default.
42
+ 2. variants (Hash)
43
+ Defines the available style variants and their possible values.
44
+
45
+ Example Usage
46
+ ```ruby
47
+ # app/components/alert_component.rb
48
+ class Alert
49
+ include Cva::Helper
50
+
51
+ cva("relative w-full rounded-lg border px-4 py-3 text-sm "\
52
+ "[&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7", {
53
+ variants: {
54
+ variant: {
55
+ primary: "bg-background text-foreground",
56
+ destructive:
57
+ "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
58
+ },
59
+ size: {
60
+ small: "px-3 py-2",
61
+ medium: "px-5 py-4"
62
+ }
63
+ },
64
+ })
65
+ end
66
+ ```
67
+
68
+ Rendered in a view as:
69
+
70
+ ```erb
71
+ <div class="<%= Alert.variants({ variant: :primary, size: :small }) %>"></div>
72
+ <div class="<%= Alert.variants({ variant: :destructive, size: :medium }) %>"></div>
73
+ ```
74
+
75
+ How it works
76
+ ```ruby
77
+ Alert.variants({ variant: :primary, size: :small })
78
+ ```
79
+ This method call combines the base classes of the Alert component with the classes defined for the :primary and :small variants.
80
+ - The base classes are always applied to the component.
81
+ - The selected variant classes (:primary and :small) are conditionally added, resulting in a combined class list.
82
+
83
+ This approach helps manage styling variations cleanly and efficiently.
84
+
85
+ ## Compound Components
86
+
87
+ For larger, more complex components, you may end up wanting to create a set of composable components that work together.
88
+
89
+ ```ruby
90
+ class BtnComponent
91
+ include Cva::Helper
92
+
93
+ cva("border px-4 py-2", {
94
+ variants: {
95
+ size: {
96
+ small: "text-sm",
97
+ medium: "text-base"
98
+ },
99
+ color: {
100
+ green: "text-green-100",
101
+ blue: "text-blue-100"
102
+ }
103
+ },
104
+ compound_variants: [
105
+ {
106
+ size: :small,
107
+ class: "h-10"
108
+ }
109
+ ]
110
+ })
111
+ end
112
+
113
+ BtnComponent.variants({ size: :medium, color: :green }) # => border px-4 py-2 text-green-100 text-base
114
+ BtnComponent.variants({ size: :small, color: :green }) # => border px-4 py-2 text-green-100 text-base h-10
115
+ ```
116
+
117
+ ## Default Variants
118
+
119
+ You can define default variants in the schema to
120
+ automatically apply specific styles when no variant is explicitly provided.
121
+
122
+ ```ruby
123
+ class BtnComponent
124
+ include Cva::Helper
125
+
126
+ cva("border px-4 py-2", {
127
+ variants: {
128
+ size: {
129
+ small: "text-sm",
130
+ medium: "text-base"
131
+ },
132
+ color: {
133
+ green: "text-green-100",
134
+ blue: "text-blue-100"
135
+ }
136
+ },
137
+ compound_variants: [
138
+ {
139
+ size: :small,
140
+ class: "h-10"
141
+ }
142
+ ],
143
+ default_variants: {
144
+ size: :medium,
145
+ color: :green
146
+ }
147
+ })
148
+ end
149
+
150
+ BtnComponent.variants # => border px-4 py-2 text-green-100 text-base
151
+ ```
152
+
153
+ ## Example with TailwindCSS, [ViewComponent](https://viewcomponent.org/) and [TailwindMerge](https://github.com/gjtorikian/tailwind_merge)
154
+
155
+ ViewComponent is a framework for creating reusable, testable & encapsulated view components, built to integrate seamlessly with Ruby on Rails.
156
+ TailwindMerge is utility function to efficiently merge Tailwind CSS classes without style conflicts.
157
+
158
+ ```ruby
159
+ # app/components/button_component.rb
160
+
161
+ class ButtonComponent < ViewComponent::Base
162
+ include Cva::Helper
163
+
164
+ cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm "\
165
+ "font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 "\
166
+ "focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 "\
167
+ "[&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", {
168
+ variants: {
169
+ variant: {
170
+ default:
171
+ "bg-primary text-primary-foreground shadow hover:bg-primary/90",
172
+ destructive:
173
+ "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
174
+ outline:
175
+ "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
176
+ secondary:
177
+ "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
178
+ ghost: "hover:bg-accent hover:text-accent-foreground",
179
+ link: "text-primary underline-offset-4 hover:underline",
180
+ },
181
+ size: {
182
+ default: "h-9 px-4 py-2",
183
+ sm: "h-8 rounded-md px-3 text-xs",
184
+ lg: "h-10 rounded-md px-8",
185
+ icon: "h-9 w-9",
186
+ },
187
+ }
188
+ })
189
+
190
+ erb_template <<-ERB
191
+ <a href="<%= @href %>" class="<%= TailwindMerge::Merger.new.merge(variants(@style_variants)) %>"><%= content %></a>
192
+ ERB
193
+
194
+ def initialize(href:, style_variants = {})
195
+ @href = href
196
+ @style_variants = style_variants
197
+ end
198
+ end
199
+ ```
200
+
201
+ Rendered in a view as:
202
+
203
+ ```erb
204
+ <%= render(ButtonComponent.new(href: submit_path, { variant: :outline, size: :lg })) do %>
205
+ Submit
206
+ <% end %>
207
+ ```
208
+
209
+ Returning:
210
+ ```html
211
+ <a href="/submit" class="base classes + outline classes + size classes">Submit</a>
212
+ ```
213
+
214
+ ## Development
215
+
216
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests.
217
+ You can also run `bin/console` for an interactive prompt that will allow you to experiment.
218
+
219
+ To install this gem onto your local machine, run `bundle exec rake install`.
220
+ To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`,
221
+ which will create a git tag for the version, push git commits and the created tag,
222
+ and push the `.gem` file to [rubygems.org](https://rubygems.org).
223
+
224
+ ## Conventional Commits
225
+
226
+ This project uses [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) for commit messages.
227
+
228
+ Types of commits are:
229
+ - `feat`: a new feature
230
+ - `fix`: a bug fix
231
+ - `perf`: code that improves performance
232
+ - `chore`: updating build tasks, configs, formatting etc; no code change
233
+ - `docs`: changes to documentation
234
+ - `refactor`: refactoring code
235
+ - `test`: changes to test
236
+
237
+ ## Contributing
238
+
239
+ Bug reports and pull requests are welcome on GitHub at https://github.com/defvova/cva_rails.
240
+
241
+ ## License
242
+
243
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/lib/cva/helper.rb ADDED
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cva
4
+ # This module provides functionality for managing variants
5
+ # and class names dynamically based on a schema and parameters.
6
+ #
7
+ module Helper
8
+ extend ActiveSupport::Concern
9
+
10
+ included do
11
+ extend Clsx::Helper
12
+ class_attribute :cva_data
13
+ end
14
+
15
+ class_methods do # rubocop:disable Metrics/BlockLength
16
+ # Defines the base class names and variant schema for a given class.
17
+ # This data is shared through the class and
18
+ # can be accessed to build variant-specific class names dynamically.
19
+ #
20
+ # @param base [Array<String> | String] Base class names applied to the object/component.
21
+ # @param schema [Hash] Schema for defining variants, default variants, and compound variants.
22
+ #
23
+ # @return [void]
24
+ #
25
+ # @example
26
+ # class Button
27
+ # include Cva::Helper
28
+ #
29
+ # cva(['px-4', 'py-2 bg-red-100'], {
30
+ # variants: {
31
+ # size: {
32
+ # small: ["text-sm", "py-1", "px-2"],
33
+ # medium: ["text-base", "h-4"]
34
+ # }
35
+ # },
36
+ # compound_variants: [
37
+ # {
38
+ # size: :medium,
39
+ # class: "hover:bg-blue-100"
40
+ # }
41
+ # ],
42
+ # default_variants: {
43
+ # size: :small
44
+ # }
45
+ # })
46
+ # end
47
+ #
48
+ def cva(base, schema = {})
49
+ schema = {} if schema.nil?
50
+
51
+ validate_type(schema[:variants], Hash, "schema variants")
52
+ validate_type(schema[:compound_variants], Array, "schema compound_variants")
53
+ validate_type(schema[:default_variants], Hash, "schema default_variants")
54
+
55
+ self.cva_data = { base:, schema: schema.transform_keys(&:to_sym) }.freeze
56
+ end
57
+
58
+ # Builds a variants of class names based on the given parameters,
59
+ # including base classes, variant-specific classes, and compound variant classes.
60
+ #
61
+ # @param params [Hash<Symbol, String | Symbol>] A hash of user-specified variants and an optional custom class.
62
+ #
63
+ # @return [Array<String>] A combined array of class names based on the base, variant, and compound rules.
64
+ #
65
+ # **Expected Keys in params**
66
+ # - Keys matching those defined in variants schema.
67
+ # - :class (Optional) – Custom class to be included.
68
+ #
69
+ # @example
70
+ # class Button
71
+ # include Cva::Helper
72
+ #
73
+ # cva(...)
74
+ # end
75
+ #
76
+ # # show.html.erb
77
+ # <%= link_to 'Button', '#', class: Button.variants({ size: :medium, class: 'w-10' }) %>
78
+ #
79
+ # # output:
80
+ # <a href='#' class="px-4 py-2 bg-red-100 text-base h-4 w-10">Button</a>
81
+ #
82
+ def variants(params = {})
83
+ base_classes = cva_data[:base]
84
+ variant_classes = build_variant_class_names(params)
85
+ compound_classes = build_compound_variant_class_names(params)
86
+
87
+ clsx(base_classes, variant_classes, compound_classes, params[:class])
88
+ end
89
+
90
+ private
91
+
92
+ # Generates an array of class names based on individual variant keys.
93
+ #
94
+ # @param params [Hash<Symbol, String | Symbol>] Parameters specifying which variants to apply.
95
+ #
96
+ # @return [Array<String>] Class names associated with specified or default variants.
97
+ #
98
+ def build_variant_class_names(params)
99
+ variants = cva_data.dig(:schema, :variants)
100
+ return [] if variants.nil?
101
+
102
+ variants.keys.flat_map do |key|
103
+ selected_variant = params.fetch(key, cva_data.dig(:schema, :default_variants, key))
104
+ variants.dig(key, selected_variant&.to_sym)
105
+ end.compact
106
+ end
107
+
108
+ # Generates an array of class names based on compound variant rules
109
+ # if the conditions match the given parameters.
110
+ #
111
+ # @param params [Hash<Symbol, String | Symbol>] Parameters specifying variant values.
112
+ #
113
+ # @return [Array<String>] Class names for matching compound variants.
114
+ #
115
+ def build_compound_variant_class_names(params)
116
+ compound_variants = cva_data.dig(:schema, :compound_variants) || []
117
+ compound_variants.each_with_object([]) do |compound_variant, acc|
118
+ next unless compound_variant.except(:class) <= params
119
+
120
+ acc << compound_variant[:class]
121
+ end
122
+ end
123
+
124
+ # Validates the type of a given value, raising an error if the type does not match the expected type.
125
+ #
126
+ # @param value [Object] The value to be validated. Can be any object, including `nil`.
127
+ # @param expected_type [Class] The expected class/type of the value (e.g., `Hash`, `Array`, `String`).
128
+ # @param description [String] A description of the value being validated, used in the error message.
129
+ #
130
+ # @raise [ArgumentError] If the value is not `nil` and does not match the expected type.
131
+ #
132
+ def validate_type(value, expected_type, description)
133
+ return if value.nil? || value.is_a?(expected_type)
134
+
135
+ raise ArgumentError,
136
+ "Expected a #{expected_type} for #{description}, but got #{value.class}. " \
137
+ "Please ensure the #{description} is properly formatted."
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cva
4
+ VERSION = "1.0.0"
5
+ end
data/lib/cva_rails.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "action_view"
5
+ require "clsx-rails"
6
+
7
+ require_relative "cva/version"
8
+ require_relative "cva/helper"
9
+
10
+ # :nodoc:
11
+ module Cva
12
+ ActiveSupport.on_load(:action_view) { include Helper }
13
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cva_rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Volodymyr Partytskyi
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-02-10 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: actionview
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '6.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '6.1'
26
+ - !ruby/object:Gem::Dependency
27
+ name: clsx-rails
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '1.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '1.0'
40
+ description: A Rails helper designed to generate and manage multiple style or configuration
41
+ variants for components, enabling flexible and dynamic customization based on provided
42
+ parameters.
43
+ email:
44
+ - volodymyr.partytskyi@gmail.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - CHANGELOG.md
50
+ - LICENSE.txt
51
+ - README.md
52
+ - lib/cva/helper.rb
53
+ - lib/cva/version.rb
54
+ - lib/cva_rails.rb
55
+ homepage: https://github.com/defvova/cva_rails
56
+ licenses:
57
+ - MIT
58
+ metadata:
59
+ homepage_uri: https://github.com/defvova/cva_rails
60
+ source_code_uri: https://github.com/defvova/cva_rails
61
+ changelog_uri: https://github.com/defvova/cva_rails/blob/main/CHANGELOG.md
62
+ rubygems_mfa_required: 'true'
63
+ rdoc_options: []
64
+ require_paths:
65
+ - lib
66
+ required_ruby_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: 3.1.0
71
+ required_rubygems_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ requirements: []
77
+ rubygems_version: 3.6.3
78
+ specification_version: 4
79
+ summary: cva(Class Variance Authority) for rails views.
80
+ test_files: []