velvetkit 0.4.0 → 0.4.2

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 (84) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +47 -2
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/card/action.html.erb +1 -0
  5. data/registry/app/components/ui/card/action.rb +14 -0
  6. data/registry/app/components/ui/card/content.html.erb +1 -1
  7. data/registry/app/components/ui/card/content.rb +4 -2
  8. data/registry/app/components/ui/card/description.html.erb +1 -1
  9. data/registry/app/components/ui/card/description.rb +4 -2
  10. data/registry/app/components/ui/card/footer.html.erb +1 -1
  11. data/registry/app/components/ui/card/footer.rb +4 -2
  12. data/registry/app/components/ui/card/header.html.erb +1 -1
  13. data/registry/app/components/ui/card/header.rb +9 -2
  14. data/registry/app/components/ui/card/title.html.erb +1 -1
  15. data/registry/app/components/ui/card/title.rb +4 -2
  16. data/registry/app/components/ui/card.html.erb +1 -1
  17. data/registry/app/components/ui/card.rb +49 -3
  18. data/registry/app/components/ui/money_input.html.erb +8 -0
  19. data/registry/app/components/ui/money_input.rb +153 -0
  20. data/registry/app/components/ui/scan_input.html.erb +6 -0
  21. data/registry/app/components/ui/scan_input.rb +94 -0
  22. data/registry/app/components/ui/slider.html.erb +23 -0
  23. data/registry/app/components/ui/slider.rb +254 -0
  24. data/registry/app/javascript/controllers/ui/money_input_controller.ts +228 -0
  25. data/registry/app/javascript/controllers/ui/scan_input_controller.ts +143 -0
  26. data/registry/app/javascript/controllers/ui/slider_controller.ts +216 -0
  27. data/registry/components.yml +7 -1
  28. data/registry/config/locales/velvetkit.en.yml +6 -0
  29. data/registry/icons/lucide/scan-barcode.svg +21 -0
  30. data/registry/icons/lucide/volume-2.svg +17 -0
  31. data/registry/icons/lucide/volume-x.svg +17 -0
  32. data/registry/icons/phosphor/barcode.svg +2 -0
  33. data/registry/icons/phosphor/speaker-high.svg +2 -0
  34. data/registry/icons/phosphor/speaker-x.svg +2 -0
  35. data/registry/icons/tabler/barcode.svg +23 -0
  36. data/registry/icons/tabler/volume-3.svg +17 -0
  37. data/registry/icons/tabler/volume.svg +18 -0
  38. data/registry/icons.yml +3 -0
  39. data/registry/test/components/previews/ui/card_preview/edge_to_edge.html.erb +19 -0
  40. data/registry/test/components/previews/ui/card_preview/image.html.erb +12 -0
  41. data/registry/test/components/previews/ui/card_preview/just_content.html.erb +10 -0
  42. data/registry/test/components/previews/ui/card_preview/open_bill.html.erb +18 -0
  43. data/registry/test/components/previews/ui/card_preview/playground.html.erb +17 -0
  44. data/registry/test/components/previews/ui/card_preview/settings_form.html.erb +15 -24
  45. data/registry/test/components/previews/ui/card_preview/sign_in.html.erb +23 -0
  46. data/registry/test/components/previews/ui/card_preview/small.html.erb +17 -0
  47. data/registry/test/components/previews/ui/card_preview/spacing.html.erb +13 -0
  48. data/registry/test/components/previews/ui/card_preview/stats.html.erb +11 -0
  49. data/registry/test/components/previews/ui/card_preview/team.html.erb +21 -0
  50. data/registry/test/components/previews/ui/card_preview.rb +42 -28
  51. data/registry/test/components/previews/ui/money_input_preview/cash_tendered.html.erb +24 -0
  52. data/registry/test/components/previews/ui/money_input_preview/currencies.html.erb +7 -0
  53. data/registry/test/components/previews/ui/money_input_preview/invoice.html.erb +24 -0
  54. data/registry/test/components/previews/ui/money_input_preview/sizes_and_states.html.erb +9 -0
  55. data/registry/test/components/previews/ui/money_input_preview.rb +34 -0
  56. data/registry/test/components/previews/ui/scan_input_preview/_simulate.html.erb +20 -0
  57. data/registry/test/components/previews/ui/scan_input_preview/library_checkout.html.erb +30 -0
  58. data/registry/test/components/previews/ui/scan_input_preview/playground.html.erb +13 -0
  59. data/registry/test/components/previews/ui/scan_input_preview/stock_count.html.erb +24 -0
  60. data/registry/test/components/previews/ui/scan_input_preview/ticket_check_in.html.erb +34 -0
  61. data/registry/test/components/previews/ui/scan_input_preview/till.html.erb +9 -0
  62. data/registry/test/components/previews/ui/scan_input_preview.rb +33 -0
  63. data/registry/test/components/previews/ui/slider_preview/named_steps.html.erb +7 -0
  64. data/registry/test/components/previews/ui/slider_preview/opening_hours.html.erb +5 -0
  65. data/registry/test/components/previews/ui/slider_preview/price_range.html.erb +6 -0
  66. data/registry/test/components/previews/ui/slider_preview/sizes_and_states.html.erb +9 -0
  67. data/registry/test/components/previews/ui/slider_preview/text_size.html.erb +16 -0
  68. data/registry/test/components/previews/ui/slider_preview/tip.html.erb +22 -0
  69. data/registry/test/components/previews/ui/slider_preview/volume.html.erb +5 -0
  70. data/registry/test/components/previews/ui/slider_preview.rb +45 -0
  71. data/registry/test/components/ui/card/action_test.rb +19 -0
  72. data/registry/test/components/ui/card/content_test.rb +1 -11
  73. data/registry/test/components/ui/card/footer_test.rb +3 -2
  74. data/registry/test/components/ui/card/header_test.rb +3 -4
  75. data/registry/test/components/ui/card/title_test.rb +3 -4
  76. data/registry/test/components/ui/card_test.rb +63 -2
  77. data/registry/test/components/ui/money_input_test.rb +149 -0
  78. data/registry/test/components/ui/scan_input_test.rb +110 -0
  79. data/registry/test/components/ui/slider_test.rb +190 -0
  80. metadata +55 -5
  81. data/registry/test/components/previews/ui/card_preview/complete.html.erb +0 -31
  82. data/registry/test/components/previews/ui/card_preview/default.html.erb +0 -7
  83. data/registry/test/components/previews/ui/card_preview/with_footer.html.erb +0 -13
  84. data/registry/test/components/previews/ui/card_preview/with_header.html.erb +0 -11
