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
@@ -1,119 +1,243 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # UI::DatePicker — a typed date field with a calendar beside it.
4
- #
5
- # Three inputs in one: what the user types (DD/MM/YYYY), what the form submits
6
- # (ISO, hidden), and the calendar. The typed field comes first because people
7
- # who know the date type it in a second: reaching a date years away in a
8
- # calendar means clicking back month after month.
3
+ require "securerandom"
4
+
5
+ # UI::DatePicker — a typed date with a calendar under it, or a range of two.
9
6
  #
10
- # The written format is not decided here. It comes from `date.formats.typed`
11
- # in the locale, and this component derives the placeholder, the parse order
12
- # and the separator from that one string — so a locale that writes dates
13
- # differently changes what the field accepts, what it shows and what the hint
14
- # says, together, with nothing hardcoded.
7
+ # <%= render(UI::DatePicker.new(form: f, field: :starts_on, required: true)) %>
8
+ # <%= render(UI::DatePicker.new(name: "event[date]", value: @date, label: "Date")) %>
9
+ # <%= render(UI::DatePicker.new(range: true, label: "Period", from: params[:from], to: params[:to])) %>
10
+ # <%= render(UI::DatePicker.new(range: true, form: f, from_field: :starts_on, to_field: :ends_on)) %>
15
11
  #
16
- # The shipped English format is day-first; change `date.formats.typed` for
17
- # month-first. A native date input follows the browser's locale instead, which
18
- # is how the same form reads MM/DD on one machine and DD/MM on another, and how
19
- # the 2nd of May gets recorded as the 5th of February.
12
+ # People who know a date type it; the rest pick it. The field takes digits
13
+ # only and puts the separators in as you go, in the locale's order
14
+ # (`date.formats.typed`, dd/mm/yyyy in English), and the form gets an ISO date
15
+ # in a hidden field, so a date typed for a British office isn't read the
16
+ # American way. Clicking or tabbing into the field opens the calendar, whose
17
+ # month and year headings jump to a month or a year.
20
18
  #
21
- # Cally is ~9 KB gzipped and loaded only when the calendar is first opened, so
22
- # a form nobody opens a calendar on downloads nothing.
19
+ # `range: true` is two dates, From and To, for report filters: typed, picked
20
+ # on a calendar of two months (one on a phone), or chosen from presets such as
21
+ # "Last 7 days", worked out from `Date.current`. `presets: false` leaves those
22
+ # out; an array of `[label, from, to]` replaces them. Choosing a range, a date
23
+ # or a preset, or clearing it, fires `change` on the field, so a filter form
24
+ # can send itself.
23
25
  #
24
- # Usage:
25
- # <%= render(UI::DatePicker.new(form: f, field: :starts_on, required: true)) %>
26
- # <%= render(UI::DatePicker.new(name: "event[date]", value: @date, label: "Date")) %>
26
+ # The calendar is Vanilla Calendar Pro, loaded with its stylesheet the first
27
+ # time a calendar opens, so a page nobody opens one on downloads neither.
27
28
  class UI::DatePicker < UI::Base
28
29
  def initialize(name: nil, value: nil, form: nil, field: nil, label: nil,
29
- required: false, error: nil, disabled: false, hint: true,
30
+ range: false, from: nil, to: nil, from_name: "from", to_name: "to", from_field: nil, to_field: nil,
31
+ presets: true, required: false, error: nil, disabled: false, hint: true,
30
32
  min: nil, max: nil, class: nil, **html_attrs)
31
- @name = name
32
- @value = value
33
- @form = form
34
- @field = field
35
- @label = label
36
- @required = required
33
+ @name = name
34
+ @value = value
35
+ @form = form
36
+ @field = field
37
+ @label = label
38
+ @range = range
39
+ @from = from
40
+ @to = to
41
+ @from_name = from_name
42
+ @to_name = to_name
43
+ @from_field = from_field
44
+ @to_field = to_field
45
+ @presets = presets
46
+ @required = required
37
47
  # The hint teaches the format, which a form field wants and a filter
