velvetkit 0.5.1 → 0.6.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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -0
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/carousel.html.erb +9 -4
  5. data/registry/app/components/ui/carousel.rb +42 -1
  6. data/registry/app/components/ui/file_tree/file_item.html.erb +9 -0
  7. data/registry/app/components/ui/file_tree/file_item.rb +50 -0
  8. data/registry/app/components/ui/file_tree/folder.html.erb +9 -0
  9. data/registry/app/components/ui/file_tree/folder.rb +76 -0
  10. data/registry/app/components/ui/file_tree.html.erb +1 -0
  11. data/registry/app/components/ui/file_tree.rb +93 -0
  12. data/registry/app/components/ui/rating.html.erb +16 -0
  13. data/registry/app/components/ui/rating.rb +200 -0
  14. data/registry/app/components/ui/sidebar/menu_button.html.erb +10 -1
  15. data/registry/app/components/ui/sidebar/menu_button.rb +44 -6
  16. data/registry/app/components/ui/sidebar/menu_item.rb +4 -3
  17. data/registry/app/components/ui/sidebar/wrapper.html.erb +1 -1
  18. data/registry/app/components/ui/sidebar/wrapper.rb +45 -7
  19. data/registry/app/components/ui/sidebar.html.erb +10 -1
  20. data/registry/app/components/ui/sidebar.rb +60 -4
  21. data/registry/app/javascript/controllers/ui/carousel_controller.ts +59 -1
  22. data/registry/app/javascript/controllers/ui/file_tree_controller.ts +189 -0
  23. data/registry/app/javascript/controllers/ui/rating_controller.ts +117 -0
  24. data/registry/app/javascript/controllers/ui/sidebar_controller.ts +17 -0
  25. data/registry/app/javascript/controllers/ui/tooltip_controller.ts +3 -0
  26. data/registry/components.yml +4 -0
  27. data/registry/config/locales/velvetkit.en.yml +13 -0
  28. data/registry/test/components/previews/ui/carousel_preview/with_indicators.html.erb +10 -0
  29. data/registry/test/components/previews/ui/carousel_preview.rb +7 -3
  30. data/registry/test/components/previews/ui/file_tree_preview/changes.html.erb +13 -0
  31. data/registry/test/components/previews/ui/file_tree_preview/from_data.html.erb +14 -0
  32. data/registry/test/components/previews/ui/file_tree_preview/picking_a_file.html.erb +25 -0
  33. data/registry/test/components/previews/ui/file_tree_preview/without_guides.html.erb +10 -0
  34. data/registry/test/components/previews/ui/file_tree_preview.rb +41 -0
  35. data/registry/test/components/previews/ui/image_preview/radii.html.erb +3 -3
  36. data/registry/test/components/previews/ui/image_preview/sizing.html.erb +9 -4
  37. data/registry/test/components/previews/ui/image_preview.rb +14 -1
  38. data/registry/test/components/previews/ui/rating_preview/in_form.html.erb +6 -0
  39. data/registry/test/components/previews/ui/rating_preview/model_errors.html.erb +20 -0
  40. data/registry/test/components/previews/ui/rating_preview/playground.html.erb +5 -0
  41. data/registry/test/components/previews/ui/rating_preview/scores.html.erb +18 -0
  42. data/registry/test/components/previews/ui/rating_preview/sizes.html.erb +6 -0
  43. data/registry/test/components/previews/ui/rating_preview.rb +28 -0
  44. data/registry/test/components/previews/ui/sidebar_preview/_top_bar.html.erb +19 -0
  45. data/registry/test/components/previews/ui/sidebar_preview/icon_rail.html.erb +81 -0
  46. data/registry/test/components/previews/ui/sidebar_preview/site_header.html.erb +52 -0
  47. data/registry/test/components/previews/ui/sidebar_preview.rb +23 -0
  48. data/registry/test/components/ui/carousel_test.rb +48 -0
  49. data/registry/test/components/ui/file_tree_test.rb +187 -0
  50. data/registry/test/components/ui/rating_test.rb +271 -0
  51. data/registry/test/components/ui/sidebar/menu_button_test.rb +49 -0
  52. data/registry/test/components/ui/sidebar/wrapper_test.rb +30 -0
  53. data/registry/test/components/ui/sidebar_test.rb +50 -0
  54. metadata +28 -1
