velvetkit 0.3.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 (216) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +109 -0
  3. data/README.md +5 -1
  4. data/lib/generators/velvetkit/add/add_generator.rb +58 -0
  5. data/lib/velvetkit/version.rb +4 -1
  6. data/lib/velvetkit.rb +7 -0
  7. data/registry/app/assets/tailwind/velvetkit.css +90 -155
  8. data/registry/app/components/ui/chart.html.erb +47 -0
  9. data/registry/app/components/ui/chart.rb +177 -0
  10. data/registry/app/components/ui/command/group.rb +27 -0
  11. data/registry/app/components/ui/command/item.rb +64 -0
  12. data/registry/app/components/ui/command.html.erb +41 -0
  13. data/registry/app/components/ui/command.rb +122 -0
  14. data/registry/app/components/ui/date_picker.html.erb +58 -64
  15. data/registry/app/components/ui/date_picker.rb +199 -75
  16. data/registry/app/components/ui/file_field.html.erb +14 -4
  17. data/registry/app/components/ui/file_field.rb +179 -28
  18. data/registry/app/components/ui/gallery/image.rb +20 -0
  19. data/registry/app/components/ui/gallery.html.erb +52 -0
  20. data/registry/app/components/ui/gallery.rb +164 -0
  21. data/registry/app/components/ui/kbd.html.erb +27 -0
  22. data/registry/app/components/ui/kbd.rb +134 -0
  23. data/registry/app/components/ui/money_input.html.erb +8 -0
  24. data/registry/app/components/ui/money_input.rb +153 -0
  25. data/registry/app/components/ui/number_input.html.erb +11 -0
  26. data/registry/app/components/ui/number_input.rb +103 -0
  27. data/registry/app/components/ui/progress/segment.rb +25 -0
  28. data/registry/app/components/ui/progress.html.erb +25 -0
  29. data/registry/app/components/ui/progress.rb +182 -0
  30. data/registry/app/components/ui/scan_input.html.erb +6 -0
  31. data/registry/app/components/ui/scan_input.rb +94 -0
  32. data/registry/app/components/ui/select.html.erb +24 -5
  33. data/registry/app/components/ui/select.rb +44 -5
  34. data/registry/app/components/ui/slider.html.erb +23 -0
  35. data/registry/app/components/ui/slider.rb +254 -0
  36. data/registry/app/components/ui/timeline/item.html.erb +21 -0
  37. data/registry/app/components/ui/timeline/item.rb +145 -0
  38. data/registry/app/components/ui/timeline.html.erb +1 -0
  39. data/registry/app/components/ui/timeline.rb +42 -0
  40. data/registry/app/javascript/chart_js.ts +37 -0
  41. data/registry/app/javascript/controllers/ui/_internal/date_format.ts +74 -0
  42. data/registry/app/javascript/controllers/ui/_internal/shortcut.ts +80 -0
  43. data/registry/app/javascript/controllers/ui/chart_controller.ts +585 -0
  44. data/registry/app/javascript/controllers/ui/command_controller.ts +454 -0
  45. data/registry/app/javascript/controllers/ui/date_picker_controller.ts +247 -82
  46. data/registry/app/javascript/controllers/ui/file_field_controller.ts +288 -16
  47. data/registry/app/javascript/controllers/ui/gallery_controller.ts +568 -0
  48. data/registry/app/javascript/controllers/ui/kbd_controller.ts +60 -0
  49. data/registry/app/javascript/controllers/ui/money_input_controller.ts +228 -0
  50. data/registry/app/javascript/controllers/ui/number_input_controller.ts +111 -0
  51. data/registry/app/javascript/controllers/ui/progress_controller.ts +87 -0
  52. data/registry/app/javascript/controllers/ui/scan_input_controller.ts +143 -0
  53. data/registry/app/javascript/controllers/ui/select_controller.ts +198 -8
  54. data/registry/app/javascript/controllers/ui/slider_controller.ts +216 -0
  55. data/registry/app/javascript/vanilla_calendar.ts +15 -0
  56. data/registry/components.yml +25 -3
  57. data/registry/config/locales/velvetkit.en.yml +79 -0
  58. data/registry/icons/lucide/download.svg +17 -0
  59. data/registry/icons/lucide/file-plus.svg +18 -0
  60. data/registry/icons/lucide/file.svg +16 -0
  61. data/registry/icons/lucide/folder.svg +15 -0
  62. data/registry/icons/lucide/keyboard.svg +23 -0
  63. data/registry/icons/lucide/minus.svg +15 -0
  64. data/registry/icons/lucide/package.svg +18 -0
  65. data/registry/icons/lucide/pause.svg +16 -0
  66. data/registry/icons/lucide/percent.svg +17 -0
  67. data/registry/icons/lucide/printer.svg +17 -0
  68. data/registry/icons/lucide/receipt.svg +17 -0
  69. data/registry/icons/lucide/scan-barcode.svg +21 -0
  70. data/registry/icons/lucide/sun-moon.svg +19 -0
  71. data/registry/icons/lucide/truck.svg +19 -0
  72. data/registry/icons/lucide/user-plus.svg +18 -0
  73. data/registry/icons/lucide/volume-2.svg +17 -0
  74. data/registry/icons/lucide/volume-x.svg +17 -0
  75. data/registry/icons/lucide/zoom-in.svg +18 -0
  76. data/registry/icons/lucide/zoom-out.svg +17 -0
  77. data/registry/icons/phosphor/barcode.svg +2 -0
  78. data/registry/icons/phosphor/circle-half.svg +2 -0
  79. data/registry/icons/phosphor/download-simple.svg +2 -0
  80. data/registry/icons/phosphor/file-plus.svg +2 -0
  81. data/registry/icons/phosphor/file.svg +2 -0
  82. data/registry/icons/phosphor/folder.svg +2 -0
  83. data/registry/icons/phosphor/keyboard.svg +2 -0
  84. data/registry/icons/phosphor/magnifying-glass-minus.svg +2 -0
  85. data/registry/icons/phosphor/magnifying-glass-plus.svg +2 -0
  86. data/registry/icons/phosphor/minus.svg +2 -0
  87. data/registry/icons/phosphor/package.svg +2 -0
  88. data/registry/icons/phosphor/pause.svg +2 -0
  89. data/registry/icons/phosphor/percent.svg +2 -0
  90. data/registry/icons/phosphor/printer.svg +2 -0
  91. data/registry/icons/phosphor/receipt.svg +2 -0
  92. data/registry/icons/phosphor/speaker-high.svg +2 -0
  93. data/registry/icons/phosphor/speaker-x.svg +2 -0
  94. data/registry/icons/phosphor/truck.svg +2 -0
  95. data/registry/icons/phosphor/user-plus.svg +2 -0
  96. data/registry/icons/tabler/barcode.svg +23 -0
  97. data/registry/icons/tabler/download.svg +18 -0
  98. data/registry/icons/tabler/file-plus.svg +19 -0
  99. data/registry/icons/tabler/file.svg +17 -0
  100. data/registry/icons/tabler/folder.svg +16 -0
  101. data/registry/icons/tabler/keyboard.svg +23 -0
  102. data/registry/icons/tabler/minus.svg +16 -0
  103. data/registry/icons/tabler/package.svg +20 -0
  104. data/registry/icons/tabler/percentage.svg +18 -0
  105. data/registry/icons/tabler/player-pause.svg +17 -0
  106. data/registry/icons/tabler/printer.svg +18 -0
  107. data/registry/icons/tabler/receipt.svg +16 -0
  108. data/registry/icons/tabler/sun-moon.svg +21 -0
  109. data/registry/icons/tabler/truck.svg +18 -0
  110. data/registry/icons/tabler/user-plus.svg +19 -0
  111. data/registry/icons/tabler/volume-3.svg +17 -0
  112. data/registry/icons/tabler/volume.svg +18 -0
  113. data/registry/icons/tabler/zoom-in.svg +19 -0
  114. data/registry/icons/tabler/zoom-out.svg +18 -0
  115. data/registry/icons.yml +19 -0
  116. data/registry/test/components/previews/ui/chart_preview/cash_flow.html.erb +6 -0
  117. data/registry/test/components/previews/ui/chart_preview/donut.html.erb +6 -0
  118. data/registry/test/components/previews/ui/chart_preview/margin.html.erb +6 -0
  119. data/registry/test/components/previews/ui/chart_preview/pie.html.erb +6 -0
  120. data/registry/test/components/previews/ui/chart_preview/sales.html.erb +6 -0
  121. data/registry/test/components/previews/ui/chart_preview/stock.html.erb +6 -0
  122. data/registry/test/components/previews/ui/chart_preview/takings.html.erb +8 -0
  123. data/registry/test/components/previews/ui/chart_preview.rb +46 -0
  124. data/registry/test/components/previews/ui/command_preview/_picked.html.erb +14 -0
  125. data/registry/test/components/previews/ui/command_preview/dialog.html.erb +24 -0
  126. data/registry/test/components/previews/ui/command_preview/inline.html.erb +16 -0
  127. data/registry/test/components/previews/ui/command_preview/playground.html.erb +15 -0
  128. data/registry/test/components/previews/ui/command_preview/server_search.html.erb +24 -0
  129. data/registry/test/components/previews/ui/command_preview/shortcuts.html.erb +12 -0
  130. data/registry/test/components/previews/ui/command_preview/till.html.erb +17 -0
  131. data/registry/test/components/previews/ui/command_preview.rb +25 -0
  132. data/registry/test/components/previews/ui/date_picker_preview/custom_presets.html.erb +6 -0
  133. data/registry/test/components/previews/ui/date_picker_preview/in_form.html.erb +11 -0
  134. data/registry/test/components/previews/ui/date_picker_preview/range.html.erb +5 -0
  135. data/registry/test/components/previews/ui/date_picker_preview/states.html.erb +4 -3
  136. data/registry/test/components/previews/ui/date_picker_preview.rb +26 -6
  137. data/registry/test/components/previews/ui/file_field_preview/multiple_files.html.erb +1 -1
  138. data/registry/test/components/previews/ui/file_field_preview/product_photos.html.erb +12 -0
  139. data/registry/test/components/previews/ui/file_field_preview/single_image.html.erb +4 -0
  140. data/registry/test/components/previews/ui/file_field_preview.rb +32 -5
  141. data/registry/test/components/previews/ui/gallery_preview/hover_zoom.html.erb +13 -0
  142. data/registry/test/components/previews/ui/gallery_preview/landscape.html.erb +5 -0
  143. data/registry/test/components/previews/ui/gallery_preview/product_page.html.erb +13 -0
  144. data/registry/test/components/previews/ui/gallery_preview/single.html.erb +3 -0
  145. data/registry/test/components/previews/ui/gallery_preview.rb +45 -0
  146. data/registry/test/components/previews/ui/kbd_preview/bound.html.erb +20 -0
  147. data/registry/test/components/previews/ui/kbd_preview/keys.html.erb +13 -0
  148. data/registry/test/components/previews/ui/kbd_preview/menu.html.erb +13 -0
  149. data/registry/test/components/previews/ui/kbd_preview/search_field.html.erb +8 -0
  150. data/registry/test/components/previews/ui/kbd_preview/shortcuts_list.html.erb +17 -0
  151. data/registry/test/components/previews/ui/kbd_preview/till.html.erb +23 -0
  152. data/registry/test/components/previews/ui/kbd_preview/tooltip_and_buttons.html.erb +14 -0
  153. data/registry/test/components/previews/ui/kbd_preview.rb +32 -0
  154. data/registry/test/components/previews/ui/money_input_preview/cash_tendered.html.erb +24 -0
  155. data/registry/test/components/previews/ui/money_input_preview/currencies.html.erb +7 -0
  156. data/registry/test/components/previews/ui/money_input_preview/invoice.html.erb +24 -0
  157. data/registry/test/components/previews/ui/money_input_preview/sizes_and_states.html.erb +9 -0
  158. data/registry/test/components/previews/ui/money_input_preview.rb +34 -0
  159. data/registry/test/components/previews/ui/number_input_preview/cart.html.erb +11 -0
  160. data/registry/test/components/previews/ui/number_input_preview/decimals.html.erb +4 -0
  161. data/registry/test/components/previews/ui/number_input_preview/sizes.html.erb +5 -0
  162. data/registry/test/components/previews/ui/number_input_preview/states.html.erb +7 -0
  163. data/registry/test/components/previews/ui/number_input_preview/stock_adjustment.html.erb +3 -0
  164. data/registry/test/components/previews/ui/number_input_preview.rb +36 -0
  165. data/registry/test/components/previews/ui/progress_preview/file_upload.html.erb +36 -0
  166. data/registry/test/components/previews/ui/progress_preview/free_shipping.html.erb +4 -0
  167. data/registry/test/components/previews/ui/progress_preview/indeterminate.html.erb +4 -0
  168. data/registry/test/components/previews/ui/progress_preview/sizes_and_tones.html.erb +8 -0
  169. data/registry/test/components/previews/ui/progress_preview/steps.html.erb +9 -0
  170. data/registry/test/components/previews/ui/progress_preview/storage.html.erb +8 -0
  171. data/registry/test/components/previews/ui/progress_preview/storage_by_category.html.erb +7 -0
  172. data/registry/test/components/previews/ui/progress_preview/tasks_by_status.html.erb +14 -0
  173. data/registry/test/components/previews/ui/progress_preview/traffic_by_source.html.erb +15 -0
  174. data/registry/test/components/previews/ui/progress_preview.rb +46 -0
  175. data/registry/test/components/previews/ui/scan_input_preview/_simulate.html.erb +20 -0
  176. data/registry/test/components/previews/ui/scan_input_preview/library_checkout.html.erb +30 -0
  177. data/registry/test/components/previews/ui/scan_input_preview/playground.html.erb +13 -0
  178. data/registry/test/components/previews/ui/scan_input_preview/stock_count.html.erb +24 -0
  179. data/registry/test/components/previews/ui/scan_input_preview/ticket_check_in.html.erb +34 -0
  180. data/registry/test/components/previews/ui/scan_input_preview/till.html.erb +9 -0
  181. data/registry/test/components/previews/ui/scan_input_preview.rb +33 -0
  182. data/registry/test/components/previews/ui/select_preview/server_search.html.erb +22 -0
  183. data/registry/test/components/previews/ui/select_preview.rb +5 -0
  184. data/registry/test/components/previews/ui/slider_preview/named_steps.html.erb +7 -0
  185. data/registry/test/components/previews/ui/slider_preview/opening_hours.html.erb +5 -0
  186. data/registry/test/components/previews/ui/slider_preview/price_range.html.erb +6 -0
  187. data/registry/test/components/previews/ui/slider_preview/sizes_and_states.html.erb +9 -0
  188. data/registry/test/components/previews/ui/slider_preview/text_size.html.erb +16 -0
  189. data/registry/test/components/previews/ui/slider_preview/tip.html.erb +22 -0
  190. data/registry/test/components/previews/ui/slider_preview/volume.html.erb +5 -0
  191. data/registry/test/components/previews/ui/slider_preview.rb +45 -0
  192. data/registry/test/components/previews/ui/timeline_preview/activity_log.html.erb +7 -0
  193. data/registry/test/components/previews/ui/timeline_preview/colored.html.erb +7 -0
  194. data/registry/test/components/previews/ui/timeline_preview/colored_by_meaning.html.erb +7 -0
  195. data/registry/test/components/previews/ui/timeline_preview/failed_delivery.html.erb +6 -0
  196. data/registry/test/components/previews/ui/timeline_preview/order_status.html.erb +9 -0
  197. data/registry/test/components/previews/ui/timeline_preview/real_dates.html.erb +5 -0
  198. data/registry/test/components/previews/ui/timeline_preview/stock_history.html.erb +6 -0
  199. data/registry/test/components/previews/ui/timeline_preview.rb +40 -0
  200. data/registry/test/components/ui/chart_test.rb +187 -0
  201. data/registry/test/components/ui/command/group_test.rb +19 -0
  202. data/registry/test/components/ui/command/item_test.rb +47 -0
  203. data/registry/test/components/ui/command_test.rb +110 -0
  204. data/registry/test/components/ui/date_picker_test.rb +129 -111
  205. data/registry/test/components/ui/file_field_test.rb +105 -9
  206. data/registry/test/components/ui/gallery_test.rb +192 -0
  207. data/registry/test/components/ui/kbd_test.rb +150 -0
  208. data/registry/test/components/ui/money_input_test.rb +149 -0
  209. data/registry/test/components/ui/number_input_test.rb +155 -0
  210. data/registry/test/components/ui/progress_test.rb +188 -0
  211. data/registry/test/components/ui/scan_input_test.rb +110 -0
  212. data/registry/test/components/ui/select_test.rb +62 -0
  213. data/registry/test/components/ui/slider_test.rb +190 -0
  214. data/registry/test/components/ui/timeline_test.rb +175 -0
  215. metadata +188 -2
  216. data/registry/app/javascript/cally.ts +0 -8