38
- # toolbar does not — there the value is already on
39
- # screen in the format the hint would describe.
40
- @hint = hint
41
- @error = error
42
- @disabled = disabled
43
- @min = min
44
- @max = max
48
+ # toolbar does not: there the value is already on screen in that format.
49
+ @hint = hint
50
+ @error = error
51
+ @disabled = disabled
52
+ @min = min
53
+ @max = max
45
54
  @user_class = binding.local_variable_get(:class)
46
55
  @html_attrs = html_attrs
47
56
  # Only for the error: the label and the format hint are laid out here.
48
- @wrapper = UI::FormField.new(label: false, error: error, form: form, field: field, for: input_id)
57
+ @wrapper = UI::FormField.new(label: false, error: error, form: form, field: range ? from_field : field, for: input_id)
49
58
  end
50
59
 
51
60
  attr_reader :wrapper
52
61
 
53
- def field_name = @name || (@form && @field && "#{@form.object_name}[#{@field}]")
62
+ def range? = @range
63
+ def required? = @required
64
+ def disabled? = @disabled
65
+
66
+ # ── The written format ────────────────────────────────────────────────────
67
+
68
+ # The one string everything else is derived from.
69
+ def self.date_format = I18n.t("date.formats.typed")
70
+
71
+ # "%d/%m/%Y" -> "dd/mm/yyyy": the placeholder and the hint, so what people
72
+ # are told matches what the field accepts by construction. Lower case, as
73
+ # browsers write it, which also takes about the width of a typed date.
74
+ def self.placeholder
75
+ date_format.gsub("%d", "dd").gsub("%m", "mm").gsub("%Y", "yyyy").gsub("%y", "yy")
76
+ end
77
+
78
+ # "%d/%m/%Y" -> "DMY", for the controller's mask and parser.
79
+ def self.part_order = date_format.scan(/%([dmyY])/).flatten.map(&:upcase).join
80
+
81
+ def self.separator = date_format[/[^%a-zA-Z]/] || "/"
54
82
 
55
- # The value the form submits, always ISO, whatever was typed.
56
- def iso_value
57
- raw = @value || (@form && @field && @form.object&.public_send(@field))
58
- raw.respond_to?(:strftime) ? raw.strftime("%Y-%m-%d") : raw.presence
83
+ # A Date or ISO string in the locale's written format, so the field is right
84
+ # before any JavaScript has run.
85
+ def self.typed(value)
86
+ return nil if value.blank?
87
+
88
+ date = value.respond_to?(:strftime) ? value : Date.parse(value.to_s)
89
+ I18n.l(date, format: :typed)
90
+ rescue Date::Error
91
+ value
92
+ end
93
+
94
+ def self.iso(value)
95
+ value.respond_to?(:strftime) ? value.strftime("%Y-%m-%d") : value.presence
96
+ end
97
+
98
+ def placeholder = self.class.placeholder
99
+
100
+ # ── Fields ────────────────────────────────────────────────────────────────
101
+
102
+ def input_id = @input_id ||= "ui-date-#{SecureRandom.hex(4)}"
103
+ def to_id = "#{input_id}-to"
104
+ def panel_id = "#{input_id}-panel"
105
+ def hint_id = "#{input_id}-hint"
106
+
107
+ # What each typed field submits through: [target, hidden name, ISO value].
108
+ def fields
109
+ if range?
110
+ [ [ :from, hidden_name(@from_field, @from_name), self.class.iso(bound(@from_field) || @from) ],
111
+ [ :to, hidden_name(@to_field, @to_name), self.class.iso(bound(@to_field) || @to) ] ]
112
+ else
113
+ [ [ :input, hidden_name(@field, @name), self.class.iso(bound(@field) || @value) ] ]
114
+ end
59
115
  end
60
116
 
117
+ def value? = fields.any? { |_, _, iso| iso.present? }
118
+
61
119
  def label_text
62
120
  return @label if @label.present?
63
- return nil unless @form && @field
121
+ return nil unless @form && (@field || @from_field)
64
122
 
65
- @form.object.class.try(:human_attribute_name, @field) || @field.to_s.humanize
123
+ @form.object.class.try(:human_attribute_name, @field || @from_field) || (@field || @from_field).to_s.humanize
66
124
  end
67
125
 
68
126
  def render_label? = @label != false && label_text.present?
