velvetkit 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -2
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/money_input.html.erb +8 -0
  5. data/registry/app/components/ui/money_input.rb +153 -0
  6. data/registry/app/components/ui/scan_input.html.erb +6 -0
  7. data/registry/app/components/ui/scan_input.rb +94 -0
  8. data/registry/app/components/ui/slider.html.erb +23 -0
  9. data/registry/app/components/ui/slider.rb +254 -0
  10. data/registry/app/javascript/controllers/ui/money_input_controller.ts +228 -0
  11. data/registry/app/javascript/controllers/ui/scan_input_controller.ts +143 -0
  12. data/registry/app/javascript/controllers/ui/slider_controller.ts +216 -0
  13. data/registry/components.yml +6 -0
  14. data/registry/config/locales/velvetkit.en.yml +6 -0
  15. data/registry/icons/lucide/scan-barcode.svg +21 -0
  16. data/registry/icons/lucide/volume-2.svg +17 -0
  17. data/registry/icons/lucide/volume-x.svg +17 -0
  18. data/registry/icons/phosphor/barcode.svg +2 -0
  19. data/registry/icons/phosphor/speaker-high.svg +2 -0
  20. data/registry/icons/phosphor/speaker-x.svg +2 -0
  21. data/registry/icons/tabler/barcode.svg +23 -0
  22. data/registry/icons/tabler/volume-3.svg +17 -0
  23. data/registry/icons/tabler/volume.svg +18 -0
  24. data/registry/icons.yml +3 -0
  25. data/registry/test/components/previews/ui/money_input_preview/cash_tendered.html.erb +24 -0
  26. data/registry/test/components/previews/ui/money_input_preview/currencies.html.erb +7 -0
  27. data/registry/test/components/previews/ui/money_input_preview/invoice.html.erb +24 -0
  28. data/registry/test/components/previews/ui/money_input_preview/sizes_and_states.html.erb +9 -0
  29. data/registry/test/components/previews/ui/money_input_preview.rb +34 -0
  30. data/registry/test/components/previews/ui/scan_input_preview/_simulate.html.erb +20 -0
  31. data/registry/test/components/previews/ui/scan_input_preview/library_checkout.html.erb +30 -0
  32. data/registry/test/components/previews/ui/scan_input_preview/playground.html.erb +13 -0
  33. data/registry/test/components/previews/ui/scan_input_preview/stock_count.html.erb +24 -0
  34. data/registry/test/components/previews/ui/scan_input_preview/ticket_check_in.html.erb +34 -0
  35. data/registry/test/components/previews/ui/scan_input_preview/till.html.erb +9 -0
  36. data/registry/test/components/previews/ui/scan_input_preview.rb +33 -0
  37. data/registry/test/components/previews/ui/slider_preview/named_steps.html.erb +7 -0
  38. data/registry/test/components/previews/ui/slider_preview/opening_hours.html.erb +5 -0
  39. data/registry/test/components/previews/ui/slider_preview/price_range.html.erb +6 -0
  40. data/registry/test/components/previews/ui/slider_preview/sizes_and_states.html.erb +9 -0
  41. data/registry/test/components/previews/ui/slider_preview/text_size.html.erb +16 -0
  42. data/registry/test/components/previews/ui/slider_preview/tip.html.erb +22 -0
  43. data/registry/test/components/previews/ui/slider_preview/volume.html.erb +5 -0
  44. data/registry/test/components/previews/ui/slider_preview.rb +45 -0
  45. data/registry/test/components/ui/money_input_test.rb +149 -0
  46. data/registry/test/components/ui/scan_input_test.rb +110 -0
  47. data/registry/test/components/ui/slider_test.rb +190 -0
  48. metadata +42 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1946e018660d08bfab63d5e0a9b9e00e2e41a138bacf878e66832c0eebb0400b
4
- data.tar.gz: 7b5ae9a20372f619449b42520d0f1d643b9b8d6094437d00715c8faebb883029
3
+ metadata.gz: fbe4ce28e9bb9313488c3564f6b7fd9d3ac256be4239a51ce4c7fc9b5281d7f0
4
+ data.tar.gz: 88f169fe4f0888b41bb0f3c946f1481255b65ec4dd0f12ea7da7824818d8edfb
5
5
  SHA512:
