velvetkit 0.5.0 → 0.6.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 (60) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +63 -18
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/accordion/trigger.rb +1 -1
  5. data/registry/app/components/ui/badge.rb +1 -1
  6. data/registry/app/components/ui/base.rb +2 -2
  7. data/registry/app/components/ui/button.rb +1 -1
  8. data/registry/app/components/ui/carousel.html.erb +9 -4
  9. data/registry/app/components/ui/carousel.rb +42 -1
  10. data/registry/app/components/ui/checkbox.rb +2 -2
  11. data/registry/app/components/ui/file_tree/file_item.html.erb +9 -0
  12. data/registry/app/components/ui/file_tree/file_item.rb +50 -0
  13. data/registry/app/components/ui/file_tree/folder.html.erb +9 -0
  14. data/registry/app/components/ui/file_tree/folder.rb +76 -0
  15. data/registry/app/components/ui/file_tree.html.erb +1 -0
  16. data/registry/app/components/ui/file_tree.rb +93 -0
  17. data/registry/app/components/ui/gallery.rb +4 -4
  18. data/registry/app/components/ui/link.rb +1 -1
  19. data/registry/app/components/ui/menu/item.rb +1 -1
  20. data/registry/app/components/ui/radio_group/item.rb +1 -1
  21. data/registry/app/components/ui/rating.html.erb +16 -0
  22. data/registry/app/components/ui/rating.rb +200 -0
  23. data/registry/app/components/ui/sidebar/group_label.rb +1 -1
  24. data/registry/app/components/ui/sidebar/menu_button.rb +1 -1
  25. data/registry/app/components/ui/sidebar/menu_item.rb +1 -1
  26. data/registry/app/components/ui/sidebar/menu_sub.rb +1 -1
  27. data/registry/app/components/ui/switch.rb +2 -2
  28. data/registry/app/components/ui/tabs/trigger.rb +1 -1
  29. data/registry/app/javascript/controllers/ui/carousel_controller.ts +59 -1
  30. data/registry/app/javascript/controllers/ui/file_tree_controller.ts +189 -0
  31. data/registry/app/javascript/controllers/ui/rating_controller.ts +117 -0
  32. data/registry/components.yml +4 -0
  33. data/registry/config/locales/velvetkit.en.yml +13 -0
  34. data/registry/test/components/previews/ui/carousel_preview/with_indicators.html.erb +10 -0
  35. data/registry/test/components/previews/ui/carousel_preview.rb +7 -3
  36. data/registry/test/components/previews/ui/file_tree_preview/changes.html.erb +13 -0
  37. data/registry/test/components/previews/ui/file_tree_preview/from_data.html.erb +14 -0
  38. data/registry/test/components/previews/ui/file_tree_preview/picking_a_file.html.erb +25 -0
  39. data/registry/test/components/previews/ui/file_tree_preview/without_guides.html.erb +10 -0
  40. data/registry/test/components/previews/ui/file_tree_preview.rb +41 -0
  41. data/registry/test/components/previews/ui/image_preview/radii.html.erb +3 -3
  42. data/registry/test/components/previews/ui/image_preview/sizing.html.erb +9 -4
  43. data/registry/test/components/previews/ui/image_preview.rb +14 -1
  44. data/registry/test/components/previews/ui/rating_preview/in_form.html.erb +6 -0
  45. data/registry/test/components/previews/ui/rating_preview/model_errors.html.erb +20 -0
  46. data/registry/test/components/previews/ui/rating_preview/playground.html.erb +5 -0
  47. data/registry/test/components/previews/ui/rating_preview/scores.html.erb +18 -0
  48. data/registry/test/components/previews/ui/rating_preview/sizes.html.erb +6 -0
  49. data/registry/test/components/previews/ui/rating_preview.rb +28 -0
  50. data/registry/test/components/ui/base_test.rb +27 -0
  51. data/registry/test/components/ui/button_test.rb +2 -2
  52. data/registry/test/components/ui/carousel_test.rb +48 -0
  53. data/registry/test/components/ui/confirm_dialog_test.rb +3 -0
  54. data/registry/test/components/ui/file_tree_test.rb +187 -0
  55. data/registry/test/components/ui/gallery_test.rb +4 -4
  56. data/registry/test/components/ui/link_test.rb +1 -1
  57. data/registry/test/components/ui/number_input_test.rb +1 -1
  58. data/registry/test/components/ui/rating_test.rb +271 -0
  59. data/registry/test/components/ui/switch_test.rb +4 -4
  60. metadata +25 -1
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ # A score out of five stars (or `max:`), shown or chosen.
6
+ #
7
+ # Shown, it fills to the nearest half star and reads as one image: "Rated 4.5
8
+ # out of 5". `show_value: true` prints the number beside the stars and
9
+ # `count:` how many ratings it's the average of.
10
+ #
11
+ # <%= render(UI::Rating.new(value: 4.5, count: 128, show_value: true)) %>
12
+ #
13
+ # Given a `name:` (or `form:` and `field:`), it's a field: a radio for each
14
+ # half-star, so it posts in 0.5-point steps, resets with the form and needs no
15
+ # JavaScript. Arrow keys move between the half-star values. With JavaScript,
16
+ # hovering either half previews the score it gives.
17
+ #
18
+ # <%= render(UI::Rating.new(name: "review[rating]", legend: "Your rating", required: true)) %>
19
+ #
20
+ # With JavaScript, choosing a score clears the field's error, as it's been
21
+ # answered. `thanks: true` then shows "Thank you for your rating" (or the
22
+ # string given) in its place. Resetting the form brings the error back.
23
+ # `show_value: true` prints the score beside the stars, "4.5/5", and keeps
24
+ # it to the one chosen; it goes back to where it started with the form.
25
+ #
26
+ # <%= render(UI::Rating.new(form: f, field: :rating, legend: true, thanks: true)) %>
27
+ #
28
+ # As with RadioGroup, a `legend:` (and a `hint:` or `error:`) renders it
29
+ # through UI::Fieldset, which names the group and shows the model's errors when
30
+ # it's bound to a form; `legend: true` uses the attribute's name. Without a
31
+ # legend, `label:` is the field's hidden name ("Rating" if not given).
32
+ #
33
+ # `icon:` draws another icon from the library.
34
+ class UI::Rating < UI::Base
35
+ variants(
36
+ base: "inline-flex shrink-0 items-center",
37
+ variants: {
38
+ size: {
39
+ sm: "gap-0.5 [&_svg]:size-4",
40
+ default: "gap-0.5 [&_svg]:size-5",
41
+ lg: "gap-1 [&_svg]:size-6"
42
+ }
43
+ },
44
+ defaults: { size: :default }
45
+ )
46
+
47
+ # A filled star's colour, and an empty one's. The empty grey is a solid
48
+ # token, not a see-through one: the icon's fill and stroke overlap, and a
49
+ # see-through colour doubles where they do, outlining every empty star.
50
+ ON = "text-amber-500"
51
+ OFF = "text-border dark:text-muted"
52
+
53
+ # A field's star: lit when its own radio or a later one is checked, so the
54
+ # stars up to the chosen one fill without JavaScript. While the pointer is
55
+ # over the stars, the controller marks each one lit or not, which wins. A
56
+ # star draws no focus ring: each is half a star wide, so a ring round one
57
+ # cuts across the icon, and the lit stars already show the chosen score.
58
+ #
59
+ # The star under the pointer grows, both halves marked `data-hovered` by the
60
+ # controller, and choosing it brings it back to size; choosing one from the
61
+ # keyboard pops it instead. Each half scales from the star's middle
62
+ # (STAR_ORIGIN), so the two move as one star.
63
+ STAR = "relative cursor-pointer transition-[color,scale] text-border dark:text-muted " \
64
+ "[input:checked+&]:text-amber-500 [&:has(~input:checked)]:text-amber-500 " \
65
+ "data-[lit=true]:!text-amber-500 data-[lit=false]:!text-border dark:data-[lit=false]:!text-muted " \
66
+ "data-[hovered=true]:z-10 motion-safe:data-[hovered=true]:scale-125"
67
+ STAR_HALF_SIZE = { sm: "h-4 w-2", default: "h-5 w-2.5", lg: "h-6 w-3" }.freeze
68
+ STAR_GAP = { sm: "me-0.5", default: "me-0.5", lg: "me-1" }.freeze
69
+ STAR_ORIGIN = { start: "origin-right rtl:origin-left", end: "origin-left rtl:origin-right" }.freeze
70
+
71
+ def initialize(value: nil, max: 5, size: :default, icon: "star",
72
+ show_value: false, count: nil,
73
+ name: nil, form: nil, field: nil, required: false, disabled: false, thanks: false,
74
+ label: nil, legend: nil, hint: nil, error: nil,
75
+ class: nil, **html_attrs)
76
+ @value = value
77
+ @max = Integer(max)
78
+ @size = size
79
+ @icon = icon
80
+ @show_value = show_value
81
+ @count = count
82
+ @name = name
83
+ @form = form
84
+ @field = field
85
+ @required = required
86
+ @disabled = disabled
87
+ @thanks = thanks
88
+ @label = label
89
+ @legend = legend
90
+ @hint = hint
91
+ @error = error
92
+ @user_class = binding.local_variable_get(:class)
93
+ @html_attrs = html_attrs
94
+ end
95
+
96
+ attr_reader :max, :icon
97
+
98
+ def form_field? = @form.present? && @field.present?
99
+
100
+ # A field when it has a name to post under; otherwise it shows a score.
101
+ def input? = input_name.present?
102
+
103
+ def input_name = form_field? ? "#{@form.object_name}[#{@field}]" : @name
104
+
105
+ def score
106
+ value = @value
107
+ value = @form.object.public_send(@field) if value.nil? && form_field? && @form.object.respond_to?(@field)
108
+ Float(value, exception: false)&.clamp(0, @max)
109
+ end
110
+
111
+ # --- Shown ------------------------------------------------------------------
112
+
113
+ # :full, :half or :empty for each star, to the nearest half.
114
+ def fills
115
+ halves = ((score || 0) * 2).round
116
+ (1..@max).map { |star| halves >= star * 2 ? :full : (halves == star * 2 - 1 ? :half : :empty) }
117
+ end
118
+
119
+ # "4.5", "4" or "4,5": the score as the page's locale writes it.
120
+ def formatted_score = ActiveSupport::NumberHelper.number_to_rounded(score || 0, precision: 1, strip_insignificant_zeros: true)
121
+
122
+ def image_label = t("ui.rating.label", value: formatted_score, max: @max, default: "Rated %{value} out of %{max}")
123
+
124
+ def count? = !@count.nil?
125
+ def formatted_count = ActiveSupport::NumberHelper.number_to_delimited(@count)
126
+ def count_label = t("ui.rating.count", count: @count, default: { one: "%{count} rating", other: "%{count} ratings" })
127
+ def show_value? = @show_value
128
+
129
+ def display_attrs
130
+ @html_attrs.merge(class: cn("inline-flex items-center gap-1.5 text-sm", @user_class))
131
+ end
132
+
133
+ # --- Chosen -----------------------------------------------------------------
134
+
135
+ # Twice the selected score, so a half-star radio is an integer step.
136
+ def chosen_steps = score && (score * 2).round
137
+
138
+ def group_id = @group_id ||= @html_attrs[:id] || "ui-rating-#{SecureRandom.hex(4)}"
139
+ def option_id(value) = "#{group_id}-#{value}"
140
+ def option_value(step)
141
+ whole, half = step.divmod(2)
142
+ half.zero? ? whole : "#{whole}.5"
143
+ end
144
+ def option_label(value) = t("ui.rating.option", count: value, max: @max, default: "%{count} out of %{max}")
145
+ def required? = @required
146
+ def disabled? = @disabled
147
+
148
+ def thanks? = @thanks.present?
149
+ def thanks_text = @thanks.is_a?(String) ? @thanks : t("ui.rating.thanks", default: "Thank you for your rating")
150
+ def thanks_id = "#{group_id}-thanks"
151
+
152
+ # "4.5/5", beside a field's stars; each star carries its own, for the
153
+ # controller to show once it's chosen.
154
+ def score_label = score_text(score || 0)
155
+ def score_text(value)
156
+ t("ui.rating.score", value: ActiveSupport::NumberHelper.number_to_rounded(value, precision: 1, strip_insignificant_zeros: true),
157
+ max: @max, default: "%{value}/%{max}")
158
+ end
159
+ def score_id = "#{group_id}-score"
160
+
161
+ # The legend shows only when given: a bound field that's never been named
162
+ # doesn't grow one when it has an error.
163
+ def fieldset
164
+ @fieldset ||= UI::Fieldset.new(legend: @legend.presence || false, hint: @hint, error: @error,
165
+ form: @form, field: @field, required: @required, disabled: @disabled,
166
+ role: "radiogroup", aria: group_aria)
167
+ end
168
+
169
+ # Without a legend to name it, the field's name is `label:`.
170
+ def group_aria = { label: (@label.presence || t("ui.rating.name", default: "Rating") unless legend_names_it?) }.compact.merge(@html_attrs[:aria] || {})
171
+
172
+ # `legend: true` names it only when bound to a form, from the attribute.
173
+ def legend_names_it? = @legend == true ? form_field? : @legend.present?
174
+
175
+ # Inside a fieldset, the fieldset has the role and the aria attributes that
176
+ # name and describe the group; the stars' row keeps the rest.
177
+ def stars_attrs
178
+ wrapped = fieldset.wrap?
179
+ attrs = @html_attrs.except(:id, :aria, :data)
180
+ attrs[:role] = "radiogroup" unless wrapped
181
+ attrs[:aria] = group_aria unless wrapped
182
+ attrs[:id] = group_id
183
+ attrs[:class] = cn(variant_classes(size: @size), "w-fit gap-0", @user_class)
184
+ attrs[:data] = { controller: "ui--rating",
185
+ action: "mouseleave->ui--rating#reset reset@document->ui--rating#formReset",
186
+ "ui--rating-error-value": (fieldset.error_id if fieldset.error_message.present?),
187
+ "ui--rating-thanks-value": (thanks_id if thanks?),
188
+ "ui--rating-score-value": (score_id if show_value?) }
189
+ .compact.merge(@html_attrs[:data] || {})
190
+ attrs
191
+ end
192
+
193
+ def star_classes(step)
194
+ cn(STAR, STAR_HALF_SIZE.fetch(@size), (STAR_GAP.fetch(@size) if step.even? && step < @max * 2),
195
+ STAR_ORIGIN.fetch(step.odd? ? :start : :end),
196
+ { "cursor-not-allowed opacity-50" => @disabled })
197
+ end
198
+
199
+ def star_icon_classes(step) = cn("absolute inset-y-0 flex", step.odd? ? "start-0" : "-start-full")
200
+ end
@@ -10,7 +10,7 @@ class UI::Sidebar::GroupLabel < ViewComponent::Base
10
10
  @system_args[:data][:sidebar] = "group-label"