@@ -4,17 +4,37 @@
4
4
  # readers too (aria-current="page").
5
5
  #
6
6
  # `shape:` is :default, a compact row with a bar at the sidebar's edge for the
7
- # current page, or :pill, a taller row whose current page is filled in edge to
8
- # edge, rounded at both ends.
7
+ # current page; :block, a taller row whose current page is filled in as a
8
+ # rounded block, with no bar; :pill, the same filled in edge to edge and
9
+ # rounded at both ends; or :icon, the icon alone in a square, filled in
10
+ # for the current page, for a rail of sections (`nested: :rail` on UI::Sidebar).
11
+ # An :icon button's text stays for screen readers, and shows as a tooltip.
12
+ #
13
+ # `section:` in place of a path makes it a button that shows that section's
14
+ # panel (`nested: :panel, section:` on UI::Sidebar) beside the rail, at once,
15
+ # with no page to load:
16
+ #
17
+ # <% item.with_menu_button(section: "projects", shape: :icon, active: true) do %>
18
+ # <%= render(UI::Icon.new(name: "folder-kanban")) %><span>Projects</span>
19
+ # <% end %>
20
+ #
21
+ # `tooltip:` gives any shape a tooltip; an :icon button takes it from its text
22
+ # when left out.
9
23
  class UI::Sidebar::MenuButton < UI::Base
10
24
  SHAPES = {
11
25
  default: "h-8 rounded-md p-2 data-[active=true]:bg-sidebar-primary/10",
12
- pill: "h-10 gap-3 rounded-full px-4 data-[active=true]:bg-sidebar-primary/15 group-data-[collapsible=icon]:rounded-full!"
26
+ block: "h-9 gap-3 rounded-lg px-3 data-[active=true]:bg-sidebar-primary/15",
27
+ pill: "h-10 gap-3 rounded-full px-4 data-[active=true]:bg-sidebar-primary/15 group-data-[collapsible=icon]:rounded-full!",
28
+ icon: "size-8 shrink-0 justify-center rounded-md p-0 data-[active=true]:bg-sidebar-primary/15 [&>span]:sr-only"
13
29
  }.freeze
14
30
 
15
- def initialize(path, active: false, current: nil, shape: :default, icon: nil, **system_args) # rubocop:disable Lint/UnusedMethodArgument
31
+ # rubocop:disable Lint/UnusedMethodArgument
32
+ def initialize(path = nil, active: false, current: nil, shape: :default, section: nil, tooltip: nil, icon: nil, **system_args)
33
+ # rubocop:enable Lint/UnusedMethodArgument
16
34
  @path = path
35
+ @section = section&.to_s
17
36
  @is_active = active
37
+ @tooltip = tooltip
18
38
  @shape = SHAPES.key?(shape.to_sym) ? shape.to_sym : :default
19
39
  @system_args = system_args
20
40
 
@@ -24,9 +44,18 @@ class UI::Sidebar::MenuButton < UI::Base
24
44
  @system_args[:data][:active] = @is_active.to_s
25
45
  @system_args[:data][:shape] = @shape
26
46
 
27
- # An explicit `current:` always wins; an active button falls back to "page"
47
+ if section?
48
+ # Opens its panel, and says which one and whether it's showing.
49
+ @system_args[:type] = "button"
50
+ @system_args[:data][:section] = @section
51
+ @system_args[:data][:action] = "ui--sidebar#showSection"
52
+ @system_args[:data][:"ui--sidebar-section-param"] = @section
53
+ @system_args[:aria] = (@system_args[:aria] || {}).merge(controls: UI::Sidebar.section_id(@section), expanded: @is_active.to_s)
54
+ end
55
+
56
+ # An explicit `current:` always wins; an active link falls back to "page"
28
57
  # so assistive tech announces it without the caller repeating themselves.
