velvetkit 0.4.2 → 0.5.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +149 -2
  3. data/lib/velvetkit/version.rb +1 -1
  4. data/registry/app/components/ui/carousel.html.erb +7 -0
  5. data/registry/app/components/ui/carousel.rb +60 -0
  6. data/registry/app/components/ui/chart.html.erb +3 -3
  7. data/registry/app/components/ui/chart.rb +18 -10
  8. data/registry/app/components/ui/checkbox.html.erb +6 -0
  9. data/registry/app/components/ui/checkbox.rb +9 -2
  10. data/registry/app/components/ui/fieldset.html.erb +6 -0
  11. data/registry/app/components/ui/fieldset.rb +76 -0
  12. data/registry/app/components/ui/gallery/image.rb +14 -1
  13. data/registry/app/components/ui/gallery.html.erb +32 -3
  14. data/registry/app/components/ui/gallery.rb +44 -5
  15. data/registry/app/components/ui/radio_group/item.html.erb +1 -1
  16. data/registry/app/components/ui/radio_group/item.rb +4 -0
  17. data/registry/app/components/ui/radio_group.html.erb +1 -1
  18. data/registry/app/components/ui/radio_group.rb +42 -2
  19. data/registry/app/components/ui/scrubber.html.erb +18 -0
  20. data/registry/app/components/ui/scrubber.rb +62 -0
  21. data/registry/app/components/ui/select.html.erb +1 -1
  22. data/registry/app/components/ui/select.rb +16 -1
  23. data/registry/app/components/ui/selection_bar.html.erb +7 -0
  24. data/registry/app/components/ui/selection_bar.rb +75 -0
  25. data/registry/app/components/ui/sidebar/inset.rb +5 -2
  26. data/registry/app/components/ui/sidebar/menu_button.rb +24 -9
  27. data/registry/app/components/ui/sidebar/menu_item.html.erb +1 -1
  28. data/registry/app/components/ui/sidebar/menu_item.rb +31 -5
  29. data/registry/app/components/ui/sidebar/menu_sub.rb +59 -0
  30. data/registry/app/components/ui/sidebar.html.erb +3 -3
  31. data/registry/app/components/ui/sidebar.rb +91 -13
  32. data/registry/app/components/ui/table/column.html.erb +1 -1
  33. data/registry/app/components/ui/table/column.rb +26 -2
  34. data/registry/app/components/ui/table/head.html.erb +1 -1
  35. data/registry/app/components/ui/table/head.rb +15 -2
  36. data/registry/app/components/ui/table/row.html.erb +1 -1
  37. data/registry/app/components/ui/table/row.rb +19 -5
  38. data/registry/app/components/ui/table.html.erb +2 -2
  39. data/registry/app/components/ui/table.rb +29 -4
  40. data/registry/app/components/ui/toggle_group.html.erb +1 -1
  41. data/registry/app/components/ui/toggle_group.rb +26 -3
  42. data/registry/app/javascript/controllers/ui/carousel_controller.ts +63 -0
  43. data/registry/app/javascript/controllers/ui/file_field_controller.ts +1 -1
  44. data/registry/app/javascript/controllers/ui/gallery_controller.ts +52 -14
  45. data/registry/app/javascript/controllers/ui/scrubber_controller.ts +188 -0
  46. data/registry/app/javascript/controllers/ui/selection_bar_controller.ts +122 -0
  47. data/registry/app/javascript/controllers/ui/sidebar_controller.ts +102 -32
  48. data/registry/components.yml +11 -3
  49. data/registry/config/locales/velvetkit.en.yml +16 -0
  50. data/registry/icons/lucide/arrow-down.svg +16 -0
  51. data/registry/icons/lucide/arrow-up.svg +16 -0
  52. data/registry/icons/lucide/image.svg +17 -0
  53. data/registry/icons/lucide/star.svg +15 -0
  54. data/registry/icons/phosphor/arrow-down.svg +2 -0
  55. data/registry/icons/phosphor/arrow-up.svg +2 -0
  56. data/registry/icons/phosphor/image.svg +2 -0
  57. data/registry/icons/phosphor/star.svg +2 -0
  58. data/registry/icons/tabler/arrow-down.svg +18 -0
  59. data/registry/icons/tabler/arrow-up.svg +18 -0
  60. data/registry/icons/tabler/photo.svg +19 -0
  61. data/registry/icons/tabler/star.svg +16 -0
  62. data/registry/icons.yml +4 -0
  63. data/registry/test/components/previews/ui/carousel_preview/highlights.html.erb +17 -0
  64. data/registry/test/components/previews/ui/carousel_preview.rb +22 -0
  65. data/registry/test/components/previews/ui/chart_preview/whole_dollars.html.erb +19 -0
  66. data/registry/test/components/previews/ui/chart_preview.rb +7 -1
  67. data/registry/test/components/previews/ui/checkbox_preview/in_form.html.erb +2 -3
  68. data/registry/test/components/previews/ui/fieldset_preview/block_of_fields.html.erb +18 -0
  69. data/registry/test/components/previews/ui/fieldset_preview/groups.html.erb +14 -0
  70. data/registry/test/components/previews/ui/fieldset_preview/model_errors.html.erb +22 -0
  71. data/registry/test/components/previews/ui/fieldset_preview/playground.html.erb +5 -0
  72. data/registry/test/components/previews/ui/fieldset_preview.rb +24 -0
  73. data/registry/test/components/previews/ui/gallery_preview/grid.html.erb +25 -0
  74. data/registry/test/components/previews/ui/gallery_preview.rb +3 -0
  75. data/registry/test/components/previews/ui/scrubber_preview/default.html.erb +24 -0
  76. data/registry/test/components/previews/ui/scrubber_preview.rb +6 -0
  77. data/registry/test/components/previews/ui/selection_bar_preview/floating.html.erb +16 -0
  78. data/registry/test/components/previews/ui/selection_bar_preview/table.html.erb +26 -0
  79. data/registry/test/components/previews/ui/selection_bar_preview.rb +9 -0
  80. data/registry/test/components/previews/ui/sidebar_preview/_shell.html.erb +5 -4
  81. data/registry/test/components/previews/ui/sidebar_preview/pill_links.html.erb +52 -0
  82. data/registry/test/components/previews/ui/sidebar_preview.rb +3 -0
  83. data/registry/test/components/previews/ui/table_preview/selectable.html.erb +26 -0
  84. data/registry/test/components/previews/ui/table_preview/sortable.html.erb +20 -0
  85. data/registry/test/components/previews/ui/table_preview/sticky_header.html.erb +13 -0
  86. data/registry/test/components/previews/ui/table_preview.rb +9 -0
  87. data/registry/test/components/ui/base_test.rb +27 -0
  88. data/registry/test/components/ui/carousel_test.rb +38 -0
  89. data/registry/test/components/ui/chart_test.rb +20 -0
  90. data/registry/test/components/ui/checkbox_test.rb +11 -2
  91. data/registry/test/components/ui/confirm_dialog_test.rb +3 -0
  92. data/registry/test/components/ui/fieldset_test.rb +119 -0
  93. data/registry/test/components/ui/gallery_test.rb +36 -1
  94. data/registry/test/components/ui/radio_group_test.rb +106 -0
  95. data/registry/test/components/ui/scrubber_test.rb +43 -0
  96. data/registry/test/components/ui/select_test.rb +21 -0
  97. data/registry/test/components/ui/selection_bar_test.rb +46 -0
  98. data/registry/test/components/ui/sidebar/menu_button_test.rb +9 -0
  99. data/registry/test/components/ui/sidebar_test.rb +79 -1
  100. data/registry/test/components/ui/toggle_group_test.rb +45 -0
  101. metadata +47 -1
