velvetkit 0.3.0 → 0.4.0

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 (175) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -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/number_input.html.erb +11 -0
  24. data/registry/app/components/ui/number_input.rb +103 -0
  25. data/registry/app/components/ui/progress/segment.rb +25 -0
  26. data/registry/app/components/ui/progress.html.erb +25 -0
  27. data/registry/app/components/ui/progress.rb +182 -0
  28. data/registry/app/components/ui/select.html.erb +24 -5
  29. data/registry/app/components/ui/select.rb +44 -5
  30. data/registry/app/components/ui/timeline/item.html.erb +21 -0
  31. data/registry/app/components/ui/timeline/item.rb +145 -0
  32. data/registry/app/components/ui/timeline.html.erb +1 -0
  33. data/registry/app/components/ui/timeline.rb +42 -0
  34. data/registry/app/javascript/chart_js.ts +37 -0
  35. data/registry/app/javascript/controllers/ui/_internal/date_format.ts +74 -0
  36. data/registry/app/javascript/controllers/ui/_internal/shortcut.ts +80 -0
  37. data/registry/app/javascript/controllers/ui/chart_controller.ts +585 -0
  38. data/registry/app/javascript/controllers/ui/command_controller.ts +454 -0
  39. data/registry/app/javascript/controllers/ui/date_picker_controller.ts +247 -82
  40. data/registry/app/javascript/controllers/ui/file_field_controller.ts +288 -16
  41. data/registry/app/javascript/controllers/ui/gallery_controller.ts +568 -0
  42. data/registry/app/javascript/controllers/ui/kbd_controller.ts +60 -0
  43. data/registry/app/javascript/controllers/ui/number_input_controller.ts +111 -0
  44. data/registry/app/javascript/controllers/ui/progress_controller.ts +87 -0
  45. data/registry/app/javascript/controllers/ui/select_controller.ts +198 -8
  46. data/registry/app/javascript/vanilla_calendar.ts +15 -0
  47. data/registry/components.yml +19 -3
  48. data/registry/config/locales/velvetkit.en.yml +73 -0
  49. data/registry/icons/lucide/download.svg +17 -0
  50. data/registry/icons/lucide/file-plus.svg +18 -0
  51. data/registry/icons/lucide/file.svg +16 -0
  52. data/registry/icons/lucide/folder.svg +15 -0
  53. data/registry/icons/lucide/keyboard.svg +23 -0
  54. data/registry/icons/lucide/minus.svg +15 -0
  55. data/registry/icons/lucide/package.svg +18 -0
  56. data/registry/icons/lucide/pause.svg +16 -0
  57. data/registry/icons/lucide/percent.svg +17 -0
  58. data/registry/icons/lucide/printer.svg +17 -0
  59. data/registry/icons/lucide/receipt.svg +17 -0
  60. data/registry/icons/lucide/sun-moon.svg +19 -0
  61. data/registry/icons/lucide/truck.svg +19 -0
  62. data/registry/icons/lucide/user-plus.svg +18 -0
  63. data/registry/icons/lucide/zoom-in.svg +18 -0
  64. data/registry/icons/lucide/zoom-out.svg +17 -0
  65. data/registry/icons/phosphor/circle-half.svg +2 -0
  66. data/registry/icons/phosphor/download-simple.svg +2 -0
  67. data/registry/icons/phosphor/file-plus.svg +2 -0
  68. data/registry/icons/phosphor/file.svg +2 -0
  69. data/registry/icons/phosphor/folder.svg +2 -0
  70. data/registry/icons/phosphor/keyboard.svg +2 -0
  71. data/registry/icons/phosphor/magnifying-glass-minus.svg +2 -0
  72. data/registry/icons/phosphor/magnifying-glass-plus.svg +2 -0
  73. data/registry/icons/phosphor/minus.svg +2 -0
  74. data/registry/icons/phosphor/package.svg +2 -0
  75. data/registry/icons/phosphor/pause.svg +2 -0
  76. data/registry/icons/phosphor/percent.svg +2 -0
  77. data/registry/icons/phosphor/printer.svg +2 -0
  78. data/registry/icons/phosphor/receipt.svg +2 -0
  79. data/registry/icons/phosphor/truck.svg +2 -0
  80. data/registry/icons/phosphor/user-plus.svg +2 -0
  81. data/registry/icons/tabler/download.svg +18 -0
  82. data/registry/icons/tabler/file-plus.svg +19 -0
  83. data/registry/icons/tabler/file.svg +17 -0
  84. data/registry/icons/tabler/folder.svg +16 -0
  85. data/registry/icons/tabler/keyboard.svg +23 -0
  86. data/registry/icons/tabler/minus.svg +16 -0
  87. data/registry/icons/tabler/package.svg +20 -0
  88. data/registry/icons/tabler/percentage.svg +18 -0
  89. data/registry/icons/tabler/player-pause.svg +17 -0
  90. data/registry/icons/tabler/printer.svg +18 -0
  91. data/registry/icons/tabler/receipt.svg +16 -0
  92. data/registry/icons/tabler/sun-moon.svg +21 -0
  93. data/registry/icons/tabler/truck.svg +18 -0
  94. data/registry/icons/tabler/user-plus.svg +19 -0
  95. data/registry/icons/tabler/zoom-in.svg +19 -0
  96. data/registry/icons/tabler/zoom-out.svg +18 -0
  97. data/registry/icons.yml +16 -0
  98. data/registry/test/components/previews/ui/chart_preview/cash_flow.html.erb +6 -0
  99. data/registry/test/components/previews/ui/chart_preview/donut.html.erb +6 -0
  100. data/registry/test/components/previews/ui/chart_preview/margin.html.erb +6 -0
  101. data/registry/test/components/previews/ui/chart_preview/pie.html.erb +6 -0
  102. data/registry/test/components/previews/ui/chart_preview/sales.html.erb +6 -0
  103. data/registry/test/components/previews/ui/chart_preview/stock.html.erb +6 -0
  104. data/registry/test/components/previews/ui/chart_preview/takings.html.erb +8 -0
  105. data/registry/test/components/previews/ui/chart_preview.rb +46 -0
  106. data/registry/test/components/previews/ui/command_preview/_picked.html.erb +14 -0
  107. data/registry/test/components/previews/ui/command_preview/dialog.html.erb +24 -0
  108. data/registry/test/components/previews/ui/command_preview/inline.html.erb +16 -0
  109. data/registry/test/components/previews/ui/command_preview/playground.html.erb +15 -0
  110. data/registry/test/components/previews/ui/command_preview/server_search.html.erb +24 -0
  111. data/registry/test/components/previews/ui/command_preview/shortcuts.html.erb +12 -0
  112. data/registry/test/components/previews/ui/command_preview/till.html.erb +17 -0
  113. data/registry/test/components/previews/ui/command_preview.rb +25 -0
  114. data/registry/test/components/previews/ui/date_picker_preview/custom_presets.html.erb +6 -0
  115. data/registry/test/components/previews/ui/date_picker_preview/in_form.html.erb +11 -0
  116. data/registry/test/components/previews/ui/date_picker_preview/range.html.erb +5 -0
  117. data/registry/test/components/previews/ui/date_picker_preview/states.html.erb +4 -3
  118. data/registry/test/components/previews/ui/date_picker_preview.rb +26 -6
  119. data/registry/test/components/previews/ui/file_field_preview/multiple_files.html.erb +1 -1
  120. data/registry/test/components/previews/ui/file_field_preview/product_photos.html.erb +12 -0
  121. data/registry/test/components/previews/ui/file_field_preview/single_image.html.erb +4 -0
  122. data/registry/test/components/previews/ui/file_field_preview.rb +32 -5
  123. data/registry/test/components/previews/ui/gallery_preview/hover_zoom.html.erb +13 -0
  124. data/registry/test/components/previews/ui/gallery_preview/landscape.html.erb +5 -0
  125. data/registry/test/components/previews/ui/gallery_preview/product_page.html.erb +13 -0
  126. data/registry/test/components/previews/ui/gallery_preview/single.html.erb +3 -0
  127. data/registry/test/components/previews/ui/gallery_preview.rb +45 -0
  128. data/registry/test/components/previews/ui/kbd_preview/bound.html.erb +20 -0
  129. data/registry/test/components/previews/ui/kbd_preview/keys.html.erb +13 -0
  130. data/registry/test/components/previews/ui/kbd_preview/menu.html.erb +13 -0
  131. data/registry/test/components/previews/ui/kbd_preview/search_field.html.erb +8 -0
  132. data/registry/test/components/previews/ui/kbd_preview/shortcuts_list.html.erb +17 -0
  133. data/registry/test/components/previews/ui/kbd_preview/till.html.erb +23 -0
  134. data/registry/test/components/previews/ui/kbd_preview/tooltip_and_buttons.html.erb +14 -0
  135. data/registry/test/components/previews/ui/kbd_preview.rb +32 -0
  136. data/registry/test/components/previews/ui/number_input_preview/cart.html.erb +11 -0
  137. data/registry/test/components/previews/ui/number_input_preview/decimals.html.erb +4 -0
  138. data/registry/test/components/previews/ui/number_input_preview/sizes.html.erb +5 -0
  139. data/registry/test/components/previews/ui/number_input_preview/states.html.erb +7 -0
  140. data/registry/test/components/previews/ui/number_input_preview/stock_adjustment.html.erb +3 -0
  141. data/registry/test/components/previews/ui/number_input_preview.rb +36 -0
  142. data/registry/test/components/previews/ui/progress_preview/file_upload.html.erb +36 -0
  143. data/registry/test/components/previews/ui/progress_preview/free_shipping.html.erb +4 -0
  144. data/registry/test/components/previews/ui/progress_preview/indeterminate.html.erb +4 -0
  145. data/registry/test/components/previews/ui/progress_preview/sizes_and_tones.html.erb +8 -0
  146. data/registry/test/components/previews/ui/progress_preview/steps.html.erb +9 -0
  147. data/registry/test/components/previews/ui/progress_preview/storage.html.erb +8 -0
  148. data/registry/test/components/previews/ui/progress_preview/storage_by_category.html.erb +7 -0
  149. data/registry/test/components/previews/ui/progress_preview/tasks_by_status.html.erb +14 -0
  150. data/registry/test/components/previews/ui/progress_preview/traffic_by_source.html.erb +15 -0
  151. data/registry/test/components/previews/ui/progress_preview.rb +46 -0
  152. data/registry/test/components/previews/ui/select_preview/server_search.html.erb +22 -0
  153. data/registry/test/components/previews/ui/select_preview.rb +5 -0
  154. data/registry/test/components/previews/ui/timeline_preview/activity_log.html.erb +7 -0
  155. data/registry/test/components/previews/ui/timeline_preview/colored.html.erb +7 -0
  156. data/registry/test/components/previews/ui/timeline_preview/colored_by_meaning.html.erb +7 -0
  157. data/registry/test/components/previews/ui/timeline_preview/failed_delivery.html.erb +6 -0
  158. data/registry/test/components/previews/ui/timeline_preview/order_status.html.erb +9 -0
  159. data/registry/test/components/previews/ui/timeline_preview/real_dates.html.erb +5 -0
  160. data/registry/test/components/previews/ui/timeline_preview/stock_history.html.erb +6 -0
  161. data/registry/test/components/previews/ui/timeline_preview.rb +40 -0
  162. data/registry/test/components/ui/chart_test.rb +187 -0
  163. data/registry/test/components/ui/command/group_test.rb +19 -0
  164. data/registry/test/components/ui/command/item_test.rb +47 -0
  165. data/registry/test/components/ui/command_test.rb +110 -0
  166. data/registry/test/components/ui/date_picker_test.rb +129 -111
  167. data/registry/test/components/ui/file_field_test.rb +105 -9
  168. data/registry/test/components/ui/gallery_test.rb +192 -0
  169. data/registry/test/components/ui/kbd_test.rb +150 -0
  170. data/registry/test/components/ui/number_input_test.rb +155 -0
  171. data/registry/test/components/ui/progress_test.rb +188 -0
  172. data/registry/test/components/ui/select_test.rb +62 -0
  173. data/registry/test/components/ui/timeline_test.rb +175 -0
  174. metadata +147 -2
  175. data/registry/app/javascript/cally.ts +0 -8