29
- aria_current = current || ("page" if @is_active)
58
+ aria_current = current || ("page" if @is_active && !section?)
30
59
  if aria_current
31
60
  @system_args[:aria] = (@system_args[:aria] || {}).merge(current: aria_current)
32
61
  end
@@ -42,4 +71,13 @@ class UI::Sidebar::MenuButton < UI::Base
42
71
  @system_args[:class]
43
72
  )
44
73
  end
74
+
75
+ def section? = @section.present?
76
+
77
+ # An :icon button's tooltip is its own text unless told otherwise.
78
+ def tooltip_text
79
+ return @tooltip if @tooltip.present?
80
+
81
+ Nokogiri::HTML5.fragment(content.to_s).text.squish.presence if @shape == :icon
82
+ end
45
83
  end
@@ -20,11 +20,12 @@ class UI::Sidebar::MenuItem < UI::Base
20
20
  @system_args[:class] = class_names(
21
21
  "group/menu-item relative",
22
22
  # Active indicator: a primary bar flush with the sidebar edge, for the
23
- # default shape only; a pill is filled in instead.
23
+ # default shape only; a block, a pill or an icon is filled in instead. Not a direct
24
+ # child: a button with a tooltip sits inside the tooltip.
24
25
  "before:absolute before:-start-2 before:top-4 before:h-6 before:w-1 " \
25
26
  "before:-translate-y-1/2 before:rounded-e-full before:bg-sidebar-primary " \
26
27
  "before:opacity-0 before:transition-opacity " \
27
- "has-[>[data-active=true][data-shape=default]]:before:opacity-100",
28
+ "has-[[data-active=true][data-shape=default]]:before:opacity-100",
28
29
  @system_args[:class]
29
30
  )
30
31
  end
@@ -43,7 +44,7 @@ class UI::Sidebar::MenuItem < UI::Base
43
44
  label: t("ui.sidebar.toggle_sub", name: sub_menu.name, default: "Show the links under %{name}") },
44
45
  class: "absolute end-1 top-1 flex size-6 items-center justify-center rounded-md text-sidebar-foreground/70 outline-hidden " \
45
46
  "ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus:ring-2 " \
46
- "group-data-[collapsible=icon]:hidden group-has-[>[data-shape=pill]]/menu-item:top-2 " \
47
+ "group-data-[collapsible=icon]:hidden group-has-[[data-shape=pill]]/menu-item:top-2 " \
47
48
  "[&[aria-expanded=true]>svg]:rotate-90 [&>svg]:transition-transform motion-reduce:[&>svg]:transition-none" }
48
49
  end
49
50
  end
@@ -1 +1 @@
1
- <%= tag.div(**@system_args) do %><%= content %><% end %>
1
+ <%= tag.div(**@system_args) do %><% if header? %><%= header %><div data-slot="sidebar-wrapper-body" class="flex min-h-0 w-full flex-1"><%= content %></div><% else %><%= content %><% end %><% end %>
@@ -1,9 +1,31 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # Holds the sidebar and the page beside it, and the Stimulus controller that
4
+ # collapses and opens it.
5
+ #
6
+ # Two layouts:
7
+ #
8
+ # - Without a `header`, the sidebar runs the full height of the window and the
9
+ # page's own header goes at the top of `UI::Sidebar::Inset`.
10
+ # - With one, the header stretches across the top, sidebar and page below it:
11
+ #
12
+ # <%= render(UI::Sidebar::Wrapper.new(header_height: "3.5rem")) do |wrapper| %>
13
+ # <% wrapper.with_header(class: "gap-2 px-4") do %>…logo, search, avatar…<% end %>
14
+ # <%= render(UI::Sidebar.new(id: "app-sidebar")) do |sidebar| %>…<% end %>
15
+ # <%= render(UI::Sidebar::Inset.new) do %>…<% end %>
16
+ # <% end %>
17
+ #
18
+ # The header sticks to the top, and the sidebar sticks just under it, as tall
19
+ # as what's left of the window. `header_height:` is the one place that height
20
+ # is written; it's `--header-height` to anything inside.
21
+ #
22
+ # `sidebar_width:` widens the sidebar, say for an icon rail with a second
23
+ # sidebar beside it (see `nested:` on UI::Sidebar).
3
24
  class UI::Sidebar::Wrapper < UI::Base