@@ -1,29 +1,107 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ # An app's sidebar: a header, groups of links, and a footer, beside the page's
4
+ # content (`UI::Sidebar::Inset`), both inside a `UI::Sidebar::Wrapper`.
5
+ #
6
+ # <%= render(UI::Sidebar::Wrapper.new) do %>
7
+ # <%= render(UI::Sidebar.new(id: "app-sidebar", collapsible: :icon)) do |sidebar| %>
8
+ # <% sidebar.with_sidebar_content do |content| %>
9
+ # <% content.with_sidebar_group do |group| %>
10
+ # <% group.with_menu do |menu| %>
11
+ # <% menu.with_menu_item do |item| %>
12
+ # <% item.with_menu_button(photos_path, active: true, shape: :pill) do %>…<% end %>
13
+ # <% end %>
14
+ # <% end %>
15
+ # <% end %>
16
+ # <% end %>
17
+ # <% end %>
18
+ # <%= render(UI::Sidebar::Inset.new) do %>
19
+ # <%= render(UI::Sidebar::Trigger.new(sidebar_id: "app-sidebar")) %> …
20
+ # <% end %>
21
+ # <% end %>
22
+ #
23
+ # `collapsible:` says what the trigger does on a wide screen: :icon shrinks the
24
+ # sidebar to its icons, :offcanvas slides it away, and :none keeps it open.
25
+ # `state:` is whether it starts :expanded or :collapsed. Left out, it's what the
26
+ # reader last chose, kept in a cookie so the page is drawn that way from the
27
+ # start rather than changing once it loads.
28
+ #
29
+ # On a phone the sidebar is a drawer over the page, closed until the trigger
30
+ # opens it, whatever `collapsible:` says. Escape, the backdrop, or following a
31
+ # link closes it.
32
+ #
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)]"`).
3
36
  class UI::Sidebar < UI::Base
37
+ COLLAPSIBLE = %i[icon offcanvas none].freeze
38
+ STATES = %i[expanded collapsed].freeze
39
+
4
40
  renders_one :sidebar_header, UI::Sidebar::Header
5
41
  renders_one :sidebar_content, UI::Sidebar::Content
6
42
  renders_one :sidebar_footer, UI::Sidebar::Footer
7
43
 
8
- def initialize(collapsible: :none, variant: :sidebar, side: :left, state: :expanded, **system_args)
9
- @collapsible = collapsible
44
+ def initialize(collapsible: :icon, variant: :sidebar, side: :left, state: nil, **system_args)
45
+ @collapsible = COLLAPSIBLE.include?(collapsible.to_sym) ? collapsible.to_sym : :icon
10
46
  @variant = variant