@@ -0,0 +1,177 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A line, bar, pie or donut chart: sales over a month, stock by category,
4
+ # takings by day, today's takings by payment method.
5
+ #
6
+ # <%= render(UI::Chart.new(type: :line, label: "Sales, this year and last", format: :currency,
7
+ # labels: %w[Jan Feb Mar], series: [
8
+ # { name: "This year", data: [4200, 5100, 4800] },
9
+ # { name: "Last year", data: [3900, 4300, 4500] }
10
+ # ])) %>
11
+ #
12
+ # `type:` is :line, :bar, :pie or :donut, and `stacked: true` piles a bar
13
+ # chart's series on top of each other. A pie or donut is one total split into
14
+ # its parts: one series, a slice for each label, five at most, none below zero.
15
+ # Its legend gives each part's value and share, and a donut shows the total in
16
+ # its middle. `format:` is :number, :currency or :percent (values from 0 to
17
+ # 100), and the values are written in the app's locale: currency uses Rails'
18
+ # own format for it, or `unit:` ("₹"). `nil` leaves a gap.
19
+ #
20
+ # Each series takes the next of five colours, `--chart-1` to `--chart-5`, which
21
+ # change with the theme. A series keeps its colour by its place in the list, so
22
+ # a chart that sometimes leaves one out should give each its `color:` (1 to 5)
23
+ # to stop the others moving up. There's no sixth colour: fold the smallest
24
+ # series into "Other" instead.
25
+ #
26
+ # Two or more series get a legend, and a line ends with its last value. Hover,
27
+ # or focus the chart and use the arrow keys, for the values at each point; the
28
+ # numbers are also in a table under "Show the data", for screen readers too.
29
+ # Chart.js loads when the first chart on a page appears, and each chart draws
30
+ # when it scrolls into view: bars grow from the baseline and a line draws
31
+ # itself from left to right, unless the system asks for reduced motion.
32
+ class UI::Chart < UI::Base
33
+ TYPES = %i[line bar pie donut].freeze
34
+ CIRCULAR = %i[pie donut].freeze
35
+ FORMATS = %i[number currency percent].freeze
36
+ COLORS = 5
37
+
38
+ # Written out in full so Tailwind finds them.
39
+ SWATCHES = { 1 => "bg-chart-1", 2 => "bg-chart-2", 3 => "bg-chart-3", 4 => "bg-chart-4", 5 => "bg-chart-5" }.freeze
40
+
41
+ Series = Struct.new(:name, :data, :color, keyword_init: true)
42
+
43
+ def initialize(labels:, series:, type: :line, label: nil, stacked: false, format: :number, unit: nil, height: 288,
44
+ class: nil, **html_attrs)
45
+ @labels = labels.map(&:to_s)
46
+ @type = TYPES.include?(type.to_sym) ? type.to_sym : :line
47
+ @label = label
48
+ @stacked = stacked && @type == :bar
49
+ @format = FORMATS.include?(format.to_sym) ? format.to_sym : :number
50
+ @unit = unit
51
+ @height = height
52
+ @user_class = binding.local_variable_get(:class)
53
+ @html_attrs = html_attrs
54
+ @series = build_series(series)
55
+ check_slices if circular?
56
+ end
57
+
58
+ attr_reader :labels, :series
59
+
60
+ def legend? = circular? || @series.size > 1
61
+ def line? = @type == :line
62
+ def circular? = CIRCULAR.include?(@type)
63
+ def swatch_classes(entry) = cn(SWATCHES[entry.color], line? ? "h-0.5 w-3.5 rounded-full" : "size-2.5 rounded-sm")
64
+
65
+ # A pie's legend is its slices, each with its value and its share.
66
+ Slice = Struct.new(:label, :color, :text, :share, keyword_init: true)
67
+
68
+ def slices
69
+ entry = @series.first
70
+ @labels.each_with_index.map do |label, index|
71
+ Slice.new(label: label, color: index + 1, text: formatted(entry.data[index]), share: share_text(entry.data[index]))
72
+ end
73
+ end
74
+
75
+ def slice_swatch(slice) = cn(SWATCHES[slice.color], "size-2.5 shrink-0 rounded-sm")
76
+
77
+ def legend_classes
78
+ if circular?
79
+ "flex flex-col gap-2 text-sm sm:w-64 sm:shrink-0"
80
+ else
81
+ "flex flex-wrap gap-x-4 gap-y-1 text-sm text-muted-foreground"
82
+ end
83
+ end
84
+
85
+ # A pie sits beside its legend once there's room; the others keep it above.
86
+ def body_classes
87
+ circular? ? "flex flex-col-reverse gap-4 sm:flex-row sm:items-center sm:gap-8" : "contents"
88
+ end
89
+
90
+ def root_attrs
91
+ attrs = @html_attrs.except(:data)
92
+ attrs[:class] = cn("flex w-full min-w-0 flex-col gap-3", @user_class)
93
+ attrs[:data] = { slot: "chart", type: @type, controller: "ui--chart",
94
+ "ui--chart-config-value": config.to_json,
95
+ # Propshaft digests the filename, so the URL has to come from Ruby.
96
+ "ui--chart-module-url-value": helpers.asset_path("chart_js.js") }
97
+ .merge(@html_attrs[:data] || {})
98
+ attrs
99
+ end
100
+
101
+ def canvas_attrs
102
+ { role: "img", tabindex: 0, class: cn("block rounded-sm", UI::Base::FOCUS_RING),
103
+ aria: { label: "#{label}. #{t('ui.chart.keyboard', default: 'Use the arrow keys to read each value.')}" },
104
+ data: { "ui--chart-target": "canvas",
105
+ action: "keydown->ui--chart#keydown blur->ui--chart#blur" } }
106
+ end
107
+
108
+ def frame_style = "height: #{@height.to_i}px"
109
+ def frame_classes = cn("relative w-full", { "sm:flex-1" => circular? })
110
+
111
+ def label = @label || t("ui.chart.label", default: "Chart")
112
+
113
+ def formatted(value)
114
+ return t("ui.chart.missing", default: "—") if value.nil?
115
+
116
+ case @format
117
+ when :currency then ActiveSupport::NumberHelper.number_to_currency(value, **{ unit: @unit }.compact)
118
+ when :percent then ActiveSupport::NumberHelper.number_to_percentage(value, precision: 1, strip_insignificant_zeros: true)
119
+ else ActiveSupport::NumberHelper.number_to_delimited(value)
120
+ end
121
+ end
122
+
123
+ def share_text(value)
124
+ return t("ui.chart.missing", default: "—") if value.nil? || total.zero?
125
+
126
+ ActiveSupport::NumberHelper.number_to_percentage(value.to_f / total * 100, precision: 0)
127
+ end
128
+
129
+ private
130
+
131
+ def total = @total ||= @series.first.data.compact.sum
132
+
133
+ def check_slices
134
+ raise ArgumentError, "a #{@type} chart shows one series; draw several as bars instead" if @series.size != 1
135
+ if @labels.size > COLORS
136
+ raise ArgumentError, "a #{@type} chart draws up to #{COLORS} slices; fold the rest into one called \"Other\""
137
+ end
138
+ raise ArgumentError, "a #{@type} chart can't show values below zero" if @series.first.data.compact.any?(&:negative?)
139
+ end
140
+
141
+ def build_series(series)
142
+ if series.size > COLORS
143
+ raise ArgumentError, "UI::Chart draws up to #{COLORS} series; fold the rest into one called \"Other\""
144
+ end
145
+
146
+ series.each_with_index.map do |entry, index|
147
+ entry = entry.to_h.symbolize_keys
148
+ data = Array(entry.fetch(:data))
149
+ if data.size != @labels.size
150
+ raise ArgumentError, "series #{entry[:name].inspect} has #{data.size} values for #{@labels.size} labels"
151
+ end
152
+
153
+ color = entry[:color].to_i.between?(1, COLORS) ? entry[:color].to_i : index + 1
154
+ Series.new(name: entry.fetch(:name).to_s, data: data, color: color)
155
+ end
156
+ end
157
+
158
+ # What the controller draws from. The values arrive written out already, so
159
+ # the tooltip shows them the same way as the table.
160
+ def config
161
+ config = { type: @type, stacked: @stacked, labels: @labels,
162
+ series: @series.map { |entry| { name: entry.name, color: entry.color, data: entry.data, text: entry.data.map { |value| formatted(value) } } },
163
+ axis: axis_format }
164
+ return config unless circular?
165
+
166
+ config[:series].first.merge!(colors: (1..@labels.size).to_a, shares: @series.first.data.map { |value| share_text(value) })
167
+ config.merge(total: formatted(total), total_label: t("ui.chart.total", default: "Total"))
168
+ end
169
+
170
+ # Axis ticks aren't data, so the browser writes them, in the same locale and
171
+ # with the same currency sign.
172
+ def axis_format
173
+ { style: @format, locale: I18n.locale.to_s,
174
+ unit: @unit || I18n.t("number.currency.format.unit", default: "$"),
175
+ pattern: I18n.t("number.currency.format.format", default: "%u%n") }
176
+ end
177
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ # A titled section of a UI::Command: "Pages", "Actions". Hidden while none of
6
+ # its items match what's typed.
7
+ class UI::Command::Group < UI::Base
8
+ renders_many :items, "UI::Command::Item"
9
+
10
+ def initialize(heading: nil, class: nil, **html_attrs)
11
+ @heading = heading
12
+ @user_class = binding.local_variable_get(:class)
13
+ @html_attrs = html_attrs
14
+ @heading_id = "ui-command-group-#{SecureRandom.hex(4)}"
15
+ end
16
+
17
+ def call
18
+ tag.div(role: "group", **@html_attrs, class: cn("py-1 [&:not(:first-child)]:border-t", @user_class),
19
+ aria: { labelledby: (@heading_id if @heading) }.compact,
20
+ data: { "ui--command-target": "group", **(@html_attrs[:data] || {}) }) do
21
+ safe_join([
22
+ (tag.div(@heading, id: @heading_id, class: "px-2 pt-1.5 pb-1 text-xs font-medium text-muted-foreground") if @heading),
23
+ safe_join(items.map(&:to_s))
24
+ ])
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ # One thing to pick in a UI::Command: a page to go to (`href:`) or an action
6
+ # (`value:`, handled from `ui--command:select`). `keywords:` are other words
7
+ # it's found by. A block replaces how it looks; the label still finds it.
8
+ #
9
+ # `shortcut:` shows the item's shortcut, with UI::Kbd; with `bind: true` the
10
+ # shortcut also picks it from anywhere on the page, palette open or not.
11
+ class UI::Command::Item < UI::Base
12
+ BASE = "relative flex cursor-default select-none items-center gap-3 rounded-md px-2 py-2 text-sm outline-none " \
13
+ "data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground " \
14
+ "aria-disabled:pointer-events-none aria-disabled:opacity-50"
15
+
16
+ def initialize(label:, href: nil, value: nil, icon: nil, description: nil, keywords: nil, shortcut: nil, bind: false,
17
+ disabled: false, class: nil, **html_attrs)
18
+ @label = label
19
+ @href = href
20
+ @value = value || href || label
21
+ @icon = icon
22
+ @description = description
23
+ @keywords = Array(keywords).join(" ")
24
+ @shortcut = shortcut
25
+ @bind = bind
26
+ @disabled = disabled
27
+ @user_class = binding.local_variable_get(:class)
28
+ @html_attrs = html_attrs
29
+ @id = html_attrs[:id] || "ui-command-item-#{SecureRandom.hex(4)}"
30
+ end
31
+
32
+ def call
33
+ tag.div(**@html_attrs, id: @id, role: "option", class: cn(BASE, @user_class),
34
+ aria: { disabled: (true if @disabled), selected: "false" }.compact,
35
+ data: { "ui--command-target": "item", value: @value, href: @href, label: @label,
36
+ keywords: (@keywords if @keywords.present?), **(@html_attrs[:data] || {}) }.compact) do
37
+ safe_join([ icon, body, shortcut ].compact)
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def icon
44
+ return unless @icon
45
+
46
+ tag.span(render(UI::Icon.new(name: @icon, size: :sm)), class: "flex shrink-0 text-muted-foreground", aria: { hidden: true })
47
+ end
48
+
49
+ def body
50
+ return tag.span(content, class: "min-w-0 flex-1") if content?
51
+
52
+ tag.span(class: "flex min-w-0 flex-1 flex-col") do
53
+ safe_join([ tag.span(@label, class: "truncate"),
54
+ (tag.span(@description, class: "truncate text-xs text-muted-foreground") if @description) ].compact)
55
+ end
56
+ end
57
+
58
+ def shortcut
59
+ return unless @shortcut
60
+
61
+ render(UI::Kbd.new(@shortcut, size: :sm, class: "ms-auto text-muted-foreground",
62
+ bind: (@bind && !@disabled ? "##{@id}" : nil)))
63
+ end
64
+ end
@@ -0,0 +1,41 @@
1
+ <%# frozen_string_literal: true %>
2
+ <% panel = capture do %>
3
+ <div class="<%= panel_class %>" data-ui--command-target="panel">
4
+ <div class="flex items-center gap-2 border-b px-3">
5
+ <%# The magnifying glass turns into a spinner while a server search is slow. %>
6
+ <span class="flex shrink-0 text-muted-foreground" data-ui--command-target="searchIcon" aria-hidden="true"><%= render(UI::Icon.new(name: "search", size: :sm)) %></span>
7
+ <span class="hidden shrink-0 text-muted-foreground" data-ui--command-target="spinner" aria-hidden="true"><%= render(UI::Icon.new(name: "loader", size: :sm, class: "animate-spin motion-reduce:animate-[spin_1.5s_linear_infinite]")) %></span>
8
+ <%= tag.input(type: "text", id: input_id, role: "combobox", autocomplete: "off", spellcheck: "false", placeholder: placeholder,
9
+ class: "h-11 w-full min-w-0 bg-transparent text-sm outline-none placeholder:text-muted-foreground",
10
+ aria: { label: label, expanded: "true", controls: listbox_id, autocomplete: "list" },
11
+ data: { "ui--command-target": "input", action: "input->ui--command#search keydown->ui--command#navigate" }) %>
12
+ </div>
13
+ <div id="<%= listbox_id %>" role="listbox" aria-label="<%= label %>" class="min-h-0 flex-1 scroll-py-1 overflow-y-auto overscroll-contain p-1 <%= "max-h-80" unless dialog? %>"
14
+ data-ui--command-target="list" data-action="click->ui--command#pick pointermove->ui--command#hover">
15
+ <% groups.each do |group| %><%= group %><% end %>
16
+ <div data-ui--command-target="results"></div>
17
+ <p class="py-6 text-center text-sm text-muted-foreground" data-ui--command-target="empty" hidden></p>
18
+ <p class="py-6 text-center text-sm text-muted-foreground" data-ui--command-target="status" role="status" hidden></p>
19
+ </div>
20
+ <% if dialog? %>
21
+ <%# Key hints, so hidden where there's rarely a keyboard. %>
22
+ <div class="hidden items-center gap-4 border-t px-3 py-2 text-xs text-muted-foreground sm:flex" aria-hidden="true">
23
+ <span class="flex items-center gap-1.5"><%= render(UI::Kbd.new("up", size: :sm)) %><%= render(UI::Kbd.new("down", size: :sm)) %><%= t("ui.command.to_move", default: "to move") %></span>
24
+ <span class="flex items-center gap-1.5"><%= render(UI::Kbd.new("enter", size: :sm)) %><%= t("ui.command.to_pick", default: "to pick") %></span>
25
+ <span class="ms-auto flex items-center gap-1.5"><%= render(UI::Kbd.new("esc", size: :sm)) %><%= t("ui.command.to_close", default: "to close") %></span>
26
+ </div>
27
+ <% end %>
28
+ <%# A server result, copied for each one. %>
29
+ <template data-ui--command-target="template">
30
+ <%= render(UI::Command::Item.new(label: "", id: "", data: { remote: true })) %>
31
+ </template>
32
+ </div>
33
+ <% end %>
34
+ <%= tag.div(**root_attrs) do %>
35
+ <% if dialog? %>
36
+ <%= trigger %>
37
+ <dialog class="<%= UI::Command::DIALOG %>" aria-label="<%= label %>" data-ui--command-target="dialog"><%= panel %></dialog>
38
+ <% else %>
39
+ <%= panel %>
40
+ <% end %>
41
+ <% end %>
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ # A search box over everything you can do or go to: pages, actions, and, with
6
+ # `url:`, records from the server. Type to narrow it, arrows to move, Enter to
7
+ # go. On a page as it is, or `dialog: true` for the ⌘K kind, over the page.
8
+ #
9
+ # <%= render(UI::Command.new(dialog: true, url: search_path)) do |command| %>
10
+ # <% command.with_trigger %>
11
+ # <% command.with_group(heading: "Pages") do |group| %>
12
+ # <% group.with_item(label: "Dashboard", href: dashboard_path, icon: "house") %>
13
+ # <% group.with_item(label: "Settings", href: settings_path, icon: "settings", shortcut: "mod+,") %>
14
+ # <% end %>
15
+ # <% command.with_group(heading: "Actions") do |group| %>
16
+ # <% group.with_item(label: "New invoice", value: "new-invoice", icon: "plus", keywords: "create bill") %>
17
+ # <% end %>
18
+ # <% end %>
19
+ #
20
+ # An item with `href:` is visited (with Turbo when it's there; ⌘ or Ctrl+Enter
21
+ # opens a new tab). Every pick fires `ui--command:select` with its value,
22
+ # label and href first; cancel it to handle the pick yourself.
23
+ #
24
+ # Typing filters the items on the page by label and `keywords:`, best matches
25
+ # first, every word counting. With `url:` it also asks the server, as UI::Select
26
+ # does: GET url?q=… returning [{ label, href, value, description, group }],
27
+ # listed under `group`, or "Results". Searches are spaced out, a slow one shows
28
+ # a spinner, and answers are remembered for a minute.
29
+ #
30
+ # The dialog opens on `shortcut:` (mod+k) from anywhere on the page, from the
31
+ # trigger, or from any element with data-action="ui--command#open" inside it.
32
+ # `shortcut:` can be a list, like ["mod+k", "/"]; the trigger shows the first.
33
+ #
34
+ # `sort_groups: true` puts the group with the best match first, so a strong
35
+ # match isn't buried under a weak one in an earlier group. `empty:` says what
36
+ # to show when nothing matches. After each search it fires
37
+ # `ui--command:search` with the query and how many items match, for
38
+ # analytics, say.
39
+ class UI::Command < UI::Base
40
+ renders_many :groups, "UI::Command::Group"
41
+
42
+ # The button that opens the dialog: "Search…" and the shortcut, unless a
43
+ # block says otherwise. Takes UI::Button's options.
44
+ renders_one :trigger, lambda { |label: nil, **opts, &block|
45
+ content = block ? view_context.capture(&block) : default_trigger_content(label)
46
+ actions = [ "ui--command#open", opts.dig(:data, :action) ].compact.join(" ")
47
+ render(UI::Button.new(variant: :outline, **opts,
48
+ class: cn("justify-between gap-6 font-normal text-muted-foreground", opts[:class]),
49
+ aria: { haspopup: "dialog", **(opts[:aria] || {}) },
50
+ data: { **(opts[:data] || {}), action: actions })) { content }
51
+ }
52
+
53
+ # The dialog sits near the top, where the eye already is, and doesn't jump
54
+ # as the list shrinks.
55
+ DIALOG = "fixed inset-0 m-0 p-0 max-w-none max-h-none w-full h-full bg-transparent border-0 overflow-visible " \
56
+ "open:flex open:items-start open:justify-center open:px-4 open:pt-[12vh] " \
57
+ "backdrop:bg-black/50 backdrop:backdrop-blur-[1px]"
58
+
59
+ PANEL = "flex w-full flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground"
60
+
61
+ def initialize(placeholder: nil, dialog: false, shortcut: "mod+k", url: nil, param: "q", results_heading: nil,
62
+ label: nil, empty: nil, sort_groups: false, class: nil, **html_attrs)
63
+ @placeholder = placeholder
64
+ @dialog = dialog
65
+ @shortcuts = Array(shortcut).map(&:to_s).reject(&:empty?)
66
+ @empty = empty
67
+ @sort_groups = sort_groups
68
+ @url = url
69
+ @param = param
70
+ @results_heading = results_heading
71
+ @label = label
72
+ @user_class = binding.local_variable_get(:class)
73
+ @html_attrs = html_attrs
74
+ @id = html_attrs[:id] || "ui-command-#{SecureRandom.hex(4)}"
75
+ end
76
+
77
+ attr_reader :id
78
+
79
+ # The one the trigger shows.
80
+ def shortcut = @shortcuts.first
81
+
82
+ def dialog? = @dialog
83
+ def remote? = @url.present?
84
+
85
+ def listbox_id = "#{id}-list"
86
+ def input_id = "#{id}-input"
87
+
88
+ def placeholder = @placeholder || t("ui.command.placeholder", default: "Type a command or search…")
89
+ def label = @label || t("ui.command.label", default: "Command menu")
90
+ def results_heading = @results_heading || t("ui.command.results", default: "Results")
91
+
92
+ def root_attrs
93
+ { **@html_attrs.except(:id), id: id, class: cn(!dialog? && "w-full", @user_class),
94
+ data: { controller: "ui--command", **controller_values, **(@html_attrs[:data] || {}) } }
95
+ end
96
+
97
+ def panel_class = cn(PANEL, dialog? ? "max-w-xl shadow-2xl max-h-[min(32rem,76vh)]" : "shadow-sm")
98
+
99
+ private
100
+
101
+ def default_trigger_content(label)
102
+ safe_join([
103
+ tag.span(class: "flex items-center gap-2") do
104
+ safe_join([ render(UI::Icon.new(name: "search", size: :sm)), label || t("ui.command.trigger", default: "Search…") ])
105
+ end,
106
+ (render(UI::Kbd.new(shortcut, size: :sm)) if shortcut)
107
+ ])
108
+ end
109
+
110
+ def controller_values
111
+ # Shortcuts never have spaces ("space" is the key), so they're listed with them.
112
+ values = { "ui--command-dialog-value": dialog?, "ui--command-shortcut-value": (dialog? ? @shortcuts.join(" ") : ""),
113
+ "ui--command-sort-groups-value": @sort_groups,
114
+ "ui--command-empty-value": @empty || t("ui.command.empty", default: "No results found."),
115
+ "ui--command-searching-value": t("ui.command.searching", default: "Searching…"),
116
+ "ui--command-failed-value": t("ui.command.failed", default: "Couldn't search. Try again.") }
117
+ return values unless remote?
118
+
119
+ values.merge("ui--command-url-value": @url, "ui--command-param-value": @param,
120
+ "ui--command-results-heading-value": results_heading)
121
+ end
122
+ end
@@ -1,73 +1,67 @@
1
- <div class="<%= classes %>" data-controller="ui--date-picker"
2
- data-ui--date-picker-module-url-value="<%= helpers.asset_path('cally.js') %>"
3
- data-ui--date-picker-order-value="<%= part_order %>"
4
- data-ui--date-picker-separator-value="<%= separator %>"
5
- data-action="click@window->ui--date-picker#closeOnOutsideClick keydown@window->ui--date-picker#closeOnEscape"
6
- <%= tag.attributes(@html_attrs) %>>
1
+ <%= tag.div(**root_attrs) do %>
7
2
  <% if render_label? %>