69
127
  def render_hint? = @hint != false
70
128
 
71
- def input_id = @input_id ||= "ui-date-#{SecureRandom.hex(4)}"
129
+ def hint_text
130
+ key = range? ? "hint_range" : "hint"
131
+ default = range? ? "Type the dates as %{pattern}, or pick them" : "Type the date as %{pattern}, or use the calendar"
132
+ t("ui.date_picker.#{key}", pattern: placeholder, default: default)
133
+ end
72
134
 
73
135
  def describedby
74
- [ ("#{input_id}-hint" if render_hint?), (wrapper.error_id if wrapper.error_message) ].compact.join(" ").presence
136
+ [ (hint_id if render_hint?), (wrapper.error_id if wrapper.error_message) ].compact.join(" ").presence
75
137
  end
76
- def panel_id = "#{input_id}-panel"
77
138
 
78
- def classes = cn("relative", @user_class)
139
+ def input_attrs(target, iso)
140
+ from = target == :to ? false : true
141
+ { type: "text", id: from ? input_id : to_id, inputmode: "numeric", autocomplete: "off",
142
+ placeholder: placeholder, value: self.class.typed(iso), maxlength: placeholder.length,
143
+ required: required?, disabled: disabled?, size: placeholder.length,
144
+ class: input_classes,
145
+ aria: { label: (t("ui.date_picker.#{target}", default: target == :from ? "Start date" : "End date") if range?),
146
+ describedby: describedby, invalid: ("true" if wrapper.error?) },
147
+ data: { "ui--date-picker-target": "field", action: "input->ui--date-picker#typed focus->ui--date-picker#open " \
148
+ "click->ui--date-picker#open keydown->ui--date-picker#keydown" } }
149
+ end
79
150
 
151
+ # Sized to a date, so a range reads "01/09/2026 – 30/09/2026" with nothing
152
+ # between the dates and the buttons.
153
+ # A range on a phone is snugger, so both dates fit beside the clear button.
80
154
  def input_classes
81
- cn(
82
- "flex w-full rounded-md border border-input bg-background text-foreground",
83
- "placeholder:text-muted-foreground transition-all focus:outline-none",
84
- "focus:ring-2 focus:ring-primary focus:ring-offset-1 ring-offset-background",
85
- "disabled:cursor-not-allowed disabled:opacity-50 h-9 pl-3 pr-10 py-2 text-sm",
86
- # aria-invalid rather than a Ruby flag, so a date the user mistypes is
87
- # marked without a round trip.
88
- "aria-invalid:border-destructive aria-invalid:ring-destructive",
89
- wrapper.error? && "border-destructive"
90
- )
155
+ cn("h-full w-[calc(10ch+1.5rem)] min-w-0 bg-transparent px-3 tabular-nums outline-none",
156
+ "placeholder:text-muted-foreground disabled:cursor-not-allowed",
157
+ { "max-sm:w-[calc(10ch+1rem)] max-sm:px-2" => range? })
91
158
  end
92
159
 
93
- # The one string everything else here is derived from.
94
- def date_format = I18n.t("date.formats.typed")
160
+ # On a phone, a range drops the calendar icon: tapping a date opens the
161
+ # calendar anyway, and the room goes to the dates.
162
+ def toggle_classes
163
+ cn("flex h-full w-9 items-center justify-center rounded-r-md text-muted-foreground hover:text-foreground focus:outline-none",
164
+ { "max-sm:hidden" => range? })
165
+ end
95
166
 
96
- # "%d/%m/%Y" -> "DD/MM/YYYY". Shown as the placeholder and in the hint, so
97
- # what the user is told matches what the parser accepts by construction.
98
- def placeholder
99
- date_format.gsub("%d", "DD").gsub("%m", "MM").gsub("%Y", "YYYY").gsub("%y", "YY")
167
+ # The typed fields share one border, lit while either has focus. It's as
168
+ # wide as what's in it, since a date is always the same length; it shrinks
169
+ # with a narrow screen.
170
+ def group_classes
171
+ cn("flex h-9 w-fit max-w-full items-center rounded-md border border-input bg-background text-sm text-foreground",
172
+ "transition-all ring-offset-background has-[input:focus]:ring-2 has-[input:focus]:ring-primary has-[input:focus]:ring-offset-1",
173
+ "has-[[aria-invalid=true]]:border-destructive",
174
+ { "border-destructive" => wrapper.error?, "cursor-not-allowed opacity-50" => disabled? })
100
175
  end