@@ -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
@@ -0,0 +1,228 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--money-input"
4
+ //
5
+ // Regroups the amount as it's typed and keeps the caret where it was among
6
+ // the digits, so typing in the middle of "1,23,456" doesn't throw it to the
7
+ // end. The hidden field gets the plain number, built from the digits as a
8
+ // string: no floats, so nothing is rounded on the way to the server.
9
+ const MAX_DIGITS = 15;
10
+
11
+ type Amount = { negative: boolean; whole: string; fraction: string; point: boolean };
12
+
13
+ export default class extends Controller<HTMLElement> {
14
+ static targets = ['field', 'value'];
15
+ static values = {
16
+ separator: { type: String, default: '.' },
17
+ delimiter: { type: String, default: ',' },
18
+ precision: { type: Number, default: 2 },
19
+ grouping: { type: String, default: 'thousands' },
20
+ negative: Boolean,
21
+ step: { type: String, default: '1' },
22
+ };
23
+
24
+ declare readonly fieldTarget: HTMLInputElement;
25
+ declare readonly valueTarget: HTMLInputElement;
26
+ declare readonly separatorValue: string;
27
+ declare readonly delimiterValue: string;
28
+ declare readonly precisionValue: number;
29
+ declare readonly groupingValue: string;
30
+ declare readonly negativeValue: boolean;
31
+ declare readonly stepValue: string;
32
+
33
+ connect() {
34
+ this.element.closest('form')?.addEventListener('reset', this.afterReset);
35
+ }
36
+
37
+ disconnect() {
38
+ this.element.closest('form')?.removeEventListener('reset', this.afterReset);
39
+ }
40
+
41
+ type() {
42
+ const field = this.fieldTarget;
43
+ const caret = field.selectionStart ?? field.value.length;
44
+ const { amount, kept } = this.read(field.value, caret);
45
+ const text = this.write(amount);
46
+
47
+ field.value = text;
48
+ const at = this.caretAt(text, kept);
49
+ if (document.activeElement === field) field.setSelectionRange(at, at);
50
+ this.valueTarget.value = this.plain(amount);
51
+ }
52
+
53
+ // Before a keystroke lands. Backspace just after a delimiter, or Delete
54
+ // just before one, would remove only the comma, which regrouping puts
55
+ // straight back: step over it so the digit beside it goes instead.
56
+ guard(event: InputEvent) {
57
+ const field = this.fieldTarget;
58
+ // No decimals: a typed point is refused, or the digits after it would
59
+ // join the whole amount once it's dropped.
60
+ if (event.inputType === 'insertText' && this.precisionValue === 0 && event.data && this.isPoint(event.data)) {
61
+ event.preventDefault();
62
+ return;
63
+ }
64
+
65
+ const { selectionStart: start, selectionEnd: end } = field;
66
+ if (start === null || start !== end) return;
67
+
68
+ if (event.inputType === 'deleteContentBackward' && field.value[start - 1] === this.delimiterValue) {
69
+ field.setSelectionRange(start - 1, start - 1);
70
+ } else if (event.inputType === 'deleteContentForward' && field.value[start] === this.delimiterValue) {
71
+ field.setSelectionRange(start + 1, start + 1);
72
+ }
73
+ }
74
+
75
+ // ↑ and ↓ add or take away a step (one whole unit unless `step:` says),
76
+ // Shift ten. Counted in paise or cents as whole numbers, so nothing drifts.
77
+ nudge(event: KeyboardEvent) {
78
+ if ((event.key !== 'ArrowUp' && event.key !== 'ArrowDown') || event.altKey || event.metaKey || event.ctrlKey) return;
79
+ if (this.fieldTarget.readOnly) return;
80
+
81
+ event.preventDefault();
82
+ const { amount } = this.read(this.fieldTarget.value, 0);
83
+ const scale = 10n ** BigInt(this.precisionValue);
84
+ let minor = this.minor(amount, scale);
85
+ const step = this.minor(this.read(this.stepValue.replace('.', this.separatorValue), 0).amount, scale) || scale;
86
+ minor += (event.key === 'ArrowUp' ? 1n : -1n) * step * (event.shiftKey ? 10n : 1n);
87
+ if (minor < 0n && !this.negativeValue) minor = 0n;
88
+
89
+ const digits = (minor < 0n ? -minor : minor).toString().padStart(this.precisionValue + 1, '0');
90
+ const cut = digits.length - this.precisionValue;
91
+ const next: Amount = {
92
+ negative: minor < 0n,
93
+ whole: digits.slice(0, cut),
94
+ fraction: digits.slice(cut),
95
+ point: this.precisionValue > 0,
96
+ };
97
+ const text = this.write(next);
98
+ if (text === this.fieldTarget.value) return;
99
+
100
+ this.fieldTarget.value = text;
101
+ this.fieldTarget.setSelectionRange(text.length, text.length);
102
+ this.valueTarget.value = this.plain(next);
103
+ this.fieldTarget.dispatchEvent(new Event('input', { bubbles: true }));
104
+ this.fieldTarget.dispatchEvent(new Event('change', { bubbles: true }));
105
+ }
106
+
107
+ // Leaving the field fills in the decimals: "1,200" becomes "1,200.00".
108
+ finish() {
109
+ const { amount } = this.read(this.fieldTarget.value, 0);
110
+ if (!amount.whole && !amount.fraction) {
111
+ this.fieldTarget.value = '';
112
+ this.valueTarget.value = '';
113
+ return;
114
+ }
115
+
116
+ const full = { ...amount, whole: amount.whole || '0', point: this.precisionValue > 0 };
117
+ full.fraction = full.fraction.padEnd(this.precisionValue, '0');
118
+ this.fieldTarget.value = this.write(full);
119
+ this.valueTarget.value = this.plain(full);
120
+ }
121
+
122
+ // What was typed or pasted, as an amount, and how many of its characters
123
+ // (digits, the point, a minus) came before the caret.
124
+ private read(text: string, caret: number): { amount: Amount; kept: number } {
125
+ const amount: Amount = { negative: false, whole: '', fraction: '', point: false };
126
+ let kept = 0;
127
+ let zeros = 0;
128
+ let zeroBefore = false;
129
+ // A point typed where there are no decimals ends the amount: "15800.5" is 15800.
130
+ let ended = false;
131
+
132
+ [...text].forEach((char, index) => {
133
+ const before = index < caret;
134
+ if (ended) return;
135
+ if (char === '-' && this.negativeValue && !amount.negative && !amount.whole && !amount.point) {
136
+ amount.negative = true;
137
+ } else if (this.isPoint(char) && !amount.point && this.precisionValue === 0) {
138
+ ended = true;
139
+ return;
140
+ } else if (this.isPoint(char) && !amount.point) {
141
+ amount.point = true;
142
+ // ".5" reads as "0.5"; the 0 is one more character before the caret.
143
+ if (!amount.whole) {
144
+ amount.whole = '0';
145
+ if (before) kept += 1;
146
+ }
147
+ } else if (/\d/.test(char)) {
148
+ if (amount.point) {
149
+ if (amount.fraction.length >= this.precisionValue) return;
150
+ amount.fraction += char;
151
+ } else {
152
+ if (amount.whole.length >= MAX_DIGITS) return;
153
+ // Leading zeros go, unless the 0 is all there is.
154
+ if (amount.whole === '0') {
155
+ amount.whole = char;
156
+ if (zeroBefore) zeros += 1;
157
+ } else {
158
+ amount.whole += char;
159
+ }
160
+ if (amount.whole === '0') zeroBefore = before;
161
+ }
162
+ } else {
163
+ return;
164
+ }
165
+ if (before) kept += 1;
166
+ });
167
+
168
+ return { amount, kept: kept - zeros };
169
+ }
170
+
171
+ // An amount in paise or cents, as a whole number.
172
+ private minor(amount: Amount, scale: bigint): bigint {
173
+ const whole = BigInt(amount.whole || '0') * scale;
174
+ const fraction = BigInt(amount.fraction.padEnd(this.precisionValue, '0') || '0');
175
+ const total = whole + fraction;
176
+ return amount.negative ? -total : total;
177
+ }
178
+
179
+ private write(amount: Amount): string {
180
+ const whole = this.group(amount.whole);
181
+ const point = amount.point ? this.separatorValue + amount.fraction : '';
182
+ return `${amount.negative ? '-' : ''}${whole}${point}`;
183
+ }
184
+
185
+ private plain(amount: Amount): string {
186
+ if (!amount.whole && !amount.fraction) return '';
187
+
188
+ const fraction = amount.fraction ? `.${amount.fraction}` : '';
189
+ return `${amount.negative ? '-' : ''}${amount.whole || '0'}${fraction}`;
190
+ }
191
+
192
+ // 1234567 as 1,234,567, or the Indian way, 12,34,567.
193
+ private group(digits: string): string {
194
+ const d = this.delimiterValue;
195
+ if (this.groupingValue !== 'indian') return digits.replace(/\B(?=(\d{3})+(?!\d))/g, d);
196
+ if (digits.length <= 3) return digits;
197
+
198
+ return `${digits.slice(0, -3).replace(/\B(?=(\d{2})+(?!\d))/g, d)}${d}${digits.slice(-3)}`;
199
+ }
200
+
201
+ // The place in the new text after `kept` characters that aren't delimiters.
202
+ private caretAt(text: string, kept: number): number {
203
+ if (kept <= 0) return 0;
204
+
205
+ let seen = 0;
206
+ for (let index = 0; index < text.length; index += 1) {
207
+ if (text[index] !== this.delimiterValue || index === this.pointIndex(text)) seen += 1;
208
+ if (seen === kept) return index + 1;
209
+ }
210
+ return text.length;
211
+ }
212
+
213
+ private pointIndex(text: string): number {
214
+ return this.separatorValue === this.delimiterValue ? -1 : text.indexOf(this.separatorValue);
215
+ }
216
+
217
+ // The locale's decimal mark, or a full stop where that isn't the delimiter:
218
+ // the key on a phone's decimal pad.
219
+ private isPoint(char: string): boolean {
220
+ return char === this.separatorValue || (char === '.' && this.delimiterValue !== '.');
221
+ }
222
+
223
+ private afterReset = () =>
224
+ requestAnimationFrame(() => {
225
+ this.type();
226
+ this.finish();
227
+ });
228
+ }
@@ -0,0 +1,143 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--scan-input"
4
+ //
5
+ // A scanner types a code and presses Enter (or Tab). On that key this fires
6
+ // `ui--scan-input:scan`, then submits the form with the code and empties the
7
+ // field. While a Turbo submission is on its way, later codes queue and go
8
+ // one after another, so none is lost to a busy form. Focus is kept on the
9
+ // field when it would otherwise fall to the page.
10
+ const SCANNED_FOR = 700;
11
+
12
+ export default class extends Controller<HTMLElement> {
13
+ static targets = ['field'];
14
+ static values = {
15
+ submit: { type: Boolean, default: true },
16
+ clear: { type: Boolean, default: true },
17
+ keepFocus: { type: Boolean, default: true },
18
+ capture: Boolean,
19
+ suffix: { type: String, default: 'enter' },
20
+ };
21
+
22
+ declare readonly fieldTarget: HTMLInputElement;
23
+ declare readonly submitValue: boolean;
24
+ declare readonly clearValue: boolean;
25
+ declare readonly keepFocusValue: boolean;
26
+ declare readonly captureValue: boolean;
27
+ declare readonly suffixValue: string;
28
+
29
+ private queue: string[] = [];
30
+ private sending = false;
31
+ private form: HTMLFormElement | null = null;
32
+ private scannedTimer?: number;
33
+
34
+ connect() {
35
+ this.form = this.fieldTarget.form;
36
+ this.form?.addEventListener('turbo:submit-start', this.started);
37
+ this.form?.addEventListener('turbo:submit-end', this.ended);
38
+ this.fieldTarget.addEventListener('blur', this.blurred);
39
+ if (this.keepFocusValue) document.addEventListener('visibilitychange', this.refocus);
40
+ if (this.captureValue) document.addEventListener('keydown', this.captured);
41
+ // autofocus only works on page load; back in a Turbo update, focus here.
42
+ if (this.fieldTarget.autofocus) this.refocus();
43
+ }
44
+
45
+ disconnect() {
46
+ this.form?.removeEventListener('turbo:submit-start', this.started);
47
+ this.form?.removeEventListener('turbo:submit-end', this.ended);
48
+ this.fieldTarget.removeEventListener('blur', this.blurred);
49
+ document.removeEventListener('visibilitychange', this.refocus);
50
+ document.removeEventListener('keydown', this.captured);
51
+ window.clearTimeout(this.scannedTimer);
52
+ }
53
+
54
+ key(event: KeyboardEvent) {
55
+ if (event.isComposing || !this.isSuffix(event)) return;
56
+
57
+ event.preventDefault();
58
+ const code = this.fieldTarget.value.trim();
59
+ if (!code) return;
60
+
61
+ this.flash();
62
+ const scan = new CustomEvent('ui--scan-input:scan', { detail: { code }, bubbles: true, cancelable: true });
63
+ this.element.dispatchEvent(scan);
64
+ if (scan.defaultPrevented || !this.submitValue || !this.form) {
65
+ if (this.clearValue) this.fieldTarget.value = '';
66
+ return;
67
+ }
68
+
69
+ if (this.sending) {
70
+ this.queue.push(code);
71
+ if (this.clearValue) this.fieldTarget.value = '';
72
+ } else {
73
+ this.send(code);
74
+ }
75
+ }
76
+
77
+ // The form data is read as the submit event runs, so the field can be
78
+ // emptied straight after.
79
+ private send(code: string) {
80
+ this.fieldTarget.value = code;
81
+ this.form?.requestSubmit();
82
+ if (this.clearValue) this.fieldTarget.value = '';
83
+ }
84
+
85
+ private started = () => {
86
+ this.sending = true;
87
+ };
88
+
89
+ private ended = () => {
90
+ this.sending = false;
91
+ const next = this.queue.shift();
92
+ if (next !== undefined) this.send(next);
93
+ };
94
+
95
+ private isSuffix(event: KeyboardEvent): boolean {
96
+ if (event.altKey || event.ctrlKey || event.metaKey) return false;
97
+ if (this.suffixValue === 'tab') return event.key === 'Tab' && !event.shiftKey;
98
+
99
+ return event.key === 'Enter';
100
+ }
101
+
102
+ private flash() {
103
+ this.element.dataset.scanned = '';
104
+ window.clearTimeout(this.scannedTimer);
105
+ this.scannedTimer = window.setTimeout(() => delete this.element.dataset.scanned, SCANNED_FOR);
106
+ }
107
+
108
+ // Only when focus has fallen to the page: a person moving to another field,
109
+ // a button or a dialog keeps it.
110
+ private blurred = () => {
111
+ if (!this.keepFocusValue) return;
112
+
113
+ requestAnimationFrame(() => this.refocus());
114
+ };
115
+
116
+ private refocus = () => {
117
+ const field = this.fieldTarget;
118
+ if (document.visibilityState !== 'visible' || field.disabled || field.readOnly) return;
119
+ if (!this.keepFocusValue && !field.autofocus) return;
120
+
121
+ const active = document.activeElement;
122
+ if (active && active !== document.body && active !== document.documentElement) return;
123
+
124
+ field.focus({ preventScroll: true });
125
+ };
126
+
127
+ // Typed anywhere but another field, a character goes to this one: focusing it
128
+ // during keydown lets the browser put the key there.
129
+ private captured = (event: KeyboardEvent) => {
130
+ if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.key.length !== 1) return;
131
+ if (this.fieldTarget.disabled || this.isEditable(event.target)) return;
132
+ // Space presses a focused button; leave that alone.
133
+ if (event.key === ' ' && event.target instanceof HTMLElement && event.target.closest('button, a, [role=button]')) return;
134
+
135
+ this.fieldTarget.focus({ preventScroll: true });
136
+ };
137
+
138
+ private isEditable(target: EventTarget | null): boolean {
139
+ if (!(target instanceof HTMLElement)) return false;
140
+
141
+ return target.isContentEditable || target.closest('input, textarea, select, [role=textbox], [role=combobox]') !== null;
142
+ }
143
+ }