8
- <label for="<%= input_id %>" class="mb-1.5 block text-sm font-medium text-foreground">
9
- <%= label_text %><% if @required %><span class="ml-0.5 text-destructive">*</span><% end %>
10
- </label>
3
+ <%= tag.label for: input_id, class: "mb-1.5 block text-sm font-medium text-foreground" do %><%= label_text %><% if required? %><span class="ml-0.5 text-destructive">*</span><% end %><% end %>
11
4
  <% end %>
12
5
 
13
- <div class="relative">
14
- <%# What the user types. Not name'd: it is never submitted, so a
15
- half-typed date cannot reach the server. %>
16
- <input type="text" id="<%= input_id %>" inputmode="numeric" autocomplete="off"
17
- placeholder="<%= placeholder %>" class="<%= input_classes %>"
18
- value="<%= typed_value %>"
19
- <%= "required" if @required %> <%= "disabled" if @disabled %>
20
- <%= tag.attributes("aria-describedby": describedby, "aria-invalid": ("true" if wrapper.error?)) %>
21
- data-ui--date-picker-target="input"
22
- data-action="input->ui--date-picker#typed">
23
-
24
- <%# What the form submits. %>
25
- <input type="hidden" name="<%= field_name %>" value="<%= iso_value %>"
26
- data-ui--date-picker-target="hidden">
27
-
28
- <button type="button" aria-haspopup="dialog" aria-expanded="false"
29
- aria-controls="<%= panel_id %>"
30
- aria-label="<%= t("ui.date_picker.open") %>"
31
- class="absolute inset-y-0 right-0 flex w-9 items-center justify-center rounded-r-md text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
32
- <%= "disabled" if @disabled %>
33
- data-ui--date-picker-target="toggle"
34
- data-action="ui--date-picker#toggle">
35
- <%= render(UI::Icon.new(name: "calendar", class: "size-4")) %>
36
- </button>
37
- </div>
6
+ <%= tag.div class: group_classes do %>
7
+ <%# What people type. Not named: only the hidden ISO fields are submitted,
8
+ so a half-typed date can't reach the server. %>
9
+ <% fields.each_with_index do |(target, _, iso), index| %>
10
+ <% if index.positive? %><span class="shrink-0 text-muted-foreground" aria-hidden="true">–</span><% end %>
11
+ <%= tag.input(**input_attrs(target, iso)) %>
12
+ <% end %>
13
+ <span class="flex h-full shrink-0 items-center">
14
+ <%= tag.button type: "button", hidden: !value? || required? || disabled?,
15
+ aria: { label: t("ui.date_picker.clear", default: "Clear") },
16
+ class: "flex size-7 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground #{UI::Base::FOCUS_RING}",
17
+ data: { "ui--date-picker-target": "clear", action: "ui--date-picker#clear" } do %>
18
+ <%= render(UI::Icon.new(name: "x", size: :sm)) %>
19
+ <% end %>
20
+ <%= tag.button type: "button", disabled: disabled?, tabindex: -1,
21
+ aria: { haspopup: "dialog", expanded: "false", controls: panel_id, label: t("ui.date_picker.open", default: "Open the calendar") },
22
+ class: toggle_classes,
23
+ data: { "ui--date-picker-target": "toggle", action: "ui--date-picker#toggle" } do %>
24
+ <%= render(UI::Icon.new(name: "calendar", size: :sm)) %>
25
+ <% end %>
26
+ </span>
27
+ <% end %>
28
+ <% fields.each do |target, name, iso| %>
29
+ <%= tag.input type: "hidden", name: name, value: iso, data: { "ui--date-picker-target": "hidden", field: target } %>
30
+ <% end %>
38
31
 
