velvetkit 0.2.0 → 0.2.2

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3f1a9f75abb6d157cc285024ed4c2e3e711a7a9d1dc44447506c0747427ccc03
4
- data.tar.gz: 2e07ef2baa716064b2e629e08acacd331576449434ebadf18288eb136870b044
3
+ metadata.gz: d08ba86d71423280c8ee7e6402a9bfd41f0bc169e104b9f4d79d0dc233900a7e
4
+ data.tar.gz: b429da49e5336283efd3c237197a68ae8124ff272f06f539b73c320583b176a5
5
5
  SHA512:
6
- metadata.gz: 6eafdabafa53ea356315c8ebe68f36d816cc3937844c013970b0a27360a92b0b623daa27bd4501f8bcb83b65b2a1eaabf8a7421b06a8096b3df4b3f209a87629
7
- data.tar.gz: e675121815d2bf88bab7b9689ef1bcaa916ed8eae2865e04400cc060e5a6d9425a2bc93b3f34dd306c9f5fe993e988af7e85755206e7a452c4f4b8befb572abd
6
+ metadata.gz: 83049f0da572339daf86fce1e387624a3cf9531e9c1bb95f173625d2bef5660d3e44740bf3ecd91fe090bb1b7736dc7b5d0770d4c5a91d0dc803b14f304fda50
7
+ data.tar.gz: 598f00a866bd796c3af74e60bd652f9fd35f069f80d41aaee233f81e2b5a31541e2c5c863d41c5cdcdb0aa85f124006b3313f728231d406697b7a3d6302bb248
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Velvetkit
4
- VERSION = "0.2.0"
4
+ VERSION = "0.2.2"
5
5
  end