101
176
 
102
- # "%d/%m/%Y" -> "DMY". The controller builds its parser from this rather
103
- # than assuming an order.
104
- def part_order = date_format.scan(/%([dmyY])/).flatten.map(&:upcase).join
177
+ def root_attrs
178
+ attrs = @html_attrs.except(:data)
179
+ attrs[:class] = cn("relative w-full", @user_class)
180
+ attrs[:data] = { controller: "ui--date-picker",
181
+ # Propshaft digests the filenames, so the URLs come from Ruby.
182
+ "ui--date-picker-module-url-value": helpers.asset_path("vanilla_calendar.js"),
183
+ "ui--date-picker-style-url-value": helpers.asset_path("vanilla_calendar.css"),
184
+ "ui--date-picker-order-value": self.class.part_order,
185
+ "ui--date-picker-separator-value": self.class.separator,
186
+ "ui--date-picker-range-value": range?,
187
+ "ui--date-picker-min-value": self.class.iso(@min),
188
+ "ui--date-picker-max-value": self.class.iso(@max),
189
+ "ui--date-picker-locale-value": I18n.locale == :en ? "en-IN" : I18n.locale.to_s,
190
+ "ui--date-picker-labels-value": labels.to_json,
191
+ action: "click@window->ui--date-picker#closeOnOutsideClick keydown@window->ui--date-picker#closeOnEscape " \
192
+ "focusout->ui--date-picker#leave" }
193
+ .merge(@html_attrs[:data] || {}).compact
194
+ attrs
195
+ end
105
196
 
106
- def separator = date_format[/[^%a-zA-Z]/] || "/"
197
+ # Words the calendar shows or says, from the locale.
198
+ def labels
199
+ { pickEnd: t("ui.date_picker.pick_end", default: "Now pick an end date"),
200
+ previous: t("ui.date_picker.previous", default: "Previous month"),
201
+ next: t("ui.date_picker.next", default: "Next month"),
202
+ days: t("ui.date_picker.days", default: "%{count} days") }
203
+ end
107
204
 
108
- # Rendered server-side in the locale's format, so the field is already right
109
- # before any JavaScript has loaded.
110
- def typed_value
111
- iso = iso_value
112
- return nil if iso.blank?
205
+ # ── Presets ───────────────────────────────────────────────────────────────
113
206
 
114
- date = iso.respond_to?(:strftime) ? iso : Date.parse(iso.to_s)
115
- I18n.l(date, format: :typed)
116
- rescue Date::Error
117
- iso
207
+ # [label, from, to], as ISO dates. Only for a range.
208
+ def preset_list
209
+ return [] unless range?
210
+
211
+ list = @presets == true ? default_presets : Array(@presets.presence)
212
+ list.map { |name, from, to| [ name, self.class.iso(from), self.class.iso(to) ] }
118
213
  end
214
+
215
+ def preset_pressed?(from, to) = fields.map(&:last) == [ from, to ]
216
+
217
+ private
218
+
219
+ def hidden_name(field, name)
220
+ return "#{@form.object_name}[#{field}]" if @form && field
221
+
222
+ name
223
+ end
224
+
225
+ def bound(field)
226
+ return nil unless @form && field && @form.object.respond_to?(field)
227
+
228
+ @form.object.public_send(field)
229
+ end
230
+
231
+ def default_presets
232
+ today = Date.current
233
+ [ [ preset(:today, "Today"), today, today ],
234
+ [ preset(:yesterday, "Yesterday"), today - 1, today - 1 ],
235
+ [ preset(:last_7_days, "Last 7 days"), today - 6, today ],
236
+ [ preset(:last_30_days, "Last 30 days"), today - 29, today ],
237
+ [ preset(:this_month, "This month"), today.beginning_of_month, today ],
238
+ [ preset(:last_month, "Last month"), today.prev_month.beginning_of_month, today.prev_month.end_of_month ],
239
+ [ preset(:this_year, "This year"), today.beginning_of_year, today ] ]
240
+ end
241
+
242
+ def preset(key, default) = t("ui.date_picker.presets.#{key}", default: default)
119
243
  end