39
32
  <% if render_hint? %>
40
- <p id="<%= input_id %>-hint" class="mt-1 text-xs text-muted-foreground">
41
- <%= t("ui.date_picker.hint", pattern: placeholder) %>
42
- </p>
33
+ <%= tag.p hint_text, id: hint_id, class: "mt-1 text-xs text-muted-foreground" %>
43
34
  <% end %>
44
35
  <% if wrapper.error_message %>
45
- <%= tag.p(wrapper.error_message, id: wrapper.error_id, class: "mt-1 text-xs text-destructive") %>
36
+ <%= tag.p wrapper.error_message, id: wrapper.error_id, class: "mt-1 text-xs text-destructive" %>
46
37
  <% end %>
47
38
 
48
- <div id="<%= panel_id %>" role="dialog" hidden
49
- class="absolute z-30 mt-1 rounded-md border bg-popover p-3 text-popover-foreground shadow-md"
50
- data-ui--date-picker-target="panel">
51
- <%# calendar-select-year is why this library was chosen: reaching 2012 for
52
- a date of birth is one click, not a hundred and seventy. %>
53
- <%# Cally puts each arrow inside its own button, so ours are icons with
54
- words for screen readers; the month and year selects fill its heading
55
- slot, between the arrows. %>
56
- <%= tag.send(:"calendar-date",
57
- safe_join([
58
- tag.span(safe_join([ render(UI::Icon.new(name: "chevron-left", size: :sm)),
59
- tag.span(t("ui.date_picker.previous"), class: "sr-only") ]),
60
- slot: "previous", class: "inline-flex"),
61
- tag.span(safe_join([ render(UI::Icon.new(name: "chevron-right", size: :sm)),
62
- tag.span(t("ui.date_picker.next"), class: "sr-only") ]),
63
- slot: "next", class: "inline-flex"),
64
- tag.div(safe_join([ tag.send(:"calendar-select-month"), tag.send(:"calendar-select-year") ]),
65
- slot: "heading", class: "flex items-center gap-1.5"),
66
- tag.send(:"calendar-month")
67
- ]),
68
- locale: I18n.locale == :en ? "en-IN" : I18n.locale.to_s,
69
- "first-day-of-week": 1, min: @min, max: @max,
70
- data: { "ui--date-picker-target": "calendar",
71
- action: "change->ui--date-picker#picked" }) %>
72
- </div>
73
- </div>
39
+ <%# Below the field, or a sheet from the bottom of the screen on a phone. %>
40
+ <%= tag.div id: panel_id, role: "dialog", hidden: true,
41
+ aria: { label: t(range? ? "ui.date_picker.dialog_range" : "ui.date_picker.dialog", default: range? ? "Choose dates" : "Choose a date") },
42
+ class: "absolute left-0 top-full z-40 mt-1 flex w-max flex-col rounded-md border bg-popover text-popover-foreground shadow-md " \
43
+ "sm:flex-row max-sm:fixed max-sm:inset-x-0 max-sm:top-auto max-sm:bottom-0 max-sm:mt-0 max-sm:w-auto " \
44
+ "max-sm:max-h-[85dvh] max-sm:overflow-y-auto max-sm:rounded-b-none max-sm:border-x-0 max-sm:border-b-0",
45
+ data: { "ui--date-picker-target": "panel" } do %>
46
+ <% if preset_list.any? %>
47
+ <%= tag.ul class: "flex gap-1 overflow-x-auto border-b p-2 sm:flex-col sm:overflow-visible sm:border-b-0 sm:border-e",
48
+ aria: { label: t("ui.date_picker.presets_label", default: "Quick ranges") } do %>
49
+ <% preset_list.each do |name, from, to| %>
50
+ <li class="shrink-0"><%= tag.button name, type: "button", aria: { pressed: preset_pressed?(from, to).to_s },
51
+ class: "w-full whitespace-nowrap rounded-md px-3 py-1.5 text-start text-sm hover:bg-accent hover:text-accent-foreground " \
52
+ "aria-pressed:bg-primary/10 aria-pressed:font-medium aria-pressed:text-primary dark:aria-pressed:text-foreground #{UI::Base::FOCUS_RING}",
53
+ data: { action: "ui--date-picker#preset", "ui--date-picker-from-param": from,
54
+ "ui--date-picker-to-param": to, "ui--date-picker-target": "preset" } %></li>
55
+ <% end %>
56
+ <% end %>
57
+ <% end %>
58
+ <div class="flex min-w-0 flex-col">
59
+ <%# The calendar replaces the classes of the element it's given, so the
60
+ kit's colours sit on this wrapper instead. %>
61
+ <div class="velvetkit-calendar p-2"><%= tag.div data: { "ui--date-picker-target": "calendar" } %></div>
62
+ <% if range? %>
63
+ <%= tag.p "", role: "status", class: "min-h-5 px-4 pb-3 text-xs text-muted-foreground", data: { "ui--date-picker-target": "status" } %>
64
+ <% end %>
65
+ </div>
66
+ <% end %>
67
+ <% end %>