@@ -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,111 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--number-input"
4
+ //
5
+ // The stepping itself is the browser's: stepUp() and stepDown() already respect
6
+ // min, max and step, and don't drift on decimals. This adds holding a button to
7
+ // keep counting, and turns a button off at its limit.
8
+ const HOLD_DELAY = 400;
9
+ const REPEAT_EVERY = 100;
10
+
11
+ type Direction = 'up' | 'down';
12
+ type StepEvent<E extends Event> = E & { params: { direction: Direction } };
13
+
14
+ export default class extends Controller<HTMLElement> {
15
+ static targets = ['input', 'decrement', 'increment'];
16
+
17
+ declare readonly inputTarget: HTMLInputElement;
18
+ declare readonly decrementTarget: HTMLButtonElement;
19
+ declare readonly incrementTarget: HTMLButtonElement;
20
+
21
+ private holdTimer?: number;
22
+ private repeatTimer?: number;
23
+ private changed = false;
24
+
25
+ connect() {
26
+ this.sync();
27
+ }
28
+
29
+ disconnect() {
30
+ this.release();
31
+ }
32
+
33
+ // One step at once, then repeating until the button is let go. Listens on the
34
+ // window: a button that reaches its limit is disabled, and a disabled button
35
+ // doesn't hear the pointer come up.
36
+ press(event: StepEvent<PointerEvent>) {
37
+ if (event.button !== 0) return;
38
+
39
+ this.release();
40
+ const { direction } = event.params;
41
+ if (!this.step(direction)) return;
42
+
43
+ window.addEventListener('pointerup', this.release);
44
+ window.addEventListener('pointercancel', this.release);
45
+ window.addEventListener('blur', this.release);
46
+ this.holdTimer = window.setTimeout(() => {
47
+ this.repeatTimer = window.setInterval(() => {
48
+ if (!this.step(direction)) this.stopRepeating();
49
+ }, REPEAT_EVERY);
50
+ }, HOLD_DELAY);
51
+ }
52
+
53
+ // A pointer has already stepped in press(). A click with no pointer behind it
54
+ // (detail 0) is the keyboard or a screen reader.
55
+ click(event: StepEvent<MouseEvent>) {
56
+ if (event.detail !== 0) return;
57
+
58
+ if (this.step(event.params.direction)) this.release();
59
+ }
60
+
61
+ sync() {
62
+ const input = this.inputTarget;
63
+ const locked = input.disabled || input.readOnly;
64
+ const value = input.valueAsNumber;
65
+ this.decrementTarget.disabled = locked || value <= parseFloat(input.min);
66
+ this.incrementTarget.disabled = locked || value >= parseFloat(input.max);
67
+ }
68
+
69
+ private release = () => {
70
+ this.stopRepeating();
71
+ window.removeEventListener('pointerup', this.release);
72
+ window.removeEventListener('pointercancel', this.release);
73
+ window.removeEventListener('blur', this.release);
74
+ if (!this.changed) return;
75
+
76
+ this.changed = false;
77
+ this.inputTarget.dispatchEvent(new Event('change', { bubbles: true }));
78
+ };
79
+
80
+ private stopRepeating() {
81
+ window.clearTimeout(this.holdTimer);
82
+ window.clearInterval(this.repeatTimer);
83
+ }
84
+
85
+ private step(direction: Direction): boolean {
86
+ const input = this.inputTarget;
87
+ const before = input.value;
88
+
89
+ if (input.step === 'any') {
90
+ this.stepByOne(direction);
91
+ } else if (direction === 'up') {
92
+ input.stepUp();
93
+ } else {
94
+ input.stepDown();
95
+ }
96
+ if (input.value === before) return false;
97
+
98
+ this.changed = true;
99
+ input.dispatchEvent(new Event('input', { bubbles: true }));
100
+ return true;
101
+ }
102
+
103
+ // stepUp() throws on step="any", and limits are then up to us.
104
+ private stepByOne(direction: Direction) {
105
+ const input = this.inputTarget;
106
+ const next = (input.valueAsNumber || 0) + (direction === 'up' ? 1 : -1);
107
+ const min = parseFloat(input.min);
108
+ const max = parseFloat(input.max);
109
+ input.value = String(Math.min(Number.isNaN(max) ? next : max, Math.max(Number.isNaN(min) ? next : min, next)));
110
+ }
111
+ }
@@ -0,0 +1,87 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--progress"
4
+ //
5
+ // Moves the bar when its value changes. Set the value from anywhere, an
6
+ // upload's progress event for one:
7
+ //
8
+ // bar.setAttribute('data-ui--progress-value-value', String(loaded / total * 100))
9
+ //
10
+ // Removing the attribute puts it back to "working on it", with no amount.
11
+ // The bar is drawn by the server first, so with no JavaScript it still shows
12
+ // where things stood; this only keeps it moving.
13
+ export default class extends Controller<HTMLElement> {
14
+ static targets = ['bar', 'indicator', 'text'];
15
+ static values = { value: Number, max: { type: Number, default: 100 }, format: { type: String, default: '%{percent}%' } };
16
+ static classes = ['determinate', 'indeterminate'];
17
+
18
+ declare readonly barTarget: HTMLElement;
19
+ declare readonly indicatorTarget: HTMLElement;
20
+ declare readonly textTarget: HTMLElement;
21
+ declare readonly hasTextTarget: boolean;
22
+ declare valueValue: number;
23
+ declare readonly hasValueValue: boolean;
24
+ declare readonly maxValue: number;
25
+ declare readonly formatValue: string;
26
+ declare readonly determinateClasses: string[];
27
+ declare readonly indeterminateClasses: string[];
28
+
29
+ private wasComplete = false;
30
+
31
+ connect() {
32
+ this.wasComplete = this.barTarget.dataset.state === 'complete';
33
+ }
34
+
35
+ valueValueChanged() {
36
+ if (!this.hasBarTarget) return;
37
+ this.hasValueValue ? this.showAmount() : this.showWorking();
38
+ }
39
+
40
+ maxValueChanged() {
41
+ this.valueValueChanged();
42
+ }
43
+
44
+ private showAmount() {
45
+ const max = this.maxValue > 0 ? this.maxValue : 100;
46
+ const value = Math.min(Math.max(this.valueValue, 0), max);
47
+ // Rounded down, so it never says 100% before it's done.
48
+ const percent = Math.floor((value / max) * 100);
49
+ const text = this.formatValue
50
+ .replaceAll('%{value}', this.number(value))
51
+ .replaceAll('%{max}', this.number(max))
52
+ .replaceAll('%{percent}', String(percent));
53
+ const complete = value >= max;
54
+
55
+ this.indicatorTarget.classList.remove(...this.indeterminateClasses);
56
+ this.indicatorTarget.classList.add(...this.determinateClasses);
57
+ this.indicatorTarget.style.width = `${percent}%`;
58
+ this.barTarget.dataset.state = complete ? 'complete' : 'loading';
59
+ this.barTarget.setAttribute('aria-valuenow', this.number(value));
60
+ this.barTarget.setAttribute('aria-valuemax', this.number(max));
61
+ this.barTarget.setAttribute('aria-valuetext', text);
62
+ this.barTarget.toggleAttribute('aria-busy', !complete);
63
+ if (this.hasTextTarget) this.textTarget.textContent = text;
64
+
65
+ if (complete && !this.wasComplete) this.dispatch('complete', { detail: { value, max } });
66
+ this.wasComplete = complete;
67
+ }
68
+
69
+ private showWorking() {
70
+ this.indicatorTarget.classList.remove(...this.determinateClasses);
71
+ this.indicatorTarget.classList.add(...this.indeterminateClasses);
72
+ this.indicatorTarget.style.removeProperty('width');
73
+ this.barTarget.dataset.state = 'indeterminate';
74
+ this.barTarget.removeAttribute('aria-valuenow');
75
+ this.barTarget.removeAttribute('aria-valuetext');
76
+ this.barTarget.setAttribute('aria-busy', 'true');
77
+ if (this.hasTextTarget) this.textTarget.textContent = '';
78
+ this.wasComplete = false;
79
+ }
80
+
81
+ // 3, not 3.0; 2.5 stays 2.5.
82
+ private number(n: number) {
83
+ return Number.isInteger(n) ? String(n) : String(Math.round(n * 100) / 100);
84
+ }
85
+
86
+ declare readonly hasBarTarget: boolean;
87
+ }
@@ -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
+ }