4
25
  SIDEBAR_WIDTH = "16rem"
5
26
  SIDEBAR_WIDTH_MOBILE = "18rem"
6
27
  SIDEBAR_WIDTH_ICON = "3rem"
28
+ HEADER_HEIGHT = "3.5rem"
7
29
 
8
30
  # Written out in full so Tailwind's source scanner can see each class literally;
9
31
  # an interpolated "min-h-#{...}" is invisible to it and never gets generated.
@@ -16,23 +38,39 @@ class UI::Sidebar::Wrapper < UI::Base
16
38
  none: nil
17
39
  }.freeze
18
40
 
19
- def initialize(min_height: :svh, **system_args)
41
+ renders_one :header, lambda { |**system_args, &block|
42
+ system_args[:data] = (system_args[:data] || {}).merge(slot: "sidebar-wrapper-header")
43
+ # The sidebar's surface and border, so header and sidebar read as one
44
+ # frame around the page, in a dark theme as much as a light one.
45
+ system_args[:class] = cn(
46
+ "bg-sidebar text-sidebar-foreground border-sidebar-border sticky top-0 z-20 flex h-(--header-height) w-full shrink-0 items-center border-b",
47
+ system_args[:class]
48
+ )
49
+ content_tag(:header, **system_args, &block)
50
+ }
51
+
52
+ def initialize(min_height: :svh, header_height: HEADER_HEIGHT, sidebar_width: SIDEBAR_WIDTH, **system_args)
20
53
  unless MIN_HEIGHTS.key?(min_height)
21
54
  raise ArgumentError, "min_height must be one of #{MIN_HEIGHTS.keys.join(', ')} (got #{min_height.inspect})"
22
55
  end
23
56
 
24
57
  @min_height = min_height
58
+ @header_height = header_height
59
+ @sidebar_width = sidebar_width
25
60
  @system_args = system_args
61
+ end
26
62
 
27
- @system_args[:data] ||= {}
28
- @system_args[:data][:slot] = "sidebar-wrapper"
29
- @system_args[:data][:controller] = "ui--sidebar"
63
+ def before_render
64
+ @system_args[:data] = (@system_args[:data] || {}).merge(slot: "sidebar-wrapper", controller: "ui--sidebar")
30
65
 
31
- @system_args[:style] ||= {}
32
- @system_args[:style] = "--sidebar-width: #{SIDEBAR_WIDTH}; --sidebar-width-mobile: #{SIDEBAR_WIDTH_MOBILE}; --sidebar-width-icon: #{SIDEBAR_WIDTH_ICON}"
66
+ # Without a header there's nothing above the sidebar, so its offset is 0.
67
+ vars = "--sidebar-width: #{@sidebar_width}; --sidebar-width-mobile: #{SIDEBAR_WIDTH_MOBILE}; " \
68
+ "--sidebar-width-icon: #{SIDEBAR_WIDTH_ICON}; --header-height: #{header? ? @header_height : '0px'}"
69
+ @system_args[:style] = [ vars, @system_args[:style] ].compact.join("; ")
33
70
 