@@ -1,4 +1,14 @@
1
- <%= render(wrapper) do %><%= tag.label for: @input_id, class: dropzone_classes,
2
- data: { controller: "ui--file-field",
3
- "ui--file-field-target": "dropzone",
4
- action: "dragover->ui--file-field#dragOver dragleave->ui--file-field#dragLeave drop->ui--file-field#drop" } do %><%= render(UI::Icon.new(name: "upload", size: :lg, class: "text-muted-foreground", aria: { hidden: true })) %><p class="text-sm text-muted-foreground"><span class="font-medium text-primary"><%= t("ui.file_field.browse", default: "Click to upload") %></span> <%= t("ui.file_field.drop", default: "or drag and drop") %></p><p class="text-xs text-muted-foreground empty:hidden" data-ui--file-field-target="filenames"></p><% if form_field? %><%= @form.file_field(@field, **form_field_options) %><% else %><%= tag.input(**html_options) %><% end %><% end %><% end %>
1
+ <%= render(wrapper) do %><%= tag.div class: "w-full", data: root_data do %>
2
+ <%= tag.label for: @input_id, class: dropzone_classes, data: { "ui--file-field-target": "dropzone" } do %>
3
+ <%= render(UI::Icon.new(name: "upload", size: :lg, class: "text-muted-foreground", aria: { hidden: true })) %>
4
+ <p class="text-sm text-muted-foreground"><span class="font-medium text-primary"><%= t("ui.file_field.browse", default: "Click to upload") %></span> <%= t("ui.file_field.drop", default: "or drag and drop") %></p>
5
+ <% unless preview? %><p class="text-xs text-muted-foreground empty:hidden" data-ui--file-field-target="filenames"></p><% end %>
6
+ <% if form_field? %><%= @form.file_field(@field, **form_field_options) %><% else %><%= tag.input(**html_options) %><% end %>
7
+ <% end %>
8
+ <% if preview? %>
9
+ <%= tag.ul class: "mt-3 grid grid-cols-[repeat(auto-fill,minmax(7.5rem,1fr))] gap-3 empty:hidden", data: { "ui--file-field-target": "list" } do %><% existing_files.each do |file| %><%= tile(**file) %><% end %><% end %>
10
+ <template data-ui--file-field-target="template"><%= tile(state: "chosen") %></template>
11
+ <p class="mt-2 text-xs text-muted-foreground empty:hidden" data-ui--file-field-target="notice"></p>
12
+ <p class="sr-only" aria-live="polite" data-ui--file-field-target="status"></p>
13
+ <% end %>
14
+ <% end %><% end %>
@@ -2,43 +2,64 @@
2
2
 
3
3
  require "securerandom"
4
4
 
5
- # UI::FileField — a drag-and-drop dropzone over a native file input.
5
+ # UI::FileField — a drag-and-drop dropzone over a native file input, with
6
+ # previews of what's chosen and, optionally, uploads straight to storage.
6
7
  #
7
- # The input itself is sr-only, not hidden: it stays in the accessibility
8
- # tree and keyboard/native-picker behavior (Tab, Enter/Space, the OS file
9
- # dialog) comes from the real <input type="file">, same as every other
10
- # styled-native-control component here. The dropzone is a <label> around it,
11
- # so clicking anywhere in it opens the picker without any JS, and the
12
- # ui--file-field controller only adds what a label can't: drag-over
13
- # highlighting and listing the chosen file names.
8
+ # <%= render(UI::FileField.new(form: f, field: :photos, multiple: true, accept: "image/*",
9
+ # max_size: 5.megabytes, direct_upload: true)) %>
10
+ #
11
+ # The input itself is sr-only, not hidden: it stays in the accessibility tree,
12
+ # and keyboard and the system file dialog come from the real
13
+ # <input type="file">. The dropzone is a <label> around it, so clicking
14
+ # anywhere in it opens the picker with no JavaScript.
15
+ #
16
+ # Each chosen file shows as a tile: a thumbnail for an image, an icon for
17
+ # anything else, its name and size, and a button to take it out again.
18
+ # `accept:` and `max_size:` (bytes) are checked as files are added, dropped
19
+ # ones included, and a file that fails says why instead of being sent.
20
+ # `preview: false` goes back to listing the names under the dropzone.
21
+ #
22
+ # `direct_upload: true` sends each file to storage the moment it's chosen,
23
+ # through Active Storage's direct uploads, with a progress bar on its tile; the
24
+ # form then submits only the uploaded files' signed ids, so a big photo never
25
+ # holds up the form. Sending the form while files are still uploading waits
26
+ # for them, then sends. It needs Active Storage's JavaScript and, for a bucket
27
+ # such as Cloudflare R2 or S3, CORS rules allowing PUT from your site.
28
+ #
29
+ # Bound to a form, the record's current attachments show as tiles too, kept by
30
+ # their signed ids, so removing a tile and saving removes that file.
14
31
  class UI::FileField < UI::Base