11
47
  @side = side
12
- @state = state
48
+ @state = state&.to_sym
13
49
  @system_args = system_args
50
+ end
14
51
 
15
- @system_args[:data] ||= {}
16
- @system_args[:data][:slot] = "sidebar"
17
- @system_args[:data][:variant] = @variant
18
- @system_args[:data][:collapsible] = @collapsible
19
- @system_args[:data][:side] = @side
20
- @system_args[:data][:state] = @state
21
- @system_args[:data]["ui--sidebar-target"] = "sidebar"
22
-
52
+ # The cookie the controller writes the reader's choice to, one per sidebar.
53
+ def self.cookie_name(id) = "ui_sidebar_#{id.presence || 'state'}".tr("-", "_")
23
54
 
24
- @system_args[:class] = class_names(
25
- "group peer text-sidebar-foreground md:block",
55
+ def before_render
56
+ @system_args[:data] = (@system_args[:data] || {}).merge(
57
+ slot: "sidebar", variant: @variant, side: @side, state: state,
58
+ # What the sidebar is doing now: "icon" or "offcanvas" while collapsed,
59
+ # empty while open. The styles hang off this.
60
+ collapsible: (state == :collapsed ? @collapsible : ""),
61
+ collapsible_mode: @collapsible,
62
+ "ui--sidebar-target": "sidebar",
63
+ cookie: self.class.cookie_name(@system_args[:id])
64
+ )
65
+ @system_args[:class] = cn(
66
+ "group peer shrink-0 text-sidebar-foreground w-0 md:w-(--sidebar-width) md:transition-[width] md:duration-200 md:ease-linear",
67
+ "md:data-[collapsible=icon]:w-(--sidebar-width-icon) md:data-[collapsible=offcanvas]:w-0 data-[side=right]:order-last",
68
+ # The floating and inset sidebars pad their panel, so their icons need that much more room.
69
+ "md:data-[variant=floating]:data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+1rem)]",
70
+ "md:data-[variant=inset]:data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+1rem)]",
26
71
  @system_args[:class]
27
72
  )
28
73
  end
74
+
75
+ def state
76
+ return :collapsed if @collapsible != :none && @state == :collapsed
77
+ return :expanded if @state || @collapsible == :none
78
+
79
+ saved = helpers.request&.cookies&.[](self.class.cookie_name(@system_args[:id]))
80
+ saved == "collapsed" ? :collapsed : :expanded
81
+ rescue NoMethodError
82
+ :expanded
83
+ end
84
+
85
+ # A drawer on a phone, beside the content from `md` up.
86
+ def container_classes
87
+ cn(
88
+ "fixed inset-y-0 start-0 z-50 flex w-(--sidebar-width-mobile) max-w-[85vw] invisible",
89
+ "-translate-x-full rtl:translate-x-full group-data-[side=right]:start-auto group-data-[side=right]:end-0",
90
+ "group-data-[side=right]:translate-x-full transition-[translate,visibility] duration-200 ease-out",
91
+ "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",
93
+ "md:transition-[width,translate] md:group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
94
+ "md:group-data-[variant=floating]:group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+1rem)]",
95
+ "md:group-data-[variant=inset]:group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+1rem)]",
96
+ "md:group-data-[collapsible=offcanvas]:-translate-x-full md:group-data-[collapsible=offcanvas]:invisible!",
97
+ "md:group-data-[side=left]:border-e md:group-data-[side=right]:border-s",
98
+ "md:group-data-[variant=floating]:border-0 md:group-data-[variant=inset]:border-0",
99
+ "md:group-data-[variant=floating]:p-2 md:group-data-[variant=inset]:p-2"
100
+ )
101
+ end
102
+
103
+ def backdrop_classes
104
+ "fixed inset-0 z-40 bg-black/50 invisible opacity-0 transition-[opacity,visibility] duration-200 " \
105
+ "group-data-[mobile=open]:visible group-data-[mobile=open]:opacity-100 motion-reduce:transition-none md:hidden"
106
+ end
29
107
  end
@@ -1 +1 @@
1
- <%= tag.th scope: "col", class: classes, **@html_attrs do %><%= content %><% end %>
1
+ <%= tag.th(**th_attrs) do %><% if sortable? %><%= link_to @sort_href, class: link_classes do %><span><%= content %></span><%= render(UI::Icon.new(name: sort_icon, class: icon_classes)) %><% end %><% else %><%= content %><% end %><% end %>
@@ -2,17 +2,41 @@
2
2
 
3
3
  # A header cell. Renders <th scope="col"> so assistive technology announces it
4
4
  # as a header rather than as data.
5
+ #
6
+ # With `sort_href:` the header is a link that sorts by the column, and
7
+ # `sorted:` (:asc or :desc) says it's sorted that way now.
5
8
  class UI::Table::Column < UI::Base
6
9
  ALIGNMENTS = { start: "text-left", center: "text-center", end: "text-right" }.freeze
10
+ SORT_ICONS = { asc: "arrow-up", desc: "arrow-down", none: "chevrons-up-down" }.freeze
7
11
 
8
- def initialize(align: :start, class: nil, **html_attrs)
12
+ def initialize(align: :start, sort_href: nil, sorted: nil, sticky: false, class: nil, **html_attrs)
9
13
  @align = align
14
+ @sort_href = sort_href
15
+ @sorted = sorted&.to_sym
16
+ @sticky = sticky
10
17
  @user_class = binding.local_variable_get(:class)
11
18
  @html_attrs = html_attrs
12
19
  end
13
20
 
21
+ def sortable? = @sort_href.present?
22
+
23
+ def sort_icon = SORT_ICONS.fetch(@sorted || :none, SORT_ICONS[:none])
24
+
25
+ def th_attrs
26
+ attrs = { scope: "col", class: classes, **@html_attrs }
27
+ attrs[:"aria-sort"] = { asc: "ascending", desc: "descending" }[@sorted] if sortable? && @sorted
28
+ attrs
29
+ end
30
+
31
+ def link_classes
32
+ cn("-mx-2 inline-flex h-8 items-center gap-1.5 rounded-md px-2 hover:bg-accent hover:text-accent-foreground",
33
+ { "flex-row-reverse" => @align == :end }, UI::Base::FOCUS_RING)
34
+ end
35
+
36
+ def icon_classes = cn("size-3.5", { "text-muted-foreground/60" => @sorted.nil? })
37
+
14
38
  def classes
15
39
  cn("h-10 px-2 align-middle font-medium text-foreground whitespace-nowrap",
16
- ALIGNMENTS.fetch(@align, ALIGNMENTS[:start]), @user_class)
40
+ ALIGNMENTS.fetch(@align, ALIGNMENTS[:start]), { "sticky top-0 z-10 bg-muted" => @sticky }, @user_class)
17
41
  end