34
- @system_args[:class] = class_names(
71
+ @system_args[:class] = cn(
35
72
  "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex w-full",
73
+ ("flex-col" if header?),
36
74
  MIN_HEIGHTS[@min_height],
37
75
  @system_args[:class]
38
76
  )
@@ -1,7 +1,15 @@
1
+ <% if nested? %>
2
+ <%= tag.div(**@system_args) do %>
3
+ <%= sidebar_header if sidebar_header %>
4
+ <%= sidebar_content if sidebar_content %>
5
+ <%= sidebar_footer if sidebar_footer %>
6
+ <%= content %>
7
+ <% end %>
8
+ <% else %>
1
9
  <%= tag.aside(**@system_args) do %>
2
10
  <div data-slot="sidebar-backdrop" aria-hidden="true" class="<%= backdrop_classes %>" data-action="click->ui--sidebar#close"></div>
3
11
  <div data-slot="sidebar-container" class="<%= container_classes %>" data-ui--sidebar-target="container" data-action="click->ui--sidebar#navigate">
4
- <div data-sidebar="sidebar" data-slot="sidebar-inner" class="bg-sidebar flex h-full w-full flex-col overflow-hidden shadow-xl md:shadow-none group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border md:group-data-[variant=floating]:shadow-sm">
12
+ <div data-sidebar="sidebar" data-slot="sidebar-inner" class="bg-sidebar flex h-full w-full flex-col has-[>[data-nested]]:flex-row overflow-hidden shadow-xl md:shadow-none group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border md:group-data-[variant=floating]:shadow-sm">
5
13
  <%= sidebar_header if sidebar_header %>
6
14
  <%= sidebar_content if sidebar_content %>
7
15
  <%= sidebar_footer if sidebar_footer %>
@@ -9,3 +17,4 @@
9
17
  </div>
10
18
  </div>
11
19
  <% end %>
20
+ <% end %>
@@ -31,17 +31,47 @@
31
31
  # link closes it.
32
32
  #
33
33
  # The sidebar sticks to the top of the window and is as tall as it, or as the
34
- # wrapper when that's shorter, so a bar above the app doesn't push its footer
35
- # out of sight: give the wrapper a height (`class: "h-[calc(100svh-3rem)]"`).
34
+ # wrapper when that's shorter. Under a wrapper's `header` it sticks just below
35
+ # the header instead, as tall as what's left (see UI::Sidebar::Wrapper).
36
+ #
37
+ # An icon rail with a second sidebar beside it, the rail switching between
38
+ # sections and the second listing the pages of the current one, is two
39
+ # `nested:` sidebars inside an outer one:
40
+ #
41
+ # <%= render(UI::Sidebar::Wrapper.new(sidebar_width: "20rem")) do %>
42
+ # <%= render(UI::Sidebar.new(id: "app-sidebar", collapsible: :icon)) do %>
43
+ # <%= render(UI::Sidebar.new(nested: :rail)) do |rail| %>
44
+ # …menu buttons with `shape: :icon, section: "projects"`…
45
+ # <% end %>
46
+ # <%= render(UI::Sidebar.new(nested: :panel, section: "projects", active: true)) do |panel| %>…<% end %>
47
+ # <%= render(UI::Sidebar.new(nested: :panel, section: "inbox")) do |panel| %>…<% end %>
48
+ # <% end %>
49
+ # <%= render(UI::Sidebar::Inset.new) do %>…<% end %>
50
+ # <% end %>
51
+ #
52
+ # A panel for each section, the `active:` one showing; a rail button with
53
+ # `section:` shows its panel in the browser, no page to load, and opens the
54
+ # sidebar first if it was collapsed. One panel with no `section:` is the
55
+ # same, without the switching: its links are the pages of the section the
56
+ # server says you're in.
57
+ #
58
+ # The outer one is the drawer on a phone, and what collapses: to the rail with
59
+ # `collapsible: :icon`, the panel hidden. A nested sidebar is a plain column
60
+ # with the same header, content and footer slots.
36
61
  class UI::Sidebar < UI::Base
37
62
  COLLAPSIBLE = %i[icon offcanvas none].freeze
38
63
  STATES = %i[expanded collapsed].freeze
64
+ NESTED = %i[rail panel].freeze
39
65
 
40
66
  renders_one :sidebar_header, UI::Sidebar::Header
41
67
  renders_one :sidebar_content, UI::Sidebar::Content
42
68
  renders_one :sidebar_footer, UI::Sidebar::Footer
43
69
 
44
- def initialize(collapsible: :icon, variant: :sidebar, side: :left, state: nil, **system_args)
70
+ def initialize(collapsible: :icon, variant: :sidebar, side: :left, state: nil, nested: nil, section: nil, active: false,
71
+ **system_args)
72
+ @nested = NESTED.include?(nested&.to_sym) ? nested.to_sym : nil
73
+ @section = section&.to_s.presence
74
+ @active = active
45
75
  @collapsible = COLLAPSIBLE.include?(collapsible.to_sym) ? collapsible.to_sym : :icon
46
76
  @variant = variant
47
77
  @side = side
@@ -52,7 +82,14 @@ class UI::Sidebar < UI::Base
52
82
  # The cookie the controller writes the reader's choice to, one per sidebar.
53
83
  def self.cookie_name(id) = "ui_sidebar_#{id.presence || 'state'}".tr("-", "_")
54
84
 
85
+ # The id of a section's panel, which its rail button points aria-controls at.
86
+ def self.section_id(section) = "sidebar-section-#{section}".parameterize
87
+
88
+ def nested? = !@nested.nil?
89
+
55
90
  def before_render
91
+ return nested_before_render if nested?
92
+
56
93
  @system_args[:data] = (@system_args[:data] || {}).merge(
57
94
  slot: "sidebar", variant: @variant, side: @side, state: state,
58
95
  # What the sidebar is doing now: "icon" or "offcanvas" while collapsed,
@@ -72,6 +109,23 @@ class UI::Sidebar < UI::Base
72
109
  )
73
110
  end
74
111
 
112
+ # A column inside the outer sidebar. The rail is as wide as the collapsed
113
+ # sidebar, so it's all that's left showing once that collapses; the panel
114
+ # takes the rest of the width and hides then, out of the tab order too.
115
+ def nested_before_render
116
+ @system_args[:data] = (@system_args[:data] || {}).merge(slot: "sidebar", nested: @nested)
117
+ if @section
118
+ @system_args[:id] ||= self.class.section_id(@section)
119
+ @system_args[:data][:section] = @section
120
+ @system_args[:hidden] = true unless @active
121
+ end
122
+ @system_args[:class] = cn(
123
+ "bg-sidebar text-sidebar-foreground flex h-full min-h-0 flex-col overflow-hidden",
124
+ (@nested == :rail ? "w-(--sidebar-width-icon) shrink-0 border-e border-sidebar-border" : "min-w-0 flex-1 md:group-data-[collapsible=icon]:hidden"),
125
+ @system_args[:class]
126
+ )
127
+ end
128
+
75
129
  def state
76
130
  return :collapsed if @collapsible != :none && @state == :collapsed
77
131
  return :expanded if @state || @collapsible == :none
@@ -89,7 +143,9 @@ class UI::Sidebar < UI::Base
89
143
  "-translate-x-full rtl:translate-x-full group-data-[side=right]:start-auto group-data-[side=right]:end-0",
90
144
  "group-data-[side=right]:translate-x-full transition-[translate,visibility] duration-200 ease-out",
91
145
  "group-data-[mobile=open]:visible group-data-[mobile=open]:translate-x-0 motion-reduce:transition-none",
92
- "md:visible md:sticky md:top-0 md:z-10 md:h-svh md:max-h-full md:w-(--sidebar-width) md:translate-x-0",
146
+ # Below the wrapper's header, when there is one; --header-height is 0 otherwise.
147
+ "md:visible md:sticky md:top-(--header-height) md:z-10 md:h-[calc(100svh-var(--header-height))] md:max-h-full",
148
+ "md:w-(--sidebar-width) md:translate-x-0",
93
149
  "md:transition-[width,translate] md:group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
94
150
  "md:group-data-[variant=floating]:group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+1rem)]",
95
151
  "md:group-data-[variant=inset]:group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+1rem)]",
@@ -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
+ }