15
- def initialize(multiple: false, accept: nil,
32
+ def initialize(multiple: false, accept: nil, preview: true, direct_upload: false, max_size: nil,
16
33
  label: nil, label_size: :default, label_weight: :medium,
17
34
  hint: nil, required: false, error: nil, disabled: false,
18
- form: nil, field: nil,
35
+ form: nil, field: nil, existing: nil,
19
36
  class: nil, **html_attrs)
20
- @form = form
21
- @field = field
22
- @multiple = multiple
23
- @accept = accept
24
- @required = required
25
- @disabled = disabled
26
- @user_class = binding.local_variable_get(:class)
27
- @html_attrs = html_attrs
28
- @wrapper = UI::FormField.new(label: label, hint: hint, error: error,
29
- required: required, disabled: disabled,
30
- label_size: label_size, label_weight: label_weight,
31
- form: form, field: field)
32
- @input_id = @html_attrs[:id] || "ui-file-field-#{SecureRandom.hex(4)}"
37
+ @form = form
38
+ @field = field
39
+ @multiple = multiple
40
+ @accept = accept
41
+ @preview = preview
42
+ @direct_upload = direct_upload
43
+ @max_size = max_size
44
+ @existing = existing
45
+ @required = required
46
+ @disabled = disabled
47
+ @user_class = binding.local_variable_get(:class)
48
+ @html_attrs = html_attrs
49
+ @wrapper = UI::FormField.new(label: label, hint: hint, error: error,
50
+ required: required, disabled: disabled,
51
+ label_size: label_size, label_weight: label_weight,
52
+ form: form, field: field)
53
+ @input_id = @html_attrs[:id] || "ui-file-field-#{SecureRandom.hex(4)}"
33
54
  @html_attrs[:id] = @input_id
34
55
  @wrapper.for = @input_id
35
56
  end
36
57
 
37
58
  attr_reader :wrapper
38
59
 
39
- def form_field?
40
- @form.present? && @field.present?
41
- end
60
+ def form_field? = @form.present? && @field.present?
61
+ def preview? = @preview
62
+ def direct_upload? = @direct_upload
42
63
 
43
64
  def dropzone_classes
44
65
  cn(
@@ -51,6 +72,20 @@ class UI::FileField < UI::Base
51
72
  )
52
73
  end
53
74
 
75
+ def root_data
76
+ { controller: "ui--file-field",
77
+ "ui--file-field-preview-value": preview?,
78
+ "ui--file-field-direct-upload-value": direct_upload?,
79
+ "ui--file-field-url-value": (direct_upload_url if direct_upload?),
80
+ "ui--file-field-name-value": signed_id_name,
81
+ "ui--file-field-multiple-value": @multiple,
82
+ "ui--file-field-accept-value": @accept,
83
+ "ui--file-field-max-size-value": @max_size,
84
+ "ui--file-field-required-value": @required,
85
+ "ui--file-field-labels-value": labels.to_json,
86
+ action: "dragover->ui--file-field#dragOver dragleave->ui--file-field#dragLeave drop->ui--file-field#drop" }.compact
87
+ end
88
+
54
89
  def html_options
55
90
  opts = @html_attrs.dup
56
91
  opts[:type] = "file"
@@ -58,9 +93,10 @@ class UI::FileField < UI::Base
58
93
  opts[:multiple] = true if @multiple
59
94
  opts[:accept] = @accept if @accept
60
95
  opts[:disabled] = true if @disabled
61
- opts[:required] = true if @required
96
+ # A file already kept satisfies `required`; the controller keeps this in step.
97
+ opts[:required] = true if @required && existing_files.empty?
62
98
  opts[:"data-ui--file-field-target"] = "input"
63
- opts[:"data-action"] = "change->ui--file-field#updateNames"
99
+ opts[:"data-action"] = "change->ui--file-field#chosen"
64
100
  opts[:"aria-invalid"] = "true" if wrapper.error?
65
101
  opts[:"aria-describedby"] = wrapper.describedby if wrapper.describedby
66
102
  opts
@@ -70,4 +106,119 @@ class UI::FileField < UI::Base
70
106
  def form_field_options
71
107
  html_options.except(:name, :type)
72
108
  end
109
+
110
+ # ── Kept and uploaded files ──────────────────────────────────────────────
111
+
112
+ # Where a kept or uploaded file's signed id is posted: the field's own
113
+ # name, so Active Storage takes it like an upload.
114
+ def signed_id_name
115
+ name = form_field? ? "#{@form.object_name}[#{@field}]" : @html_attrs[:name].to_s
116
+ return name if name.empty?
117
+
118
+ @multiple && !name.end_with?("[]") ? "#{name}[]" : name
119
+ end
120
+
121
+ # The record's current attachments, or `existing:`: anything with a
122
+ # signed_id, filename, byte_size and content_type.
123
+ def existing_files
124
+ return [] unless preview?
125
+
126
+ @existing_files ||= Array(@existing.nil? ? bound_attachments : @existing).map do |file|
127
+ { signed_id: file.signed_id, name: file.filename.to_s, size: file.byte_size,
128
+ image: file.content_type.to_s.start_with?("image/"), url: file_url(file) }
129
+ end
130
+ end
131
+
132
+ def human_size(bytes) = ActiveSupport::NumberHelper.number_to_human_size(bytes)
133
+
134
+ def labels
135
+ { remove: t("ui.file_field.remove", default: "Remove %{name}"),
136
+ uploading: t("ui.file_field.uploading", default: "Uploading…"),
137
+ uploaded: t("ui.file_field.uploaded", default: "Uploaded"),
138
+ failed: t("ui.file_field.failed", default: "Upload failed"),
139
+ retry: t("ui.file_field.retry", default: "Try again"),
140
+ too_big: t("ui.file_field.too_big", default: "Too big: %{max} at most"),
141
+ max: (human_size(@max_size) if @max_size),
142
+ wrong_type: t("ui.file_field.wrong_type", default: "Not a file this field takes"),
143
+ waiting: t("ui.file_field.waiting", default: "Waiting for the uploads to finish…"),
144
+ added: t("ui.file_field.added", default: "%{name} added"),
145
+ removed: t("ui.file_field.removed", default: "%{name} removed"),
146
+ units: storage_units }
147
+ end
148
+
149
+ def tile_classes
150
+ "group relative flex min-w-0 flex-col overflow-hidden rounded-lg border bg-card text-card-foreground " \
151
+ "data-[state=error]:border-destructive"
152
+ end
153
+
154
+ # One file: its thumbnail or an icon, a button to take it out, a progress
155
+ # bar for an upload, its name and size, and the signed id that keeps it. The
156
+ # controller fills in a blank one for each file chosen.
157
+ def tile(name: "", size: nil, url: nil, image: false, signed_id: nil, state: "kept")
158
+ thumb = image && url.present?
159
+ tag.li(class: tile_classes, data: { "ui--file-field-target": "item", state: state }) do
160
+ safe_join([
161
+ tag.div(class: "relative aspect-square bg-muted") do
162
+ safe_join([
163
+ tag.img(src: url, alt: "", class: "size-full object-cover", hidden: !thumb, data: { role: "thumb" }),
164
+ tag.span(render(UI::Icon.new(name: "file", size: :lg)), hidden: thumb, data: { role: "icon" },
165
+ class: "absolute inset-0 flex items-center justify-center text-muted-foreground"),
166
+ tag.button(render(UI::Icon.new(name: "x", size: :xs)), type: "button",
167
+ aria: { label: labels[:remove].sub("%{name}", name.to_s) },
168
+ class: "absolute end-1.5 top-1.5 flex size-6 items-center justify-center rounded-full border bg-background/90 " \
169
+ "text-foreground shadow-sm hover:bg-background #{UI::Base::FOCUS_RING}",
170
+ data: { action: "ui--file-field#remove", role: "remove" }),
171
+ tag.div(tag.div(class: "h-full w-0 bg-primary transition-[width] duration-200", data: { role: "bar" }),
172
+ hidden: true, role: "progressbar", aria: { valuemin: 0, valuemax: 100, label: name },
173
+ class: "absolute inset-x-0 bottom-0 h-1 bg-foreground/10", data: { role: "progress" })
174
+ ])
175
+ end,
176
+ tag.div(class: "min-w-0 p-2") do
177
+ safe_join([
178
+ tag.p(name, title: name, class: "truncate text-xs font-medium", data: { role: "name" }),
179
+ tag.p(size ? human_size(size) : "", class: "line-clamp-2 text-xs text-muted-foreground group-data-[state=error]:text-destructive",
180
+ data: { role: "meta" }),
181
+ tag.button(labels[:retry], type: "button", hidden: true, data: { action: "ui--file-field#retry", role: "retry" },
182
+ class: "mt-1 rounded-sm text-xs font-medium text-primary underline-offset-4 hover:underline #{UI::Base::FOCUS_RING}")
183
+ ])
184
+ end,
185
+ (tag.input(type: "hidden", name: signed_id_name, value: signed_id, data: { role: "signed" }) if signed_id)
186
+ ])
187
+ end
188
+ end
189
+
190
+ private
191
+
192
+ # The units Rails' number_to_human_size uses, so a size written in the
193
+ # browser matches the ones written here.
194
+ def storage_units
195
+ units = I18n.t("number.human.storage_units.units", default: {})
196
+ { byte: (units[:byte].is_a?(Hash) ? units[:byte][:other] : units[:byte]) || "Bytes",
197
+ kb: units[:kb] || "KB", mb: units[:mb] || "MB", gb: units[:gb] || "GB" }
198
+ end
199
+
200
+ def bound_attachments
201
+ return [] unless form_field? && @form.object.respond_to?(@field)
202
+
203
+ value = @form.object.public_send(@field)
204
+ if value.respond_to?(:attachments) then value.attachments
205
+ elsif value.respond_to?(:attached?) && value.attached? then [ value.attachment ]
206
+ else []
207
+ end
208
+ end
209
+
210
+ # An Active Storage file is shown through the app's blob route; anything
211
+ # else passed as `existing:` brings its own url.
212
+ def file_url(file)
213
+ if defined?(ActiveStorage::Attachment) && file.is_a?(ActiveStorage::Attachment)
214
+ helpers.main_app.rails_blob_path(file)
215
+ else
216
+ file.try(:url)
217
+ end
218
+ end
219
+
220
+ def direct_upload_url
221
+ routes = helpers.respond_to?(:main_app) ? helpers.main_app : helpers
222
+ routes.respond_to?(:rails_direct_uploads_url) ? routes.rails_direct_uploads_url : "/rails/active_storage/direct_uploads"
223
+ end
73
224
  end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ # One image in a UI::Gallery. Holds what the gallery needs to draw it in three
4
+ # places (the main view, its thumbnail and the zoomed view); it draws nothing
5
+ # itself.
6
+ class UI::Gallery::Image < UI::Base
7
+ attr_reader :src, :alt
8
+
9
+ def initialize(src:, alt:, zoom_src: nil, thumbnail_src: nil)
10
+ @src = src
11
+ @alt = alt
12
+ @zoom_src = zoom_src
13
+ @thumbnail_src = thumbnail_src
14
+ end
15
+
16
+ def zoom_src = @zoom_src || @src
17
+ def thumbnail_src = @thumbnail_src || @src
18
+
19
+ def call = nil
20
+ end