18
42
  end
@@ -1 +1 @@
1
- <%= tag.thead class: classes, **@html_attrs do %><tr><%= columns.map(&:to_s).join.html_safe %></tr><% end %>
1
+ <%= tag.thead class: classes, **@html_attrs do %><tr><% if selection? %><%= tag.th class: selection_cell_classes do %><%= render(select_all_box) %><% end %><% end %><%= columns.map(&:to_s).join.html_safe %></tr><% end %>
@@ -2,12 +2,25 @@
2
2
 
3
3
  # The header row of a UI::Table.
4
4
  class UI::Table::Head < UI::Base
5
- renders_many :columns, UI::Table::Column
5
+ renders_many :columns, ->(**args) { UI::Table::Column.new(sticky: @sticky, **args) }
6
6
 
7
- def initialize(class: nil, **html_attrs)
7
+ def initialize(selection: nil, sticky: false, form: nil, class: nil, **html_attrs)
8
+ @selection = selection
9
+ @sticky = sticky
10
+ @form = form
8
11
  @user_class = binding.local_variable_get(:class)
9
12
  @html_attrs = html_attrs
10
13
  end
11
14
 
15
+ def selection? = @selection.present?
16
+
17
+ def select_all_box
18
+ UI::SelectionBar.checkbox(:all, label: t("ui.table.select_all", default: "Select all rows"), form: nil)
19
+ end
20
+
21
+ def selection_cell_classes
22
+ cn("h-10 w-px ps-3 pe-1 align-middle", { "sticky top-0 z-10 bg-muted" => @sticky })
23
+ end
24
+
12
25
  def classes = cn("border-b border-border bg-muted/50", @user_class)
13
26
  end
@@ -1 +1 @@
1
- <%= tag.tr(**html_options) do %><%= cells.map(&:to_s).join.html_safe %><% end %>
1
+ <%= tag.tr(**html_options) do %><% if selection_column? %><td class="w-px ps-3 pe-1 align-middle"><% if selectable? %><%= render(select_box) %><% end %></td><% end %><%= cells.map(&:to_s).join.html_safe %><% end %>
@@ -1,26 +1,40 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # A body row.
3
+ # A body row. In a table with `selection:`, `value:` is what its checkbox
4
+ # posts and `label:` names the row for it ("Select Acme").
4
5
  class UI::Table::Row < UI::Base
5
6
  renders_many :cells, UI::Table::Cell
6
7
 
7
- def initialize(selected: false, class: nil, **html_attrs)
8
+ def initialize(selected: false, value: nil, label: nil, selection: nil, form: nil, class: nil, **html_attrs)
8
9
  @selected = selected
10
+ @value = value
11
+ @label = label
12
+ @selection = selection
13
+ @form = form
9
14
  @user_class = binding.local_variable_get(:class)
10
15
  @html_attrs = html_attrs
11
16
  end
12
17
 
18
+ def selectable? = @selection.present? && !@value.nil?
19
+ def selection_column? = @selection.present?
20
+
21
+ def select_box
22
+ UI::SelectionBar.checkbox(:item, name: @selection, value: @value, form: @form, checked: @selected,
23
+ label: t("ui.table.select_row", label: @label || @value, default: "Select %{label}"))
24
+ end
25
+
13
26
  def classes