11
11
 
12
12
  @system_args[:class] = class_names(
13
- "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
13
+ "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
14
14
  "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
15
15
  @system_args[:class]
16
16
  )
@@ -33,7 +33,7 @@ class UI::Sidebar::MenuButton < UI::Base
33
33
 
34
34
  @system_args[:class] = cn(
35
35
  "peer/menu-button flex w-full items-center gap-2 overflow-hidden text-left text-sm outline-hidden ring-sidebar-ring " \
36
- "transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 " \
36
+ "transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus:ring-2 " \
37
37
  "active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 " \
38
38
  "group-has-data-[sidebar=menu-action]/menu-item:pe-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 " \
39
39
  "data-[active=true]:font-semibold data-[active=true]:text-sidebar-primary data-[active=true]:[&>svg]:stroke-current " \
@@ -42,7 +42,7 @@ class UI::Sidebar::MenuItem < UI::Base
42
42
  aria: { expanded: sub_menu.open?.to_s, controls: sub_menu_id,
43
43
  label: t("ui.sidebar.toggle_sub", name: sub_menu.name, default: "Show the links under %{name}") },
44
44
  class: "absolute end-1 top-1 flex size-6 items-center justify-center rounded-md text-sidebar-foreground/70 outline-hidden " \
45
- "ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 " \
45
+ "ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus:ring-2 " \
46
46
  "group-data-[collapsible=icon]:hidden group-has-[>[data-shape=pill]]/menu-item:top-2 " \
47
47
  "[&[aria-expanded=true]>svg]:rotate-90 [&>svg]:transition-transform motion-reduce:[&>svg]:transition-none" }