6
- metadata.gz: e4cb6bacd3d8e0ccc231e5d655ac639d40df556e49d7b02f1aa0feb5d2ccb8f46aa2a99a08853f26ceb789e920d5f4a5e779c29e3a816c28296547a6b6549200
7
- data.tar.gz: 7624a9d18314e65a4c43a883c9e42b1ac0291ba84b8c5bccb1641a594311384112933abd158ed412877b4b2252f971853ecc5b4d5fbbcbcf000dfe0aaa74aa52
6
+ metadata.gz: c03d6d45997176736fe174e23d30b3196694cde7113721a24f5ad604013aae3b54d9a5d541ab678b0c037c087dbdd32e486975ede353624263222a034a31a7bf
7
+ data.tar.gz: 9f25335d481267dc430c903f5b8ae0d95e4b6cb2101d7358d297c1798f9d68a973ba7208cf63bb09594a2c9e9c4091541a26277cc048427381f557c5bafd641b
data/CHANGELOG.md CHANGED
@@ -1,6 +1,24 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.4.1 — 2026-11-09
4
+
5
+ New components:
6
+
7
+ - `Slider`: a handle to drag for a value, or two for a range such as a price
8
+ band, with value text, labelled marks and form binding. The knob follows
9
+ the pointer freely and the value keeps to the step.
10
+ - `MoneyInput`: an amount of money, grouped as it's typed (1,23,456.78 for
11
+ rupees, 123,456.78 otherwise) with its currency sign, decimals filled in
12
+ when the field is left, and the plain number (123456.78) posted in a
13
+ hidden field. The sign, separators and decimals follow the app's locale.
14
+ ↑ and ↓ step by one unit, or `step:`, and Shift by ten.
15
+ - `ScanInput`: a field for barcode and QR scanners. Enter (or Tab) submits
16
+ the form with the code and empties the field, codes scanned while one is
17
+ still being sent wait their turn, and it keeps focus when focus falls to
18
+ the page. A `scan` event lets the page handle codes itself; `capture:`,
19
+ `keyboard: false` and `suffix: :tab` suit scan-only pages and handhelds.
20
+
21
+ ## 0.4.0 — 2026-11-08
4
22
 
5
23
  New components:
6
24
 
@@ -13,6 +31,15 @@ New components:
13
31
  - `Chart`: line, bar, stacked bar, pie and donut charts on Chart.js, with a
14
32
  legend, tooltips, keyboard reading, a table of the numbers, and animation.
15
33
  The docs site has a Charts section with a page for each.
34
+ - `Progress`: a bar for an upload, an import or storage used, with a value or
35
+ sliding while there's none yet, in tones, and split into coloured segments
36
+ with a legend. Setting its value attribute from JavaScript moves it live.
37
+ - `Kbd`: a key or shortcut, shown as each reader's computer labels it (⌘ on a
38
+ Mac, Ctrl on Windows, Super on Linux), with `bind:` to press a button or
39
+ focus a field when the shortcut is pressed.
40
+ - `Command`: a search box over pages, actions and records, inline or opened
41
+ with ⌘K, ranking by best match, with groups, shortcuts, and server search
42
+ with `url:`.
16
43
 
17
44
  Changes:
18
45
 
@@ -34,6 +61,7 @@ Changes:
34
61
  JavaScript build: `bun.config.js`, `webpack.config.js`, or a build script
35
62
  that lists `application.js`. Before, they were copied but never built, so
36
63
  those components failed to load their library.
64
+ - The docs site's search is the kit's own `Command`.
37
65
 
38
66
  Upgrading an app: re-run `velvetkit:add` for `date_picker`, `select` and
39
67
  `file_field`, and copy the new `--chart-*` values into your `velvetkit.css`.
@@ -41,7 +69,8 @@ Upgrading an app: re-run `velvetkit:add` for `date_picker`, `select` and
41
69
  `app/javascript/vanilla_calendar.ts` as its own entry point; `file_field`
42
70
  needs `@rails/activestorage`. If you added `chart_js.ts`,
43
71
  `vanilla_calendar.ts` or `ag_grid.ts` to your build by hand, `add` leaves
44
- it as it is.
72
+ it as it is. `progress` needs the `velvetkit-progress` keyframes from the new
73
+ `velvetkit.css`; without them a bar with no value doesn't move.
45
74
 
46
75
  - Fix: Rails 8.1.4.1, for security advisories in Active Storage and Action Pack.
47
76
  - Fix: the docs site shows a component added to the catalog without a server
@@ -4,5 +4,5 @@ module Velvetkit
4
4
  # Not the released version: the release workflow takes that from the tag
5
5
  # (v0.3.0 publishes 0.3.0) and writes it here on the runner only, so this
6
6
  # file can stay behind. See .github/workflows/release.yml.
7
- VERSION = "0.4.0"
7
+ VERSION = "0.4.1"
8
8
  end