14
27
  cn("border-b border-border transition-colors hover:bg-muted/50",
15
- { "bg-muted" => @selected }, @user_class)
28
+ "has-[[data-selection=item]:checked]:bg-primary/5 has-[[data-selection=item]:checked]:hover:bg-primary/10",
29
+ { "bg-muted" => @selected && !selection_column? }, @user_class)
16
30
  end
17
31
 
18
32
  def html_options
19
33
  opts = @html_attrs.dup
20
34
  opts[:class] = classes
21
35
  # aria-selected rather than colour alone, so the state is not conveyed by
22
- # appearance only.
23
- opts[:"aria-selected"] = "true" if @selected
36
+ # appearance only. A row with a checkbox has that to say it instead.
37
+ opts[:"aria-selected"] = "true" if @selected && !selection_column?
24
38
  opts
25
39
  end
26
40
  end
@@ -1,4 +1,4 @@
1
1
  <%# The wrapper scrolls sideways so a wide table never breaks the page. %>
2
- <div class="relative w-full overflow-x-auto rounded-md border border-border">
2
+ <%= tag.div(**wrapper_attrs) do %>
3
3
  <%= tag.table class: classes, **@html_attrs do %><% if caption.present? %><caption class="mt-4 px-2 text-sm text-muted-foreground text-left"><%= caption %></caption><% end %><%= head %><tbody class="[&_tr:last-child]:border-0"><% if show_empty_state? %><tr><td colspan="<%= column_count %>" class="p-8 text-center text-sm text-muted-foreground"><%= empty_state %></td></tr><% else %><%= rows.map(&:to_s).join.html_safe %><% end %></tbody><% end %>
4
- </div>
4
+ <% end %>
@@ -19,15 +19,35 @@
19
19
  # <% end %>
20
20
  # <% table.with_empty_state { "No invoices yet" } %>
21
21
  # <% end %>
22
+ #
23
+ # A column sorts on the server: give it the link that sorts by it, and which
24
+ # way it's sorted now, and the header becomes that link with an arrow, read
25
+ # out by screen readers as sorted (aria-sort).
26
+ #
27
+ # <% head.with_column(sort_href: invoices_path(sort: "amount", dir: "desc"), sorted: :asc) { "Amount" } %>
28
+ #
29
+ # `selection: "ids[]"` adds a checkbox to each row, named that, with the
30
+ # value each row gives (`with_row(value: invoice.id, label: invoice.number)`),
31
+ # and a box in the header for all of them (made with UI::SelectionBar.checkbox). `form:` is the id of the form the
32
+ # boxes post with, when the table isn't inside it. A `UI::SelectionBar` for
33
+ # the table counts what's chosen, shows the actions for it and handles
34
+ # select-all and Shift-click.
35
+ #
36
+ # `sticky_header: true` keeps the header in sight while the rows scroll under
37
+ # it, inside `max_height:` ("32rem"); the table scrolls in its own box then.
22
38
  class UI::Table < UI::Base
23
- renders_one :head, UI::Table::Head
24
- renders_many :rows, UI::Table::Row
39
+ renders_one :head, ->(**args) { UI::Table::Head.new(selection: @selection, sticky: @sticky_header, form: @form, **args) }
40
+ renders_many :rows, ->(**args) { UI::Table::Row.new(selection: @selection, form: @form, **args) }
25
41
  # Shown only when there are no rows, so an empty table reads as empty
26
42
  # rather than as a header with nothing under it.
27
43
  renders_one :empty_state
28
44
 
29
- def initialize(caption: nil, class: nil, **html_attrs)
45
+ def initialize(caption: nil, selection: nil, form: nil, sticky_header: false, max_height: nil, class: nil, **html_attrs)
30
46
  @caption = caption
47
+ @selection = selection
48
+ @form = form
49
+ @sticky_header = sticky_header
50
+ @max_height = max_height
31
51
  @user_class = binding.local_variable_get(:class)
32
52
  @html_attrs = html_attrs
33
53
  end
@@ -41,5 +61,10 @@ class UI::Table < UI::Base
41
61
  def show_empty_state? = empty? && empty_state?
42
62
 
43
63
  # Spans the full width so the message centres under the header.
44
- def column_count = head? ? head.columns.size : 1
64
+ def column_count = (head? ? head.columns.size : 1) + (@selection ? 1 : 0)
65
+
66
+ def wrapper_attrs
67
+ { class: cn("relative w-full overflow-x-auto rounded-md border border-border", { "overflow-y-auto" => @max_height }),
68
+ style: ("max-height: #{@max_height}" if @max_height), data: { slot: "table" } }
69
+ end
45
70
  end
@@ -1 +1 @@
1
- <%= tag.div(**root_attrs) do %><% if multiple? && input_name %><%= tag.input type: "hidden", name: input_name, value: "", autocomplete: "off" %><% end %><% items.each do |item| %><%= item %><% end %><% end %>
1
+ <% group = capture do %><%= tag.div(**root_attrs) do %><% if multiple? && input_name %><%= tag.input type: "hidden", name: input_name, value: "", autocomplete: "off" %><% end %><% items.each do |item| %><%= item %><% end %><% end %><% end %><% if fieldset.wrap? %><%= render(fieldset) { group } %><% else %><%= group %><% end %>
@@ -13,6 +13,11 @@
13
13
  # joins bordered buttons. Give the group a `label:` (its accessible name), and