48
48
  end
@@ -50,7 +50,7 @@ class UI::Sidebar::MenuSub < UI::Base
50
50
  link_to(item.path, aria: { current: ("page" if item.active) },
51
51
  data: { active: item.active.to_s },
52
52
  class: "flex h-7 min-w-0 items-center gap-2 rounded-md px-2 text-sm text-sidebar-foreground/80 outline-hidden " \
53
- "ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 " \
53
+ "ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus:ring-2 " \
54
54
  "data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground " \
55
55
  "[&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0") do
56
56
  capture(&item.content)
@@ -11,8 +11,8 @@ class UI::Switch < UI::Base
11
11
  base: "absolute inset-0 rounded-full " \
12
12
  "bg-input peer-checked:bg-primary " \
13
13
  "transition-all duration-200 " \
14
- "peer-focus:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-primary " \
15
- "peer-focus-visible:ring-offset-1 ring-offset-background " \
14
+ "peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-primary " \
15
+ "peer-focus:ring-offset-1 ring-offset-background " \
16
16
  "peer-disabled:cursor-not-allowed",
17
17
  variants: {
18
18
  size: {
@@ -4,7 +4,7 @@ class UI::Tabs::Trigger < UI::Base
4
4
  variants(
5
5
  base: "inline-flex items-center justify-center gap-2 whitespace-nowrap " \
6
6
  "font-medium transition-all " \
7
- "focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1 " \
7
+ "focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-1 " \
8
8
  "disabled:pointer-events-none disabled:bg-muted! disabled:text-muted-foreground!",
9
9
  variants: {
10
10
  variant: {
@@ -4,14 +4,17 @@ import { Controller } from '@hotwired/stimulus';
4
4
  //
5
5
  // The strip scrolls by itself (scroll-snap); this only moves it a page at a
6
6
  // time from the buttons, and shows each button while there's more that way.
7
+ // With indicators, it shows one for each place the strip can stop, lights the
8
+ // one in view, and scrolls to an indicator's card.
7
9
  const EDGE = 2;
8
10
 
9
11
  export default class extends Controller<HTMLElement> {
10
- static targets = ['track', 'previous', 'next'];
12
+ static targets = ['track', 'previous', 'next', 'indicator'];
11
13
 
12
14
  declare readonly trackTarget: HTMLElement;
13
15
  declare readonly previousTarget: HTMLButtonElement;
14
16
  declare readonly nextTarget: HTMLButtonElement;
17
+ declare readonly indicatorTargets: HTMLButtonElement[];
15
18
 
16
19
  private frame?: number;
17
20
  private observer?: ResizeObserver;
@@ -35,6 +38,12 @@ export default class extends Controller<HTMLElement> {
35
38
  this.page(1);
36
39
  }
37
40
 
41
+ go({ params }: { params: { index: number } }) {
42
+ const track = this.trackTarget;
43
+ const forward = getComputedStyle(track).direction === 'rtl' ? -1 : 1;
44
+ track.scrollTo({ left: forward * this.stops()[params.index] });
45
+ }
46
+
38
47
  update() {
39
48
  if (this.frame) return;
40
49
 
@@ -45,6 +54,7 @@ export default class extends Controller<HTMLElement> {
45
54
  const scrolled = Math.abs(track.scrollLeft);
46
55
  this.show(this.previousTarget, this.nextTarget, scrolled > EDGE);
47
56
  this.show(this.nextTarget, this.previousTarget, scrolled + track.clientWidth < track.scrollWidth - EDGE);
57
+ if (this.indicatorTargets.length) this.light(scrolled);
48
58
  });
49
59
  }
50
60
 
@@ -55,6 +65,54 @@ export default class extends Controller<HTMLElement> {
55
65
  track.scrollBy({ left: direction * forward * track.clientWidth * 0.85 });
56
66
  }
57
67
 
68
+ // How far the strip scrolls to bring each card to its start, held to the
69
+ // end: the last few cards can't reach the start, so they share the end.
70
+ private stops() {
71
+ const track = this.trackTarget;
72
+ const rtl = getComputedStyle(track).direction === 'rtl';
73
+ const box = track.getBoundingClientRect();
74
+ const scrolled = Math.abs(track.scrollLeft);
75
+ const end = track.scrollWidth - track.clientWidth;
76
+ const starts = Array.from(track.children, (item) => {
77
+ const card = item.getBoundingClientRect();
78
+ return (rtl ? box.right - card.right : card.left - box.left) + scrolled;
79
+ });
80
+ return starts.map((start) => Math.min(Math.max(start - starts[0], 0), end));
81
+ }
82
+
83
+ // An indicator for each place the strip can stop, and none when it can't scroll.
84
+ // Between two stops, the one it's leaving empties as the one it's nearing
85
+ // fills, in step with the scroll, so the pill slides with a finger rather
86
+ // than jumping halfway. The current one is the fuller of the two.
87
+ private light(scrolled: number) {
88
+ const stops = this.stops();
89
+ const shown = this.indicatorTargets.flatMap((_, index) =>
90
+ index === 0 || stops[index] - stops[index - 1] > EDGE ? [index] : [],
91
+ );
92
+ const fills = this.indicatorTargets.map(() => 0);
93
+ const after = shown.findIndex((index) => stops[index] > scrolled);
94
+ if (after <= 0) {
95
+ fills[shown[after === 0 ? 0 : shown.length - 1]] = 1;
96
+ } else {
97
+ const from = shown[after - 1];
98
+ const to = shown[after];
99
+ const progress = (scrolled - stops[from]) / (stops[to] - stops[from]);
100
+ fills[from] = 1 - progress;
101
+ fills[to] = progress;
102
+ }
103
+ const lit = fills.indexOf(Math.max(...fills));
104
+ const scrolls = shown.length > 1;
105
+
106
+ this.indicatorTargets.forEach((indicator, index) => {
107
+ const hidden = !scrolls || !shown.includes(index);
108
+ if (hidden && scrolls && document.activeElement === indicator) this.indicatorTargets[lit].focus();
109
+ indicator.hidden = hidden;
110
+ indicator.style.setProperty('--fill', fills[index].toFixed(3));
111
+ if (index === lit) indicator.setAttribute('aria-current', 'true');
112
+ else indicator.removeAttribute('aria-current');
113
+ });
114
+ }
115
+
58
116
  // A button that hides under the keyboard would drop focus to the page.
59
117
  private show(button: HTMLButtonElement, other: HTMLButtonElement, shown: boolean) {
60
118
  if (!shown && document.activeElement === button) other.focus();
@@ -0,0 +1,189 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // A file tree after the WAI-ARIA tree pattern: one row in the tab order, the
4
+ // arrow keys to move and to open and close folders, a letter to jump to a name.
5
+ // Picking a file that isn't a link selects it and dispatches
6
+ // `ui--file-tree:select` with `{ value, name }`.
7
+
8
+ // The curve iOS sheets and drawers settle on: quick to start, a long soft
9
+ // landing.
10
+ const EASING = 'cubic-bezier(0.32, 0.72, 0, 1)';
11
+ const OPEN_MS = 380;
12
+ const CLOSE_MS = 300;
13
+
14
+ export default class extends Controller<HTMLElement> {
15
+ static targets = ['item'];
16
+
17
+ declare readonly itemTargets: HTMLElement[];
18
+
19
+ private animations = new Map<HTMLElement, Animation>();
20
+ private reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
21
+
22
+ disconnect() {
23
+ this.animations.forEach((animation) => animation.finish());
24
+ }
25
+
26
+ connect() {
27
+ const visible = this.visibleItems();
28
+ const start = visible.find((item) => item.getAttribute('aria-selected') === 'true') ?? visible[0];
29
+ if (start) this.makeTabbable(start);
30
+ }
31
+
32
+ click(event: MouseEvent) {
33
+ const item = this.itemFor(event.target);
34
+ if (!item) return;
35
+ this.makeTabbable(item);
36
+ if (this.isFolder(item)) this.setOpen(item, !this.isOpen(item));
37
+ else this.select(item);
38
+ }
39
+
40
+ keydown(event: KeyboardEvent) {
41
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
42
+ const item = this.itemFor(event.target);
43
+ if (!item) return;
44
+ const visible = this.visibleItems();
45
+ const index = visible.indexOf(item);
46
+ const rtl = getComputedStyle(this.element).direction === 'rtl';
47
+ const key = rtl && event.key === 'ArrowLeft' ? 'ArrowRight' : rtl && event.key === 'ArrowRight' ? 'ArrowLeft' : event.key;
48
+ let next: HTMLElement | null | undefined;
49
+
50
+ switch (key) {
51
+ case 'ArrowDown':
52
+ next = visible[index + 1];
53
+ break;
54
+ case 'ArrowUp':
55
+ next = visible[index - 1];
56
+ break;
57
+ case 'Home':
58
+ next = visible[0];
59
+ break;
60
+ case 'End':
61
+ next = visible[visible.length - 1];
62
+ break;
63
+ case 'ArrowRight':
64
+ if (!this.isFolder(item)) break;
65
+ if (this.isOpen(item)) next = this.childrenOf(item)[0];
66
+ else this.setOpen(item, true);
67
+ break;
68
+ case 'ArrowLeft':
69
+ if (this.isFolder(item) && this.isOpen(item)) this.setOpen(item, false);
70
+ else next = this.parentOf(item);
71
+ break;
72
+ case 'Enter':
73
+ case ' ':
74
+ // Enter on a link follows it, and the click that makes marks it.
75
+ if (key === 'Enter' && item instanceof HTMLAnchorElement) return;
76
+ item.click();
77
+ break;
78
+ default:
79
+ if (key.length !== 1 || key === ' ') return;
80
+ next = this.startingWith(visible, index, key);
81
+ if (!next) return;
82
+ }
83
+
84
+ event.preventDefault();
85
+ if (next) {
86
+ this.makeTabbable(next);
87
+ next.focus();
88
+ }
89
+ }
90
+
91
+ private itemFor(target: EventTarget | null): HTMLElement | null {
92
+ const item = (target as Element | null)?.closest<HTMLElement>('[role="treeitem"]');
93
+ return item && this.itemTargets.includes(item) ? item : null;
94
+ }
95
+
96
+ // A closing group is still drawn until its animation ends, but its rows are
97
+ // already out of reach of the keyboard.
98
+ private visibleItems(): HTMLElement[] {
99
+ return this.itemTargets.filter((item) => !item.closest('[role="group"][data-state="closed"]'));
100
+ }
101
+
102
+ private isFolder(item: HTMLElement) {
103
+ return item.hasAttribute('aria-expanded');
104
+ }
105
+
106
+ private isOpen(item: HTMLElement) {
107
+ return item.getAttribute('aria-expanded') === 'true';
108
+ }
109
+
110
+ private groupOf(item: HTMLElement): HTMLElement | null {
111
+ const id = item.getAttribute('aria-owns');
112
+ return id ? document.getElementById(id) : null;
113
+ }
114
+
115
+ private setOpen(item: HTMLElement, open: boolean) {
116
+ item.setAttribute('aria-expanded', String(open));
117
+ const group = this.groupOf(item);
118
+ if (!group) return;
119
+ group.dataset.state = open ? 'open' : 'closed';
120
+ this.animate(group, open);
121
+ }
122
+
123
+ // Grows or shrinks the group between nothing and its full height while its
124
+ // rows fade and settle into place. Clicked again part way, it turns round
125
+ // from wherever it has got to rather than starting over.
126
+ private animate(group: HTMLElement, open: boolean) {
127
+ const running = this.animations.get(group);
128
+ const from = group.hidden ? 0 : group.getBoundingClientRect().height;
129
+ const opacity = group.hidden ? 0 : Number(getComputedStyle(group).opacity);
130
+ running?.cancel();
131
+ group.hidden = false;
132
+ group.inert = !open;
133
+
134
+ if (this.reducedMotion.matches) {
135
+ group.hidden = !open;
136
+ return;
137
+ }
138
+
139
+ const to = open ? group.scrollHeight : 0;
140
+ const animation = group.animate(
141
+ [
142
+ { height: `${from}px`, opacity, transform: `translateY(${open && !running ? -6 : 0}px)` },
143
+ { height: `${to}px`, opacity: open ? 1 : 0, transform: `translateY(${open ? 0 : -4}px)` },
144
+ ],
145
+ { duration: open ? OPEN_MS : CLOSE_MS, easing: EASING },
146
+ );
147
+ group.style.overflow = 'hidden';
148
+ this.animations.set(group, animation);
149
+
150
+ animation.onfinish = () => {
151
+ this.animations.delete(group);
152
+ group.style.overflow = '';
153
+ group.inert = false;
154
+ if (!open) group.hidden = true;
155
+ };
156
+ }
157
+
158
+ private childrenOf(item: HTMLElement): HTMLElement[] {
159
+ const group = this.groupOf(item);
160
+ return group ? Array.from(group.querySelectorAll<HTMLElement>(':scope > li > [role="treeitem"]')) : [];
161
+ }
162
+
163
+ private parentOf(item: HTMLElement): HTMLElement | null {
164
+ const group = item.closest<HTMLElement>('[role="group"]');
165
+ return group?.parentElement?.querySelector<HTMLElement>(':scope > [role="treeitem"]') ?? null;
166
+ }
167
+
168
+ // The next visible row, after this one and round to the top, whose name
169
+ // starts with the letter typed.
170
+ private startingWith(visible: HTMLElement[], index: number, letter: string) {
171
+ const wanted = letter.toLocaleLowerCase();
172
+ for (let step = 1; step <= visible.length; step++) {
173
+ const candidate = visible[(index + step) % visible.length];
174
+ if (candidate?.dataset.name?.toLocaleLowerCase().startsWith(wanted)) return candidate;
175
+ }
176
+ return undefined;
177
+ }
178
+
179
+ private makeTabbable(item: HTMLElement) {
180
+ this.itemTargets.forEach((other) => (other.tabIndex = other === item ? 0 : -1));
181
+ }
182
+
183
+ private select(item: HTMLElement) {
184
+ this.itemTargets.forEach((other) => {
185
+ if (other.hasAttribute('aria-selected')) other.setAttribute('aria-selected', String(other === item));
186
+ });
187
+ this.dispatch('select', { detail: { value: item.dataset.value ?? '', name: item.dataset.name ?? '' } });
188
+ }
189
+ }
@@ -0,0 +1,117 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--rating"
4
+ //
5
+ // Each half-star is the label of a radio, and CSS fills the stars up to the
6
+ // checked one. Over a half-star, this lights that half and the ones before it,
7
+ // and grows the star it's in; leaving the stars, or choosing one, hands them
8
+ // back. It also gives the choice some feedback: a chosen star settles back to
9
+ // size, or pops when chosen from the keyboard. Choosing also clears the field's error, if it has one, and
10
+ // shows its thanks, if it has those, and writes the score beside the stars, if
11
+ // it's shown; resetting the form brings them back as they were (the score is an
12
+ // <output>, which the form resets itself).
13
+ export default class extends Controller<HTMLElement> {
14
+ static targets = ['star'];
15
+ static values = { error: String, thanks: String, score: String };
16
+
17
+ declare readonly starTargets: HTMLLabelElement[];
18
+ declare readonly errorValue: string;
19
+ declare readonly thanksValue: string;
20
+ declare readonly scoreValue: string;
21
+
22
+ // The star just chosen under the pointer, kept at its size until the
23
+ // pointer moves to another.
24
+ private settled: number | null = null;
25
+
26
+ preview(event: MouseEvent) {
27
+ const star = event.currentTarget as HTMLLabelElement;
28
+ if ((star.control as HTMLInputElement | null)?.disabled) return;
29
+
30
+ const value = Number(star.dataset.value);
31
+ this.starTargets.forEach((each) => {
32
+ each.dataset.lit = String(Number(each.dataset.value) <= value);
33
+ });
34
+
35
+ const whole = Math.ceil(value);
36
+ if (whole !== this.settled) this.settled = null;
37
+ this.hover(this.settled === null ? this.halvesOf(whole) : []);
38
+ }
39
+
40
+ reset() {
41
+ for (const star of this.starTargets) delete star.dataset.lit;
42
+ this.hover([]);
43
+ this.settled = null;
44
+ }
45
+
46
+ choose(event: Event) {
47
+ const input = event.target as HTMLInputElement;
48
+ const whole = Math.ceil(Number(input.value));
49
+ const halves = this.halvesOf(whole);
50
+
51
+ for (const star of this.starTargets) delete star.dataset.lit;
52
+
53
+ if (halves.some((half) => half.dataset.hovered)) {
54
+ this.hover([]);
55
+ this.settled = whole;
56
+ } else {
57
+ this.pop(halves);
58
+ }
59
+
60
+ this.showAnswered(true);
61
+
62
+ // The chosen star carries its score, "4.5/5". Its value, not its text,
63
+ // which is what the form's reset goes back to.
64
+ const score = this.scoreValue && (document.getElementById(this.scoreValue) as HTMLOutputElement | null);
65
+ if (score) score.value = input.labels?.[0]?.dataset.score ?? '';
66
+ }
67
+
68
+ // The form's reset puts the radios back; this puts back the rest.
69
+ formReset(event: Event) {
70
+ if (!(event.target as Node).contains(this.element)) return;
71
+
72
+ this.reset();
73
+ this.showAnswered(false);
74
+ }
75
+
76
+ // Answered, the error's hidden and gone from what the group says about
77
+ // itself, and the thanks, which are a status, are read out as they show.
78
+ private showAnswered(answered: boolean) {
79
+ const error = this.errorValue && document.getElementById(this.errorValue);
80
+ if (error) {
81
+ error.hidden = answered;
82
+ const group = this.element.closest('[role="radiogroup"]');
83
+ const others = (group?.getAttribute('aria-describedby') ?? '').split(' ').filter((id) => id && id !== this.errorValue);
84
+ const describedby = answered ? others : [...others, this.errorValue];
85
+ if (answered) group?.removeAttribute('aria-invalid');
86
+ else group?.setAttribute('aria-invalid', 'true');
87
+ if (describedby.length) group?.setAttribute('aria-describedby', describedby.join(' '));
88
+ else group?.removeAttribute('aria-describedby');
89
+ }
90
+
91
+ const thanks = this.thanksValue && document.getElementById(this.thanksValue);
92
+ if (thanks) thanks.hidden = !answered;
93
+ }
94
+
95
+ // Both half-star labels of a whole star.
96
+ private halvesOf(whole: number) {
97
+ return this.starTargets.filter((each) => Math.ceil(Number(each.dataset.value)) === whole);
98
+ }
99
+
100
+ private hover(halves: HTMLLabelElement[]) {
101
+ for (const star of this.starTargets) {
102
+ if (halves.includes(star)) star.dataset.hovered = 'true';
103
+ else delete star.dataset.hovered;
104
+ }
105
+ }
106
+
107
+ private pop(halves: HTMLLabelElement[]) {
108
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
109
+
110
+ for (const half of halves) {
111
+ half.animate([1, 1.25, 1].map((scale) => ({ transform: `scale(${scale})` })), {
112
+ duration: 250,
113
+ easing: 'ease-out',
114
+ });
115
+ }
116
+ }
117
+ }