@@ -0,0 +1,8 @@
1
+ <%# frozen_string_literal: true %>
2
+ <%= tag.div(**root_attrs) do %>
3
+ <% control = capture do %><%= render(group_component) do |g| %>
4
+ <% g.with_field(**field_options) %>
5
+ <% g.with_addon(align: unit_align) { unit } %>
6
+ <% end %><%= tag.input(**hidden_attrs) %><% end %>
7
+ <%= render(wrapper) { control } %>
8
+ <% end %>
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+ require "securerandom"
5
+
6
+ # An amount of money, written the way people read it: grouped as it's typed,
7
+ # with the currency sign beside it and the paise or cents filled in when the
8
+ # field is left. The form gets the plain number.
9
+ #
10
+ # <%= render(UI::MoneyInput.new(name: "amount", value: 123456.5, unit: "₹", label: "Amount")) %>
11
+ # <%= render(UI::MoneyInput.new(form: f, field: :price)) %>
12
+ #
13
+ # The reader sees "1,23,456.50"; a hidden field posts "123456.50", so the
14
+ # controller never has to strip commas. Typing anything but digits and one
15
+ # decimal point is ignored, a pasted "₹1,23,456.789" is cleaned up, and no
16
+ # more decimals than `precision:` can be typed. It's a text field with the
17
+ # decimal keypad on phones, not type="number", which can't show grouping.
18
+ #
19
+ # The sign, separator, delimiter, precision and the sign's side come from the
20
+ # app's locale (`number.currency.format`), so each can be left out. `unit: "₹"`
21
+ # groups the Indian way (1,23,45,678) unless `grouping: :thousands` says
22
+ # otherwise; `grouping: :indian` asks for it with any sign. `precision: 0` is
23
+ # for whole amounts. Amounts can't be negative unless `negative: true`.
24
+ #
25
+ # ↑ and ↓ add or take away one whole unit, or `step:` (0.5, 100), and Shift
26
+ # ten of them. Each press fires `input` and `change`, as a number field does.
27
+ #
28
+ # It takes the same label, hint, error, size and form-builder options as
29
+ # UI::NumberInput. The visible field fires `input` and `change` as usual; read
30
+ # the amount from the hidden field (`[data-ui--money-input-target=value]`).
31
+ class UI::MoneyInput < UI::Base
32
+ SIZES = {
33
+ sm: "h-8 [&>input]:h-full [&>input]:text-xs",
34
+ default: "h-9",
35
+ lg: "h-12 [&>input]:h-full [&>input]:text-base"
36
+ }.freeze
37
+
38
+ GROUPINGS = %i[thousands indian].freeze
39
+
40
+ def initialize(name: nil, value: nil, form: nil, field: nil, unit: nil, precision: nil, separator: nil,
41
+ delimiter: nil, grouping: nil, negative: false, step: 1, size: :default, label: nil, hint: nil,
42
+ error: nil, required: false, disabled: false, placeholder: nil, class: nil, **html_attrs)
43
+ @name = name
44
+ @form = form
45
+ @field = field
46
+ @unit = unit || currency(:unit, "$")
47
+ @precision = Integer(precision || currency(:precision, 2))
48
+ @separator = separator || currency(:separator, ".")
49
+ @delimiter = delimiter || currency(:delimiter, ",")
50
+ @grouping = GROUPINGS.include?(grouping&.to_sym) ? grouping.to_sym : (@unit == "₹" ? :indian : :thousands)
51
+ @negative = negative
52
+ @step = step
53
+ @size = SIZES.key?(size.to_sym) ? size.to_sym : :default
54
+ @required = required
55
+ @disabled = disabled
56
+ @placeholder = placeholder
57
+ @user_class = binding.local_variable_get(:class)
58
+ @html_attrs = html_attrs
59
+ @input_id = html_attrs.delete(:id) || "ui-money-input-#{SecureRandom.hex(4)}"
60
+ @amount = amount(bound || value)
61
+ @wrapper = UI::FormField.new(label: label, hint: hint, error: error, required: required, disabled: disabled,
62
+ form: form, field: field, for: @input_id)
63
+ end
64
+
65
+ attr_reader :wrapper
66
+
67
+ def root_attrs
68
+ { class: cn("w-full", @user_class),
69
+ data: { slot: "money-input", controller: "ui--money-input", "ui--money-input-separator-value": @separator,
70
+ "ui--money-input-delimiter-value": @delimiter, "ui--money-input-precision-value": @precision,
71
+ "ui--money-input-grouping-value": @grouping, "ui--money-input-negative-value": @negative,
72
+ "ui--money-input-step-value": BigDecimal(@step.to_s).to_s("F").delete_suffix(".0") } }
73
+ end
74
+
75
+ def group_component
76
+ UI::InputGroup.new(class: cn("[&>input]:tabular-nums", SIZES[@size]),
77
+ data: { disabled: (true if @disabled) }.compact)
78
+ end
79
+
80
+ def field_options
81
+ data = @html_attrs[:data] || {}
82
+ action = [ "beforeinput->ui--money-input#guard keydown->ui--money-input#nudge input->ui--money-input#type " \
83
+ "blur->ui--money-input#finish", data[:action] ].compact.join(" ")
84
+ { type: :text, inputmode: "decimal", autocomplete: "off", spellcheck: false, value: shown,
85
+ placeholder: @placeholder || shown(BigDecimal(0)), required: @required, disabled: @disabled,
86
+ error: wrapper.error?, "aria-describedby": wrapper.describedby, **@html_attrs, id: @input_id,
87
+ data: data.merge("ui--money-input-target": "field", action: action) }.compact
88
+ end
89
+
90
+ def hidden_attrs
91
+ { type: "hidden", name: hidden_name, value: plain, disabled: (true if @disabled),
92
+ data: { "ui--money-input-target": "value" } }.compact
93
+ end
94
+
95
+ def unit = @unit
96
+
97
+ # The sign goes where the locale writes it: "%u%n" before, "%n %u" after.
98
+ def unit_align
99
+ pattern = currency(:format, "%u%n")
100
+ pattern.index("%u").to_i > pattern.index("%n").to_i ? "inline-end" : "inline-start"
101
+ end
102
+
103
+ # What the reader sees: "1,23,456.50".
104
+ def shown(amount = @amount) = written(amount, @separator) { |whole| group(whole) }
105
+
106
+ # What the form posts: "123456.50". Built from the digits, never a float.
107
+ def plain = written(@amount, ".").to_s
108
+
109
+ private
110
+
111
+ def written(amount, separator)
112
+ return nil if amount.nil?
113
+
114
+ whole, fraction = amount.abs.to_s("F").split(".")
115
+ text = block_given? ? yield(whole) : whole
116
+ text += separator + fraction.to_s.ljust(@precision, "0")[0, @precision] if @precision.positive?
117
+ amount.negative? ? "-#{text}" : text
118
+ end
119
+
120
+ def currency(key, default) = I18n.t("number.currency.format.#{key}", default: default)
121
+
122
+ def hidden_name
123
+ return "#{@form.object_name}[#{@field}]" if @form && @field
124
+
125
+ @name
126
+ end
127
+
128
+ def bound
129
+ return nil unless @form && @field && @form.object.respond_to?(@field)
130
+
131
+ @form.object.public_send(@field)
132
+ end
133
+
134
+ def amount(value)
135
+ return nil if value.blank?
136
+
137
+ number = value.is_a?(Numeric) ? BigDecimal(value.to_s) : BigDecimal(value.to_s.delete(@delimiter).tr(@separator, "."))
138
+ number = number.abs unless @negative
139
+ # round(0) gives an Integer; keep a BigDecimal.
140
+ BigDecimal(number.round(@precision).to_s)
141
+ rescue ArgumentError
142
+ nil
143
+ end
144
+
145
+ # 1234567 -> 1,234,567, or the Indian way, 12,34,567: the last three
146
+ # digits, then twos.
147
+ def group(digits)
148
+ return digits.gsub(/\B(?=(\d{3})+(?!\d))/, @delimiter) unless @grouping == :indian
149
+ return digits if digits.length <= 3
150
+
151
+ "#{digits[0...-3].gsub(/\B(?=(\d{2})+(?!\d))/, @delimiter)}#{@delimiter}#{digits[-3..]}"
152
+ end
153
+ end
@@ -0,0 +1,6 @@
1
+ <%# frozen_string_literal: true %>
2
+ <% group = capture do %><%= render(group_component) do |g| %>
3
+ <% g.with_field(**field_options) %>
4
+ <% g.with_addon(align: "inline-start") { |a| a.with_icon(name: "scan-barcode") } %>
5
+ <% end %><% end %>
6
+ <%= render(wrapper) { group } %>
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ # A field for a barcode or QR scanner, or a code typed by hand. A scanner is
6
+ # a keyboard that types very fast and presses Enter; this field is ready for
7
+ # it: focused, with nothing in the way, and sending each code as it comes.
8
+ #
9
+ # <%= form_with url: cart_items_path do |f| %>
10
+ # <%= render(UI::ScanInput.new(name: "code", label: "Scan an item")) %>
11
+ # <% end %>
12
+ #
13
+ # Enter submits the form with the code and empties the field for the next
14
+ # one. A code that arrives while the last is still being sent (a Turbo form
15
+ # submission) waits its turn, so two quick scans are two requests, not one
16
+ # lost. Before that it fires `ui--scan-input:scan` with `{ code }`; call
17
+ # `preventDefault()` on it to handle the code in JavaScript instead.
18
+ # `submit: false` never submits, and only fires the event.
19
+ #
20
+ # It's focused on load and when it comes back in a Turbo update, and
21
+ # `keep_focus:` (on by default) takes focus back when it falls to the page,
22
+ # after a click on empty space or a dialog closing; moving to another field
23
+ # or button is left alone. `capture: true` goes further: keys typed with
24
+ # nothing focused go into the field, for a page that's only for scanning.
25
+ #
26
+ # `keyboard: false` keeps the on-screen keyboard down, for handheld scanners
27
+ # with a phone's screen. `suffix: :tab` is for scanners set to end a code
28
+ # with Tab instead of Enter. Spelling, capitals and autofill are off, since a
29
+ # code isn't a word.
30
+ #
31
+ # Each scan briefly rings the field, so the person scanning can see it took.
32
+ # It takes the same label, hint, error, size and form-builder options as
33
+ # UI::Input.
34
+ class UI::ScanInput < UI::Base
35
+ SIZES = {
36
+ sm: "h-8 [&>input]:h-full [&>input]:text-xs",
37
+ default: "h-9",
38
+ lg: "h-12 [&>input]:h-full [&>input]:text-base"
39
+ }.freeze
40
+
41
+ SUFFIXES = %i[enter tab].freeze
42
+
43
+ # The ring after a scan, over the group's own focus ring.
44
+ SCANNED = "data-scanned:border-emerald-500 data-scanned:ring-3 data-scanned:ring-emerald-500/30 " \
45
+ "motion-reduce:transition-none"
46
+
47
+ def initialize(name: nil, value: nil, form: nil, field: nil, label: nil, hint: nil, error: nil, placeholder: nil,
48
+ submit: true, clear: true, keep_focus: true, capture: false, keyboard: true, suffix: :enter,
49
+ autofocus: true, size: :default, required: false, disabled: false, class: nil, **html_attrs)
50
+ @name = name
51
+ @value = value
52
+ @form = form
53
+ @field = field
54
+ @placeholder = placeholder
55
+ @submit = submit
56
+ @clear = clear
57
+ @keep_focus = keep_focus
58
+ @capture = capture
59
+ @keyboard = keyboard
60
+ @suffix = SUFFIXES.include?(suffix&.to_sym) ? suffix.to_sym : :enter
61
+ @autofocus = autofocus
62
+ @size = SIZES.key?(size.to_sym) ? size.to_sym : :default
63
+ @required = required
64
+ @disabled = disabled
65
+ @user_class = binding.local_variable_get(:class)
66
+ @html_attrs = html_attrs
67
+ @input_id = html_attrs.delete(:id) || "ui-scan-input-#{SecureRandom.hex(4)}"
68
+ @wrapper = UI::FormField.new(label: label, hint: hint, error: error, required: required, disabled: disabled,
69
+ form: form, field: field, for: @input_id)
70
+ end
71
+
72
+ attr_reader :wrapper
73
+
74
+ def group_component
75
+ UI::InputGroup.new(
76
+ class: cn(SCANNED, SIZES[@size], @user_class),
77
+ data: { controller: "ui--scan-input", disabled: (true if @disabled),
78
+ "ui--scan-input-submit-value": @submit, "ui--scan-input-clear-value": @clear,
79
+ "ui--scan-input-keep-focus-value": @keep_focus, "ui--scan-input-capture-value": @capture,
80
+ "ui--scan-input-suffix-value": @suffix }.compact
81
+ )
82
+ end
83
+
84
+ def field_options
85
+ data = @html_attrs[:data] || {}
86
+ action = [ "keydown->ui--scan-input#key", data[:action] ].compact.join(" ")
87
+ { type: :text, form: @form, field: @field, name: (@name unless @form && @field), value: @value, label: false,
88
+ placeholder: @placeholder || t("ui.scan_input.placeholder", default: "Scan or type a code"),
89
+ required: @required, disabled: @disabled, error: wrapper.error?, "aria-describedby": wrapper.describedby,
90
+ autocomplete: "off", autocapitalize: "off", autocorrect: "off", spellcheck: false, enterkeyhint: "go",
91
+ inputmode: ("none" unless @keyboard), autofocus: (true if @autofocus && !@disabled),
92
+ **@html_attrs, id: @input_id, data: data.merge("ui--scan-input-target": "field", action: action) }.compact
93
+ end
94
+ end
@@ -0,0 +1,23 @@
1
+ <%# frozen_string_literal: true %>
2
+ <%= tag.div(**root_attrs) do %>
3
+ <% if header? %>
4
+ <div class="flex items-baseline justify-between gap-3 text-sm">
5
+ <% if label_text %><%= tag.label(label_text, id: label_id, for: (fields.first[:id] unless range?), class: "font-medium leading-none") %><% end %>
6
+ <% if show_value? %><%= tag.output(output_text, class: "ms-auto tabular-nums text-muted-foreground", "aria-hidden": "true", data: { "ui--slider-target": "output" }) %><% end %>
7
+ </div>
8
+ <% end %>
9
+ <%= render(wrapper) do %>
10
+ <%= tag.div(**track_attrs) do %>
11
+ <%= tag.div(class: track_class) do %>
12
+ <%= tag.div(class: UI::Slider::FILL, style: fill_style, data: { slot: "slider-fill" }) %>
13
+ <% end %>
14
+ <%# Each knob follows the input just before it; the span keeps a range's pairs apart. %>
15
+ <% fields.each do |handle| %><span class="contents"><%= render_input(handle) %><%= tag.span(class: UI::Slider::KNOB, style: knob_style(handle), "aria-hidden": "true", data: { slot: "slider-thumb" }) %></span><% end %>
16
+ <% end %>
17
+ <% if marks? %>
18
+ <%= tag.div(class: "relative h-4 text-xs text-muted-foreground", "aria-hidden": "true") do %>
19
+ <% marks.each do |mark| %><%= tag.span(mark[:label], **mark_attrs(mark)) %><% end %>
20
+ <% end %>
21
+ <% end %>
22
+ <% end %>
23
+ <% end %>
@@ -0,0 +1,254 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ # A handle to drag along a track: volume, a zoom level, how often to be
6
+ # emailed. `range: true` gives it two, a low and a high, for filters like a
7
+ # price band or opening hours.
8
+ #
9
+ # <%= render(UI::Slider.new(name: "volume", value: 40, label: "Volume", value_text: "%{value}%", show_value: true)) %>
10
+ # <%= render(UI::Slider.new(form: f, field: :alert_at, min: 50, max: 100, step: 5)) %>
11
+ # <%= render(UI::Slider.new(range: true, label: "Price", min: 0, max: 500, step: 10,
12
+ # from: params[:min_price] || 0, to: params[:max_price] || 500,
13
+ # from_name: "min_price", to_name: "max_price", value_text: "$%{value}", show_value: true)) %>
14
+ # <%= render(UI::Slider.new(range: true, form: f, from_field: :opens_at, to_field: :closes_at, max: 24)) %>
15
+ #
16
+ # Each handle is the browser's own <input type="range">, so it submits with
17
+ # the form, the arrow keys, Page Up and Down, Home and End move it, and screen
18
+ # readers announce it as a slider. Pressing anywhere on the track moves the
19
+ # nearest handle there and drags it. The two handles of a range can meet but
20
+ # not pass each other.
21
+ #
22
+ # `value_text:` formats a value for the reader to see (with
23
+ # `show_value: true`) and for a screen reader to hear: "%{value}%",
24
+ # "$%{value}", "%{value}:00". A range shows both, as "$20 – $80".
25
+ #
26
+ # `marks:` labels points along the track: an array of values, or a hash of
27
+ # value => label. A labelled value is also what's shown and heard there, so
28
+ #
29
+ # <%= render(UI::Slider.new(name: "quality", min: 1, max: 3, value: 2, show_value: true, label: "Quality",
30
+ # marks: { 1 => "Low", 2 => "Medium", 3 => "High" })) %>
31
+ #
32
+ # says "Medium" rather than 2. Pressing a mark moves the nearest handle to it.
33
+ #
34
+ # `aria:` goes on the input, or on a range's group: with `label: false`, give
35
+ # it `aria: { label: "Volume" }` so it still has a name.
36
+ #
37
+ # It fires the inputs' own `input` while a handle moves and `change` when it's
38
+ # let go, so a filter form can submit on change. Setting a handle's value from
39
+ # JavaScript, dispatch `input` on it after, and the track follows.
40
+ class UI::Slider < UI::Base
41
+ SIZES = {
42
+ sm: { thumb: "1.375rem", thumb_height: "1rem", track: "h-1.5" },
43
+ default: { thumb: "1.75rem", thumb_height: "1.25rem", track: "h-2.5" },
44
+ lg: { thumb: "2.25rem", thumb_height: "1.625rem", track: "h-3.5" }
45
+ }.freeze
46
+
47
+ # The input is there for the keyboard, the form and screen readers, and
48
+ # can't be seen. Its thumb could only sit on a step, so the knob is drawn
49
+ # separately: it follows the pointer freely while dragged, and glides onto
50
+ # the value otherwise. Pointer events go to the track (see the controller).
51
+ INPUT = "peer absolute inset-0 m-0 h-(--thumb-h) w-full cursor-[inherit] opacity-0 pointer-events-none"
52
+
53
+ # A white pill lifted by a shadow. The keyboard's focus and a drag each put
54
+ # a ring around it, outside its edge.
55
+ KNOB = "pointer-events-none absolute top-1/2 h-(--thumb-h) w-(--thumb) -translate-y-1/2 rounded-full bg-white " \
56
+ "shadow-[0_1px_3px_rgb(0_0_0/0.3),0_0_0_0.5px_rgb(0_0_0/0.08)] " \
57
+ "transition-[inset-inline-start,box-shadow] duration-150 ease-out motion-reduce:transition-none " \
58
+ "group-data-dragging/slider:transition-[box-shadow] " \
59
+ "peer-focus-visible:ring-3 peer-focus-visible:ring-ring/50 " \
60
+ "peer-data-active:shadow-none peer-data-active:ring-4 peer-data-active:ring-foreground/15"
61
+
62
+ # The fill glides with the knob, and keeps up with it during a drag.
63
+ FILL = "absolute inset-y-0 bg-primary transition-[inset-inline-start,width] duration-150 ease-out " \
64
+ "motion-reduce:transition-none group-data-dragging/slider:transition-none"
65
+
66
+ # The ends sit flush with the track's ends; the rest centre on their value.
67
+ MARK_PLACES = { 0.0 => { shift: "", style: "inset-inline-start: 0px" },
68
+ 1.0 => { shift: "-translate-x-full rtl:translate-x-full", style: "inset-inline-start: 100%" } }.freeze
69
+
70
+ # Where a value sits along the track: the thumb's centre goes from half a
71
+ # thumb in at one end to half a thumb in at the other.
72
+ def self.at(fraction) = "calc(var(--thumb) / 2 + (100% - var(--thumb)) * #{fraction})"
73
+
74
+ def initialize(name: nil, value: nil, min: 0, max: 100, step: 1, form: nil, field: nil,
75
+ range: false, from: nil, to: nil, from_name: "from", to_name: "to", from_field: nil, to_field: nil,
76
+ label: nil, hint: nil, error: nil, value_text: nil, show_value: false, marks: nil,
77
+ size: :default, disabled: false, class: nil, **html_attrs)
78
+ @min = min.to_f
79
+ @max = [ max.to_f, @min ].max
80
+ @step = step.to_f.positive? ? step.to_f : 1.0
81
+ @form = form
82
+ @range = range
83
+ @label = label
84
+ @value_text = value_text
85
+ @show_value = show_value
86
+ @marks = marks.is_a?(Hash) ? marks.transform_keys(&:to_f) : Array(marks).to_h { |m| [ m.to_f, nil ] }
87
+ @size = SIZES.key?(size.to_sym) ? size.to_sym : :default
88
+ @disabled = disabled
89
+ @user_class = binding.local_variable_get(:class)
90
+ @aria = html_attrs.delete(:aria) || {}
91
+ @html_attrs = html_attrs
92
+ @id = html_attrs.delete(:id) || "ui-slider-#{SecureRandom.hex(4)}"
93
+ @fields = handles(name: name, value: value, field: field, from: from, to: to, from_name: from_name,
94
+ to_name: to_name, from_field: from_field, to_field: to_field)
95
+ @wrapper = UI::FormField.new(label: false, hint: hint, error: error, form: form,
96
+ field: range ? from_field : field, for: @id)
97
+ end
98
+
99
+ attr_reader :wrapper, :fields
100
+
101
+ def range? = @range
102
+ def disabled? = @disabled
103
+ def show_value? = @show_value
104
+
105
+ def label_id = "#{@id}-label"
106
+
107
+ def label_text
108
+ return nil if @label == false
109
+ return @label if @label.present?
110
+
111
+ field = @fields.first[:field]
112
+ return nil unless @form && field
113
+
114
+ @form.object.class.try(:human_attribute_name, field) || field.to_s.humanize
115
+ end
116
+
117
+ def root_attrs
118
+ { **@html_attrs, class: cn("group/slider w-full space-y-2", disabled? && "opacity-50", @user_class),
119
+ role: ("group" if range?), aria: ({ labelledby: (label_id if label_text), **@aria }.compact if range?),
120
+ style: "--thumb: #{SIZES[@size][:thumb]}; --thumb-h: #{SIZES[@size][:thumb_height]}; --from: #{number(fraction(lower))}; --to: #{number(fraction(upper))}",
121
+ data: { slot: "slider", controller: "ui--slider", "ui--slider-format-value": text_format,
122
+ "ui--slider-range-format-value": range_format, "ui--slider-labels-value": labels.to_json,
123
+ **(@html_attrs[:data] || {}) } }.compact
124
+ end
125
+
126
+ # Grows from the start of the track to the value, or between a range's two.
127
+ def fill_style
128
+ start = range? ? self.class.at("var(--from)") : "0px"
129
+ width = range? ? "calc((100% - var(--thumb)) * (var(--to) - var(--from)))" : self.class.at("var(--to)")
130
+ "inset-inline-start: #{start}; width: #{width}"
131
+ end
132
+
133
+ def track_attrs
134
+ { class: cn("relative h-(--thumb-h) touch-pan-y select-none", disabled? ? "cursor-not-allowed" : "cursor-pointer"),
135
+ data: { "ui--slider-target": "track",
136
+ action: ("pointerdown->ui--slider#press" unless disabled?) } }.compact
137
+ end
138
+
139
+ # The knob's start edge: its centre is where self.at puts the value.
140
+ def knob_style(handle)
141
+ fraction = range? && handle.equal?(@fields.first) ? "var(--from)" : "var(--to)"
142
+ "inset-inline-start: calc((100% - var(--thumb)) * #{fraction})"
143
+ end
144
+
145
+ def track_class = cn("absolute inset-x-0 top-1/2 -translate-y-1/2 overflow-hidden rounded-full bg-foreground/10",
146
+ SIZES[@size][:track])
147
+
148
+ def input_attrs(handle)
149
+ { type: "range", id: handle[:id], min: number(@min), max: number(@max), step: number(@step),
150
+ value: number(handle[:value]), disabled: (true if disabled?), class: INPUT,
151
+ "aria-valuetext": value_text(handle[:value]), "aria-label": handle_name(handle),
152
+ "aria-describedby": wrapper.describedby, "aria-invalid": ("true" if wrapper.error?),
153
+ data: { "ui--slider-target": "input", action: "input->ui--slider#sync" },
154
+ aria: (@aria unless range?) }.compact
155
+ end
156
+
157
+ # Renders the bound field through the form builder, so it takes the model's
158
+ # name, id prefix and value the way a Rails form expects.
159
+ def render_input(handle)
160
+ attrs = input_attrs(handle)
161
+ if @form && handle[:field]
162
+ @form.range_field(handle[:field], **attrs.except(:type, :value), value: attrs[:value])
163
+ else
164
+ tag.input(**attrs, name: handle[:name])
165
+ end
166
+ end
167
+
168
+ def output_text = range? ? range_text(lower, upper) : value_text(upper)
169
+
170
+ def header? = label_text.present? || show_value?
171
+
172
+ def marks? = @marks.any?
173
+
174
+ # Each mark's label and where it sits.
175
+ def marks
176
+ @marks.filter_map do |value, label|
177
+ next unless value.between?(@min, @max)
178
+
179
+ at = fraction(value)
180
+ { label: label.presence || format_value(value), value: number(value), **MARK_PLACES.fetch(at.to_f) { centred(at) } }
181
+ end
182
+ end
183
+
184
+ def centred(at) = { shift: "-translate-x-1/2 rtl:translate-x-1/2", style: "inset-inline-start: #{self.class.at(at)}" }
185
+
186
+ def mark_attrs(mark)
187
+ { class: cn("absolute top-0 whitespace-nowrap", mark[:shift], !disabled? && "cursor-pointer hover:text-foreground"),
188
+ style: mark[:style],
189
+ data: { action: ("click->ui--slider#pick" unless disabled?), "ui--slider-value-param": mark[:value] }.compact }
190
+ end
191
+
192
+ def value_text(value)
193
+ labels[number(value)] || text_format.gsub("%{value}", format_value(value))
194
+ end
195
+
196
+ private
197
+
198
+ def handles(name:, value:, field:, from:, to:, from_name:, to_name:, from_field:, to_field:)
199
+ if @range
200
+ low = snap(clamp(bound(from_field) || from || @min))
201
+ high = snap(clamp(bound(to_field) || to || @max))
202
+ low, high = high, low if low > high
203
+ [ { id: @id, name: from_name, field: from_field, value: low, aria_label: :from },
204
+ { id: "#{@id}-to", name: to_name, field: to_field, value: high,
205
+ aria_label: :to } ]
206
+ else
207
+ # With no value, the middle, as the browser would.
208
+ start = bound(field) || value || (@min + ((@max - @min) / 2))
209
+ [ { id: @id, name: name, field: field, value: snap(clamp(start)), aria_label: nil } ]
210
+ end
211
+ end
212
+
213
+ # A range's handles are named for screen readers; a single one has the label.
214
+ def handle_name(handle)
215
+ return nil unless handle[:aria_label]
216
+
217
+ t("ui.slider.#{handle[:aria_label]}", default: handle[:aria_label] == :from ? "Minimum" : "Maximum")
218
+ end
219
+
220
+ def lower = range? ? @fields.first[:value] : @min
221
+ def upper = @fields.last[:value]
222
+
223
+ def bound(field)
224
+ return nil unless @form && field && @form.object.respond_to?(field)
225
+
226
+ @form.object.public_send(field).presence
227
+ end
228
+
229
+ def clamp(value) = value.to_f.clamp(@min, @max)
230
+
231
+ # To the nearest step from min, the way the browser rounds a range input.
232
+ def snap(value) = (@min + (((value - @min) / @step).round * @step)).clamp(@min, @max).round(decimals)
233
+
234
+ def fraction(value)
235
+ return 0 if @max == @min
236
+
237
+ ((value - @min) / (@max - @min)).round(4)
238
+ end
239
+
240
+ def text_format = @value_text || "%{value}"
241
+
242
+ def range_format = t("ui.slider.range_text", default: "%{from} – %{to}")
243
+
244
+ def range_text(low, high) = range_format.gsub("%{from}", value_text(low)).gsub("%{to}", value_text(high))
245
+
246
+ def labels = @marks.each_with_object({}) { |(value, label), all| all[number(value)] = label if label.present? }
247
+
248
+ def format_value(value) = number(value.to_f.round(decimals))
249
+
250
+ def decimals = number(@step)[/\.(\d+)\z/, 1].to_s.length
251
+
252
+ # 3, not 3.0; 2.5 stays 2.5.
253
+ def number(n) = (n.to_f % 1).zero? ? n.to_i.to_s : n.to_f.to_s
254
+ end