14
14
  # give an icon-only item a `label:` too, which becomes its hidden text and
15
15
  # tooltip. Listen for `change` on the group to act as soon as the choice changes.
16
+ #
17
+ # For a visible name, give it a `legend:` (and a `hint:` or `error:`): it then
18
+ # renders through UI::Fieldset, which takes the group's role and name, around
19
+ # the buttons. Bound to a form, the model's errors on the field show on their
20
+ # own, and `legend: true` uses the attribute's name.
16
21
  class UI::ToggleGroup < UI::Base
17
22
  variants(
18
23
  base: "inline-flex w-fit items-center",
@@ -31,7 +36,8 @@ class UI::ToggleGroup < UI::Base
31
36
  }
32
37
 
33
38
  def initialize(name: nil, value: nil, multiple: false, variant: :default, size: :default,
34
- label: nil, form: nil, field: nil, required: false, disabled: false,
39
+ label: nil, legend: nil, hint: nil, error: nil,
40
+ form: nil, field: nil, required: false, disabled: false,
35
41
  class: nil, **html_attrs)
36
42
  @name = name
37
43
  @value = value
@@ -39,6 +45,9 @@ class UI::ToggleGroup < UI::Base
39
45
  @variant = variant
40
46
  @size = size
41
47
  @label = label
48
+ @legend = legend
49
+ @hint = hint
50
+ @error = error
42
51
  @form = form
43
52
  @field = field
44
53
  @required = required
@@ -68,12 +77,26 @@ class UI::ToggleGroup < UI::Base
68
77
  Array(value).map(&:to_s)
69
78
  end
70
79
 
80
+ def role = multiple? ? "group" : "radiogroup"
81
+
82
+ # The legend shows only when given: a bound group that's never been named
83
+ # doesn't grow one when it has an error.
84
+ def fieldset
85
+ @fieldset ||= UI::Fieldset.new(legend: @legend.presence || false, hint: @hint, error: @error,
86
+ form: @form, field: @field,
87
+ required: required?, disabled: @disabled,
88
+ role: role, aria: { label: @label.presence }.compact.merge(@html_attrs[:aria] || {}))
89
+ end
90
+
91
+ # Inside a fieldset, the fieldset has the role and the aria attributes that
92
+ # name and describe the group; the buttons' track keeps the rest.
71
93
  def root_attrs
94
+ wrapped = fieldset.wrap?
72
95
  attrs = @html_attrs.except(:data, :aria)
73
- attrs[:role] = multiple? ? "group" : "radiogroup"
96
+ attrs[:role] = role unless wrapped
74
97
  attrs[:class] = cn(variant_classes(variant: @variant), @user_class)
75
98
  attrs[:data] = { slot: "toggle-group", variant: @variant }.merge(@html_attrs[:data] || {})
76
- attrs[:aria] = { label: @label.presence }.compact.merge(@html_attrs[:aria] || {})
99
+ attrs[:aria] = { label: @label.presence }.compact.merge(@html_attrs[:aria] || {}) unless wrapped
77
100
  attrs
78
101
  end
79
102
  end