@@ -0,0 +1,16 @@
1
+ <%# Run the block first, so with_link calls and any custom panel markup exist
2
+ before deciding whether this item is a trigger or a plain link. %>
3
+ <% body = content %>
4
+ <%= tag.li(**li_options) do %>
5
+ <% if links? || body.present? %>
6
+ <%= tag.button(**trigger_options) do %><%= label %><%= render(UI::Icon.new(name: "chevron-down", size: :xs, class: "transition-transform duration-200 group-aria-expanded/nav-item:rotate-180 motion-reduce:transition-none")) %><% end %>
7
+ <%= tag.div(**panel_options) do %>
8
+ <% if links? %>
9
+ <ul class="<%= list_classes %>"><% links.each do |link| %><li><%= link %></li><% end %></ul>
10
+ <% end %>
11
+ <%= body %>
12
+ <% end %>
13
+ <% else %>
14
+ <%= tag.a(**link_options) do %><%= label %><% end %>
15
+ <% end %>
16
+ <% end %>
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ # UI::NavigationMenu::Item — one entry in the top row.
4
+ #
5
+ # With `with_link`s (or any block content) it is a trigger that opens a
6
+ # panel; without, give it `href:` and it is a plain link.
7
+ #
8
+ # label: the text in the top row
9
+ # href: makes it a plain link (ignored when it has a panel)
10
+ # active: marks the current section: aria-current="page" on a plain
11
+ # link, a highlight on a trigger
12
+ # columns: 1 or 2 columns of links in the panel
13
+ # panel_class: extra classes for the panel, e.g. a width
14
+ class UI::NavigationMenu::Item < UI::Base
15
+ TOP_ITEM = "group/nav-item inline-flex h-9 items-center justify-center gap-1 rounded-md px-3 " \
16
+ "text-sm font-medium whitespace-nowrap text-foreground transition-colors " \
17
+ "hover:bg-accent hover:text-accent-foreground " \
18
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1 " \
19
+ "aria-expanded:bg-accent aria-expanded:text-accent-foreground " \
20
+ "data-[active]:bg-accent/60 aria-[current=page]:bg-accent/60"
21
+
22
+ renders_many :links, ->(title:, href:, **opts) { UI::NavigationMenu::Link.new(title: title, href: href, **opts) }
23
+
24
+ def initialize(label:, href: nil, active: false, columns: 1, panel_class: nil, class: nil, **html_attrs)
25
+ @label = label
26
+ @href = href
27
+ @active = active
28
+ @columns = columns == 2 ? 2 : 1
29
+ @panel_class = panel_class
30
+ @user_class = binding.local_variable_get(:class)
31
+ @html_attrs = html_attrs
32
+ end
33
+
34
+ attr_reader :label
35
+
36
+ def set_navigation_context(nav, index:)
37
+ @nav = nav
38
+ @index = index
39
+ end
40
+
41
+ def trigger_id; "#{@nav.id}-trigger-#{@index}"; end
42
+ def panel_id; "#{@nav.id}-panel-#{@index}"; end
43
+
44
+ def li_options
45
+ { class: cn("relative", @user_class), **@html_attrs }
46
+ end
47
+
48
+ def link_options
49
+ {
50
+ href: @href,
51
+ class: TOP_ITEM,
52
+ "aria-current": (@active ? "page" : nil),
53
+ data: { "ui--navigation-menu-target": "top", action: "keydown->ui--navigation-menu#topKeydown" }
54
+ }
55
+ end
56
+
57
+ def trigger_options
58
+ {
59
+ type: "button",
60
+ id: trigger_id,
61
+ class: TOP_ITEM,
62
+ "aria-expanded": "false",
63
+ "aria-controls": panel_id,
64
+ data: {
65
+ "ui--navigation-menu-target": "top trigger",
66
+ active: (@active ? "" : nil),
67
+ action: [
68
+ "click->ui--navigation-menu#toggle",
69
+ "pointerenter->ui--navigation-menu#hoverOpen",
70
+ "pointerleave->ui--navigation-menu#hoverClose",
71
+ "keydown->ui--navigation-menu#topKeydown"
72
+ ].join(" ")
73
+ }
74
+ }
75
+ end
76
+
77
+ def panel_options
78
+ {
79
+ id: panel_id,
80
+ hidden: true,
81
+ class: cn(
82
+ "z-50 max-w-[calc(100vw-1rem)] rounded-lg border bg-popover p-2 text-popover-foreground shadow-md",
83
+ "animate-in fade-in-0 zoom-in-95",
84
+ @columns == 2 ? "w-[36rem]" : "w-96",
85
+ @panel_class
86
+ ),
87
+ data: {
88
+ "ui--navigation-menu-target": "panel",
89
+ state: "closed",
90
+ action: [
91
+ "pointerenter->ui--navigation-menu#cancelClose",
92
+ "pointerleave->ui--navigation-menu#hoverClose",
93
+ "keydown->ui--navigation-menu#panelKeydown"
94
+ ].join(" ")
95
+ }
96
+ }
97
+ end
98
+
99
+ def list_classes
100
+ cn("grid gap-1", { "sm:grid-cols-2" => @columns == 2 })
101
+ end
102
+ end
@@ -0,0 +1,9 @@
1
+ <%= tag.a(**link_options) do %>
2
+ <% if icon %>
3
+ <span class="flex size-9 shrink-0 items-center justify-center rounded-md border bg-background text-muted-foreground"><%= render(UI::Icon.new(name: icon, size: :sm)) %></span>
4
+ <% end %>
5
+ <span class="min-w-0">
6
+ <span class="block font-medium leading-snug"><%= title %></span>
7
+ <% if description %><span class="mt-1 line-clamp-2 block leading-snug text-muted-foreground"><%= description %></span><% end %>
8
+ </span>
9
+ <% end %>
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ # UI::NavigationMenu::Link — a rich link in a panel: a title, an optional
4
+ # one- or two-line description and an optional leading icon.
5
+ #
6
+ # title: the link text
7
+ # href: where it goes
8
+ # description: muted text under the title
9
+ # icon: a Lucide icon name, shown in a tile on the left
10
+ # active: the current page (aria-current="page")
11
+ class UI::NavigationMenu::Link < UI::Base
12
+ def initialize(title:, href:, description: nil, icon: nil, active: false, class: nil, **html_attrs)
13
+ @title = title
14
+ @href = href
15
+ @description = description
16
+ @icon = icon
17
+ @active = active
18
+ @user_class = binding.local_variable_get(:class)
19
+ @html_attrs = html_attrs
20
+ end
21
+
22
+ attr_reader :title, :description, :icon
23
+
24
+ def link_options
25
+ user_data = @html_attrs[:data] || {}
26
+ @html_attrs.except(:data).merge(
27
+ href: @href,
28
+ class: cn(
29
+ "flex gap-3 rounded-md p-3 text-sm outline-none transition-colors",
30
+ # A title alone sits level with its icon; with a description, both
31
+ # start at the top.
32
+ @description ? "items-start" : "items-center",
33
+ "hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground",
34
+ "focus-visible:ring-2 focus-visible:ring-primary aria-[current=page]:bg-accent/60",
35
+ @user_class
36
+ ),
37
+ "aria-current": (@active ? "page" : nil),
38
+ data: user_data.merge("ui--navigation-menu-target": "link")
39
+ )
40
+ end
41
+ end
@@ -0,0 +1,3 @@
1
+ <%= tag.nav(id: id, "aria-label": nav_label, class: root_classes, data: root_data, **@html_attrs.except(:data)) do %>
2
+ <ul class="flex flex-wrap items-center gap-1"><% items.each do |item| %><%= item %><% end %></ul>
3
+ <% end %>
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ # UI::NavigationMenu — a site's main navigation: plain links, and triggers
4
+ # that open a panel of rich links (title, description, optional icon).
5
+ #
6
+ # Follows the WAI-ARIA disclosure navigation pattern (buttons with
7
+ # aria-expanded controlling a panel of ordinary links), not role="menu",
8
+ # which is for application menus.
9
+ #
10
+ # <%= render(UI::NavigationMenu.new) do |nav| %>
11
+ # <% nav.with_item(label: "Getting started") do |item| %>
12
+ # <% item.with_link(title: "Introduction", href: "/docs",
13
+ # description: "Re-usable components built with Tailwind CSS.") %>
14
+ # <% end %>
15
+ # <% nav.with_item(label: "Docs", href: "/docs") %>
16
+ # <% end %>
17
+ #
18
+ # A panel opens on hover (mouse, after `open_delay` ms; instantly when
19
+ # another panel is already open), on click, or with Enter/Space/ArrowDown.
20
+ # Escape, a click outside or tabbing away closes it.
21
+ #
22
+ # Compound:
23
+ # UI::NavigationMenu — the <nav> and its list
24
+ # UI::NavigationMenu::Item — a plain link, or a trigger plus its panel
25
+ # UI::NavigationMenu::Link — a rich link inside a panel
26
+ class UI::NavigationMenu < UI::Base
27
+ renders_many :items, ->(label:, **opts) {
28
+ @item_count = (@item_count || 0) + 1
29
+ UI::NavigationMenu::Item.new(label: label, **opts).tap { |i| i.set_navigation_context(self, index: @item_count) }
30
+ }
31
+
32
+ # label: accessible name of the <nav> (several navs on a page need
33
+ # different names)
34
+ # open_delay: ms of hovering before a panel opens
35
+ # close_delay: ms after the pointer leaves before it closes, so it can
36
+ # cross the gap between trigger and panel
37
+ def initialize(label: nil, open_delay: 150, close_delay: 200, class: nil, **html_attrs)
38
+ @label = label
39
+ @open_delay = open_delay
40
+ @close_delay = close_delay
41
+ @user_class = binding.local_variable_get(:class)
42
+ @html_attrs = html_attrs
43
+ @id = @html_attrs.delete(:id) || "ui-navigation-menu-#{SecureRandom.hex(4)}"
44
+ end
45
+
46
+ attr_reader :id
47
+
48
+ def nav_label
49
+ @label || t("ui.navigation_menu.label", default: "Main")
50
+ end
51
+
52
+ def root_classes
53
+ cn("relative", @user_class)
54
+ end
55
+
56
+ def root_data
57
+ {
58
+ controller: "ui--navigation-menu",
59
+ "ui--navigation-menu-open-delay-value": @open_delay,
60
+ "ui--navigation-menu-close-delay-value": @close_delay,
61
+ action: "focusin->ui--navigation-menu#focusIn focusout->ui--navigation-menu#focusOut"
62
+ }.merge(@html_attrs[:data] || {})
63
+ end
64
+ end
@@ -0,0 +1,265 @@
1
+ import { Controller } from '@hotwired/stimulus';
2
+ import { useFloating } from './_internal/use_floating.js';
3
+
4
+ /**
5
+ * UI::NavigationMenu controller — disclosure navigation: triggers open a
6
+ * panel of links below them. One panel is open at a time.
7
+ *
8
+ * Mouse: hover a trigger to open its panel after openDelay; once a panel is
9
+ * open, hovering another trigger switches at once. A panel opened by hover
10
+ * closes closeDelay after the pointer leaves trigger and panel (long enough
11
+ * to cross the gap). One opened by click or keyboard stays until Escape, a
12
+ * click outside or focus leaving — so moving the mouse away to scroll
13
+ * doesn't close it. Click toggles (the only way in on touch).
14
+ *
15
+ * The panel opens below its trigger and flips above when there isn't room
16
+ * below (a menu in a footer, or a header scrolled near the bottom), and
17
+ * follows the trigger as the page or any container scrolls.
18
+ *
19
+ * Keyboard: Left/Right/Home/End move along the top row; Enter, Space or
20
+ * ArrowDown on a trigger opens its panel (ArrowDown also focuses its first
21
+ * link); Up/Down move between links in the panel; Escape closes and returns
22
+ * focus to the trigger. Tabbing out of the nav, or clicking outside, closes.
23
+ */
24
+ export default class extends Controller<HTMLElement> {
25
+ static targets = ['top', 'trigger', 'panel', 'link'];
26
+ static values = {
27
+ openDelay: { type: Number, default: 150 },
28
+ closeDelay: { type: Number, default: 200 },
29
+ };
30
+
31
+ declare readonly topTargets: HTMLElement[];
32
+ declare readonly triggerTargets: HTMLButtonElement[];
33
+ declare readonly panelTargets: HTMLElement[];
34
+ declare openDelayValue: number;
35
+ declare closeDelayValue: number;
36
+
37
+ private openTrigger: HTMLButtonElement | null = null;
38
+ private openedBy: 'hover' | 'click' | 'keyboard' | null = null;
39
+ private openedByHoverAt = 0;
40
+ private openTimer: number | null = null;
41
+ private closeTimer: number | null = null;
42
+ private floatingCleanup: (() => void) | null = null;
43
+
44
+ disconnect() {
45
+ this.close({ restoreFocus: false });
46
+ this.clearTimers();
47
+ }
48
+
49
+ // ── Click ──────────────────────────────────────────────────────────────
50
+
51
+ toggle(event: MouseEvent) {
52
+ const trigger = event.currentTarget as HTMLButtonElement;
53
+ this.clearTimers();
54
+ if (this.openTrigger === trigger) {
55
+ // A click that lands just after hover opened the panel is the user
56
+ // reaching for it, not asking to close it.
57
+ if (this.openedBy === 'hover' && Date.now() - this.openedByHoverAt < 400) {
58
+ this.openedBy = 'click'; // the click claims it: no longer closes on leave
59
+ return;
60
+ }
61
+ this.close({ restoreFocus: false });
62
+ } else {
63
+ // Enter/Space on a focused button also arrive as a click (detail 0).
64
+ this.open(trigger, event.detail === 0 ? 'keyboard' : 'click');
65
+ }
66
+ }
67
+
68
+ // ── Hover (mouse only) ─────────────────────────────────────────────────
69
+
70
+ hoverOpen(event: PointerEvent) {
71
+ if (event.pointerType !== 'mouse') return;
72
+ const trigger = event.currentTarget as HTMLButtonElement;
73
+ this.clearTimers();
74
+ if (this.openTrigger === trigger) return;
75
+
76
+ const show = () => {
77
+ this.open(trigger, 'hover');
78
+ this.openedByHoverAt = Date.now();
79
+ };
80
+ if (this.openTrigger) show(); // already browsing panels: switch at once
81
+ else this.openTimer = window.setTimeout(show, this.openDelayValue);
82
+ }
83
+
84
+ hoverClose(event: PointerEvent) {
85
+ if (event.pointerType !== 'mouse') return;
86
+ this.clearOpenTimer();
87
+ if (!this.openTrigger || this.openedBy !== 'hover') return;
88
+ this.clearCloseTimer();
89
+ this.closeTimer = window.setTimeout(() => this.close({ restoreFocus: false }), this.closeDelayValue);
90
+ }
91
+
92
+ cancelClose() {
93
+ this.clearCloseTimer();
94
+ }
95
+
96
+ // ── Keyboard ───────────────────────────────────────────────────────────
97
+
98
+ topKeydown(event: KeyboardEvent) {
99
+ const item = event.currentTarget as HTMLElement;
100
+ const tops = this.topTargets;
101
+ const index = tops.indexOf(item);
102
+ const isTrigger = this.triggerTargets.includes(item as HTMLButtonElement);
103
+
104
+ switch (event.key) {
105
+ case 'ArrowRight':
106
+ this.focusTop(tops[(index + 1) % tops.length]);
107
+ break;
108
+ case 'ArrowLeft':
109
+ this.focusTop(tops[(index - 1 + tops.length) % tops.length]);
110
+ break;
111
+ case 'Home':
112
+ this.focusTop(tops[0]);
113
+ break;
114
+ case 'End':
115
+ this.focusTop(tops[tops.length - 1]);
116
+ break;
117
+ case 'ArrowDown':
118
+ if (!isTrigger) return;
119
+ this.open(item as HTMLButtonElement, 'keyboard');
120
+ this.linksOf(this.panelFor(item as HTMLButtonElement))[0]?.focus();
121
+ break;
122
+ case 'Escape':
123
+ if (!this.openTrigger) return;
124
+ this.close({ restoreFocus: true });
125
+ break;
126
+ default:
127
+ return;
128
+ }
129
+ event.preventDefault();
130
+ }
131
+
132
+ panelKeydown(event: KeyboardEvent) {
133
+ const panel = event.currentTarget as HTMLElement;
134
+ const links = this.linksOf(panel);
135
+ const index = links.indexOf(document.activeElement as HTMLElement);
136
+
137
+ switch (event.key) {
138
+ case 'ArrowDown':
139
+ links[(index + 1) % links.length]?.focus();
140
+ break;
141
+ case 'ArrowUp':
142
+ if (index <= 0) this.openTrigger?.focus();
143
+ else links[index - 1]?.focus();
144
+ break;
145
+ case 'Home':
146
+ links[0]?.focus();
147
+ break;
148
+ case 'End':
149
+ links[links.length - 1]?.focus();
150
+ break;
151
+ case 'Escape':
152
+ this.close({ restoreFocus: true });
153
+ break;
154
+ default:
155
+ return;
156
+ }
157
+ event.preventDefault();
158
+ }
159
+
160
+ // Focus landed somewhere that isn't the open panel or its trigger — the
161
+ // next top-level item after Tabbing past the last link, or anything else
162
+ // on the page — so the panel no longer belongs to where the user is.
163
+ focusIn(event: FocusEvent) {
164
+ this.closeUnlessWithinOpen(event.target as Node);
165
+ }
166
+
167
+ focusOut(event: FocusEvent) {
168
+ const next = event.relatedTarget as Node | null;
169
+ // Focus went nowhere (a click on plain page): the outside-pointer
170
+ // handler decides. Moving within the nav: focusIn decides.
171
+ if (next === null || this.element.contains(next)) return;
172
+ this.close({ restoreFocus: false });
173
+ }
174
+
175
+ private closeUnlessWithinOpen(node: Node) {
176
+ const trigger = this.openTrigger;
177
+ if (!trigger) return;
178
+ if (trigger.contains(node) || this.panelFor(trigger)?.contains(node)) return;
179
+ this.close({ restoreFocus: false });
180
+ }
181
+
182
+ // ── Open / close ───────────────────────────────────────────────────────
183
+
184
+ private open(trigger: HTMLButtonElement, by: 'hover' | 'click' | 'keyboard') {
185
+ if (this.openTrigger === trigger) return;
186
+ this.close({ restoreFocus: false });
187
+
188
+ const panel = this.panelFor(trigger);
189
+ if (!panel) return;
190
+
191
+ panel.hidden = false;
192
+ panel.dataset.state = 'open';
193
+ trigger.setAttribute('aria-expanded', 'true');
194
+ this.floatingCleanup = useFloating(trigger, panel, {
195
+ placement: 'bottom-start',
196
+ offset: 6,
197
+ flip: true,
198
+ shift: true,
199
+ strategy: 'fixed',
200
+ }).destroy;
201
+
202
+ this.openTrigger = trigger;
203
+ this.openedBy = by;
204
+ document.addEventListener('pointerdown', this.onOutsidePointer, true);
205
+ }
206
+
207
+ private close({ restoreFocus }: { restoreFocus: boolean }) {
208
+ const trigger = this.openTrigger;
209
+ if (!trigger) return;
210
+ const panel = this.panelFor(trigger);
211
+
212
+ this.floatingCleanup?.();
213
+ this.floatingCleanup = null;
214
+ if (panel) {
215
+ panel.hidden = true;
216
+ panel.dataset.state = 'closed';
217
+ }
218
+ trigger.setAttribute('aria-expanded', 'false');
219
+ this.openTrigger = null;
220
+ this.openedBy = null;
221
+ this.openedByHoverAt = 0;
222
+ document.removeEventListener('pointerdown', this.onOutsidePointer, true);
223
+ if (restoreFocus) trigger.focus();
224
+ }
225
+
226
+ private onOutsidePointer = (event: PointerEvent) => {
227
+ if (this.element.contains(event.target as Node)) return;
228
+ this.close({ restoreFocus: false });
229
+ };
230
+
231
+ // ── Helpers ────────────────────────────────────────────────────────────
232
+
233
+ private panelFor(trigger: HTMLButtonElement): HTMLElement | null {
234
+ const id = trigger.getAttribute('aria-controls');
235
+ return this.panelTargets.find((p) => p.id === id) ?? null;
236
+ }
237
+
238
+ private linksOf(panel: HTMLElement | null): HTMLElement[] {
239
+ if (!panel) return [];
240
+ return Array.from(panel.querySelectorAll<HTMLElement>('a[href], button:not([disabled])'));
241
+ }
242
+
243
+ // Moving along the top row closes a panel left behind, so an open panel
244
+ // always belongs to the item with focus.
245
+ private focusTop(item: HTMLElement | undefined) {
246
+ if (!item) return;
247
+ if (this.openTrigger && item !== this.openTrigger) this.close({ restoreFocus: false });
248
+ item.focus();
249
+ }
250
+
251
+ private clearOpenTimer() {
252
+ if (this.openTimer !== null) window.clearTimeout(this.openTimer);
253
+ this.openTimer = null;
254
+ }
255
+
256
+ private clearCloseTimer() {
257
+ if (this.closeTimer !== null) window.clearTimeout(this.closeTimer);
258
+ this.closeTimer = null;
259
+ }
260
+
261
+ private clearTimers() {
262
+ this.clearOpenTimer();
263
+ this.clearCloseTimer();
264
+ }
265
+ }
@@ -15,14 +15,18 @@ import {
15
15
  CircleAlert,
16
16
  CircleCheck,
17
17
  Ellipsis,
18
+ EllipsisVertical,
18
19
  Eye,
19
20
  EyeOff,
21
+ GripVertical,
20
22
  Info,
21
23
  Loader,
22
24
  Mail,
23
25
  Monitor,
24
26
  Moon,
25
27
  PanelLeft,
28
+ Plus,
29
+ Search,
26
30
  Sun,
27
31
  Upload,
28
32
  X,
@@ -38,14 +42,18 @@ const icons = {
38
42
  CircleAlert,
39
43
  CircleCheck,
40
44
  Ellipsis,
45
+ EllipsisVertical,
41
46
  Eye,
42
47
  EyeOff,
48
+ GripVertical,
43
49
  Info,
44
50
  Loader,
45
51
  Mail,
46
52
  Monitor,
47
53
  Moon,
48
54
  PanelLeft,
55
+ Plus,
56
+ Search,
49
57
  Sun,
50
58
  Upload,
51
59
  X,
@@ -71,6 +71,8 @@ components:
71
71
  description: A link styled as text or as a button.
72
72
  menu:
73
73
  description: A dropdown menu with keyboard navigation.
74
+ navigation_menu:
75
+ description: Site navigation with links and hover or click panels of rich links.
74
76
  pagination:
75
77
  description: Page links for a long list, from a Pagy object.
76
78
  gems: [pagy]
@@ -34,6 +34,8 @@ en:
34
34
  toggle: 'Toggle sidebar'
35
35
  table_of_contents:
36
36
  label: 'On this page'
37
+ navigation_menu:
38
+ label: 'Main'
37
39
  pagination:
38
40
  label: 'Pages'
39
41
  summary: 'Showing %{from}–%{to} of %{count}'
@@ -0,0 +1,20 @@
1
+ <%# Any markup can go in a panel alongside, or instead of, its links. %>
2
+ <div class="flex min-h-[28rem] justify-center pt-8">
3
+ <%= render(UI::NavigationMenu.new) do |nav| %>
4
+ <% nav.with_item(label: "Company", panel_class: "w-[32rem]") do |item| %>
5
+ <% item.with_link(title: "About", href: "#about", description: "Who we are and why we build this.") %>
6
+ <% item.with_link(title: "Careers", href: "#careers", description: "Open roles, remote-first.") %>
7
+ <% item.with_link(title: "Customers", href: "#customers", description: "Teams that run on Acme, in their words.") %>
8
+ <% item.with_link(title: "Contact", href: "#contact", description: "Sales, support and partnerships.") %>
9
+ <div class="mt-2 flex items-center justify-between gap-4 rounded-md bg-muted p-4">
10
+ <div>
11
+ <p class="text-sm font-medium">We're hiring</p>
12
+ <p class="mt-1 text-sm text-muted-foreground">Three engineering roles are open this quarter.</p>
13
+ </div>
14
+ <%= render(UI::Button.new(size: :sm, variant: :outline)) { "See roles" } %>
15
+ </div>
16
+ <% end %>
17
+ <% nav.with_item(label: "Blog", href: "#blog") %>
18
+ <% nav.with_item(label: "Contact", href: "#contact") %>
19
+ <% end %>
20
+ </div>
@@ -0,0 +1,73 @@
1
+ <div class="min-h-screen bg-background">
2
+ <header class="sticky top-0 z-40 border-b bg-background/95 backdrop-blur">
3
+ <div class="mx-auto flex h-14 max-w-6xl items-center gap-6 px-4">
4
+ <a href="#" class="flex items-center gap-2 font-semibold"><span class="size-6 rounded-md bg-primary"></span>Acme</a>
5
+
6
+ <%= render(UI::NavigationMenu.new(label: "Main", open_delay: open_delay, close_delay: close_delay)) do |nav| %>
7
+ <% nav.with_item(label: "Products", columns: 2) do |item| %>
8
+ <% item.with_link(title: "Analytics", href: "#analytics", icon: "chart-column", description: "See what customers do, as they do it.") %>
9
+ <% item.with_link(title: "Automations", href: "#automations", icon: "workflow", description: "Run the repetitive parts on a schedule.") %>
10
+ <% item.with_link(title: "Inbox", href: "#inbox", icon: "message-circle", description: "Every conversation in one place.") %>
11
+ <% item.with_link(title: "Billing", href: "#billing", icon: "credit-card", description: "Invoices, plans and payment methods.") %>
12
+ <% item.with_link(title: "Storefront", href: "#storefront", icon: "store", description: "Sell online with a page you own.") %>
13
+ <% item.with_link(title: "Notifications", href: "#notifications", icon: "bell", description: "Email, SMS and push from one API.") %>
14
+ <% item.with_link(title: "Security", href: "#security", icon: "shield", description: "SSO, audit logs and roles.") %>
15
+ <% item.with_link(title: "Integrations", href: "#integrations", icon: "layout-grid", description: "Connect the tools you already use.") %>
16
+ <% end %>
17
+ <% nav.with_item(label: "Solutions", columns: 2) do |item| %>
18
+ <% item.with_link(title: "Startups", href: "#startups", description: "Everything to launch, on a free plan.") %>
19
+ <% item.with_link(title: "Enterprise", href: "#enterprise", description: "Scale, compliance and a named contact.") %>
20
+ <% item.with_link(title: "Agencies", href: "#agencies", description: "Run every client from one account.") %>
21
+ <% item.with_link(title: "Education", href: "#education", description: "Discounts for schools and students.") %>
22
+ <% item.with_link(title: "Nonprofits", href: "#nonprofits", description: "Half price for registered charities.") %>
23
+ <% item.with_link(title: "Developers", href: "#developers", description: "APIs, webhooks and SDKs.") %>
24
+ <% end %>
25
+ <% nav.with_item(label: "Resources") do |item| %>
26
+ <% item.with_link(title: "Documentation", href: "#docs", icon: "book-open", description: "Guides and the API reference.") %>
27
+ <% item.with_link(title: "Blog", href: "#blog", icon: "newspaper", description: "Product news and how-tos.") %>
28
+ <% item.with_link(title: "Changelog", href: "#changelog", icon: "rocket", description: "What shipped this week.") %>
29
+ <% item.with_link(title: "Academy", href: "#academy", icon: "graduation-cap", description: "Free courses, start to finish.") %>
30
+ <% item.with_link(title: "Help centre", href: "#help", icon: "life-buoy", description: "Answers, and a human when you need one.") %>
31
+ <% end %>
32
+ <% nav.with_item(label: "Pricing", href: "#pricing") %>
33
+ <% nav.with_item(label: "Docs", href: "#docs", active: true) %>
34
+ <% end %>
35
+
36
+ <div class="ml-auto flex items-center gap-2">
37
+ <%= render(UI::Button.new(variant: :ghost, size: :sm)) { "Sign in" } %>
38
+ <%= render(UI::Button.new(size: :sm)) { "Get started" } %>
39
+ </div>
40
+ </div>
41
+ </header>
42
+
43
+ <main class="mx-auto max-w-3xl space-y-6 px-4 py-12">
44
+ <h1 class="text-3xl font-bold tracking-tight">Scroll this page with a menu open</h1>
45
+ <p class="text-muted-foreground">The header sticks to the top and its panels stay attached to their triggers. At the bottom there's a footer menu: its panels open upwards, because there's no room below.</p>
46
+ <% 8.times do |i| %>
47
+ <section class="space-y-2">
48
+ <h2 class="text-lg font-semibold">Section <%= i + 1 %></h2>
49
+ <p class="text-sm text-muted-foreground">Placeholder copy so the page is long enough to scroll. Open a menu in the header, then scroll up and down: the panel follows the trigger. Then scroll to the footer and open one of its menus.</p>
50
+ <div class="h-32 rounded-lg border bg-muted/40"></div>
51
+ </section>
52
+ <% end %>
53
+ </main>
54
+
55
+ <footer class="border-t">
56
+ <div class="mx-auto flex max-w-6xl items-center justify-between gap-4 px-4 py-6">
57
+ <span class="text-sm text-muted-foreground">© Acme</span>
58
+ <%= render(UI::NavigationMenu.new(label: "Footer")) do |nav| %>
59
+ <% nav.with_item(label: "Company") do |item| %>
60
+ <% item.with_link(title: "About", href: "#about", description: "Who we are and why we build this.") %>
61
+ <% item.with_link(title: "Careers", href: "#careers", description: "Open roles, remote-first.") %>
62
+ <% item.with_link(title: "Press", href: "#press", description: "Logos, photos and contacts.") %>
63
+ <% end %>
64
+ <% nav.with_item(label: "Legal") do |item| %>
65
+ <% item.with_link(title: "Terms", href: "#terms") %>
66
+ <% item.with_link(title: "Privacy", href: "#privacy") %>
67
+ <% item.with_link(title: "Cookies", href: "#cookies") %>
68
+ <% end %>
69
+ <% nav.with_item(label: "Status", href: "#status") %>
70
+ <% end %>
71
+ </div>
72
+ </footer>
73
+ </div>
@@ -0,0 +1,23 @@
1
+ <div class="flex min-h-96 justify-center pt-8">
2
+ <%= render(UI::NavigationMenu.new) do |nav| %>
3
+ <% nav.with_item(label: "Getting started") do |item| %>
4
+ <% item.with_link(title: "Introduction", href: "#introduction", description: "Re-usable components built with Tailwind CSS.") %>
5
+ <% item.with_link(title: "Installation", href: "#installation", description: "How to install dependencies and structure your app.") %>
6
+ <% item.with_link(title: "Typography", href: "#typography", description: "Styles for headings, paragraphs, lists…etc") %>
7
+ <% end %>
8
+ <% nav.with_item(label: "Components", columns: 2) do |item| %>
9
+ <% item.with_link(title: "Alert", href: "#alert", description: "A callout for important information.") %>
10
+ <% item.with_link(title: "Dialog", href: "#dialog", description: "A modal window on top of the page.") %>
11
+ <% item.with_link(title: "Menu", href: "#menu", description: "A list of actions behind a button.") %>
12
+ <% item.with_link(title: "Tabs", href: "#tabs", description: "Panels shown one at a time.") %>
13
+ <% item.with_link(title: "Toast", href: "#toast", description: "A short message that disappears on its own.") %>
14
+ <% item.with_link(title: "Tooltip", href: "#tooltip", description: "A label that appears on hover or focus.") %>
15
+ <% end %>
16
+ <% nav.with_item(label: "With Icon") do |item| %>
17
+ <% item.with_link(title: "Backlog", href: "#backlog", icon: "circle-alert") %>
18
+ <% item.with_link(title: "To do", href: "#todo", icon: "info") %>
19
+ <% item.with_link(title: "Done", href: "#done", icon: "circle-check") %>
20
+ <% end %>
21
+ <% nav.with_item(label: "Docs", href: "#docs") %>
22
+ <% end %>
23
+ </div>
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A site's main navigation. Hover a trigger with a mouse (or click, or press
4
+ # Enter / ArrowDown) to open its panel; Escape, a click outside or Tab away
5
+ # closes it. Panels follow their trigger as the page scrolls, and open
6
+ # upwards when there isn't room below.
7
+ class UI::NavigationMenuPreview < ViewComponent::Preview
8
+ # A sticky site header with several menus, on a page long enough to
9
+ # scroll, and a second menu in the footer whose panels open upwards.
10
+ #
11
+ # @label Site header
12
+ # @param open_delay number
13
+ # @param close_delay number
14
+ def playground(open_delay: 150, close_delay: 200)
15
+ render_with_template(locals: { open_delay: open_delay.to_i, close_delay: close_delay.to_i })
16
+ end
17
+
18
+ # @label Simple
19
+ def simple; render_with_template; end
20
+
21
+ # @label Custom panel
22
+ def custom_panel; render_with_template; end
23
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "test_helper"
4
+
5
+ class UI::NavigationMenuTest < ViewComponent::TestCase
6
+ def setup_fixtures(*); end
7
+ def teardown_fixtures(*); end
8
+
9
+ def render_nav(**opts)
10
+ render_inline(UI::NavigationMenu.new(**opts)) do |nav|
11
+ nav.with_item(label: "Getting started") do |item|
12
+ item.with_link(title: "Introduction", href: "/docs", description: "Re-usable components.")
13
+ item.with_link(title: "Installation", href: "/docs/install")
14
+ end
15
+ nav.with_item(label: "Docs", href: "/docs")
16
+ end
17
+ end
18
+
19
+ def test_is_a_labelled_nav_with_the_controller
20
+ render_nav
21
+ nav = page.find("nav[data-controller~='ui--navigation-menu']")
22
+ assert_equal "Main", nav["aria-label"]
23
+ assert nav[:id].start_with?("ui-navigation-menu-")
24
+ assert_includes nav["data-action"], "focusout->ui--navigation-menu#focusOut"
25
+ assert_includes nav["data-action"], "focusin->ui--navigation-menu#focusIn"
26
+ end
27
+
28
+ def test_custom_label_and_delays
29
+ render_nav(label: "Product", open_delay: 0, close_delay: 500)
30
+ nav = page.find("nav")
31
+ assert_equal "Product", nav["aria-label"]
32
+ assert_equal "0", nav["data-ui--navigation-menu-open-delay-value"]
33
+ assert_equal "500", nav["data-ui--navigation-menu-close-delay-value"]
34
+ end
35
+
36
+ def test_item_with_links_is_a_disclosure_trigger
37
+ render_nav
38
+ trigger = page.find("button", text: "Getting started")
39
+ assert_equal "false", trigger["aria-expanded"]
40
+ panel = page.find("##{trigger['aria-controls']}", visible: :all)
41
+ assert panel[:hidden]
42
+ assert_equal "closed", panel["data-state"]
43
+ assert_includes trigger["data-action"], "click->ui--navigation-menu#toggle"
44
+ assert_includes trigger["data-action"], "pointerenter->ui--navigation-menu#hoverOpen"
45
+ assert_includes trigger["data-ui--navigation-menu-target"].split, "trigger"
46
+ end
47
+
48
+ def test_it_is_not_an_aria_menu
49
+ render_nav
50
+ assert_no_selector "[role='menu'], [role='menuitem']", visible: :all
51
+ end
52
+
53
+ def test_trigger_has_a_rotating_chevron
54
+ render_nav
55
+ icon = page.find("button", text: "Getting started").find("[data-lucide='chevron-down']", visible: :all)
56
+ assert_includes icon[:class], "group-aria-expanded/nav-item:rotate-180"
57
+ end
58
+
59
+ def test_item_without_panel_is_a_plain_link
60
+ render_nav
61
+ link = page.find("a", text: "Docs")
62
+ assert_equal "/docs", link[:href]
63
+ assert_nil link["aria-expanded"]
64
+ assert_includes link["data-ui--navigation-menu-target"], "top"
65
+ end
66
+
67
+ def test_active_plain_link_is_current_page
68
+ render_inline(UI::NavigationMenu.new) { |nav| nav.with_item(label: "Docs", href: "/docs", active: true) }
69
+ assert_selector "a[aria-current='page']", text: "Docs"
70
+ end
71
+
72
+ def test_panel_links_have_title_and_description
73
+ render_nav
74
+ link = page.find("a[href='/docs']", text: "Introduction", visible: :all)
75
+ assert link.has_text?(:all, "Re-usable components.")
76
+ assert_equal "link", link["data-ui--navigation-menu-target"]
77
+ assert_selector "a[href='/docs/install']", text: "Installation", visible: :all
78
+ end
79
+
80
+ def test_panel_link_icon_and_active
81
+ render_inline(UI::NavigationMenu.new) do |nav|
82
+ nav.with_item(label: "More") { |i| i.with_link(title: "Status", href: "/s", icon: "circle-check", active: true) }
83
+ end
84
+ link = page.find("a[href='/s']", visible: :all)
85
+ assert link.has_selector?("[data-lucide='circle-check']", visible: :all)
86
+ assert_includes link[:class], "items-center"
87
+ assert_equal "page", link["aria-current"]
88
+ end
89
+
90
+ def test_two_columns
91
+ render_inline(UI::NavigationMenu.new) do |nav|
92
+ nav.with_item(label: "Components", columns: 2) { |i| i.with_link(title: "A", href: "/a") }
93
+ end
94
+ assert_selector "ul.sm\\:grid-cols-2", visible: :all
95
+ assert_includes page.find("[data-ui--navigation-menu-target='panel']", visible: :all)[:class], "w-[36rem]"
96
+ end
97
+
98
+ def test_custom_panel_content
99
+ render_inline(UI::NavigationMenu.new) do |nav|
100
+ nav.with_item(label: "Company", panel_class: "w-96") { "<p class='promo'>We're hiring</p>".html_safe }
101
+ end
102
+ assert_selector "button", text: "Company"
103
+ panel = page.find("[data-ui--navigation-menu-target='panel']", visible: :all)
104
+ assert panel.has_selector?("p.promo", visible: :all)
105
+ assert_includes panel[:class], "w-96"
106
+ end
107
+
108
+ def test_ids_are_unique_per_item
109
+ render_inline(UI::NavigationMenu.new(id: "nav")) do |nav|
110
+ nav.with_item(label: "One") { |i| i.with_link(title: "A", href: "/a") }
111
+ nav.with_item(label: "Two") { |i| i.with_link(title: "B", href: "/b") }
112
+ end
113
+ assert_equal %w[nav-panel-1 nav-panel-2], page.all("button", visible: :all).map { _1["aria-controls"] }
114
+ end
115
+
116
+ def test_active_trigger_is_marked
117
+ render_inline(UI::NavigationMenu.new) do |nav|
118
+ nav.with_item(label: "Docs", active: true) { |i| i.with_link(title: "A", href: "/a") }
119
+ end
120
+ assert_selector "button[data-active]", text: "Docs"
121
+ end
122
+
123
+ def test_class_and_attrs_on_nav
124
+ render_nav(class: "my-nav", data: { turbo_permanent: true })
125
+ nav = page.find("nav")
126
+ assert_includes nav[:class], "my-nav"
127
+ assert_equal "true", nav["data-turbo-permanent"]
128
+ assert_equal "ui--navigation-menu", nav["data-controller"]
129
+ end
130
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: velvetkit
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.2.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rathan Kumar
@@ -166,6 +166,12 @@ files:
166
166
  - registry/app/components/ui/menu/trigger.rb
167
167
  - registry/app/components/ui/native_select.html.erb
168
168
  - registry/app/components/ui/native_select.rb
169
+ - registry/app/components/ui/navigation_menu.html.erb
170
+ - registry/app/components/ui/navigation_menu.rb
171
+ - registry/app/components/ui/navigation_menu/item.html.erb
172
+ - registry/app/components/ui/navigation_menu/item.rb
173
+ - registry/app/components/ui/navigation_menu/link.html.erb
174
+ - registry/app/components/ui/navigation_menu/link.rb
169
175
  - registry/app/components/ui/pagination.html.erb
170
176
  - registry/app/components/ui/pagination.rb
171
177
  - registry/app/components/ui/password_input.html.erb
@@ -286,6 +292,7 @@ files:
286
292
  - registry/app/javascript/controllers/ui/dialog_controller.ts
287
293
  - registry/app/javascript/controllers/ui/file_field_controller.ts
288
294
  - registry/app/javascript/controllers/ui/menu_controller.ts
295
+ - registry/app/javascript/controllers/ui/navigation_menu_controller.ts
289
296
  - registry/app/javascript/controllers/ui/password_visibility_controller.ts
290
297
  - registry/app/javascript/controllers/ui/popover_controller.ts
291
298
  - registry/app/javascript/controllers/ui/select_controller.ts
@@ -413,6 +420,10 @@ files:
413
420
  - registry/test/components/previews/ui/native_select_preview.rb
414
421
  - registry/test/components/previews/ui/native_select_preview/sizes.html.erb
415
422
  - registry/test/components/previews/ui/native_select_preview/states.html.erb
423
+ - registry/test/components/previews/ui/navigation_menu_preview.rb
424
+ - registry/test/components/previews/ui/navigation_menu_preview/custom_panel.html.erb
425
+ - registry/test/components/previews/ui/navigation_menu_preview/playground.html.erb
426
+ - registry/test/components/previews/ui/navigation_menu_preview/simple.html.erb
416
427
  - registry/test/components/previews/ui/pagination_preview.rb
417
428
  - registry/test/components/previews/ui/pagination_preview/states.html.erb
418
429
  - registry/test/components/previews/ui/password_input_preview.rb
@@ -548,6 +559,7 @@ files:
548
559
  - registry/test/components/ui/menu/trigger_test.rb
549
560
  - registry/test/components/ui/menu_test.rb
550
561
  - registry/test/components/ui/native_select_test.rb
562
+ - registry/test/components/ui/navigation_menu_test.rb
551
563
  - registry/test/components/ui/pagination_test.rb
552
564
  - registry/test/components/ui/password_input_test.rb
553
565
  - registry/test/components/ui/popover/content_test.rb