@@ -0,0 +1,63 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+
3
+ // Connects to data-controller="ui--carousel"
4
+ //
5
+ // The strip scrolls by itself (scroll-snap); this only moves it a page at a
6
+ // time from the buttons, and shows each button while there's more that way.
7
+ const EDGE = 2;
8
+
9
+ export default class extends Controller<HTMLElement> {
10
+ static targets = ['track', 'previous', 'next'];
11
+
12
+ declare readonly trackTarget: HTMLElement;
13
+ declare readonly previousTarget: HTMLButtonElement;
14
+ declare readonly nextTarget: HTMLButtonElement;
15
+
16
+ private frame?: number;
17
+ private observer?: ResizeObserver;
18
+
19
+ connect() {
20
+ this.observer = new ResizeObserver(() => this.update());
21
+ this.observer.observe(this.trackTarget);
22
+ this.update();
23
+ }
24
+
25
+ disconnect() {
26
+ this.observer?.disconnect();
27
+ if (this.frame) cancelAnimationFrame(this.frame);
28
+ }
29
+
30
+ previous() {
31
+ this.page(-1);
32
+ }
33
+
34
+ next() {
35
+ this.page(1);
36
+ }
37
+
38
+ update() {
39
+ if (this.frame) return;
40
+
41
+ this.frame = requestAnimationFrame(() => {
42
+ this.frame = undefined;
43
+ const track = this.trackTarget;
44
+ // scrollLeft runs negative in a right-to-left page.
45
+ const scrolled = Math.abs(track.scrollLeft);
46
+ this.show(this.previousTarget, this.nextTarget, scrolled > EDGE);
47
+ this.show(this.nextTarget, this.previousTarget, scrolled + track.clientWidth < track.scrollWidth - EDGE);
48
+ });
49
+ }
50
+
51
+ // Most of a strip's width, so the last card in view is the first one after.
52
+ private page(direction: number) {
53
+ const track = this.trackTarget;
54
+ const forward = getComputedStyle(track).direction === 'rtl' ? -1 : 1;
55
+ track.scrollBy({ left: direction * forward * track.clientWidth * 0.85 });
56
+ }
57
+
58
+ // A button that hides under the keyboard would drop focus to the page.
59
+ private show(button: HTMLButtonElement, other: HTMLButtonElement, shown: boolean) {
60
+ if (!shown && document.activeElement === button) other.focus();
61
+ button.hidden = !shown;
62
+ }
63
+ }
@@ -222,7 +222,7 @@ export default class extends Controller<HTMLElement> {
222
222
  new DirectUpload(file, this.urlValue, {
223
223
  directUploadWillCreateBlobWithXHR: (xhr: XMLHttpRequest) => { state.xhr = xhr; },
224
224
  directUploadWillStoreFileWithXHR: watch,
225
- }).create((error: Error | null, blob?: { signed_id: string }) => {
225
+ }).create((error: string | null, blob?: { signed_id: string }) => {
226
226
  state.done = true;
227
227
  if (!item.isConnected) return;
228
228
  if (error || !blob) {
@@ -33,10 +33,17 @@ type Rect = { left: number; top: number; width: number; height: number };
33
33
  type IndexEvent<E extends Event = Event> = E & { params: { index: number } };
34
34
 
35
35
  export default class extends Controller<HTMLElement> {
36
- static targets = ['track', 'slide', 'thumbnail', 'status', 'dialog', 'viewport', 'zoomImage', 'zoomStatus', 'zoomIn', 'zoomOut', 'lens', 'pane'];
36
+ static targets = ['track', 'slide', 'trigger', 'thumbnail', 'status', 'dialog', 'viewport', 'zoomImage', 'zoomStatus', 'zoomIn', 'zoomOut', 'lens', 'pane',
37
+ 'perImage', 'infoPanel', 'infoToggle'];
37
38
  static values = { position: String, zoomScale: Number };
38
39
 
40
+ declare readonly hasTrackTarget: boolean;
39
41
  declare readonly trackTarget: HTMLElement;
42
+ declare readonly triggerTargets: HTMLElement[];
43
+ declare readonly perImageTargets: HTMLElement[];
44
+ declare readonly hasInfoPanelTarget: boolean;
45
+ declare readonly infoPanelTarget: HTMLElement;
46
+ declare readonly infoToggleTarget: HTMLElement;
40
47
  declare readonly slideTargets: HTMLElement[];
41
48
  declare readonly thumbnailTargets: HTMLElement[];
42
49
  declare readonly statusTarget: HTMLElement;
@@ -90,6 +97,7 @@ export default class extends Controller<HTMLElement> {
90
97
  private goTo(index: number, behavior: ScrollBehavior = this.scrollBehavior) {
91
98
  this.heading = index;
92
99
  this.setIndex(index);
100
+ if (!this.hasTrackTarget) return;
93
101
  this.trackTarget.scrollTo({ left: this.scrollPosition(this.trackTarget, this.slideTargets[index]), behavior });
94
102
  }
95
103
 
@@ -133,7 +141,8 @@ export default class extends Controller<HTMLElement> {
133
141
  this.index = index;
134
142
  this.statusTarget.dataset.ready = 'true';
135
143
  this.statusTarget.textContent = this.position(index);
136
- this.slideTargets.forEach((_, i) => this.slideButton(i)?.setAttribute('tabindex', i === index ? '0' : '-1'));
144
+ if (this.hasTrackTarget) this.slideTargets.forEach((_, i) => this.slideButton(i)?.setAttribute('tabindex', i === index ? '0' : '-1'));
145
+ this.perImageTargets.forEach((element) => (element.hidden = Number(element.dataset.index) !== index));
137
146
  this.thumbnailTargets.forEach((thumbnail, i) => {
138
147
  if (i === index) thumbnail.setAttribute('aria-current', 'true');
139
148
  else thumbnail.removeAttribute('aria-current');
@@ -142,10 +151,34 @@ export default class extends Controller<HTMLElement> {
142
151
  if (strip) strip.scrollTo({ left: this.scrollPosition(strip, this.thumbnailTargets[index]), behavior: this.scrollBehavior });
143
152
  }
144
153
 
145
- private slideButton(index: number) {
154
+ private slideButton(index: number): HTMLElement | null {
155
+ if (!this.hasTrackTarget) return this.triggerFor(index);
146
156
  return this.slideTargets[index].querySelector('button');
147
157
  }
148
158
 
159
+ // With `strip: false` the page's own buttons open the overlay, and the image
160
+ // in each is where it grows from.
161
+ private triggerFor(index: number): HTMLElement | null {
162
+ return this.triggerTargets.find((trigger) => Number(trigger.dataset.uiGalleryIndexParam) === index) ?? null;
163
+ }
164
+
165
+ // Where image `index` is on the page, and the picture drawn there.
166
+ private origin(index: number): { frame: HTMLElement; image: HTMLImageElement | null } | null {
167
+ const frame = this.hasTrackTarget ? this.slideTargets[index] : this.triggerFor(index);
168
+ if (!frame) return null;
169
+ return { frame, image: frame.querySelector('img') };
170
+ }
171
+
172
+ toggleInfo() {
173
+ if (!this.hasInfoPanelTarget) return;
174
+
175
+ const open = this.infoPanelTarget.hidden;
176
+ this.infoPanelTarget.hidden = !open;
177
+ this.infoToggleTarget.setAttribute('aria-expanded', String(open));
178
+ this.dialogTarget.toggleAttribute('data-info', open);
179
+ this.layout();
180
+ }
181
+
149
182
  // Where to scroll `box` so `item` sits in its middle. Measured from what's on
150
183
  // screen, so it holds in a right-to-left page, where scrollLeft runs negative.
151
184
  private scrollPosition(box: HTMLElement, item: HTMLElement): number {
@@ -254,11 +287,10 @@ export default class extends Controller<HTMLElement> {
254
287
  this.animate(this.dialogTarget, { opacity: [0, 1] }, { ...fade, pseudoElement: '::backdrop' });
255
288
  this.overlayButtons.forEach((button) => this.animate(button, { opacity: [0, 1] }, fade));
256
289
 
257
- const slide = this.slideTargets[this.index];
290
+ const from = this.origin(this.index);
258
291
  const image = this.zoomImageTarget;
259
- const origin = slide.querySelector('img');
260
- if (origin?.naturalWidth && image.naturalWidth) {
261
- this.fly(this.drawnImage(slide, origin), image.getBoundingClientRect(), OPEN_MS);
292
+ if (from?.image?.naturalWidth && image.naturalWidth) {
293
+ this.fly(this.drawnImage(from.frame, from.image), image.getBoundingClientRect(), OPEN_MS);
262
294
  } else {
263
295
  this.animate(image, { opacity: [0, 1] }, fade);
264
296
  }
@@ -271,15 +303,14 @@ export default class extends Controller<HTMLElement> {
271
303
  if (this.closing) return;
272
304
 
273
305
  this.goTo(this.index, 'auto');
274
- const slide = this.slideTargets[this.index];
306
+ const to = this.origin(this.index);
275
307
  const image = this.zoomImageTarget;
276
- const origin = slide.querySelector('img');
277
308
  const fade = { duration: CLOSE_MS, easing: 'ease-in', fill: 'forwards' as const };
278
309
  const animations = [
279
310
  this.animate(this.dialogTarget, { opacity: [1, 0] }, { ...fade, pseudoElement: '::backdrop' }),
280
311
  ...this.overlayButtons.map((button) => this.animate(button, { opacity: [1, 0] }, fade)),
281
- origin?.naturalWidth && image.naturalWidth
282
- ? this.fly(image.getBoundingClientRect(), this.drawnImage(slide, origin), CLOSE_MS, true)
312
+ to?.image?.naturalWidth && image.naturalWidth && this.onScreen(to.frame)
313
+ ? this.fly(image.getBoundingClientRect(), this.drawnImage(to.frame, to.image), CLOSE_MS, true)
283
314
  : this.animate(image, { opacity: [1, 0] }, fade),
284
315
  ].filter((animation): animation is Animation => animation !== null);
285
316
 
@@ -306,7 +337,8 @@ export default class extends Controller<HTMLElement> {
306
337
  closed() {
307
338
  this.cancelClosing();
308
339
  this.goTo(this.index, 'auto');
309
- this.slideButton(this.index)?.focus({ preventScroll: true });
340
+ const button = this.slideButton(this.index);
341
+ button?.focus({ preventScroll: this.hasTrackTarget });
310
342
  this.zoomImageTarget.removeAttribute('style');
311
343
  this.setScale(MIN_ZOOM);
312
344
  }
@@ -324,7 +356,7 @@ export default class extends Controller<HTMLElement> {
324
356
  const slide = this.slideTargets[index];
325
357
  const image = this.zoomImageTarget;
326
358
  const large = slide.dataset.zoomSrc ?? '';
327
- const shown = slide.querySelector('img');
359
+ const shown = this.origin(index)?.image;
328
360
  const ready = shown?.complete && shown.naturalWidth > 0 ? shown.currentSrc : '';
329
361
 
330
362
  if (direction) this.slideOut(direction);
@@ -406,6 +438,12 @@ export default class extends Controller<HTMLElement> {
406
438
  return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
407
439
  }
408
440
 
441
+ // A grid scrolled on behind the overlay may have left the image out of sight.
442
+ private onScreen(element: HTMLElement): boolean {
443
+ const rect = element.getBoundingClientRect();
444
+ return rect.bottom > 0 && rect.top < window.innerHeight;
445
+ }
446
+
409
447
  private get overlayButtons(): HTMLElement[] {
410
448
  return Array.from(this.dialogTarget.querySelectorAll('button'));
411
449
  }
@@ -530,7 +568,7 @@ export default class extends Controller<HTMLElement> {
530
568
  if (event.ctrlKey || event.metaKey || event.altKey) return;
531
569
 
532
570
  if (this.dialogTarget.open) this.dialogKeydown(event);
533
- else if (this.element.contains(event.target as Node)) this.galleryKeydown(event);
571
+ else if (this.hasTrackTarget && this.element.contains(event.target as Node)) this.galleryKeydown(event);
534
572
  }
535
573
 
536
574
  private galleryKeydown(event: KeyboardEvent) {